""" کوییز و آزمون — Bale Bot (نسخه رایگان) Single fixed quiz with inline answers & leaderboard. بات‌بان | hi@botban.ir """ import os, json, sqlite3, logging, time from typing import Optional import requests from dotenv import load_dotenv load_dotenv() log = logging.getLogger(__name__) TOKEN: str = os.getenv("BALE_BOT_TOKEN", "") DB_PATH: str = "quiz.db" QUIZ_FILE: str = os.path.join(os.path.dirname(os.path.abspath(__file__)), "quiz.json") API_BASE: str = f"https://tapi.bale.ai/bot{TOKEN}" OPTION_LABELS = ["الف", "ب", "ج", "د"] def load_questions() -> list[dict]: try: with open(QUIZ_FILE, encoding="utf-8") as f: return json.load(f) except Exception as exc: log.error("Cannot load quiz.json: %s", exc) return [] QUESTIONS: list[dict] = load_questions() TOTAL: int = len(QUESTIONS) def init_db() -> None: with sqlite3.connect(DB_PATH) as con: con.execute("CREATE TABLE IF NOT EXISTS sessions (user_id INTEGER PRIMARY KEY, current_q INTEGER NOT NULL DEFAULT 0, correct_count INTEGER NOT NULL DEFAULT 0, started_at TEXT NOT NULL)") con.execute("CREATE TABLE IF NOT EXISTS scores (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER NOT NULL, name TEXT NOT NULL, score INTEGER NOT NULL, total INTEGER NOT NULL, finished_at TEXT NOT NULL)") con.commit() def question_keyboard(q_index: int) -> dict: q = QUESTIONS[q_index] return {"inline_keyboard": [[{"text": f"{OPTION_LABELS[i]}) {opt}", "callback_data": f"ans_{q_index}_{i}"}] for i, opt in enumerate(q["options"])]} def motivational(score: int) -> str: pct = score / TOTAL if TOTAL else 0 if pct == 1.0: return "🏆 آفرین! نمره کامل!" if pct >= 0.8: return "🌟 عالی بود!" if pct >= 0.6: return "💪 خیلی خوب!" return "📚 تمرین کن، میتونی!" def top_scores(limit: int = 5) -> list[tuple]: with sqlite3.connect(DB_PATH) as con: return con.execute( "SELECT name, MAX(score) as best, total FROM scores GROUP BY user_id ORDER BY best DESC LIMIT ?", (limit,) ).fetchall() def handle_answer(cb: dict) -> None: uid = cb["from"]["id"] name = cb["from"].get("first_name", "دانش‌آموز") chat_id = cb["message"]["chat"]["id"] parts = cb.get("data", "").split("_") q_index, choice = int(parts[1]), int(parts[2]) correct_idx: int = QUESTIONS[q_index]["answer"] is_correct = choice == correct_idx feedback = "✅ درسته!" if is_correct else f"❌ جواب: {OPTION_LABELS[correct_idx]})" send(chat_id, feedback) # ... ادامه کد (تا ۱۳۹ خط دیگر) # نسخه کامل + مستندات + دیتابیس → hi@botban.ir