File size: 6,411 Bytes
5415bd2
07d9230
 
 
f613581
5415bd2
974b0f3
07d9230
5415bd2
f613581
 
 
 
 
5415bd2
 
 
 
f613581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9230
f613581
07d9230
f613581
07d9230
 
f613581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9230
 
 
 
 
 
 
 
 
f613581
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07d9230
 
 
 
5415bd2
 
07d9230
 
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
from flask import Flask
import requests
import time
import threading
import json

TOKEN = "8674461297:AAHRtDHdk_NzXWPw3HIOvWJZnRfIT3e5Y7w"
API = f"https://api.telegram.org/bot{TOKEN}"

# Supabase
SUPABASE_URL = "https://wkrlyvzmodcwlaoneuay.supabase.co"
SUPABASE_KEY = "sb_publishable_sMlsr09C_c_h7rMtA1IBzg_XzP8ekwz"
HEADERS = {"apikey": SUPABASE_KEY, "Authorization": f"Bearer {SUPABASE_KEY}", "Content-Type": "application/json"}

flask_app = Flask(__name__)

@flask_app.route("/")
def home():
    return "πŸ€– ExamFormFiller Bot 24/7"

# ========== HELPERS ==========

def send_message(chat_id, text, buttons=None):
    try:
        data = {"chat_id": chat_id, "text": text, "parse_mode": "HTML"}
        if buttons:
            data["reply_markup"] = json.dumps({"inline_keyboard": buttons})
        requests.post(f"{API}/sendMessage", json=data, timeout=10)
    except Exception as e:
        print(f"Send error: {e}")

def get_user(chat_id):
    try:
        r = requests.get(f"{SUPABASE_URL}/rest/v1/users?telegram_id=eq.{chat_id}", headers=HEADERS)
        users = r.json()
        return users[0] if users else None
    except:
        return None

def save_user(chat_id, data):
    try:
        requests.post(f"{SUPABASE_URL}/rest/v1/users", headers={**HEADERS, "Prefer": "return=minimal"}, json={"telegram_id": chat_id, **data})
    except: pass

def update_user(chat_id, data):
    try:
        requests.patch(f"{SUPABASE_URL}/rest/v1/users?telegram_id=eq.{chat_id}", headers={**HEADERS, "Prefer": "return=minimal"}, json=data)
    except: pass

# ========== MAIN MENU ==========

def show_menu(chat_id, name):
    buttons = [
        [{"text": "πŸ“‹ Mera Profile", "callback_data": "profile"}],
        [{"text": "πŸ”” Active Exams", "callback_data": "exams"}],
        [{"text": "πŸ“ Form Guide", "callback_data": "guide"}],
        [{"text": "πŸ’° Premium", "callback_data": "premium"}],
    ]
    send_message(chat_id, f"🎯 <b>Main Menu</b>\n\nNamaste {name}! Kya karna hai?", buttons)

# ========== HANDLERS ==========

def handle_start(chat_id):
    user = get_user(chat_id)
    if user and user.get("onboarding_done"):
        show_menu(chat_id, user.get("full_name", "User"))
        return
    
    if not user:
        save_user(chat_id, {"onboarding_step": "name", "created_at": "now()"})
    
    send_message(chat_id, "πŸ™ <b>Namaste! ExamFormFiller mein swagat hai!</b>\n\nMain aapka exam assistant hoon.\nβœ… Exam notifications\nβœ… Form filling guide\nβœ… Common mistakes se bachao\n\n<b>Pehle aapka naam kya hai?</b>\n(Jaise 10th certificate mein likha hai)")

def handle_text(chat_id, text):
    user = get_user(chat_id)
    if not user: return
    
    step = user.get("onboarding_step", "")
    
    if step == "name":
        update_user(chat_id, {"full_name": text, "onboarding_step": "category"})
        buttons = [
            [{"text": "General", "callback_data": "cat_general"}, {"text": "OBC", "callback_data": "cat_obc"}],
            [{"text": "SC", "callback_data": "cat_sc"}, {"text": "ST", "callback_data": "cat_st"}],
            [{"text": "EWS", "callback_data": "cat_ews"}],
        ]
        send_message(chat_id, "βœ… Naam save ho gaya!\n\n<b>Category kya hai?</b>", buttons)
    
    elif step == "education":
        update_user(chat_id, {"highest_qual": text, "onboarding_step": "state"})
        send_message(chat_id, "βœ… Education save!\n\n<b>Kis state se ho?</b>\n(Jaise: Uttar Pradesh, Bihar, Maharashtra)")

    elif step == "state":
        update_user(chat_id, {"state": text, "onboarding_step": "done", "onboarding_done": True})
        send_message(chat_id, "πŸŽ‰ <b>Profile Complete!</b>")
        show_menu(chat_id, user.get("full_name", "User"))

def handle_callback(chat_id, data):
    user = get_user(chat_id)
    
    if data.startswith("cat_"):
        cat = data.replace("cat_", "").upper()
        update_user(chat_id, {"category": cat, "onboarding_step": "education"})
        send_message(chat_id, "βœ… Category save!\n\n<b>Highest education?</b>\n(10th/12th/Graduate/Post Graduate)")
    
    elif data == "profile":
        u = user or {}
        send_message(chat_id, f"πŸ“‹ <b>Profile</b>\n\nπŸ‘€ {u.get('full_name','?')}\nπŸ“Š {u.get('category','?')}\nπŸŽ“ {u.get('highest_qual','?')}\nπŸ“ {u.get('state','?')}")
    
    elif data == "exams":
        send_message(chat_id, "πŸ”” <b>Active Exams</b>\n\nNaye exams jald add honge!\nAbhi database setup ho raha hai.")
    
    elif data == "guide":
        send_message(chat_id, "πŸ“ <b>Form Guide</b>\n\nPehle kuch exams add karte hain, phir guide milega!")
    
    elif data == "premium":
        send_message(chat_id, "πŸ’° <b>Premium</b>\n\nβ‚Ή99/month β€” jald launch ho raha hai!\nβœ… Unlimited guides\nβœ… Deadline alerts\nβœ… Priority support")

# ========== BOT LOOP ==========

def run_bot():
    offset = 0
    print("πŸ€– Bot started!")
    while True:
        try:
            r = requests.get(f"{API}/getUpdates?offset={offset}&timeout=30", timeout=35)
            updates = r.json().get("result", [])
            for update in updates:
                offset = update["update_id"] + 1
                
                # Callback query (button press)
                if "callback_query" in update:
                    cb = update["callback_query"]
                    chat_id = cb["message"]["chat"]["id"]
                    data = cb["data"]
                    requests.post(f"{API}/answerCallbackQuery", json={"callback_query_id": cb["id"]})
                    handle_callback(chat_id, data)
                
                # Text message
                elif "message" in update:
                    msg = update["message"]
                    chat_id = msg["chat"]["id"]
                    text = msg.get("text", "")
                    
                    if text == "/start":
                        handle_start(chat_id)
                    elif text == "/menu":
                        u = get_user(chat_id)
                        if u:
                            show_menu(chat_id, u.get("full_name", "User"))
                    else:
                        handle_text(chat_id, text)
            
            time.sleep(1)
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(5)

if __name__ == "__main__":
    threading.Thread(target=run_bot, daemon=True).start()
    flask_app.run(host="0.0.0.0", port=7860)