File size: 25,821 Bytes
96d4b41
 
 
 
 
 
2d83c40
dd2cce4
96d4b41
 
dd2cce4
58f8b8d
119d2aa
58f8b8d
10b6ebf
96d4b41
 
 
 
8c80a61
 
9b8df11
8619e9f
9b8df11
58f8b8d
5fcc166
e5df29a
96d4b41
58f8b8d
1c0019c
2d83c40
 
96d4b41
 
 
 
 
 
 
dd2cce4
 
404a901
 
 
dd2cce4
 
404a901
 
 
 
 
dd2cce4
404a901
 
58f8b8d
 
 
96d4b41
 
 
 
5fcc166
9b8df11
 
 
 
 
 
96d4b41
 
58f8b8d
 
9b8df11
96d4b41
9b8df11
96d4b41
 
 
 
9b8df11
2d83c40
9b8df11
2d83c40
 
 
 
9b8df11
 
 
 
2d83c40
 
 
 
 
404a901
8821d65
dd2cce4
 
2d83c40
9b8df11
96d4b41
 
 
 
9b8df11
2d83c40
9b8df11
2d83c40
 
 
 
 
9b8df11
2d83c40
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
e5df29a
96d4b41
 
 
 
9b8df11
96d4b41
 
 
 
 
 
 
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
 
 
 
58f8b8d
96d4b41
 
 
 
 
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
9b8df11
96d4b41
 
 
9b8df11
 
96d4b41
9b8df11
96d4b41
 
 
 
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
 
9b8df11
96d4b41
 
9b8df11
1c0019c
58f8b8d
96d4b41
 
9b8df11
96d4b41
 
 
 
 
9b8df11
96d4b41
9b8df11
96d4b41
 
9b8df11
96d4b41
 
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
9b8df11
 
 
96d4b41
 
 
9b8df11
96d4b41
 
 
 
9b8df11
96d4b41
 
9b8df11
96d4b41
 
9b8df11
96d4b41
 
 
 
 
 
9b8df11
96d4b41
 
 
 
 
9b8df11
 
96d4b41
9b8df11
96d4b41
 
 
 
 
 
 
9b8df11
96d4b41
9b8df11
 
 
 
 
96d4b41
 
 
 
 
 
 
 
9b8df11
 
 
96d4b41
 
9b8df11
96d4b41
9b8df11
96d4b41
9b8df11
96d4b41
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
 
 
 
9b8df11
96d4b41
 
9b8df11
96d4b41
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
 
 
 
 
 
 
9b8df11
 
 
96d4b41
9b8df11
58f8b8d
9b8df11
96d4b41
 
 
 
 
 
 
 
 
 
 
9b8df11
96d4b41
 
9b8df11
96d4b41
 
 
 
9b8df11
5fcc166
9b8df11
b5a9862
dd2cce4
 
 
 
 
 
 
119d2aa
96d4b41
dd2cce4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
import os
import time
import threading
import requests
import asyncio
import re
import random
import queue
from flask import Flask, jsonify, make_response, request
from supabase import create_client
from pyrogram import Client, filters, enums, idle
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo

# ================= CONFIGURATION =================
BOT_TOKEN = "8628213901:AAFvfHBpZ6tok40ZQuhIDLAVIMrHeiheMNY"

API_ID = 2040         
API_HASH = "b18441a1ff607e10a989891a5462e627"     

SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"

WEB_APP_URL = "https://rony90790.github.io/Forward-bot/app.html" 

BYSE_API_KEY = "133323knboif885fhgwxvf"
ADMIN_IDS = [7307789267]

app = Flask(__name__)
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
admin_states = {}
temp_otps = {}

bot = Client(
    "file_unlocker_bot",
    api_id=API_ID,
    api_hash=API_HASH,
    bot_token=BOT_TOKEN
)

# === ম্যাজিক ফিক্স: থ্রেড-সেফ কিউ সিস্টেম (Thread-safe Queue) ===
send_queue = queue.Queue()

async def background_worker():
    while True:
        while not send_queue.empty():
            msg = send_queue.get()
            try:
                # সরাসরি বটের নিজস্ব কানেকশন দিয়ে মেসেজ পাঠানো হচ্ছে
                await bot.send_message(chat_id=int(msg['chat_id']), text=msg['text'], parse_mode=enums.ParseMode.HTML)
            except Exception as e:
                print("Error sending OTP via MTProto:", e)
        await asyncio.sleep(1)
# ==========================================================

async def db_query(func):
    return await asyncio.to_thread(func)

# ================= FLASK API ROUTES =================
@app.route('/')
def index():
    return "Bot and API are Running smoothly! 🚀"

def add_cors_headers(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
    response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
    return response

@app.route('/api/videos')
def api_videos():
    try:
        res = supabase.table('videos').select('*').order('id', desc=True).execute()
        return add_cors_headers(make_response(jsonify(res.data)))
    except Exception as e:
        return add_cors_headers(make_response(jsonify([])))

@app.route('/api/send_code', methods=['POST', 'OPTIONS'])
def api_send_code():
    if request.method == 'OPTIONS':
        return add_cors_headers(make_response())
    
    data = request.json or {}
    phone = data.get('phone')
    user_id = data.get('user_id')
    
    if not user_id:
        return add_cors_headers(make_response(jsonify({"status": "error", "msg": "User ID missing! Please try again inside Telegram."})))
        
    if str(user_id) == '123456':
        return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Please Open WebApp inside Telegram Bot!"})))
        
    otp = str(random.randint(10000, 99999))
    hash_val = str(random.randint(1000000, 9999999))
    temp_otps[hash_val] = otp
    
    text_msg = f"🔐 আপনার Video Unlocker Pro এর Verification Code হচ্ছে: <b>{otp}</b>\n\nঅনুগ্রহ করে এটি কারো সাথে শেয়ার করবেন না।"
    
    # মেসেজটি কিউতে যোগ করা হলো
    send_queue.put({"chat_id": user_id, "text": text_msg})
    
    return add_cors_headers(make_response(jsonify({"status": "ok", "hash": hash_val})))

@app.route('/api/verify_code', methods=['POST', 'OPTIONS'])
def api_verify_code():
    if request.method == 'OPTIONS':
        return add_cors_headers(make_response())
        
    data = request.json or {}
    hash_val = data.get('hash')
    user_otp = data.get('otp')
    
    if temp_otps.get(hash_val) == user_otp:
        del temp_otps[hash_val]
        return add_cors_headers(make_response(jsonify({"status": "ok"})))
    else:
        return add_cors_headers(make_response(jsonify({"status": "error", "msg": "Invalid OTP!"})))

# ================= TELEGRAM BOT COMMANDS =================
@bot.on_message(filters.command("start"))
async def start(client, message):
    if message.chat.type != enums.ChatType.PRIVATE:
        try:
            bot_me = client.me if client.me else await client.get_me()
            bot_link = f"https://t.me/{bot_me.username}"
            markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Videos Now", url=bot_link)]])
            await message.reply("🔥 **Watch Premium Viral Videos for FREE!**\n\n👉 Click the button below to watch:", reply_markup=markup)
        except Exception: pass
        return

    try:
        user_id = message.from_user.id
        first_name = message.from_user.first_name
        args = message.command
        referrer_id = None
        
        if len(args) > 1:
            try: referrer_id = int(args[1])
            except ValueError: pass

        user_check = await db_query(lambda: supabase.table('referrals').select('*').eq('user_id', user_id).execute())
        
        if not user_check.data: 
            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())
            if referrer_id and referrer_id != user_id:
                ref_data = await db_query(lambda: supabase.table('referrals').select('referral_count').eq('user_id', referrer_id).execute())
                if ref_data.data:
                    new_count = ref_data.data[0]['referral_count'] + 1
                    await db_query(lambda: supabase.table('referrals').update({'referral_count': new_count}).eq('user_id', referrer_id).execute())
                    try:
                        safe_name = first_name.replace('<', '').replace('>', '') if first_name else "User"
                        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>"
                        markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Check Unlocked Videos", web_app=WebAppInfo(url=WEB_APP_URL))]])
                        await client.send_message(referrer_id, success_msg, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
                    except Exception: pass

        bot_me = client.me if client.me else await client.get_me()
        markup = InlineKeyboardMarkup([
            [InlineKeyboardButton("🔥 Play Viral Videos 🔞", web_app=WebAppInfo(url=WEB_APP_URL))],
            [InlineKeyboardButton("📢 Add to Group", url=f"https://t.me/{bot_me.username}?startgroup=true")]
        ])
        
        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>")
        await message.reply(welcome_text, parse_mode=enums.ParseMode.HTML, reply_markup=markup)
    except Exception as e: print(f"Start error: {e}")

@bot.on_message(filters.new_chat_members)
async def bot_added_to_group(client, message):
    me = client.me
    if getattr(me, "id", None) is None:
        try: me = await client.get_me()
        except: return

    for member in message.new_chat_members:
        if member.id == me.id:
            try:
                await db_query(lambda: supabase.table('groups').upsert({'group_id': message.chat.id}).execute())
                group_name = message.chat.title
                admin_msg = f"✅ <b>বট নতুন একটি গ্রুপে অ্যাড হয়েছে!</b>\n\n📌 <b>গ্রুপের নাম:</b> {group_name}\n🆔 <b>ID:</b> <code>{message.chat.id}</code>"
                for admin_id in ADMIN_IDS:
                    try: await client.send_message(chat_id=admin_id, text=admin_msg, parse_mode=enums.ParseMode.HTML)
                    except: pass
            except: pass

@bot.on_message(filters.command("blur") & filters.private & filters.user(ADMIN_IDS))
async def set_blur_state(client, message):
    try:
        args = message.text.split()
        if len(args) > 1 and args[1].lower() in ['0', '0%', 'off', 'cancel']:
            if message.chat.id in admin_states:
                admin_states[message.chat.id].pop("blur_percent", None)
                admin_states[message.chat.id].pop("clear_percent", None)
            await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>")
            return

        match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', message.text, re.IGNORECASE)
        if match:
            percent = int(match.group(1))
            clear_percent = int(match.group(2)) if match.group(2) else 0

            if percent == 0:
                if message.chat.id in admin_states:
                    admin_states[message.chat.id].pop("blur_percent", None)
                    admin_states[message.chat.id].pop("clear_percent", None)
                await message.reply("✅ <b>ব্লার মোড বন্ধ করা হয়েছে!</b>")
                return

            if message.chat.id not in admin_states: admin_states[message.chat.id] = {}
            admin_states[message.chat.id]["blur_percent"] = percent
            admin_states[message.chat.id]["clear_percent"] = clear_percent
            
            clear_msg = f"এবং উপরের <b>{clear_percent}%</b> অংশ ক্লিয়ার থাকবে।" if clear_percent > 0 else "পুরো অংশ ব্লার হবে।"
            await message.reply(f"✅ <b>ব্লার সেট করা হয়েছে: {percent}%</b>\n📌 {clear_msg}", parse_mode=enums.ParseMode.HTML)
        else:
            await message.reply("❌ <b>ভুল কমান্ড!</b> নিয়ম: `/blur 60` অথবা `/blur 60 20`")
    except Exception as e: print(e)

def upload_file_sync(upload_url, file_path, api_key):
    with open(file_path, 'rb') as f:
        return requests.post(upload_url, data={'key': api_key}, files={'file': f}, timeout=900).json()

@bot.on_message((filters.video | filters.animation | filters.photo) & filters.private & filters.user(ADMIN_IDS))
async def handle_media_upload(client, message):
    state = admin_states.get(message.chat.id, {})
    if state.get("step") == "broadcast":
        await process_broadcast(client, message)
        return

    media_type = "video" if message.video else "animation" if message.animation else "photo"
    has_blur_caption = message.caption and "/blur" in message.caption.lower()
    is_persistent_blur = bool(state.get("blur_percent"))

    if media_type == "photo" and not (has_blur_caption or is_persistent_blur):
        status = await message.reply("⏳ থাম্বনেইল সেভ হচ্ছে...")
        try:
            local_path = await message.download()
            if not local_path:
                await status.edit_text("❌ থাম্বনেইল ডাউনলোড করা সম্ভব হয়নি!")
                return
            def upload_to_supabase():
                with open(local_path, 'rb') as f: file_bytes = f.read()
                file_name = f"thumb_{int(time.time())}.jpg"
                supabase.storage.from_('thumbnails').upload(file_name, file_bytes, {"content-type": "image/jpeg"})
                return supabase.storage.from_('thumbnails').get_public_url(file_name)
            direct_link = await asyncio.to_thread(upload_to_supabase)
            if os.path.exists(local_path): os.remove(local_path)
            await status.edit_text(f"✅ <b>থাম্বনেইল সফলভাবে সেভ হয়েছে!</b>\n\n<code>{direct_link}</code>", parse_mode=enums.ParseMode.HTML)
        except Exception as e: await status.edit_text(f"⚠️ আপলোড এরর: {e}")
        return

    raw_caption = message.caption or ""
    blur_match = re.search(r'/blur\s+(\d+)%?(?:\s+(\d+)%?)?', raw_caption, re.IGNORECASE)
    is_blur = False
    blur_percent = 0
    clear_percent = 0
    clean_caption = raw_caption

    if blur_match:
        is_blur = True
        blur_percent = int(blur_match.group(1))
        clear_percent = int(blur_match.group(2)) if blur_match.group(2) else 0
        clean_caption = re.sub(r'/blur\s*\d+%?(?:\s*\d+%?)?', '', raw_caption, flags=re.IGNORECASE).strip()
    elif state.get("blur_percent"):
        is_blur = True
        blur_percent = state["blur_percent"]
        clear_percent = state.get("clear_percent", 0)

    is_large_video = False
    if media_type == "video":
        duration = message.video.duration if message.video and message.video.duration else 0
        file_size = message.video.file_size if message.video and message.video.file_size else 0
        if duration > 600 or file_size > 150 * 1024 * 1024:
            is_large_video = True
            is_blur = False

    status_msg = await message.reply("⏳ <b>ভিডিওটি বড়!</b> ব্লার স্কিপ হচ্ছে..." if is_large_video else "⏳ মিডিয়া ডাউনলোড হচ্ছে...")
    bot_me = client.me if client.me else await client.get_me()
    bot_link = f"https://t.me/{bot_me.username}"
    original_file = watermarked_file = blurred_file = final_file = embed_link = None
    
    try:
        original_file = await message.download()
        if not original_file:
            await status_msg.edit_text("❌ মিডিয়া ফাইলটি ডাউনলোড করা সম্ভব হয়নি!")
            return
            
        final_file = original_file
        
        if media_type == "video" and not is_large_video:
            await status_msg.edit_text("⏳ ভিডিও ওয়াটারমার্ক করা হচ্ছে...")
            watermarked_file = f"{original_file}_wm.mp4"
            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]
            process = await asyncio.create_subprocess_exec(*cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
            await process.communicate()
            if process.returncode == 0 and os.path.exists(watermarked_file): final_file = watermarked_file
            
        if is_blur and not is_large_video:
            await status_msg.edit_text(f"⏳ {blur_percent}% ব্লার তৈরি করা হচ্ছে...")
            radius = max(2, min(20, int((blur_percent / 100.0) * 30)))
            ext = "jpg" if media_type == "photo" else "mp4"
            blurred_file = f"{original_file}_blurred.{ext}"
            
            if clear_percent > 0:
                clear_ratio = clear_percent / 100.0
                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"]
            else:
                ff_filter = ["-vf", f"boxblur={radius}:1"]
            
            if media_type == "photo": cmd_blur = ["ffmpeg", "-y", "-i", final_file] + ff_filter + [blurred_file]
            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]
            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]
            
            process_blur = await asyncio.create_subprocess_exec(*cmd_blur, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
            await process_blur.communicate()
            if process_blur.returncode == 0 and os.path.exists(blurred_file): final_file = blurred_file

        if media_type == "video":
            await status_msg.edit_text("⏳ byse.sx সার্ভারে ভিডিও আপলোড করা হচ্ছে...")
            loop = asyncio.get_event_loop()
            result = await loop.run_in_executor(None, lambda: requests.get("https://api.byse.sx/upload/server", params={'key': BYSE_API_KEY}, timeout=30).json())
            
            if result.get('status') == 200:
                upload_res = await loop.run_in_executor(None, upload_file_sync, result.get('result'), final_file, BYSE_API_KEY)
                if upload_res.get('status') == 200 and 'files' in upload_res and len(upload_res['files']) > 0:
                    file_code = upload_res['files'][0].get('filecode')
                    if file_code: embed_link = f"https://bysesayeveum.com/e/{file_code}"
            
            if not embed_link:
                await status_msg.edit_text("❌ byse.sx আপলোড হয়েছে কিন্তু Embed Link পাওয়া যায়নি।")
                return

        if is_large_video:
            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)
            await status_msg.delete()
            return 
            
        await status_msg.edit_text("⏳ গ্রুপে পাঠানোর প্রস্তুতি চলছে...")
        
        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>")
        group_markup = InlineKeyboardMarkup([[InlineKeyboardButton("🎬 Watch Full Video Here 🔞", url=bot_link)]])
        
        admin_cap = f"✅ <b>সফল!</b> মিডিয়াটি এখন গ্রুপগুলোতে পাঠানো হচ্ছে...\n\n🔗 <b>Embed Link:</b>\n<code>{embed_link or 'N/A'}</code>"
        thumb_path = None
        
        if media_type == "video":
            v_duration = message.video.duration if message.video else 0
            v_width = message.video.width if message.video else 0
            v_height = message.video.height if message.video else 0
            thumb_path = f"{original_file}_thumb.jpg"
            proc = await asyncio.create_subprocess_exec(*["ffmpeg", "-y", "-i", final_file, "-vframes", "1", thumb_path], stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
            await proc.communicate()
            if not os.path.exists(thumb_path): thumb_path = None

        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
        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
        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
            
        await status_msg.delete()
        groups_res = await db_query(lambda: supabase.table('groups').select('group_id').execute())
        group_ids = [g['group_id'] for g in groups_res.data]
        success_count, fail_count = 0, 0
        
        for gid in set(group_ids):
            try:
                if media_type == "photo": await client.send_photo(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
                elif media_type == "animation": await client.send_animation(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
                else: await client.send_video(gid, tg_file_id, caption=caption_text, parse_mode=enums.ParseMode.HTML, reply_markup=group_markup)
                success_count += 1
                await asyncio.sleep(1.5)
            except Exception: fail_count += 1 
                
        await message.reply(f"📢 <b>ব্রডকাস্ট সম্পন্ন!</b>\n\n✅ সফল: {success_count} টি গ্রুপে\n❌ ব্যর্থ: {fail_count} টি গ্রুপে", parse_mode=enums.ParseMode.HTML)
        
    except Exception as e: await message.reply(f"⚠️ এরর হয়েছে: {str(e)}")
    finally:
        for f in [original_file, watermarked_file, blurred_file, f"{original_file}_thumb.jpg" if original_file else None]:
            if f and os.path.exists(f):
                try: os.remove(f)
                except: pass

@bot.on_message(filters.command(["stats", "users"]) & filters.private & filters.user(ADMIN_IDS))
async def bot_stats(client, message):
    try:
        users = await db_query(lambda: supabase.table('referrals').select('user_id', count='exact').execute())
        videos = await db_query(lambda: supabase.table('videos').select('*', count='exact').execute())
        groups = await db_query(lambda: supabase.table('groups').select('group_id', count='exact').execute())
        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)
    except Exception as e: print(e)

@bot.on_message(filters.command("broadcast") & filters.private & filters.user(ADMIN_IDS))
async def broadcast_command(client, message):
    admin_states[message.chat.id] = {"step": "broadcast"}
    await message.reply("📢 সবার কাছে যা পাঠাতে চান দিন। (বাতিল করতে /cancel)")

async def process_broadcast(client, message):
    text = message.text or message.caption
    if text == '/cancel':
        admin_states.pop(message.chat.id, None)
        return await message.reply("❌ বাতিল করা হয়েছে।")
    
    await message.reply("⏳ ব্রডকাস্ট শুরু হয়েছে...")
    admin_states.pop(message.chat.id, None)
    
    try:
        all_users, start, step = [], 0, 1000
        while True:
            res = await db_query(lambda: supabase.table('referrals').select('user_id').range(start, start + step - 1).execute())
            if not res.data: break
            all_users.extend(res.data)
            start += step

        success, failed = 0, 0
        for u in all_users:
            try:
                await message.copy(chat_id=u['user_id'])
                success += 1
                await asyncio.sleep(0.15) 
            except Exception: failed += 1
                
        await message.reply(f"✅ ব্রডকাস্ট সম্পন্ন!\nসফল: {success}\nব্যর্থ: {failed}")
    except Exception as e: print(e)

@bot.on_message(filters.command(["png", "addvideo"]) & filters.private & filters.user(ADMIN_IDS))
async def add_png(client, message):
    try:
        parts = message.command
        needed_ref, duration = 3, "random"
        if len(parts) == 4 and parts[1].isdigit(): needed_ref, duration, thumbnail_url = int(parts[1]), parts[2], parts[3]
        elif len(parts) == 3 and parts[1].isdigit(): needed_ref, thumbnail_url = int(parts[1]), parts[2]
        elif len(parts) == 2: thumbnail_url = parts[1]
        else: return await message.reply("❌ নিয়ম ভুল।")

        admin_states[message.chat.id] = {"step": 1, "thumbnail_url": f"{thumbnail_url}||{duration}", "needed_ref": needed_ref}
        await message.reply("✅ এখন Video/Embed Link দিন।")
    except Exception as e: print(e)

@bot.on_message(filters.private & filters.user(ADMIN_IDS) & ~filters.command(["start", "stats", "users", "broadcast", "png", "addvideo", "blur"]))
async def catch_admin_steps(client, message):
    state = admin_states.get(message.chat.id, {})
    if state.get("step") == 1:
        if not message.text: return
        video_url = message.text.strip()
        if video_url == "/cancel":
            admin_states.pop(message.chat.id, None)
            return await message.reply("❌ বাতিল করা হয়েছে।")
            
        try:
            await db_query(lambda: supabase.table('videos').insert({"video_url": video_url, "thumbnail_url": state["thumbnail_url"], "needed_ref": state["needed_ref"]}).execute())
            await message.reply("🎉 ভিডিও সফলভাবে অ্যাড হয়েছে!")
        except Exception as e: print(e)
        finally: admin_states.pop(message.chat.id, None)
            
    elif state.get("step") == "broadcast": await process_broadcast(client, message)

def run_flask(): app.run(host="0.0.0.0", port=7860)

async def main():
    await bot.start()
    print("🤖 Pyrogram Bot and Background Worker is running!")
    asyncio.create_task(background_worker())
    await idle()
    await bot.stop()

if __name__ == "__main__":
    threading.Thread(target=run_flask, daemon=True).start()
    bot.run(main())