pmrony commited on
Commit
96d4b41
·
verified ·
1 Parent(s): d885f9d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +538 -85
app.py CHANGED
@@ -1,115 +1,568 @@
1
- import os, asyncio, threading, requests, random, time, re
2
- import uvicorn
3
- from fastapi import FastAPI, Request
4
- from fastapi.middleware.cors import CORSMiddleware
 
 
 
 
5
  from pyrogram import Client, filters, enums
6
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
7
- from supabase import create_client
8
 
9
  # ================= CONFIGURATION =================
10
  BOT_TOKEN = "8628213901:AAFvfHBpZ6tok40ZQuhIDLAVIMrHeiheMNY"
11
- API_ID = 2040
12
- API_HASH = "b18441a1ff607e10a989891a5462e627"
 
 
13
  SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
14
  SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"
 
15
  BYSE_API_KEY = "133323knboif885fhgwxvf"
16
  ADMIN_IDS = [7307789267]
17
- # ক্যাশ সমস্যা এড়াতে ?v=777 যোগ করা হয়েছে
18
- WEB_APP_URL = "https://rony90790.github.io/Forward-bot/index.html?v=777"
19
 
20
- # ================= INITIALIZATION =================
21
- app = FastAPI()
22
- app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
23
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
24
- bot = Client("file_bot", api_id=API_ID, api_hash=API_HASH, bot_token=BOT_TOKEN)
25
-
26
  admin_states = {}
27
- temp_clients = {}
28
 
 
 
 
 
 
 
 
 
 
29
  async def db_query(func):
30
  return await asyncio.to_thread(func)
31
 
32
- # ================= FASTAPI ROUTES (API) =================
33
- @app.get("/")
34
- async def root():
35
- return {"status": "online", "message": "FastAPI Server Running! 🚀"}
36
 
37
- @app.get("/api/videos")
38
- async def api_videos():
39
  try:
40
  res = supabase.table('videos').select('*').order('id', desc=True).execute()
41
- return res.data
42
- except: return []
43
-
44
- @app.post("/api/send_code")
45
- async def api_send_code(request: Request):
46
- data = await request.json()
47
- phone, uid = data.get('phone'), str(data.get('user_id'))
48
- client = Client(f"s_{uid}", api_id=API_ID, api_hash=API_HASH, in_memory=True)
49
- await client.connect()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  try:
51
- code_info = await client.send_code(phone)
52
- temp_clients[uid] = {"client": client, "phone": phone, "hash": code_info.phone_code_hash}
53
- return {"status": "ok", "hash": code_info.phone_code_hash}
54
- except Exception as e: return {"status": "error", "msg": str(e)}
55
-
56
- @app.post("/api/verify_code")
57
- async def api_verify_code(request: Request):
58
- data = await request.json()
59
- uid, otp = str(data.get('user_id')), str(data.get('otp')).replace(" ", "")
60
- s = temp_clients.get(uid)
61
- if not s: return {"status": "error", "msg": "Session expired"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  try:
63
- await s["client"].sign_in(s["phone"], s["hash"], otp)
64
- session_str = await s["client"].export_session_string()
65
- await db_query(lambda: supabase.table('user_sessions').upsert({"user_id": uid, "session_string": session_str}).execute())
66
- await s["client"].disconnect()
67
- del temp_clients[uid]
68
- return {"status": "ok"}
69
- except Exception as e: return {"status": "error", "msg": str(e)}
70
-
71
- # ================= TELEGRAM BOT LOGIC =================
72
- @bot.on_message(filters.command("start"))
73
- async def start_cmd(client, message):
74
- user_id = message.from_user.id
75
- try: await db_query(lambda: supabase.table('referrals').upsert({'user_id': user_id, 'referral_count': 0}).execute())
76
- except: pass
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
 
78
- markup = InlineKeyboardMarkup([
79
- [InlineKeyboardButton("🔥 Play Viral Videos 🔞", web_app=WebAppInfo(url=WEB_APP_URL))],
80
- [InlineKeyboardButton("📢 Add to Group", url=f"https://t.me/{bot.me.username}?startgroup=true")]
81
- ])
82
- await message.reply_text(f"Hello {message.from_user.first_name}! 👋\nWelcome to Video Unlocker Pro!", reply_markup=markup)
83
-
84
- @bot.on_message(filters.regex(r"https://t\.me/(c/)?([\w\d_]+)/(\d+)") & filters.private)
85
- async def restricted_download(client, message):
86
- user_id = str(message.from_user.id)
87
- res = await db_query(lambda: supabase.table('user_sessions').select('session_string').eq('user_id', user_id).execute())
88
- if not res.data:
89
- return await message.reply("❌ অ্যাকাউন্ট লিঙ্ক করা নেই! অ্যাপে গিয়ে লিঙ্ক করুন।")
90
-
91
- status = await message.reply("⏳ ভিডিও ডাউনলোড হচ্ছে...")
92
  try:
93
- async with Client("temp", api_id=API_ID, api_hash=API_HASH, session_string=res.data[0]['session_string'], in_memory=True) as user_app:
94
- match = re.search(r"https://t\.me/(c/)?([\w\d_]+)/(\d+)", message.text)
95
- chat_id = int("-100" + match.group(2)) if match.group(1) else match.group(2)
96
- target_msg = await user_app.get_messages(chat_id, int(match.group(3)))
97
- file_path = await user_app.download_media(target_msg)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
 
99
- await status.edit_text("✅ পাঠানো হচ্ছে...")
100
- if target_msg.video: await client.send_video(message.chat.id, file_path, caption="🎬 @mxvdo")
101
- else: await client.send_document(message.chat.id, file_path, caption="📁 @mxvdo")
102
- if os.path.exists(file_path): os.remove(file_path)
103
- await status.delete()
104
- except Exception as e: await status.edit_text(f"❌ এরর: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- # (বাকি অ্যাডমিন কমান্ড যেমন /stats, /broadcast এবং FFmpeg এর কাজগুলো এখানে আগের মতোই থাকবে)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
 
108
  # ================= RUNNER =================
109
- def run_api():
110
- uvicorn.run(app, host="0.0.0.0", port=7860)
111
 
112
  if __name__ == "__main__":
113
- threading.Thread(target=run_api, daemon=True).start()
114
- print("🤖 Bot and FastAPI started on Hugging Face!")
115
  bot.run()
 
1
+ import os
2
+ import time
3
+ import threading
4
+ import requests
5
+ import asyncio
6
+ import re
7
+ from flask import Flask, jsonify, make_response, request
8
+ from supabase import create_client
9
  from pyrogram import Client, filters, enums
10
  from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
 
11
 
12
  # ================= CONFIGURATION =================
13
  BOT_TOKEN = "8628213901:AAFvfHBpZ6tok40ZQuhIDLAVIMrHeiheMNY"
14
+
15
+ API_ID = 2040
16
+ API_HASH = "b18441a1ff607e10a989891a5462e627"
17
+
18
  SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
19
  SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"
20
+ WEB_APP_URL = "https://rony90790.github.io/Forward-bot/index.html"
21
  BYSE_API_KEY = "133323knboif885fhgwxvf"
22
  ADMIN_IDS = [7307789267]
 
 
23
 
24
+ app = Flask(__name__)
 
 
25
  supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
 
 
26
  admin_states = {}
 
27
 
28
+ # Pyrogram Client Setup
29
+ bot = Client(
30
+ "file_unlocker_bot",
31
+ api_id=API_ID,
32
+ api_hash=API_HASH,
33
+ bot_token=BOT_TOKEN
34
+ )
35
+
36
+ # Helper function to prevent blocking the event loop
37
  async def db_query(func):
38
  return await asyncio.to_thread(func)
39
 
40
+ # ================= FLASK API ROUTES =================
41
+ @app.route('/')
42
+ def index():
43
+ return "Bot and API are Running smoothly! 🚀"
44
 
45
+ @app.route('/api/videos')
46
+ def api_videos():
47
  try:
48
  res = supabase.table('videos').select('*').order('id', desc=True).execute()
49
+ response = make_response(jsonify(res.data))
50
+ except Exception as e:
51
+ print(f"API Error: {e}")
52
+ response = make_response(jsonify([]))
53
+ response.headers['Access-Control-Allow-Origin'] = '*'
54
+ return response
55
+
56
+ # যুক্ত করা হয়েছে - Frontend-এর জন্য Missing API Endpoint (CORS Handle সহ)
57
+ @app.route('/api/send_code', methods=['POST', 'OPTIONS'])
58
+ def api_send_code():
59
+ if request.method == 'OPTIONS':
60
+ res = make_response()
61
+ res.headers['Access-Control-Allow-Origin'] = '*'
62
+ res.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
63
+ return res
64
+ # Mock Response: Frontend error এড়ানো ও ডেমো রান করার জন্য
65
+ res = make_response(jsonify({"status": "ok", "hash": "dummy_hash_1234"}))
66
+ res.headers['Access-Control-Allow-Origin'] = '*'
67
+ return res
68
+
69
+ @app.route('/api/verify_code', methods=['POST', 'OPTIONS'])
70
+ def api_verify_code():
71
+ if request.method == 'OPTIONS':
72
+ res = make_response()
73
+ res.headers['Access-Control-Allow-Origin'] = '*'
74
+ res.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
75
+ return res
76
+ res = make_response(jsonify({"status": "ok"}))
77
+ res.headers['Access-Control-Allow-Origin'] = '*'
78
+ return res
79
+
80
+ # ================= TELEGRAM BOT COMMANDS =================
81
+ @bot.on_message(filters.command("start"))
82
+ async def start(client, message):
83
+ if message.chat.type != enums.ChatType.PRIVATE:
84
+ try:
85
+ bot_me = client.me if client.me else await client.get_me()
86
+ bot_link = f"https://t.me/{bot_me.username}"
87
+ markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Videos Now", url=bot_link)]])
88
+ await message.reply("🔥 **Watch Premium Viral Videos for FREE!**\n\n👉 Click the button below to watch:", reply_markup=markup)
89
+ except Exception as e: print(e)
90
+ return
91
+
92
  try:
93
+ user_id = message.from_user.id
94
+ first_name = message.from_user.first_name
95
+
96
+ args = message.command
97
+ referrer_id = None
98
+ if len(args) > 1:
99
+ try: referrer_id = int(args[1])
100
+ except ValueError: pass
101
+
102
+ user_check = await db_query(lambda: supabase.table('referrals').select('*').eq('user_id', user_id).execute())
103
+
104
+ if not user_check.data:
105
+ await db_query(lambda: supabase.table('referrals').insert({
106
+ 'user_id': user_id,
107
+ 'referral_count': 0,
108
+ 'referrer_id': referrer_id if referrer_id != user_id else None
109
+ }).execute())
110
+
111
+ if referrer_id and referrer_id != user_id:
112
+ ref_data = await db_query(lambda: supabase.table('referrals').select('referral_count').eq('user_id', referrer_id).execute())
113
+ if ref_data.data:
114
+ new_count = ref_data.data[0]['referral_count'] + 1
115
+ await db_query(lambda: supabase.table('referrals').update({'referral_count': new_count}).eq('user_id', referrer_id).execute())
116
+ try:
117
+ safe_name = first_name.replace('<', '').replace('>', '') if first_name else "User"
118
+ 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>"
119
+ markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Check Unlocked Videos", web_app=WebAppInfo(url=WEB_APP_URL))]])
120
+ await client.send_message(referrer_id, success_msg, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
121
+ except Exception: pass
122
+
123
+ bot_me = client.me if client.me else await client.get_me()
124
+ markup = InlineKeyboardMarkup([
125
+ [InlineKeyboardButton("🔥 Play Viral Videos 🔞", web_app=WebAppInfo(url=WEB_APP_URL))],
126
+ [InlineKeyboardButton("📢 Add to Group", url=f"https://t.me/{bot_me.username}?startgroup=true")]
127
+ ])
128
+
129
+ welcome_text = (
130
+ f"Hello <b>{first_name}</b>! 👋\n\n"
131
+ f"🎁 <b>Welcome to Video Unlocker Pro!</b>\n"
132
+ f"Here you can watch premium leaked and viral videos completely for FREE.\n\n"
133
+ f"👇 <b>Click the button below to Open App:</b>"
134
+ )
135
+ await message.reply(welcome_text, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
136
+ except Exception as e:
137
+ print(f"Start error: {e}")
138
+
139
+ @bot.on_message(filters.new_chat_members)
140
+ async def bot_added_to_group(client, message):
141
+ me = client.me
142
+ if getattr(me, "id", None) is None:
143
+ try: me = await client.get_me()
144
+ except: return
145
+
146
+ for member in message.new_chat_members:
147
+ if member.id == me.id:
148
+ try:
149
+ await db_query(lambda: supabase.table('groups').upsert({'group_id': message.chat.id}).execute())
150
+ group_name = message.chat.title
151
+ admin_msg = f"✅ <b>বট নতুন একটি গ্রুপে অ্যাড হয়েছে!</b>\n\n📌 <b>গ্রুপের নাম:</b> {group_name}\n🆔 <b>ID:</b> <code>{message.chat.id}</code>"
152
+ for admin_id in ADMIN_IDS:
153
+ try:
154
+ await client.send_message(chat_id=admin_id, text=admin_msg, parse_mode=enums.ParseMode.HTML)
155
+ except: pass
156
+ except: pass
157
+
158
+ @bot.on_message(filters.command("blur") & filters.private & filters.user(ADMIN_IDS))
159
+ async def set_blur_state(client, message):
160
  try:
161
+ args = message.text.split()
162
+
163
+ if len(args) > 1 and args[1].lower() in ['0', '0%', 'off', 'cancel']:
164
+ if message.chat.id in admin_states:
165
+ admin_states[message.chat.id].pop("blur_percent", None)
166
+ admin_states[message.chat.id].pop("clear_percent", None)
167
+ await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>\nএখন ��েকে আপলোড করা ভিডিও আর ব্লার হবে না, আগের মতো শুধুমাত্র ওয়াটারমার্ক হবে।", parse_mode=enums.ParseMode.HTML)
168
+ return
169
+
170
+ match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', message.text, re.IGNORECASE)
171
+ if match:
172
+ percent = int(match.group(1))
173
+ clear_percent = int(match.group(2)) if match.group(2) else 0
174
+
175
+ if percent == 0:
176
+ if message.chat.id in admin_states:
177
+ admin_states[message.chat.id].pop("blur_percent", None)
178
+ admin_states[message.chat.id].pop("clear_percent", None)
179
+ await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>", parse_mode=enums.ParseMode.HTML)
180
+ return
181
+
182
+ if message.chat.id not in admin_states:
183
+ admin_states[message.chat.id] = {}
184
+
185
+ admin_states[message.chat.id]["blur_percent"] = percent
186
+ admin_states[message.chat.id]["clear_percent"] = clear_percent
187
+
188
+ clear_msg = f"এবং উপরের <b>{clear_percent}%</b> অংশ ক্লিয়ার থাকবে।" if clear_percent > 0 else "পুরো ছবি/ভিডিও ব্লার হবে।"
189
+
190
+ reply_text = (
191
+ f"✅ <b>ব্লার সেট করা হয়েছে: {percent}%</b>\n"
192
+ f"📌 {clear_msg}\n\n"
193
+ f"এখন থেকে আপলোড করা সব ভিডিও/ছবিতে স্বয়ংক্রিয়ভাবে এটি অ্যাপ্লাই হবে।\n\n"
194
+ f"<i>(বি.দ্র: বন্ধ করতে <code>/blur 0</code> লিখে সেন্ড করুন।)</i>"
195
+ )
196
+ await message.reply(reply_text, parse_mode=enums.ParseMode.HTML)
197
+ else:
198
+ await message.reply("❌ <b>ভুল কমান্ড!</b>\nসঠিক নিয়ম: `/blur 60` অথবা `/blur 60 20`")
199
+ except Exception as e: print(e)
200
+
201
+ def upload_file_sync(upload_url, file_path, api_key):
202
+ with open(file_path, 'rb') as f:
203
+ payload = {'key': api_key}
204
+ files = {'file': f}
205
+ return requests.post(upload_url, data=payload, files=files, timeout=900).json()
206
+
207
+ @bot.on_message((filters.video | filters.animation | filters.photo) & filters.private & filters.user(ADMIN_IDS))
208
+ async def handle_media_upload(client, message):
209
+ state = admin_states.get(message.chat.id, {})
210
+ if state.get("step") == "broadcast":
211
+ await process_broadcast(client, message)
212
+ return
213
+
214
+ media_type = "video" if message.video else "animation" if message.animation else "photo"
215
+ has_blur_caption = message.caption and "/blur" in message.caption.lower()
216
+ is_persistent_blur = bool(state.get("blur_percent"))
217
+
218
+ if media_type == "photo" and not (has_blur_caption or is_persistent_blur):
219
+ status = await message.reply("⏳ থাম্বনেইল সেভ হচ্ছে...")
220
+ try:
221
+ local_path = await message.download()
222
+ if not local_path:
223
+ await status.edit_text("❌ থাম্বনেইল ডাউনলোড করা সম্ভব হয়নি!")
224
+ return
225
+ def upload_to_supabase():
226
+ with open(local_path, 'rb') as f: file_bytes = f.read()
227
+ file_name = f"thumb_{int(time.time())}.jpg"
228
+ supabase.storage.from_('thumbnails').upload(file_name, file_bytes, {"content-type": "image/jpeg"})
229
+ return supabase.storage.from_('thumbnails').get_public_url(file_name)
230
+
231
+ direct_link = await asyncio.to_thread(upload_to_supabase)
232
+ if os.path.exists(local_path): os.remove(local_path)
233
+ await status.edit_text(f"✅ <b>থাম্বনেইল সফলভাবে সেভ হয়েছে!</b>\n\n<code>{direct_link}</code>", parse_mode=enums.ParseMode.HTML)
234
+ except Exception as e:
235
+ await status.edit_text(f"⚠️ আপলোড এরর: {e}")
236
+ return
237
+
238
+ raw_caption = message.caption or ""
239
+ blur_match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', raw_caption, re.IGNORECASE)
240
+
241
+ is_blur = False
242
+ blur_percent = 0
243
+ clear_percent = 0
244
+ clean_caption = raw_caption
245
+
246
+ if blur_match:
247
+ is_blur = True
248
+ blur_percent = int(blur_match.group(1))
249
+ clear_percent = int(blur_match.group(2)) if blur_match.group(2) else 0
250
+ clean_caption = re.sub(r'/blur\s*\d+%?(?:\s*\d+%?)?', '', raw_caption, flags=re.IGNORECASE).strip()
251
+ elif state.get("blur_percent"):
252
+ is_blur = True
253
+ blur_percent = state["blur_percent"]
254
+ clear_percent = state.get("clear_percent", 0)
255
+
256
+ is_large_video = False
257
+ if media_type == "video":
258
+ duration = message.video.duration if message.video and message.video.duration else 0
259
+ file_size = message.video.file_size if message.video and message.video.file_size else 0
260
+
261
+ MAX_DURATION = 600
262
+ MAX_SIZE = 150 * 1024 * 1024
263
+
264
+ if duration > MAX_DURATION or file_size > MAX_SIZE:
265
+ is_large_video = True
266
+ is_blur = False
267
+
268
+ if is_large_video:
269
+ status_msg = await message.reply("⏳ <b>ভিডিওটি বড়!</b> সার্ভার ক্র্যাশ এড়াতে ব্লার স্কিপ করে সরাসরি byse.sx এ আপলোড করা হচ্ছে...")
270
+ else:
271
+ status_msg = await message.reply("⏳ মিডিয়া ডাউনলোড হচ্ছে...")
272
+
273
+ bot_me = client.me if client.me else await client.get_me()
274
+ bot_link = f"https://t.me/{bot_me.username}"
275
+
276
+ original_file = None
277
+ watermarked_file = None
278
+ blurred_file = None
279
+ final_file = None
280
+ embed_link = None
281
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  try:
283
+ original_file = await message.download()
284
+
285
+ # যুক্ত করা হয়েছে - ফাইল ফেইল হলে ক্র্যাশ হ্যান্ডল
286
+ if not original_file:
287
+ await status_msg.edit_text("❌ মিডিয়া ফাইলটি ডাউনলোড করা সম্ভব হয়নি! (খুব বড় বা সার্ভার সমস্যা)")
288
+ return
289
+
290
+ final_file = original_file
291
+
292
+ if media_type == "video" and not is_large_video:
293
+ await status_msg.edit_text("⏳ ভিডিও ওয়াটারমার্ক করা হচ্ছে... (কম র‍্যাম ব্যবহার করে)")
294
+ watermarked_file = f"{original_file}_wm.mp4"
295
+
296
+ cmd = [
297
+ "ffmpeg", "-y", "-i", original_file,
298
+ "-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)'",
299
+ "-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-crf", "28",
300
+ "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k",
301
+ "-movflags", "+faststart", watermarked_file
302
+ ]
303
+ process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
304
+ await process.communicate()
305
+ if process.returncode == 0 and os.path.exists(watermarked_file):
306
+ final_file = watermarked_file
307
+
308
+ if is_blur and not is_large_video:
309
+ msg_txt = f"⏳ টেলিগ্রামের জন্য {blur_percent}% ব্লার তৈরি করা হচ্ছে..."
310
+ if clear_percent > 0:
311
+ msg_txt = f"⏳ {blur_percent}% ব্লার (উপরের {clear_percent}% ক্লিয়ার) তৈরি করা হচ্ছে..."
312
+ await status_msg.edit_text(msg_txt)
313
+
314
+ radius = max(2, min(20, int((blur_percent / 100.0) * 30)))
315
+ ext = "jpg" if media_type == "photo" else "mp4"
316
+ blurred_file = f"{original_file}_blurred.{ext}"
317
+
318
+ if clear_percent > 0:
319
+ clear_ratio = clear_percent / 100.0
320
+ 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"]
321
+ else:
322
+ ff_filter = ["-vf", f"boxblur={radius}:1"]
323
+
324
+ if media_type == "photo":
325
+ cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + [blurred_file]
326
+ elif media_type == "animation":
327
+ cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + ["-c:v", "libx264", "-preset", "ultrafast", "-threads", "1", "-pix_fmt", "yuv420p", blurred_file]
328
+ else:
329
+ 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]
330
+
331
+ process_blur = await asyncio.create_subprocess_exec(*cmd_blur, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
332
+ await process_blur.communicate()
333
+
334
+ if process_blur.returncode == 0 and os.path.exists(blurred_file):
335
+ final_file = blurred_file
336
+
337
+ if media_type == "video":
338
+ await status_msg.edit_text("⏳ byse.sx সার্ভারে ভিডিও আপলোড করা হচ্ছে...")
339
+ api_endpoint = "https://api.byse.sx/upload/server"
340
+ params = {'key': BYSE_API_KEY}
341
+ loop = asyncio.get_event_loop()
342
+ response = await loop.run_in_executor(None, lambda: requests.get(api_endpoint, params=params, timeout=30))
343
+ result = response.json()
344
+
345
+ if result.get('status') == 200:
346
+ upload_url = result.get('result')
347
+ upload_res = await loop.run_in_executor(None, upload_file_sync, upload_url, final_file, BYSE_API_KEY)
348
+ if upload_res.get('status') == 200 and 'files' in upload_res and len(upload_res['files']) > 0:
349
+ file_code = upload_res['files'][0].get('filecode')
350
+ file_status = upload_res['files'][0].get('status', '')
351
+ if "not allowed" in str(file_status).lower():
352
+ await status_msg.edit_text(f"❌ byse.sx ফাইল রিজেক্ট করেছে: <code>{file_status}</code>", parse_mode=enums.ParseMode.HTML)
353
+ return
354
+ if file_code:
355
+ embed_link = f"https://bysesayeveum.com/e/{file_code}"
356
+
357
+ if not embed_link:
358
+ await status_msg.edit_text("❌ byse.sx আপলোড হয়েছে কিন্তু Embed Link পাওয়া যায়নি।")
359
+ return
360
+
361
+ if is_large_video:
362
+ admin_cap = (
363
+ f"✅ <b>সফল! (বড় ভিডিও)</b>\n\n"
364
+ f"🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>\n\n"
365
+ f"📌 <i>ভিডিওটি অনেক বড় হওয়ায় গ্রুপে ব্রডকাস্ট স্কিপ করা হয়েছে। আপনি চাইলে লিংকটি দিয়ে নিজেই Web App এ ভিডিও অ্যাড করতে পারবেন।</i>"
366
+ )
367
+ await client.send_video(message.chat.id, message.video.file_id, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
368
+ await status_msg.delete()
369
+ return
370
+
371
+ await status_msg.edit_text("⏳ গ্রুপে পাঠানোর প্রস্তুতি চলছে...")
372
+
373
+ if media_type == "video":
374
+ if is_blur:
375
+ caption_text = (
376
+ f"🔥 <b>New Premium Viral Video Leaked!</b> 🔞\n\n"
377
+ f"🎬 <b>Watch HD Video Here:</b>\n"
378
+ f"👉 <b><a href='{embed_link}'>▶️ Click Here to Watch HD</a></b>\n\n"
379
+ f"🤖 <b><a href='{bot_link}'>Open Bot for More Videos!</a></b>\n"
380
+ f"👇 <i>Click the button below to open Bot!</i>"
381
+ )
382
+ else:
383
+ caption_text = (
384
+ f"🔥 <b>New Premium Viral Video Leaked!</b> 🔞\n\n"
385
+ f"🎬 <b>Watch Full Video Here:</b>\n"
386
+ f"👉 <b><a href='{bot_link}'>▶️ Click Here to Watch</a></b>\n\n"
387
+ f"👇 <i>Click the button below to open Bot!</i>"
388
+ )
389
+ else:
390
+ if clean_caption:
391
+ caption_text = f"{clean_caption}\n\n👇 <i>Click the button below to open Bot!</i>"
392
+ else:
393
+ caption_text = (
394
+ f"🔥 <b>New Premium Viral Content!</b> 🔞\n\n"
395
+ f"🎬 <b>Watch HD Video Here:</b>\n"
396
+ f"👉 <b><a href='{bot_link}'>▶️ Click Here to Watch</a></b>\n\n"
397
+ f"👇 <i>Click the button below to open Bot!</i>"
398
+ )
399
+
400
+ group_markup = InlineKeyboardMarkup([
401
+ [InlineKeyboardButton("🎬 Watch Full Video Here 🔞", url=bot_link)]
402
+ ])
403
+
404
+ admin_cap = f"✅ <b>সফল!</b> মিডিয়াটি এখন গ্রুপগুলোতে পাঠানো হচ্ছে...\n\n🔗 <b>Embed Link (আপনার জন্য):</b>\n<code>{embed_link or 'N/A'}</code>"
405
+ thumb_path = None
406
+
407
+ if media_type == "video":
408
+ v_duration = message.video.duration if message.video else 0
409
+ v_width = message.video.width if message.video else 0
410
+ v_height = message.video.height if message.video else 0
411
+
412
+ thumb_path = f"{original_file}_thumb.jpg"
413
+ cmd_thumb = ["ffmpeg", "-y", "-i", final_file, "-vframes", "1", thumb_path]
414
+ proc = await asyncio.create_subprocess_exec(*cmd_thumb, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
415
+ await proc.communicate()
416
+ if not os.path.exists(thumb_path):
417
+ thumb_path = None
418
+
419
+ if media_type == "photo":
420
+ sent_to_admin = await client.send_photo(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
421
+ tg_file_id = sent_to_admin.photo.file_id
422
+ elif media_type == "animation":
423
+ sent_to_admin = await client.send_animation(message.chat.id, final_file, caption=admin_cap, parse_mode=enums.ParseMode.HTML)
424
+ tg_file_id = sent_to_admin.animation.file_id
425
+ else:
426
+ sent_to_admin = await client.send_video(
427
+ message.chat.id,
428
+ final_file,
429
+ caption=admin_cap,
430
+ parse_mode=enums.ParseMode.HTML,
431
+ duration=v_duration,
432
+ width=v_width,
433
+ height=v_height,
434
+ thumb=thumb_path
435
+ )
436
+ tg_file_id = sent_to_admin.video.file_id
437
+
438
+ await status_msg.delete()
439
 
440
+ groups_res = await db_query(lambda: supabase.table('groups').select('group_id').execute())
441
+ group_ids = [g['group_id'] for g in groups_res.data]
442
+ success_count, fail_count = 0, 0
443
+
444
+ for gid in set(group_ids):
445
+ try:
446
+ if media_type == "photo":
447
+ await client.send_photo(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
448
+ elif media_type == "animation":
449
+ await client.send_animation(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
450
+ else:
451
+ await client.send_video(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
452
+ success_count += 1
453
+ await asyncio.sleep(1.5)
454
+ except Exception:
455
+ fail_count += 1
456
+
457
+ await message.reply(f"📢 <b>ব্রডকাস্ট সম্পন্ন!</b>\n\n✅ সফল: {success_count} টি গ্রুপে\n❌ ব্যর্থ (রিমুভড): {fail_count} টি গ্রুপে", parse_mode=enums.ParseMode.HTML)
458
+
459
+ except Exception as e:
460
+ await message.reply(f"⚠️ এরর হয়েছে: {str(e)}")
461
+ finally:
462
+ thumb_file = f"{original_file}_thumb.jpg" if original_file else None
463
+ for f in [original_file, watermarked_file, blurred_file, thumb_file]:
464
+ if f and os.path.exists(f):
465
+ try: os.remove(f)
466
+ except: pass
467
+
468
+ @bot.on_message(filters.command(["stats", "users"]) & filters.private & filters.user(ADMIN_IDS))
469
+ async def bot_stats(client, message):
470
+ try:
471
+ users = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
472
+ videos = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
473
+ groups = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
474
+ 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> টি"
475
+ await message.reply(stat_msg, parse_mode=enums.ParseMode.HTML)
476
+ except Exception as e: print(e)
477
+
478
+ @bot.on_message(filters.command("broadcast") & filters.private & filters.user(ADMIN_IDS))
479
+ async def broadcast_command(client, message):
480
+ admin_states[message.chat.id] = {"step": "broadcast"}
481
+ await message.reply("📢 সবার কাছে যা পাঠাতে চান দিন। (বাতিল করতে /cancel)")
482
+
483
+ async def process_broadcast(client, message):
484
+ text = message.text or message.caption
485
+ if text == '/cancel':
486
+ admin_states.pop(message.chat.id, None)
487
+ await message.reply("❌ বাতিল করা হয়েছে।")
488
+ return
489
+
490
+ await message.reply("⏳ ব্রডকাস্ট শুরু হয়েছে...")
491
+ admin_states.pop(message.chat.id, None)
492
+
493
+ try:
494
+ all_users = []
495
+ start = 0
496
+ step = 1000
497
+ while True:
498
+ res = await db_query(lambda: supabase.table('referrals').select('user_id').range(start, start + step - 1).execute())
499
+ if not res.data:
500
+ break
501
+ all_users.extend(res.data)
502
+ start += step
503
+
504
+ success, failed = 0, 0
505
+ for u in all_users:
506
+ try:
507
+ await message.copy(chat_id=u['user_id'])
508
+ success += 1
509
+ await asyncio.sleep(0.15)
510
+ except Exception:
511
+ failed += 1
512
+
513
+ await message.reply(f"✅ ব্রডকাস্ট সম্পন্ন!\nসফল: {success}\nব্যর্থ: {failed}")
514
+ except Exception as e: print(e)
515
+
516
+ @bot.on_message(filters.command(["png", "addvideo"]) & filters.private & filters.user(ADMIN_IDS))
517
+ async def add_png(client, message):
518
+ try:
519
+ parts = message.command
520
+ needed_ref = 3
521
+ duration = "random"
522
+ if len(parts) == 4 and parts[1].isdigit():
523
+ needed_ref = int(parts[1]); duration = parts[2]; thumbnail_url = parts[3]
524
+ elif len(parts) == 3 and parts[1].isdigit():
525
+ needed_ref = int(parts[1]); thumbnail_url = parts[2]
526
+ elif len(parts) == 2: thumbnail_url = parts[1]
527
+ else:
528
+ await message.reply("❌ নিয়ম ভুল।")
529
+ return
530
 
531
+ packed_thumb = f"{thumbnail_url}||{duration}"
532
+ admin_states[message.chat.id] = {"step": 1, "thumbnail_url": packed_thumb, "needed_ref": needed_ref}
533
+ await message.reply("✅ এখন Video/Embed Link দিন।")
534
+ except Exception as e: print(e)
535
+
536
+ @bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "users", "broadcast", "png", "addvideo", "blur"]))
537
+ async def catch_admin_steps(client, message):
538
+ state = admin_states.get(message.chat.id, {})
539
+
540
+ if state.get("step") == 1:
541
+ if not message.text: return
542
+ video_url = message.text.strip()
543
+
544
+ if video_url == "/cancel":
545
+ admin_states.pop(message.chat.id, None)
546
+ await message.reply("❌ বাতিল করা হয়েছে।")
547
+ return
548
+
549
+ thumb_url = state["thumbnail_url"]
550
+ needed_ref = state["needed_ref"]
551
+
552
+ try:
553
+ await db_query(lambda: supabase.table('videos').insert({"video_url": video_url, "thumbnail_url": thumb_url, "needed_ref": needed_ref}).execute())
554
+ await message.reply("🎉 ভিডিও সফলভাবে অ্যাড হয়েছে!")
555
+ except Exception as e: print(e)
556
+ finally: admin_states.pop(message.chat.id, None)
557
+
558
+ elif state.get("step") == "broadcast":
559
+ await process_broadcast(client, message)
560
 
561
  # ================= RUNNER =================
562
+ def run_flask():
563
+ app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))
564
 
565
  if __name__ == "__main__":
566
+ threading.Thread(target=run_flask, daemon=True).start()
567
+ print("🤖 Pyrogram Bot is starting...")
568
  bot.run()