Exam-bot / app.py
Snapspark's picture
Update app.py
f613581 verified
Raw
History Blame Contribute Delete
6.41 kB
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)