Telegram-Bot / bot.py
H3y-sam's picture
Update bot.py
0e20a7e verified
Raw History Blame Contribute Delete
24.5 kB
"""
JEE & NEET Daily Bot β€” Unified Port Mode (Polling + Dashboard)
Runs python-telegram-bot polling in a background thread.
HTTP server (Dashboard + API) runs on port 7860 (main thread).
"""
import os
import sys
import json
import logging
import asyncio
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
from telegram import Update
from telegram.ext import (
ApplicationBuilder, CommandHandler,
CallbackQueryHandler, MessageHandler, filters,
ChatMemberHandler
)
from telegram.request import HTTPXRequest
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from config import BOT_TOKEN, ADMIN_USER_IDS
os.makedirs("data", exist_ok=True)
logging.basicConfig(
format="%(asctime)s %(levelname)s %(name)s β€” %(message)s",
level=logging.INFO,
handlers=[logging.FileHandler("bot.log"), logging.StreamHandler()]
)
logger = logging.getLogger(__name__)
# ── Startup Lock (HF Spaces conflict prevention) ────────────────────────────
import time
STARTUP_LOCK_FILE = "data/.bot_startup_lock"
# ── All original handler imports (restores buttons, commands, callbacks) ──────
from handlers.commands import (
start_command, status_command, help_command,
channels_command, stats_command, preview_command,
coverage_command, add_channel_command, del_channel_command,
set_time_command, mcq_session_command, broadcast_command,
broadcast_channels_command, leaderboard_command,
force_digest_command, healthcheck_command
)
from handlers.callbacks import button_callback
from handlers.menu_router import menu_handler
from handlers.doubt_handler import private_doubt_handler, group_doubt_handler
from handlers.leaderboard_handler import poll_answer_handler
from handlers.poll_handler import poll_handler
from content.database import init_db
from telegram.ext import PollAnswerHandler, PollHandler
# ── Global state ───────────────────────────────────────────────────────────────
_bot_app = None
_bot_loop = None
def _trigger_reload():
"""Tell the scheduler to reload jobs after a config change."""
if _bot_loop and _bot_app:
from scheduler.job_scheduler import reload_jobs
asyncio.run_coroutine_threadsafe(reload_jobs(_bot_app), _bot_loop)
def _trigger_manual_post(ch_key, ctype):
if _bot_loop and _bot_app:
from scheduler.job_scheduler import trigger_manual_post
asyncio.run_coroutine_threadsafe(
trigger_manual_post(_bot_app, ch_key, ctype), _bot_loop
)
return True
return False
# ── Dashboard HTTP Server ──────────────────────────────────────────────────────
class BotHandler(BaseHTTPRequestHandler):
def _send(self, code, ctype, body):
if isinstance(body, str): body = body.encode()
elif not isinstance(body, bytes): body = json.dumps(body, default=str).encode()
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(body)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
self.wfile.write(body)
def _json(self, code, data): self._send(code, "application/json", data)
# ── GET ────────────────────────────────────────────────────────────────────
def do_GET(self):
path = self.path.split("?")[0].rstrip("/") or "/"
# Dashboard UI
if path in ("", "/", "/dashboard"):
try:
with open("web_app/dashboard.html", encoding="utf-8") as f:
self._send(200, "text/html", f.read())
except Exception:
self._send(200, "text/html", "<h2>Bot Running 🟒</h2>")
return
if path == "/health":
self._send(200, "text/plain", "Bot Running 🟒")
return
if path == "/api/health":
import time
from scheduler.job_scheduler import get_all_jobs
from config import GEMINI_MODEL
# Basic subsystem check
scheduler_ok = True
try: get_all_jobs()
except: scheduler_ok = False
self._json(200, {
"ok": True,
"ts": time.strftime("%H:%M:%S"),
"checks": {
"scheduler": {"ok": scheduler_ok, "msg": f"{len(get_all_jobs())} jobs active" if scheduler_ok else "Scheduler error"},
"gemini": {"ok": True, "msg": f"Model: {GEMINI_MODEL}"},
"telegram": {"ok": True, "msg": "API Online"}
}
})
return
if path == "/api/status":
try:
from content.config_manager import config_manager
from content.user_registry import get_user_count
from scheduler.job_scheduler import get_all_jobs
self._json(200, {
"ok": True,
"channels": config_manager.channels,
"schedule": config_manager.schedule,
"settings": config_manager.settings,
"user_count": get_user_count(),
"jobs": len([j for j in get_all_jobs() if j.next_run_time])
})
except Exception as e:
logger.error(f"Status API Error: {e}")
self._json(500, {"ok": False, "error": str(e)})
return
if path == "/api/syllabus":
from content.syllabus_manager import syllabus_manager
self._json(200, {"ok": True, "syllabus": syllabus_manager.syllabus})
return
if path == "/api/prompts":
from content.template_manager import template_manager
self._json(200, {"ok": True, "data": template_manager.data})
return
if path == "/api/logs":
try:
with open("bot.log", errors="ignore") as f:
lines = f.readlines()[-40:]
self._json(200, {"ok": True, "lines": [l.strip() for l in lines]})
except Exception:
self._json(200, {"ok": True, "lines": []})
return
self.send_error(404)
# ── POST ───────────────────────────────────────────────────────────────────
def do_POST(self):
path = self.path.split("?")[0].rstrip("/")
length = int(self.headers.get("content-length", 0))
raw = self.rfile.read(length)
body = json.loads(raw) if raw else {}
parts = [p for p in path.split("/") if p]
from content.config_manager import config_manager
try:
if path == "/api/update-channel":
key = body.pop("key", None)
ok = config_manager.update_channel(key, body)
_trigger_reload()
self._json(200 if ok else 404, {"ok": bool(ok)})
return
if path == "/api/add-channel":
cid = body.get("id")
if isinstance(cid, str) and cid.lstrip('-').isdigit():
cid = int(cid)
ok = config_manager.add_channel(
body.get("key"), cid, body.get("label"),
body.get("exam_focus", []), body.get("subjects", []),
body.get("mcq_only", False)
)
if ok: _trigger_reload()
self._json(200 if ok else 400, {"ok": bool(ok)})
return
if len(parts) == 3 and parts[:2] == ["api", "toggle-channel"]:
active = config_manager.toggle_channel(parts[2])
_trigger_reload()
self._json(200, {"ok": True, "active": active})
return
if len(parts) == 4 and parts[:2] == ["api", "toggle"]:
enabled = config_manager.toggle_content_type(parts[2], parts[3])
_trigger_reload()
self._json(200, {"ok": True, "enabled": enabled})
return
if path == "/api/set-schedule":
ok = config_manager.set_schedule(
body.get("content_type"), body.get("hour"), body.get("minute")
)
if ok: _trigger_reload()
self._json(200 if ok else 400, {"ok": bool(ok)})
return
if path == "/api/settings":
config_manager.update_settings(body.get("settings", {}))
self._json(200, {"ok": True})
return
if path in ("/api/trigger-now", "/api/force-post"):
ch = body.get("key") or body.get("channel_key")
ct = body.get("type") or body.get("content_type")
if _trigger_manual_post(ch, ct):
self._json(200, {"ok": True})
else:
self._json(503, {"ok": False, "error": "Engine not ready"})
return
if path == "/api/force-mcq":
ch = body.get("channel_key")
if _bot_loop and _bot_app:
from scheduler.job_scheduler import post_mcq_session
asyncio.run_coroutine_threadsafe(
post_mcq_session(_bot_app, ch), _bot_loop
)
self._json(200, {"ok": True})
return
if path == "/api/broadcast":
from content.user_registry import get_all_user_ids
msg = body.get("message", "")
uids = get_all_user_ids()
ok_count = 0
for uid in uids:
if _bot_loop and _bot_app:
asyncio.run_coroutine_threadsafe(
_bot_app.bot.send_message(uid, msg, parse_mode="MarkdownV2"),
_bot_loop
)
ok_count += 1
self._json(200, {"ok": True, "sent": ok_count})
return
if path == "/api/broadcast-channels":
msg = body.get("message", "")
channels = config_manager.channels
ok_count = 0
for ch_key, ch_cfg in channels.items():
if ch_cfg.get("active") and _bot_loop and _bot_app:
asyncio.run_coroutine_threadsafe(
_bot_app.bot.send_message(ch_cfg["id"], msg, parse_mode="HTML"),
_bot_loop
)
ok_count += 1
self._json(200, {"ok": True, "sent": ok_count})
return
if path == "/api/verify-channel":
ch_id = body.get("channel_id")
if isinstance(ch_id, str) and ch_id.lstrip('-').isdigit():
ch_id = int(ch_id)
if _bot_loop and _bot_app:
async def _verify(ch_id):
chat = await _bot_app.bot.get_chat(ch_id)
bot_me = await _bot_app.bot.get_me()
try:
member = await _bot_app.bot.get_chat_member(chat.id, bot_me.id)
is_admin = member.status in ("administrator", "creator")
except Exception:
is_admin = False
return chat, is_admin
future = asyncio.run_coroutine_threadsafe(_verify(ch_id), _bot_loop)
try:
chat, is_admin = future.result(timeout=10)
self._json(200, {
"ok": True,
"title": chat.title,
"username": chat.username or "", # fixes @undefined
"type": chat.type,
"id": chat.id,
"is_admin": is_admin # actual admin check
})
except Exception as e:
self._json(400, {"ok": False, "error": str(e)})
else:
self._json(503, {"ok": False, "error": "Engine not ready"})
return
except Exception as e:
logger.error(f"API {path} error: {e}", exc_info=True)
self._json(500, {"ok": False, "error": str(e)})
return
self.send_error(404)
def do_DELETE(self):
path = self.path.split("?")[0].rstrip("/")
parts = [p for p in path.split("/") if p]
from content.config_manager import config_manager
if len(parts) == 3 and parts[:2] == ["api", "channel"]:
ok = config_manager.delete_channel(parts[2])
_trigger_reload()
self._json(200 if ok else 404, {"ok": bool(ok)})
return
self.send_error(404)
def do_OPTIONS(self):
self.send_response(204)
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
self.send_header("Access-Control-Allow-Headers", "Content-Type")
self.end_headers()
def log_message(self, fmt, *args): return # silence access logs
# ── Bot Engine (polling, background thread) ───────────────────────────────────
def run_bot_engine():
global _bot_loop, _bot_app
_bot_loop = asyncio.new_event_loop()
asyncio.set_event_loop(_bot_loop)
_bot_loop.run_until_complete(_start_polling())
_bot_loop.run_forever()
async def chat_member_update(update: Update, context):
"""Notify admins and log when bot is added to a channel (public or private)."""
result = update.my_chat_member
if not result:
return
# Check if we were promoted to admin or added to channel/group
chat = result.chat
new_status = result.new_chat_member.status
if new_status in ("administrator", "creator", "member"):
# We were added/promoted!
safe_title = chat.title.replace('<', '&lt;').replace('>', '&gt;')
msg = (f"πŸ€– <b>Bot Added to Chat/Channel!</b>\n"
f"Title: {safe_title}\n"
f"ID: <code>{chat.id}</code>\n"
f"Type: {chat.type}\n"
f"Added by: @{result.from_user.username or result.from_user.first_name}\n\n"
f"You can use this ID to add this private channel: \n<code>/add_channel my_key {chat.id} {safe_title}</code>\n"
f"Or via the Web Dashboard.")
for admin_id in ADMIN_USER_IDS:
try:
await context.bot.send_message(chat_id=admin_id, text=msg, parse_mode="HTML")
except Exception as e:
logger.error(f"Could not notify admin {admin_id} of new chat: {e}")
async def _start_polling():
global _bot_app
import socket, ssl
# ── HF Spaces Conflict Prevention: Wait if another instance just started ───
# (When you re-deploy, old instance shuts down β†’ new one starts)
# Check if lock file exists and is fresh (< 5 seconds old)
if os.path.exists(STARTUP_LOCK_FILE):
lock_age = time.time() - os.path.getmtime(STARTUP_LOCK_FILE)
if lock_age < 5:
logger.warning(f"⏳ Another instance started recently ({lock_age:.1f}s ago). Waiting 10s before polling...")
await asyncio.sleep(10)
# Create startup lock file for next instance
os.makedirs(os.path.dirname(STARTUP_LOCK_FILE) or ".", exist_ok=True)
with open(STARTUP_LOCK_FILE, "w") as f:
f.write(str(time.time()))
# ── Read Cloudflare Worker proxy URL (set in HF Secrets as TG_PROXY_URL) ───
proxy_url = os.environ.get("TG_PROXY_URL", "").rstrip("/")
if proxy_url:
logger.info(f"πŸ›‘οΈ Using Cloudflare proxy: {proxy_url}")
# PTB appends: base_url + token + "/" + method
# So base_url must be exactly: proxy_url + "/bot"
# That gives: proxy_url/bot{token}/method ← correct
tg_base_url = f"{proxy_url}/bot"
else:
logger.info("🌐 Direct connection to api.telegram.org")
tg_base_url = None
# ── Pre-flight: Test connectivity (proxy if set, else direct) ─────────────
logger.info("πŸ” Pre-flight connectivity check...")
check_host = proxy_url.replace("https://", "").replace("http://", "").split("/")[0] if proxy_url else "api.telegram.org"
check_port = 443
proxy_healthy = False
try:
sock = socket.create_connection((check_host, check_port), timeout=20)
ctx = ssl.create_default_context()
with ctx.wrap_socket(sock, server_hostname=check_host) as ssock:
logger.info(f"βœ… TLS OK to {check_host} β€” cipher: {ssock.cipher()[0]}")
sock.close()
proxy_healthy = True
except Exception as e:
logger.warning(f"⚠️ TLS check failed for {check_host}: {e}")
if proxy_url:
logger.warning("πŸ”„ Proxy unreachable β€” falling back to direct api.telegram.org connection.")
tg_base_url = None # Reset so we connect directly
# ── Build HTTPXRequest with proxy ─────────────────────────────────────────
request_kwargs = dict(
connect_timeout=60.0,
read_timeout=60.0,
write_timeout=60.0,
pool_timeout=60.0,
connection_pool_size=8,
http_version="1.1",
)
request = HTTPXRequest(**request_kwargs)
# ── Build Application (point base_url at CF Worker if proxy is healthy) ──────────
builder = ApplicationBuilder().token(BOT_TOKEN).request(request)
if proxy_url and tg_base_url and proxy_healthy:
builder = builder.base_url(tg_base_url)
logger.info(f"πŸ›‘οΈ Connecting via Cloudflare proxy: {tg_base_url}")
else:
logger.info("🌐 Connecting directly to api.telegram.org")
_bot_app = builder.build()
# ── Register all handlers (restores buttons + all commands) ───────────────
_bot_app.add_handler(CommandHandler("start", start_command))
_bot_app.add_handler(ChatMemberHandler(chat_member_update, ChatMemberHandler.MY_CHAT_MEMBER))
_bot_app.add_handler(CommandHandler("status", status_command))
_bot_app.add_handler(CommandHandler("help", help_command))
_bot_app.add_handler(CommandHandler("channels", channels_command))
_bot_app.add_handler(CommandHandler("stats", stats_command))
_bot_app.add_handler(CommandHandler("preview", preview_command))
_bot_app.add_handler(CommandHandler("coverage", coverage_command))
_bot_app.add_handler(CommandHandler("add_channel", add_channel_command))
_bot_app.add_handler(CommandHandler("del_channel", del_channel_command))
_bot_app.add_handler(CommandHandler("set_time", set_time_command))
_bot_app.add_handler(CommandHandler("broadcast", broadcast_command))
_bot_app.add_handler(CommandHandler("broadcast_channels", broadcast_channels_command))
_bot_app.add_handler(CommandHandler("leaderboard", leaderboard_command))
_bot_app.add_handler(CommandHandler("force_digest", force_digest_command))
_bot_app.add_handler(CommandHandler("mcq_session", mcq_session_command))
_bot_app.add_handler(CommandHandler("healthcheck", healthcheck_command))
# Leaderboard handler (tracks correct poll answers)
_bot_app.add_handler(PollAnswerHandler(poll_answer_handler))
# Live Difficulty handler (tracks poll vote counts)
_bot_app.add_handler(PollHandler(poll_handler))
# Menu/Callback handlers
_bot_app.add_handler(CallbackQueryHandler(button_callback))
_bot_app.add_handler(private_doubt_handler)
_bot_app.add_handler(group_doubt_handler)
# ── Give previous instance 3 seconds to disconnect (conflict prevention) ───
logger.info("⏳ Initializing (waiting 3s for previous instance to disconnect)...")
await asyncio.sleep(3)
# ── Initialize with patient retries (up to 10 attempts) ───────────────────
logger.info("πŸ“‘ Connecting to Telegram (with retries)...")
initialized = False
for attempt in range(1, 11):
try:
await _bot_app.initialize()
initialized = True
logger.info(f"βœ… Telegram connected on attempt {attempt}.")
break
except Exception as e:
if "Conflict" in str(e) or "409" in str(e):
logger.error("πŸ›‘ [CONFLICT] Another bot instance is already running with this token! "
"Please stop any local bot scripts or close other active tabs/servers.")
wait = min(attempt * 20, 120) # 20s, 40s, 60s … max 120s
logger.error(f"❌ Attempt {attempt} failed ({type(e).__name__}: {e}). Retrying in {wait}s...")
await asyncio.sleep(wait)
if not initialized:
logger.error("❌ All 10 connection attempts failed. "
"IMPORTANT: Visit https://api.telegram.org/bot<TOKEN>/deleteWebhook "
"from your local browser, then restart the Space.")
# Keep bot_data alive so dashboard still works
return
# ── Delete any stale webhook, then start polling ───────────────────────────
try:
await _bot_app.bot.delete_webhook(drop_pending_updates=True)
logger.info("🧹 Webhook cleared β€” polling mode active.")
except Exception as e:
logger.warning(f"Could not clear webhook: {e}")
await _bot_app.start()
# ── Start scheduler ────────────────────────────────────────────────────────
from scheduler.job_scheduler import setup_scheduler
setup_scheduler(_bot_app)
# ── Begin polling ──────────────────────────────────────────────────────────
await _bot_app.updater.start_polling(
drop_pending_updates=True,
allowed_updates=Update.ALL_TYPES,
)
logger.info("πŸš€ Bot is polling for updates. All handlers active.")
# ── Main ───────────────────────────────────────────────────────────────────────
def main():
logger.info("Starting JEE & NEET Daily Bot...")
# Start bot polling engine in background
threading.Thread(target=run_bot_engine, daemon=True, name="BotEngine").start()
# Serve dashboard on port 7860 (main thread β€” keeps HF Space alive)
port = int(os.environ.get("PORT", 7860))
server = HTTPServer(("0.0.0.0", port), BotHandler)
logger.info(f"🟒 Dashboard server on port {port}")
server.serve_forever()
if __name__ == "__main__":
init_db() # Setup tables
main()