""" 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", "
{chat.id}\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/add_channel my_key {chat.id} {safe_title}\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