File size: 5,922 Bytes
119d2aa
602c934
119d2aa
db8a350
119d2aa
d8344cf
 
119d2aa
d8344cf
8c80a61
 
 
119d2aa
db8a350
 
 
fb6c815
db8a350
d8344cf
119d2aa
 
 
 
ae7cadb
 
 
db8a350
ae7cadb
db8a350
 
 
 
ae7cadb
 
db8a350
 
 
 
 
 
 
 
ae7cadb
db8a350
 
 
 
 
 
 
 
 
 
 
 
 
 
d8344cf
ae7cadb
 
 
 
 
d8344cf
 
 
 
 
 
 
 
ae7cadb
d8344cf
db8a350
d8344cf
ae7cadb
0556533
 
ae7cadb
 
d8344cf
 
 
 
 
 
 
 
 
 
 
 
 
 
119d2aa
 
602c934
8c80a61
602c934
 
 
ae7cadb
 
 
 
 
602c934
8c80a61
 
602c934
ae7cadb
 
8c80a61
 
 
ae7cadb
8c80a61
602c934
ae7cadb
 
8c80a61
ae7cadb
8c80a61
 
 
 
 
ae7cadb
db8a350
8c80a61
 
602c934
 
 
 
119d2aa
 
ae7cadb
 
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
import telebot
from telebot.types import InlineKeyboardMarkup, InlineKeyboardButton, WebAppInfo
import os
from flask import Flask, jsonify, make_response, request
from supabase import create_client
import urllib.request
import re

BOT_TOKEN = os.environ.get('BOT_TOKEN') 
SUPABASE_URL = "https://yctirvnryrzygoxbpvoy.supabase.co"
SUPABASE_KEY = "sb_publishable_aBcD-atruskWwoCiLr0lWw_inT8GLoN"
WEB_APP_URL = "https://rony90790.github.io/Forward-bot/index.html" 

HF_SPACE_URL = "https://pmrony-forwardbot.hf.space" 

CHANNEL_USERNAME = "xmlcpg"   
START_MESSAGE_ID = 3               
TOTAL_VIDEOS = 10                  

bot = telebot.TeleBot(BOT_TOKEN)
supabase = create_client(SUPABASE_URL, SUPABASE_KEY)
app = Flask(__name__)

# ইন-মেমরি ক্যাশে (যাতে বারবার টেলিগ্রাম পেজ স্ক্র্যাপ করে স্পেস স্লো না হয়)
thumbnail_cache = {}

# ==========================================
#          WEBHOOK SETUP
# ==========================================

@app.route(f'/{BOT_TOKEN}', methods=['POST'])
def webhook():
    # Content-type একটু ফ্লেক্সিবল করা হলো টেলিগ্রামের জন্য
    if 'application/json' in request.headers.get('content-type', ''):
        json_string = request.get_data().decode('utf-8')
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
        return "OK", 200
    return "Forbidden", 403

@app.route('/set_webhook')
def set_webhook():
    bot.remove_webhook()
    success = bot.set_webhook(url=f"{HF_SPACE_URL}/{BOT_TOKEN}")
    if success:
        return f"<h1>✅ Webhook Successfully Set to Hugging Face!</h1><p>আপনার বট এখন আর টাইম-আউট হবে না।</p>"
    else:
        return "<h1>❌ Failed to set webhook!</h1>"

@app.route('/')
def index():
    return "Bot is Running smoothly via Webhook!"

# ==========================================
#          VIDEO & REFERRAL LOGIC
# ==========================================

def get_telegram_thumbnail(channel, msg_id):
    cache_key = f"{channel}_{msg_id}"
    
    if cache_key in thumbnail_cache:
        return thumbnail_cache[cache_key]
        
    try:
        url = f"https://t.me/{channel}/{msg_id}?embed=1"
        req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
        html = urllib.request.urlopen(req, timeout=3).read().decode('utf-8')
        match = re.search(r'<meta property="og:image" content="([^"]+)">', html)
        if match:
            img_url = match.group(1)
            if "telegram_logo" not in img_url:
                thumbnail_cache[cache_key] = img_url
                return img_url
    except Exception:
        pass
        
    # এখানে via.placeholder.com এর বদলে placehold.co ব্যবহার করা হয়েছে, যা 100% কাজ করবে
    fallback = f"https://placehold.co/300x200/222222/FF9900/png?text=Video+{msg_id}"
    thumbnail_cache[cache_key] = fallback
    return fallback

@app.route('/api/videos')
def api_videos():
    videos_data = []
    for msg_id in range(START_MESSAGE_ID, START_MESSAGE_ID + TOTAL_VIDEOS):
        thumb = get_telegram_thumbnail(CHANNEL_USERNAME, msg_id)
        videos_data.append({
            "video_url": f"https://t.me/{CHANNEL_USERNAME}/{msg_id}",
            "thumbnail_url": thumb
        })
    response = make_response(jsonify(videos_data))
    response.headers['Access-Control-Allow-Origin'] = '*' 
    return response

@bot.message_handler(commands=['start'])
def start(message):
    user_id = message.from_user.id
    text = message.text.split() 

    referrer_id = None
    if len(text) > 1:
        try:
            # Type error এড়াতে int এ কনভার্ট
            referrer_id = int(text[1])
        except ValueError:
            referrer_id = None 

    try:
        user_check = supabase.table('referrals').select('*').eq('user_id', user_id).execute()

        # যদি ডাটাবেজে ইউজার না থাকে
        if not user_check.data:
            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:
                referrer_data = supabase.table('referrals').select('referral_count').eq('user_id', referrer_id).execute()
                if referrer_data.data:
                    new_count = referrer_data.data[0]['referral_count'] + 1
                    supabase.table('referrals').update({'referral_count': new_count}).eq('user_id', referrer_id).execute()
                    
                    try:
                        bot.send_message(referrer_id, "🎉 একজন আপনার লিংকে জয়েন করেছে! আপনার রেফারেল কাউন্ট বাড়লো।")
                    except Exception:
                        pass
    except Exception as e:
        print("Database Error:", e)

    markup = InlineKeyboardMarkup()
    markup.add(InlineKeyboardButton("Play video 🔞", web_app=WebAppInfo(url=WEB_APP_URL)))
    bot.reply_to(message, "ভাইরাল ভিডিও দেখতে নিচের বাটনে ক্লিক করো 👇", reply_markup=markup)

if __name__ == "__main__":
    # Threaded=True দিলে একই সাথে একাধিক ইউজার ওয়েবঅ্যাপ এবং বট ব্যবহার করতে পারবে
    app.run(host="0.0.0.0", port=7860, threaded=True)