Test / bot.py
Hfzune's picture
Rename app.py to bot.py
fc2227d verified
Raw History Blame Contribute Delete
66.2 kB
"""bot.py — Handlers, progressive search, admin commands, callbacks. State lives in bot_state.py. This file re-exports everything so `import bot; bot.cache_gc` etc. continue to work. """ import asyncio import csv import io import json import logging import threading import time import traceback import uuid from datetime import datetime, timezone from config import ( BACKUP_ENABLED_DEFAULT, BACKUP_CHANNEL_ID, VERSION, PAGE_SIZE, FETCH_LIMIT, QUERY_TIMEOUT, USER_COOLDOWN, BATCH_MAX, BATCH_TIMEOUT, ADMIN_TOKEN, OWNER_IDS, BROADCAST_DELAY, BROADCAST_MAX_LEN, DAILY_QUOTA, ) from engine import ( run_search_safe, search_fast_apis_filtered, asur_lookup_filtered, search_apis_filtered, dedup_records, render_page, _plain_record, normalize_phone, check_api_health, warm_phone_cache, con_ready, warmed, esc, ) from bot_state import ( ACTIVITY_LOG, ACTIVE_USERS, UNIQUE_USERS, BANNED_USERS, BAN_REASONS, MAINTENANCE_MODE, SEARCH_CACHE, SEARCH_CACHE_LOCK, USER_HISTORY, USER_LAST, STATS, PHONE_COUNTS, _activity_lock, _state_lock, tg, send, edit, send_document, _short_user, _fmt_ts, _today_utc, is_duplicate_update, check_force_join, _is_unlimited, check_quota, incr_quota, check_flood, _log_activity, _get_live_users, _get_stats, _add_to_history, _avg_latency_today, _is_banned, _ban_user, _unban_user, _get_maintenance, _set_maintenance, _is_admin_session, _grant_admin, _revoke_admin, _admin_state_get, _admin_state_set, _admin_state_clear, cache_gc, ) log = logging.getLogger("bot") # Runtime toggle (local to bot.py — mutated by /backup and admin panel) BACKUP_ENABLED = BACKUP_ENABLED_DEFAULT # ══════════════════════════════════════════════════════════════════ # ADMIN RENDERS # ══════════════════════════════════════════════════════════════════ def admin_menu_kb(): m_on, _ = _get_maintenance() maint_label = "🔴 Maintenance: ON" if m_on else "🟢 Maintenance: OFF" backup_label = "📥 Backup: ON" if BACKUP_ENABLED else "📥 Backup: OFF" return {"inline_keyboard": [ [{"text": "🔴 Live Users", "callback_data": "adm:live"}, {"text": "📈 Stats", "callback_data": "adm:stats"}], [{"text": "📜 Activity Log", "callback_data": "adm:log:0"}, {"text": "👥 All Users", "callback_data": "adm:users:0"}], [{"text": "🔍 Top Searches", "callback_data": "adm:top"}, {"text": "🚫 Banned", "callback_data": "adm:banned"}], [{"text": "🚫 Ban User", "callback_data": "adm:ban"}, {"text": "✅ Unban User", "callback_data": "adm:unban"}], [{"text": "📢 Broadcast", "callback_data": "adm:broadcast"}, {"text": "📥 Export Log", "callback_data": "adm:export"}], [{"text": "🔎 Log by Phone", "callback_data": "adm:logphone"}, {"text": maint_label, "callback_data": "adm:maint"}], [{"text": "🔧 API Status", "callback_data": "adm:apistatus"}, {"text": backup_label, "callback_data": "adm:backuptoggle"}], [{"text": "🔄 Refresh", "callback_data": "adm:menu"}], ]} def render_admin_menu(): m_on, reason = _get_maintenance() m_line = f"🔴 Maintenance ON — {esc(reason)}" if m_on else "🟢 Operational" b_line = "📥 Backup forwarding: ON" if BACKUP_ENABLED else "📥 Backup forwarding: OFF" return (f"🛡️ <b>Admin Panel</b> — v{VERSION}\n━━━━━━━━━━━━━━━━━━\n" f"{m_line}\n{b_line}\n" f"👥 Users: {len(UNIQUE_USERS)} · 🚫 Banned: {len(BANNED_USERS)}\n\n" "Tap a button or use commands:\n" "• /live /stats /log /users /top\n" "• /ban &lt;id&gt; [reason] · /unban &lt;id&gt;\n" "• /broadcast &lt;msg&gt;\n" "• /export · /logphone &lt;num&gt;\n" "• /maintenance on|off [reason]\n" "• /apistatus · /backup on|off\n" "• /reload · /cancel · /logout") def render_live(): live = _get_live_users() if not live: return (f"🔴 <b>Live Users</b>\n\n" f"No one active in the last {LIVE_WINDOW // 60} minutes.") lines = [f"🔴 <b>Live Users</b> (last {LIVE_WINDOW // 60} min): " f"<b>{len(live)}</b>\n"] for uid, ts in live[:25]: lines.append(f"• {_short_user(uid)} — {_fmt_ts(ts)}") return "\n".join(lines) def render_stats(): s = _get_stats() uptime = (time.time() - STATS["started"]) / 60 return ("📈 <b>Bot Statistics</b>\n━━━━━━━━━━━━━━━━━━\n" f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n" f"👥 Unique users: <code>{s['unique_users']}</code>\n" f"🔴 Live now: <code>{s['live_users']}</code>\n" f"📅 Active today: <code>{s['today_users']}</code>\n" f"🔍 Searches today: <code>{s['today_searches']}</code>\n" f"🔍 Total searches: <code>{s['total_searches']}</code>\n" f"📊 Peak concurrent: <code>{s['peak_concurrent']}</code>\n" f"🚫 Banned users: <code>{s['banned_count']}</code>\n" f"💾 Cached queries: <code>{s['cached_searches']}</code>\n" f"📥 Backup sent: <code>{s['backup_sent']}</code>\n" f"📜 Log entries: <code>{s['total_log_entries']}</code>\n" f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n" f"❌ Errors: <code>{STATS['errors']}</code>") def render_log(entries, page=0, page_size=8): total = len(entries) total_pages = max(1, (total + page_size - 1) // page_size) page = max(0, min(page, total_pages - 1)) chunk = entries[page * page_size:(page + 1) * page_size] if not chunk: return "📜 <b>Activity Log</b>\n\nNo activity yet.", None lines = [f"📜 <b>Activity Log</b> — page {page + 1}/{total_pages} " f"({total} entries)\n"] for e in chunk: uname = e.get("username") first = e.get("first_name") name_str = f"@{uname}" if uname else (first or "(no name)") reply = e.get("summary") or e.get("reply_type") or "-" elapsed = e.get("elapsed_ms", 0) source = e.get("source") or "" block = (f"<code>{_fmt_ts(e['ts'])}</code> · " f"<b>{esc(name_str)}</b> · <code>{e['user_id']}</code>\n") block += f" 📥 <code>{esc(e['input'] or '-')}</code>\n" reply_line = f" 📤 {esc(reply)}" if elapsed: reply_line += f" · {elapsed}ms" if source: reply_line += f" · {source}" lines.append(block + reply_line) text = "\n\n".join(lines) nav = [] if page > 0: nav.append({"text": "◀ Newer", "callback_data": f"adm:log:{page - 1}"}) nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"}) if page < total_pages - 1: nav.append({"text": "Older ▶", "callback_data": f"adm:log:{page + 1}"}) return text, ({"inline_keyboard": [nav]} if len(nav) > 1 else None) def render_users(page=0, page_size=8): users = sorted(UNIQUE_USERS.items(), key=lambda kv: -kv[1]["last_seen"]) total = len(users) total_pages = max(1, (total + page_size - 1) // page_size) page = max(0, min(page, total_pages - 1)) chunk = users[page * page_size:(page + 1) * page_size] if not chunk: return "👥 <b>All Users</b>\n\nNo users yet.", None lines = [f"👥 <b>All Users</b> — page {page + 1}/{total_pages} " f"({total} total)\n"] for uid, info in chunk: username = info.get("username") first = info.get("first_name") or "" name_str = f"@{username}" if username else (first or "(no name)") ban_mark = " 🚫" if _is_banned(uid) else "" lines.append(f"<b>{esc(name_str)}</b>{ban_mark} · " f"<code>{uid}</code>\n" f" Requests: {info['count']} · " f"Last: {_fmt_ts(info['last_seen'])}") text = "\n\n".join(lines) nav = [] if page > 0: nav.append({"text": "◀ Prev", "callback_data": f"adm:users:{page - 1}"}) nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"}) if page < total_pages - 1: nav.append({"text": "Next ▶", "callback_data": f"adm:users:{page + 1}"}) return text, ({"inline_keyboard": [nav]} if len(nav) > 1 else None) def render_top(): if not PHONE_COUNTS: return "🔍 <b>Top Searched Numbers</b>\n\nNo searches yet." lines = ["🔍 <b>Top Searched Numbers</b>\n"] for i, (num, cnt) in enumerate(PHONE_COUNTS.most_common(10), 1): lines.append(f"{i}. <code>{num}</code> — {cnt} time(s)") return "\n".join(lines) def render_banned(): with _state_lock: if not BANNED_USERS: return "🚫 <b>Banned Users</b>\n\nNo banned users." lines = [f"🚫 <b>Banned Users</b> ({len(BANNED_USERS)})\n"] for uid in list(BANNED_USERS)[:30]: reason = BAN_REASONS.get(uid) or "—" lines.append(f"• {_short_user(uid)} — {esc(reason)}") return "\n".join(lines) # ══════════════════════════════════════════════════════════════════ # BACKUP FORWARDER # ══════════════════════════════════════════════════════════════════ def _build_backup_payload(user, phone, status, elapsed, fast_data, asur_data, db_results, combined_count): return { "meta": {"ts_utc": datetime.now(timezone.utc).isoformat(), "bot_version": VERSION, "telegram_user_id": user.get("id"), "username": user.get("username"), "first_name": user.get("first_name")}, "input": {"mobile": phone}, "status": status, "elapsed_s": round(elapsed, 2), "aadhaar_resolution": asur_data.get("aadhaar_res") or {}, "api_responses_raw": {**(fast_data.get("raw") or {}), **(asur_data.get("api_results") or {})}, "api_status": {**(fast_data.get("source_status") or {}), **(asur_data.get("source_status") or {})}, "db_results": db_results or [], "records_shown": combined_count, } async def forward_to_backup(user, phone, status, elapsed, fast_data, asur_data, db_results, combined_count): if not BACKUP_CHANNEL_ID or not BACKUP_ENABLED: return try: payload = _build_backup_payload(user, phone, status, elapsed, fast_data, asur_data, db_results, combined_count) header = (f"📥 <b>New lookup</b>\n" f"👤 User: <code>{user.get('id')}</code>" f"{' (@' + esc(user.get('username')) + ')' if user.get('username') else ''}\n" f"📱 Mobile: <code>{esc(phone)}</code>\n" f"📊 Status: <b>{esc(status)}</b> · " f"📄 Records: <b>{combined_count}</b> · " f"⏱️ {elapsed:.1f}s") await send(BACKUP_CHANNEL_ID, header) json_str = json.dumps(payload, indent=2, ensure_ascii=False, default=str) await send_document(BACKUP_CHANNEL_ID, f"lookup_{phone}_{int(time.time())}.json", json_str.encode("utf-8"), caption=f"Mobile {phone} — {status}") STATS["backup_sent"] += 1 except Exception as e: log.warning(f"[backup] forward failed: {e!r}") # ══════════════════════════════════════════════════════════════════ # SEARCH FLOW # ══════════════════════════════════════════════════════════════════ async def _db_search_async(phone, loop): if not con_ready.is_set(): return [] try: return await asyncio.wait_for( loop.run_in_executor(None, run_search_safe, phone, FETCH_LIMIT), timeout=QUERY_TIMEOUT + 10) except (asyncio.TimeoutError, TimeoutError): STATS["timeouts"] += 1 log.warning(f"DB timeout for {phone}") return [] except Exception as e: STATS["errors"] += 1 log.warning(f"DB error for {phone}: {e!r}") return [] async def _show_progressive(chat_id, message_id, phone, results, elapsed, source_note="", extras_block="", asur_data=None): search_id = uuid.uuid4().hex[:10] total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE) SEARCH_CACHE[search_id] = { "ts": time.time(), "results": results, "query": phone, "elapsed": elapsed, "source_note": source_note, "extras_block": extras_block, "asur_data": asur_data or {}, } try: await edit(chat_id, message_id, render_page(results, 0, total_pages, phone, elapsed, source_note, extras_block), reply_markup=page_keyboard(search_id, 0, total_pages)) except Exception as e: log.warning(f"progressive render failed: {e!r}") return search_id async def _do_progressive_search(phone, chat_id, placeholder_id, user): t0 = time.time() loop = asyncio.get_running_loop() db_task = asyncio.create_task(_db_search_async(phone, loop)) fast_task = asyncio.create_task(search_fast_apis_filtered(phone)) asur_task = asyncio.create_task(asur_lookup_filtered(phone)) fast_data = {"records": [], "source_status": {}, "raw": {}, "elapsed": 0.0} try: fast_data = await asyncio.wait_for(fast_task, timeout=75) except asyncio.TimeoutError: log.warning(f"Fast API timeout for {phone}") except Exception as e: log.warning(f"Fast API error for {phone}: {e!r}") fast_records = dedup_records(fast_data.get("records") or []) search_id = None extras_block = "" asur_data = {"records": [], "extras": "", "aadhaar_res": {}, "api_results": {}, "source_status": {}, "elapsed": 0.0} if fast_records: search_id = await _show_progressive( chat_id, placeholder_id, phone, fast_records, fast_data.get("elapsed", 0.0), source_note="⚡ Fast results — enriching…") try: asur_data = await asyncio.wait_for(asur_task, timeout=90) except asyncio.TimeoutError: log.warning(f"ASUR timeout for {phone}") except Exception as e: log.warning(f"ASUR error for {phone}: {e!r}") asur_records = dedup_records(asur_data.get("records") or []) extras_block = asur_data.get("extras") or "" if (asur_records or extras_block) and (fast_records or search_id): combined_sofar = dedup_records(fast_records + asur_records) elapsed = time.time() - t0 note = "🪪 ASUR data added — database query ongoing…" asur_snapshot = {"aadhaar_res": asur_data.get("aadhaar_res"), "api_results": asur_data.get("api_results"), "source_status": asur_data.get("source_status")} if search_id: SEARCH_CACHE[search_id].update({ "results": combined_sofar, "extras_block": extras_block, "asur_data": asur_snapshot, "elapsed": elapsed, "source_note": note, "ts": time.time(), }) total_pages = max(1, (len(combined_sofar) + PAGE_SIZE - 1) // PAGE_SIZE) try: await edit(chat_id, placeholder_id, render_page(combined_sofar, 0, total_pages, phone, elapsed, note, extras_block), reply_markup=page_keyboard(search_id, 0, total_pages)) except Exception as e: log.warning(f"ASUR phase render failed: {e!r}") else: search_id = await _show_progressive( chat_id, placeholder_id, phone, combined_sofar, elapsed, source_note=note, extras_block=extras_block, asur_data=asur_snapshot) db_results = [] try: db_results = await db_task except Exception as e: log.warning(f"DB task raised for {phone}: {e!r}") elapsed = time.time() - t0 combined = dedup_records(fast_records + asur_records + (db_results or [])) new_from_db = max(0, len(combined) - len(dedup_records(fast_records + asur_records))) if fast_records and (asur_records or extras_block) and db_results: source = "hybrid" elif db_results: source = "duckdb" elif fast_records or asur_records or extras_block: source = "api" else: source = "empty" if not combined and not extras_block: _log_activity(user, "search", phone, "no_results", "no records", int(elapsed * 1000), source) try: await edit(chat_id, placeholder_id, f"❌ <b>No record found</b>\n\n" f"📱 <code>{esc(phone)}</code>\n" f"⏱️ {elapsed:.1f}s") except Exception: pass asyncio.create_task(forward_to_backup( user, phone, "empty", elapsed, fast_data, asur_data, db_results, 0)) return 0, elapsed, source note = "" if new_from_db > 0 and (fast_records or asur_records): note = f"➕ {new_from_db} more from database" total_pages = max(1, (len(combined) + PAGE_SIZE - 1) // PAGE_SIZE) asur_snapshot = {"aadhaar_res": asur_data.get("aadhaar_res"), "api_results": asur_data.get("api_results"), "source_status": asur_data.get("source_status")} if search_id: SEARCH_CACHE[search_id].update({ "results": combined, "elapsed": elapsed, "source_note": note, "extras_block": extras_block, "asur_data": asur_snapshot, "ts": time.time(), }) try: await edit(chat_id, placeholder_id, render_page(combined, 0, total_pages, phone, elapsed, note, extras_block), reply_markup=page_keyboard(search_id, 0, total_pages)) except Exception as e: log.warning(f"final render failed: {e!r}") else: search_id = await _show_progressive( chat_id, placeholder_id, phone, combined, elapsed, source_note=note, extras_block=extras_block, asur_data=asur_snapshot) STATS["queries"] += 1 _add_to_history(user.get("id"), phone, len(combined), elapsed, source) _log_activity(user, "search", phone, "results", f"{len(combined)} result(s) (+{new_from_db} new)", int(elapsed * 1000), source) status = "success" if len(combined) > 0 else "empty" asyncio.create_task(forward_to_backup( user, phone, status, elapsed, fast_data, asur_data, db_results, len(combined))) return len(combined), elapsed, source async def _search_quiet(phone): loop = asyncio.get_running_loop() api_task = asyncio.create_task(search_apis_filtered(phone)) db_task = asyncio.create_task(_db_search_async(phone, loop)) api_res, db_res = [], [] try: r = await asyncio.wait_for(api_task, timeout=25) api_res = r.get("records") or [] except Exception: pass try: db_res = await asyncio.wait_for(db_task, timeout=max(5, BATCH_TIMEOUT - 25)) except Exception: pass combined = dedup_records(api_res + (db_res or [])) return len(combined), len(combined) > 0 # ══════════════════════════════════════════════════════════════════ # PAGE KEYBOARD # ══════════════════════════════════════════════════════════════════ def page_keyboard(search_id, page, total_pages, has_export=True): nav = [] if page > 0: nav.append({"text": "◀ Prev", "callback_data": f"p:{search_id}:{page-1}"}) nav.append({"text": f"{page+1} / {total_pages}", "callback_data": "noop"}) if page < total_pages - 1: nav.append({"text": "Next ▶", "callback_data": f"p:{search_id}:{page+1}"}) rows = [nav] extras = [{"text": "📋 Copy page", "callback_data": f"c:{search_id}:{page}"}] if has_export: extras.append({"text": "📥 Export", "callback_data": f"e:{search_id}"}) rows.append(extras) return {"inline_keyboard": rows} # ══════════════════════════════════════════════════════════════════ # WELCOME # ══════════════════════════════════════════════════════════════════ WELCOME_TEMPLATE = ( "👋 <b>Phone Lookup Bot</b> v{v}\n\n" "Send me any <b>10-digit mobile number</b> and I'll return every " "record we have on file.\n\n" "📌 <b>Examples</b>\n" "• <code>9876543210</code>\n" "• <code>+91 98765 43210</code>\n" "• <code>9876543210,9876543211</code> (batch)\n\n" "<i>Commands:</i>\n" "• /start — this message\n" "• /info — bot info\n" "• /status — bot health\n" "• /history — your last 10 searches\n" "• /whoami — your profile &amp; quota\n" "• /daily — today's quota\n" "• /myid — your Telegram ID\n" "• /feedback &lt;msg&gt; — send feedback\n" "• /report &lt;num&gt; — flag wrong data") # ══════════════════════════════════════════════════════════════════ # MESSAGE HANDLER # ══════════════════════════════════════════════════════════════════ async def handle_message(msg): try: chat_id = msg["chat"]["id"] user = msg.get("from") or {} user_id = user.get("id") text = (msg.get("text") or "").strip() log.info(f"Message from {user_id}: {text[:50]!r}") if not text or user_id is None: return if _is_banned(user_id): with _state_lock: reason = BAN_REASONS.get(user_id) or "no reason given" await send(chat_id, f"🚫 <b>You are banned.</b>\n\nReason: {esc(reason)}") _log_activity(user, "banned_hit", text[:40], "blocked", reason) return state = _admin_state_get(user_id) if state == "await_admin_token" and not _is_admin_session(user_id): _admin_state_clear(user_id) if ADMIN_TOKEN and text == ADMIN_TOKEN: _grant_admin(user_id) _log_activity(user, "admin_login", "***", "granted", "session started") await send(chat_id, "✅ <b>Admin access granted</b>", reply_markup=admin_menu_kb()) await send(chat_id, render_admin_menu()) else: _log_activity(user, "admin_login", "***", "denied", "invalid token") await send(chat_id, "❌ <b>Invalid token.</b>\nTry /admin again.") return if state and _is_admin_session(user_id): _admin_state_clear(user_id) if state == "await_ban_id": parts = text.split(None, 1) target = parts[0].lstrip("@") reason = parts[1] if len(parts) > 1 else "" try: tid = int(target) except ValueError: await send(chat_id, "❗ Invalid user ID.") return _ban_user(tid, reason) _log_activity(user, "admin", f"/ban {tid}", "banned", reason or "no reason") await send(chat_id, f"🚫 Banned <code>{tid}</code> — " f"{esc(reason or 'no reason')}") return if state == "await_unban_id": try: tid = int(text.strip()) except ValueError: await send(chat_id, "❗ Invalid user ID.") return ok = _unban_user(tid) _log_activity(user, "admin", f"/unban {tid}", "unbanned") await send(chat_id, "✅ Unbanned." if ok else "ℹ️ User was not banned.") return if state == "await_broadcast": asyncio.create_task(_run_broadcast(chat_id, text)) _log_activity(user, "admin", "/broadcast", "sending", f"{len(text)} chars") return if state == "await_logphone": phone, hint = normalize_phone(text) if not phone: await send(chat_id, f"❗ {hint}") return entries = [e for e in ACTIVITY_LOG if e["action"] == "search" and e["input"] == phone] entries.reverse() if not entries: await send(chat_id, f"🔎 No searches logged for <code>{phone}</code>.") return lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> " f"({len(entries)} total)\n"] for e in entries[:20]: uname = e.get("username") first = e.get("first_name") nm = f"@{uname}" if uname else (first or "(anon)") lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · " f"<code>{e['user_id']}</code>") await send(chat_id, "\n".join(lines)) _log_activity(user, "admin", f"logphone {phone}", "text") return if state == "await_maint_reason": _set_maintenance(True, text[:100]) _log_activity(user, "admin", "maintenance on", "state", text[:100]) await send(chat_id, f"🔴 <b>Maintenance ON</b>\n" f"Reason: {esc(text[:100])}") return m_on, m_reason = _get_maintenance() if m_on and not _is_admin_session(user_id): if text in ("/start", "/help", "/status", "/info", "/myid"): pass else: await send(chat_id, f"🛠️ <b>Bot under maintenance</b>\n\n{esc(m_reason)}") _log_activity(user, "maintenance_block", text[:40], "blocked") return if not await check_force_join(chat_id, user, text): return if text == "/admin": if not ADMIN_TOKEN: await send(chat_id, "⚠️ Admin panel is not configured.") return if _is_admin_session(user_id): _log_activity(user, "admin", "/admin", "menu") await send(chat_id, render_admin_menu(), reply_markup=admin_menu_kb()) else: _admin_state_set(user_id, "await_admin_token") await send(chat_id, "🔐 <b>Admin access required</b>\n\n" "Send the admin token to continue. " "It expires in 3 minutes.") return if text == "/logout": if _is_admin_session(user_id): _revoke_admin(user_id) _log_activity(user, "admin_logout", "/logout", "revoked") await send(chat_id, "✅ Admin session ended.") else: await send(chat_id, "You are not logged in as admin.") return if text.startswith("/") and _is_admin_session(user_id): await _handle_admin_command(chat_id, user, text, user_id) return if text == "/status": uptime = (time.time() - STATS["started"]) / 60 m_on, _ = _get_maintenance() _log_activity(user, "status", "/status", "text") import config as _cfg await send(chat_id, f"<b>📊 Bot Status</b> — v{VERSION}\n\n" f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n" f"🔌 DuckDB main: <code>{con_ready.is_set()}</code>\n" f"🔥 Cache warmed: <code>{warmed.is_set()}</code>\n" f"📂 HiTeck: <code>{len(_cfg.PARQUET_URLS)}</code> · " f"Flipkart: <code>{len(_cfg.FLIPKART_URLS)}</code>\n" f"🔗 APIs: <code>850CR + IndData + ASUR×4</code>\n" f"🛠️ Maintenance: <code>{m_on}</code>\n" f"📥 Backup: <code>{BACKUP_ENABLED}</code>\n" f"🔍 Queries: <code>{STATS['queries']}</code>\n" f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n" f"❌ Errors: <code>{STATS['errors']}</code>") return if text == "/info": uptime = (time.time() - STATS["started"]) / 60 s = _get_stats() _log_activity(user, "info", "/info", "text") await send(chat_id, f"ℹ️ <b>About This Bot</b>\n━━━━━━━━━━━━━━━━━━\n" f"🤖 Version: <code>{VERSION}</code>\n" f"📊 Sources: HiTeck (7) + Flipkart (1) + 2 APIs + ASUR×4\n" f"👥 Unique users: <code>{s['unique_users']}</code>\n" f"🔍 Searches: <code>{s['total_searches']}</code>\n" f"⏱️ Avg latency (today): " f"<code>{_avg_latency_today():.1f}s</code>\n" f"🕒 Uptime: <code>{uptime:.0f} min</code>\n" "━━━━━━━━━━━━━━━━━━\n" "Built with ❤️ for fast, private lookups.") return if text == "/history": with _activity_lock: h = list(USER_HISTORY.get(user_id, [])) _log_activity(user, "history", "/history", "text") if not h: await send(chat_id, "📭 <b>No history yet</b>\n\n" "Search a number to start.") return rows = [[{"text": f"{i}. {item['phone']} ({item['count']} res)", "callback_data": f"h:{item['phone']}"}] for i, item in enumerate(h, 1)] await send(chat_id, "🕘 <b>Your last searches</b>\n\nTap to search again:", reply_markup={"inline_keyboard": rows}) return if text == "/myid": _log_activity(user, "myid", "/myid", "text") await send(chat_id, f"🆔 <b>Your Telegram ID</b>\n<code>{user_id}</code>") return if text == "/whoami": _, remaining = check_quota(user_id) banned = _is_banned(user_id) admin = _is_admin_session(user_id) owner = user_id in OWNER_IDS with _activity_lock: info = UNIQUE_USERS.get(user_id, {}) first_seen = info.get("first_seen") count = info.get("count", 0) lines = ["🆔 <b>Your Info</b>", f"• ID: <code>{user_id}</code>"] if user.get("username"): lines.append(f"• Username: @{esc(user['username'])}") if user.get("first_name"): lines.append(f"• Name: {esc(user['first_name'])}") if first_seen: lines.append("• First seen: " + time.strftime('%Y-%m-%d %H:%M', time.gmtime(first_seen))) lines.append(f"• Total requests: {count}") if _is_unlimited(user_id): lines.append("• Daily quota: ∞") else: lines.append(f"• Daily quota: {DAILY_QUOTA - remaining}/" f"{DAILY_QUOTA} remaining") if owner: lines.append("• Status: 👑 Owner") elif admin: lines.append("• Status: 🛡️ Admin") if banned: with _state_lock: reason = BAN_REASONS.get(user_id) or "no reason" lines.append(f"• Status: 🚫 Banned ({esc(reason)})") _log_activity(user, "whoami", "/whoami", "text") await send(chat_id, "\n".join(lines)) return if text == "/daily": if _is_unlimited(user_id): await send(chat_id, "📊 <b>Daily Quota</b>\n\n♾️ Unlimited (admin/owner)") else: _, remaining = check_quota(user_id) used = DAILY_QUOTA - remaining await send(chat_id, f"📊 <b>Daily Quota</b>\n\n" f"Used: <code>{used}</code>/" f"<code>{DAILY_QUOTA}</code>\n" f"Remaining: <code>{remaining}</code>") _log_activity(user, "daily", "/daily", "text") return if text == "/ping": uptime = (time.time() - STATS["started"]) / 60 _log_activity(user, "ping", "/ping", "text") await send(chat_id, f"🏓 <b>Pong!</b>\n\n⏱️ Uptime: {uptime:.1f} min\n" f"🕐 {time.strftime('%H:%M:%S', time.gmtime())} UTC") return if text.startswith("/feedback"): fb = text[len("/feedback"):].strip() if not fb: await send(chat_id, "❌ Usage: <code>/feedback your message</code>") return if BACKUP_CHANNEL_ID: await send(BACKUP_CHANNEL_ID, f"💬 <b>Feedback</b>\n" f"👤 {_short_user(user_id, user)}\n\n" f"{esc(fb[:3000])}") await send(chat_id, "✅ Thanks for your feedback!") _log_activity(user, "feedback", fb[:60], "text") return if text.startswith("/report"): arg = text[len("/report"):].strip() if not arg: await send(chat_id, "❌ Usage: <code>/report 9876543210 [reason]</code>") return parts = arg.split(None, 1) phone, hint = normalize_phone(parts[0]) if not phone: await send(chat_id, f"❌ Invalid number: {hint}") return reason = parts[1] if len(parts) > 1 else "" if BACKUP_CHANNEL_ID: await send(BACKUP_CHANNEL_ID, f"🚩 <b>Report</b>\n" f"👤 {_short_user(user_id, user)}\n" f"📱 <code>{phone}</code>\n" f"📝 {esc(reason or '(no reason given)')}") await send(chat_id, f"✅ Report submitted for <code>{phone}</code>.") _log_activity(user, "report", phone, "text", reason[:80]) return if text in ("/start", "/help"): _log_activity(user, "start", text, "text") await send(chat_id, WELCOME_TEMPLATE.format(v=VERSION)) if not warmed.is_set(): threading.Thread(target=warm_phone_cache, daemon=True).start() return if "," in text: parts = [p.strip() for p in text.split(",") if p.strip()] if len(parts) < 2: await send(chat_id, "❌ <b>Batch format</b>\n\n" "Example: <code>9876543210,9876543211</code>") return if len(parts) > BATCH_MAX: await send(chat_id, f"❌ Max {BATCH_MAX} numbers per batch.") return phones = [] for p in parts: ph, hint = normalize_phone(p) if not ph: await send(chat_id, f"❌ Invalid: <code>{esc(p)}</code> — {hint}") return phones.append(ph) await _handle_batch(chat_id, user, phones) return phone, hint = normalize_phone(text) if not phone: _log_activity(user, "invalid", text, "error", hint) await send(chat_id, "❌ <b>Invalid input</b>\n\n" "Send a 10-digit number.\n" "Also accepts: <code>+91 98765 43210</code>, " "<code>09876543210</code>, " "<code>9876543210,9876543211</code>") return remaining_mute = check_flood(user_id) if remaining_mute: await send(chat_id, f"⏳ Slow down! Try again in {remaining_mute}s.") _log_activity(user, "flood_muted", phone, "blocked", f"{remaining_mute}s") return now = time.time() if now - USER_LAST.get(user_id, 0) < USER_COOLDOWN: wait = USER_COOLDOWN - (now - USER_LAST.get(user_id, 0)) _log_activity(user, "cooldown", phone, "text", f"wait {wait:.0f}s") await send(chat_id, f"⏳ Wait {wait:.0f}s before next search.") return USER_LAST[user_id] = now ok, remaining = check_quota(user_id) if not ok: await send(chat_id, f"❌ <b>Daily quota reached</b>\n\n" f"You've used all {DAILY_QUOTA} queries for today.\n" f"Resets at 00:00 UTC.") _log_activity(user, "quota_exceeded", phone, "blocked") return incr_quota(user_id) if text.strip() != phone and not text.strip().isdigit(): await send(chat_id, f"ℹ️ Interpreted as <code>{phone}</code>") if not warmed.is_set(): threading.Thread(target=warm_phone_cache, daemon=True).start() placeholder = await send( chat_id, f"🔍 <b>Searching…</b>\n\n📱 <code>{esc(phone)}</code>\n\n" f"<i>Fast results appear instantly; database enrich follows.</i>") if placeholder is None: return try: await _do_progressive_search(phone, chat_id, placeholder, user) except asyncio.TimeoutError: STATS["timeouts"] += 1 _log_activity(user, "search", phone, "timeout", "progressive timeout") await edit(chat_id, placeholder, "⏱️ Timed out. Try again.") except Exception as e: STATS["errors"] += 1 log.error(f"progressive search error: {e!r}\n" f"{traceback.format_exc()}") _log_activity(user, "search", phone, "error", str(e)[:100]) await edit(chat_id, placeholder, f"❌ Error: <code>{esc(str(e)[:200])}</code>") except Exception as e: log.error(f"handle_message fatal: {e!r}\n{traceback.format_exc()}") # ══════════════════════════════════════════════════════════════════ # ADMIN COMMANDS # ══════════════════════════════════════════════════════════════════ async def _handle_admin_command(chat_id, user, text, user_id): global BACKUP_ENABLED cmd = text.split()[0].lower() args = text.split()[1:] if cmd == "/live": _log_activity(user, "admin", "/live", "text") await send(chat_id, render_live()) return if cmd == "/stats": _log_activity(user, "admin", "/stats", "text") await send(chat_id, render_stats()) return if cmd == "/users": _log_activity(user, "admin", "/users", "text") t, kb = render_users(0) await send(chat_id, t, reply_markup=kb) return if cmd == "/top": _log_activity(user, "admin", "/top", "text") await send(chat_id, render_top()) return if cmd == "/log": entries = list(ACTIVITY_LOG) entries.reverse() label = "" if args: try: tid = int(args[0]) entries = [e for e in entries if e["user_id"] == tid] label = f" (user {tid})" except ValueError: target = args[0].lstrip("@").lower() entries = [e for e in entries if (e.get("username") or "").lower() == target] label = f" (@{target})" _log_activity(user, "admin", text, "log_view") t, kb = render_log(entries, 0) if label: t = t.replace("<b>Activity Log</b>", f"<b>Activity Log{label}</b>", 1) await send(chat_id, t, reply_markup=kb) return if cmd == "/banned": _log_activity(user, "admin", "/banned", "text") await send(chat_id, render_banned()) return if cmd == "/ban": if not args: _admin_state_set(user_id, "await_ban_id") await send(chat_id, "Send user ID (and optional reason):") return try: tid = int(args[0].lstrip("@")) except ValueError: await send(chat_id, "❗ Invalid user ID.") return reason = " ".join(args[1:]) if len(args) > 1 else "" _ban_user(tid, reason) _log_activity(user, "admin", f"/ban {tid}", "banned", reason or "no reason") await send(chat_id, f"🚫 Banned <code>{tid}</code> — " f"{esc(reason or 'no reason')}") return if cmd == "/unban": if not args: _admin_state_set(user_id, "await_unban_id") await send(chat_id, "Send user ID to unban:") return try: tid = int(args[0]) except ValueError: await send(chat_id, "❗ Invalid user ID.") return ok = _unban_user(tid) _log_activity(user, "admin", f"/unban {tid}", "unbanned") await send(chat_id, "✅ Unbanned." if ok else "ℹ️ User was not banned.") return if cmd == "/broadcast": if not args: _admin_state_set(user_id, "await_broadcast") await send(chat_id, "Send the message to broadcast to all users:") return await send(chat_id, "ℹ️ Use /broadcast with no args, then send the message.") return if cmd == "/export": _log_activity(user, "admin", "/export", "file") await _send_log_export(chat_id) return if cmd == "/logphone": if not args: _admin_state_set(user_id, "await_logphone") await send(chat_id, "Send a 10-digit number to search the log:") return phone, hint = normalize_phone(args[0]) if not phone: await send(chat_id, f"❗ {hint}") return entries = [e for e in ACTIVITY_LOG if e["action"] == "search" and e["input"] == phone] entries.reverse() if not entries: await send(chat_id, f"🔎 No searches for <code>{phone}</code>.") return lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> " f"({len(entries)})\n"] for e in entries[:20]: uname = e.get("username") first = e.get("first_name") nm = f"@{uname}" if uname else (first or "(anon)") lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · " f"<code>{e['user_id']}</code>") await send(chat_id, "\n".join(lines)) return if cmd == "/maintenance": if not args: m_on, m_reason = _get_maintenance() st = "ON" if m_on else "OFF" await send(chat_id, f"🛠️ Maintenance: <b>{st}</b>" + (f"\nReason: {esc(m_reason)}" if m_on else "")) return mode = args[0].lower() if mode == "on": reason = " ".join(args[1:]) if len(args) > 1 else "" if reason: _set_maintenance(True, reason) _log_activity(user, "admin", "maintenance on", "state", reason) await send(chat_id, f"🔴 Maintenance ON — {esc(reason)}") else: _admin_state_set(user_id, "await_maint_reason") await send(chat_id, "Send a short reason for maintenance:") return elif mode == "off": _set_maintenance(False) _log_activity(user, "admin", "maintenance off", "state") await send(chat_id, "🟢 Maintenance OFF") return await send(chat_id, "Usage: /maintenance on|off [reason]") return if cmd == "/apistatus": await send(chat_id, "🔍 Pinging APIs…") h = await check_api_health() lines = ["🔧 <b>API Status</b>\n"] for name, st in h.items(): icon = "✅" if st.get("ok") else "❌" lines.append(f"{icon} <code>{name}</code> — " f"{st.get('latency_ms', '?')}ms") await send(chat_id, "\n".join(lines)) _log_activity(user, "admin", "/apistatus", "text") return if cmd == "/backup": if not args: await send(chat_id, f"📥 Backup forwarding: " f"<b>{'ON' if BACKUP_ENABLED else 'OFF'}</b>") return mode = args[0].lower() if mode == "on": BACKUP_ENABLED = True _log_activity(user, "admin", "backup on", "state") await send(chat_id, "✅ Backup forwarding ON") elif mode == "off": BACKUP_ENABLED = False _log_activity(user, "admin", "backup off", "state") await send(chat_id, "🚫 Backup forwarding OFF") else: await send(chat_id, "Usage: /backup on|off") return if cmd == "/reload": from bot_state import (_member_cache, _pending_query, _seen_updates, _member_lock, _pending_lock, _seen_updates_lock) with _member_lock: _member_cache.clear() with _pending_lock: _pending_query.clear() with _seen_updates_lock: _seen_updates.clear() SEARCH_CACHE.clear() _log_activity(user, "admin", "/reload", "state") await send(chat_id, "✅ Caches cleared") return if cmd == "/cancel": _admin_state_clear(user_id) _log_activity(user, "admin", "/cancel", "state") await send(chat_id, "✅ Pending prompt cancelled") return await send(chat_id, render_admin_menu(), reply_markup=admin_menu_kb()) # ══════════════════════════════════════════════════════════════════ # BATCH / BROADCAST / EXPORT # ══════════════════════════════════════════════════════════════════ async def _handle_batch(chat_id, user, phones): await send(chat_id, f"🔍 <b>Batch search</b> — {len(phones)} number(s)…") t0 = time.time() tasks = [asyncio.create_task(_search_quiet(p)) for p in phones] results = await asyncio.gather(*tasks, return_exceptions=True) total_elapsed = time.time() - t0 lines = [f"📊 <b>Batch results</b> ({len(phones)} numbers) — " f"{total_elapsed:.1f}s\n"] for phone, res in zip(phones, results): if isinstance(res, Exception): lines.append(f"❌ <code>{phone}</code> — error: " f"{esc(str(res)[:60])}") else: n, ok = res lines.append(f"✅ <code>{phone}</code> — {n} record(s)" if ok else f"❌ <code>{phone}</code> — no results") kb_rows = [[{"text": f"View {p}", "callback_data": f"h:{p}"}] for p in phones] _log_activity(user, "batch_search", ",".join(phones), "text", f"{len(phones)} nums in {total_elapsed:.1f}s") await send(chat_id, "\n".join(lines), reply_markup={"inline_keyboard": kb_rows}) async def _run_broadcast(admin_chat_id, message): with _activity_lock: recipients = list(UNIQUE_USERS.keys()) if not recipients: await send(admin_chat_id, "📭 No users to broadcast to.") return message = message[:BROADCAST_MAX_LEN] await send(admin_chat_id, f"📢 Broadcasting to <b>{len(recipients)}</b> users…") sent = 0 failed = 0 for uid in recipients: if _is_banned(uid): continue try: res = await tg("sendMessage", {"chat_id": uid, "text": f"📢 <b>Announcement</b>\n\n{message}", "parse_mode": "HTML", "disable_web_page_preview": True}, timeout=15) if res.get("ok"): sent += 1 else: failed += 1 except Exception: failed += 1 await asyncio.sleep(BROADCAST_DELAY) await send(admin_chat_id, f"✅ <b>Broadcast complete</b>\n\n" f"Sent: <code>{sent}</code>\n" f"Failed: <code>{failed}</code>") _log_activity({"id": 0}, "admin", "broadcast", "done", f"sent={sent} failed={failed}") async def _send_log_export(chat_id): entries = list(ACTIVITY_LOG) if not entries: await send(chat_id, "📭 No activity to export.") return buf = io.StringIO() w = csv.writer(buf) w.writerow(["timestamp", "user_id", "username", "first_name", "action", "input", "reply_type", "summary", "elapsed_ms", "source"]) for e in entries: w.writerow([ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["ts"])), e["user_id"], e.get("username") or "", e.get("first_name") or "", e["action"], e.get("input", ""), e.get("reply_type", ""), e.get("summary", ""), e.get("elapsed_ms", 0), e.get("source", ""), ]) csv_bytes = buf.getvalue().encode("utf-8") ts = time.strftime("%Y%m%d_%H%M%S") await send_document(chat_id, f"activity_log_{ts}.csv", csv_bytes, caption=f"📥 Activity log — {len(entries)} entries") # ══════════════════════════════════════════════════════════════════ # CALLBACK HANDLER # ══════════════════════════════════════════════════════════════════ async def handle_callback(cb): global BACKUP_ENABLED try: data = cb.get("data", "") cb_id = cb["id"] msg = cb.get("message") or {} chat_id = msg.get("chat", {}).get("id") message_id = msg.get("message_id") user = cb.get("from") or {} user_id = user.get("id") if not chat_id or not message_id: await tg("answerCallbackQuery", {"callback_query_id": cb_id}) return if _is_banned(user_id): await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "🚫 You are banned.", "show_alert": True}) return if data == "join:check": from bot_state import (_member_cache, _member_lock, _pending_query, _pending_lock) with _member_lock: _member_cache.pop(user_id, None) ok = await _is_channel_member(user_id) if not ok: await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "You haven't joined yet. Please join first.", "show_alert": True}) return await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "✅ Verified!"}) try: await tg("deleteMessage", {"chat_id": chat_id, "message_id": message_id}) except Exception: pass with _pending_lock: pending = _pending_query.pop(user_id, None) if pending: ptext, _, pts = pending from config import PENDING_QUERY_TTL if time.time() - pts < PENDING_QUERY_TTL: await handle_message({"chat": {"id": chat_id}, "from": user, "text": ptext}) _log_activity(user, "join_verified", ptext[:40], "replay") return await send(chat_id, "✅ <b>Thanks for joining!</b>\n\n" "Send a 10-digit mobile number to start.") _log_activity(user, "join_verified", "-", "ok") return if data.startswith("adm:"): if not _is_admin_session(user_id): await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Admin session expired — send /admin again.", "show_alert": True}) return parts = data.split(":") action = parts[1] if len(parts) > 1 else "menu" if action == "menu": await edit(chat_id, message_id, render_admin_menu(), reply_markup=admin_menu_kb()) elif action == "live": await edit(chat_id, message_id, render_live(), reply_markup=admin_menu_kb()) elif action == "stats": await edit(chat_id, message_id, render_stats(), reply_markup=admin_menu_kb()) elif action == "top": await edit(chat_id, message_id, render_top(), reply_markup=admin_menu_kb()) elif action == "banned": await edit(chat_id, message_id, render_banned(), reply_markup=admin_menu_kb()) elif action == "log": page = int(parts[2]) if len(parts) > 2 else 0 entries = list(ACTIVITY_LOG) entries.reverse() t, kb = render_log(entries, page) await edit(chat_id, message_id, t, reply_markup=kb) elif action == "users": page = int(parts[2]) if len(parts) > 2 else 0 t, kb = render_users(page) await edit(chat_id, message_id, t, reply_markup=kb) elif action == "ban": _admin_state_set(user_id, "await_ban_id") await edit(chat_id, message_id, "🚫 Send user ID (and optional reason):") elif action == "unban": _admin_state_set(user_id, "await_unban_id") await edit(chat_id, message_id, "✅ Send user ID to unban:") elif action == "broadcast": _admin_state_set(user_id, "await_broadcast") await edit(chat_id, message_id, "📢 Send the message to broadcast:") elif action == "export": await edit(chat_id, message_id, "📥 Generating export…", reply_markup=admin_menu_kb()) await _send_log_export(chat_id) elif action == "logphone": _admin_state_set(user_id, "await_logphone") await edit(chat_id, message_id, "🔎 Send a 10-digit number:") elif action == "maint": m_on, _ = _get_maintenance() if m_on: _set_maintenance(False) await edit(chat_id, message_id, "🟢 Maintenance OFF", reply_markup=admin_menu_kb()) else: _admin_state_set(user_id, "await_maint_reason") await edit(chat_id, message_id, "Send a short maintenance reason:") elif action == "apistatus": await edit(chat_id, message_id, "🔍 Pinging APIs…") h = await check_api_health() lines = ["🔧 <b>API Status</b>\n"] for name, st in h.items(): icon = "✅" if st.get("ok") else "❌" lines.append(f"{icon} <code>{name}</code> — " f"{st.get('latency_ms', '?')}ms") await edit(chat_id, message_id, "\n".join(lines), reply_markup=admin_menu_kb()) elif action == "backuptoggle": BACKUP_ENABLED = not BACKUP_ENABLED await edit(chat_id, message_id, render_admin_menu(), reply_markup=admin_menu_kb()) elif action == "noop": pass await tg("answerCallbackQuery", {"callback_query_id": cb_id}) _log_activity(user, "admin", data, "menu") return if data.startswith("h:"): phone = data.split(":", 1)[1] await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": f"Searching {phone}…"}) await handle_message({"chat": {"id": chat_id}, "from": user, "text": phone}) return if data.startswith("c:"): try: _, sid, page_s = data.split(":") page = int(page_s) except Exception: await tg("answerCallbackQuery", {"callback_query_id": cb_id}) return with SEARCH_CACHE_LOCK: entry = SEARCH_CACHE.get(sid) if not entry: await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Session expired.", "show_alert": True}) return results = entry["results"] total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE) page = max(0, min(page, total_pages - 1)) start = page * PAGE_SIZE chunk = results[start:start + PAGE_SIZE] text = "\n\n".join(_plain_record(start + i + 1, r) for i, r in enumerate(chunk)) await send(chat_id, f"<b>📋 Copy text for page {page + 1}</b>\n\n" f"<pre>{esc(text[:3500])}</pre>") await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Sent as copyable message"}) _log_activity(user, "copy", entry["query"], "text") return if data.startswith("e:"): sid = data.split(":", 1)[1] with SEARCH_CACHE_LOCK: entry = SEARCH_CACHE.get(sid) if not entry: await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Session expired.", "show_alert": True}) return phone = entry["query"] results = entry["results"] payload = json.dumps({ "phone": phone, "records": results, "extras": entry.get("extras_block", ""), "source_note": entry.get("source_note", ""), "elapsed_s": entry.get("elapsed", 0), "asurpapa": entry.get("asur_data", {}), }, indent=2, ensure_ascii=False, default=str).encode("utf-8") await send_document(chat_id, f"results_{phone}.json", payload, caption=f"📥 {len(results)} record(s) " f"for {phone}") await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Sent as file"}) _log_activity(user, "export", phone, "file", f"{len(results)} records") return if data == "noop" or not data.startswith("p:"): await tg("answerCallbackQuery", {"callback_query_id": cb_id}) return try: _, search_id, page_str = data.split(":") page = int(page_str) except Exception: await tg("answerCallbackQuery", {"callback_query_id": cb_id}) return with SEARCH_CACHE_LOCK: entry = SEARCH_CACHE.get(search_id) if not entry: await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Session expired — search again.", "show_alert": True}) return results = entry["results"] total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE) page = max(0, min(page, total_pages - 1)) await edit(chat_id, message_id, render_page(results, page, total_pages, entry["query"], entry["elapsed"], entry.get("source_note", ""), entry.get("extras_block", "")), reply_markup=page_keyboard(search_id, page, total_pages)) await tg("answerCallbackQuery", {"callback_query_id": cb_id}) _log_activity(user, "paginate", entry["query"], "page", f"page {page + 1}/{total_pages}") except Exception as e: log.error(f"handle_callback fatal: {e!r}\n{traceback.format_exc()}") # ══════════════════════════════════════════════════════════════════ # RE-EXPORTS — everything app.py and admin_panel.py need # ══════════════════════════════════════════════════════════════════ __all__ = [ "handle_message", "handle_callback", "is_duplicate_update", "cache_gc", "tg", "send", "edit", "send_document", "ACTIVITY_LOG", "UNIQUE_USERS", "ACTIVE_USERS", "BANNED_USERS", "BAN_REASONS", "MAINTENANCE_MODE", "SEARCH_CACHE", "STATS", "BACKUP_ENABLED", "USER_HISTORY", "USER_LAST", "PHONE_COUNTS", "_activity_lock", "_state_lock", "SEARCH_CACHE_LOCK", "_ban_user", "_unban_user", "_set_maintenance", "_get_maintenance", "_revoke_admin", "_is_admin_session", "_grant_admin", "_get_stats", "_get_live_users", "_short_user", "_fmt_ts", "_today_utc", "_log_activity", "_add_to_history", "_is_banned", "_is_unlimited", "check_quota", "incr_quota", "check_flood", "check_force_join", "_admin_state_get", "_admin_state_set", "_admin_state_clear", "_db_search_async", "_show_progressive", "_do_progressive_search", "page_keyboard", "WELCOME_TEMPLATE", "forward_to_backup", "_build_backup_payload", "_handle_batch", "_run_broadcast", "_send_log_export", "admin_menu_kb", "render_admin_menu", "render_live", "render_stats", "render_log", "render_users", "render_top", "render_banned", ]
"""bot.py — Handlers, progressive search, admin commands, callbacks.
State lives in bot_state.py. This file re-exports everything so
`import bot; bot.cache_gc` etc. continue to work.
"""
import asyncio
import csv
import io
import json
import logging
import threading
import time
import traceback
import uuid
from datetime import datetime, timezone
from config import (
BACKUP_ENABLED_DEFAULT, BACKUP_CHANNEL_ID, VERSION,
PAGE_SIZE, FETCH_LIMIT, QUERY_TIMEOUT, USER_COOLDOWN,
BATCH_MAX, BATCH_TIMEOUT, ADMIN_TOKEN, OWNER_IDS,
BROADCAST_DELAY, BROADCAST_MAX_LEN,
DAILY_QUOTA,
)
from engine import (
run_search_safe, search_fast_apis_filtered, asur_lookup_filtered,
search_apis_filtered, dedup_records, render_page, _plain_record,
normalize_phone, check_api_health, warm_phone_cache,
con_ready, warmed, esc,
)
from bot_state import (
ACTIVITY_LOG, ACTIVE_USERS, UNIQUE_USERS, BANNED_USERS, BAN_REASONS,
MAINTENANCE_MODE, SEARCH_CACHE, SEARCH_CACHE_LOCK, USER_HISTORY,
USER_LAST, STATS, PHONE_COUNTS,
_activity_lock, _state_lock,
tg, send, edit, send_document,
_short_user, _fmt_ts, _today_utc,
is_duplicate_update,
check_force_join,
_is_unlimited, check_quota, incr_quota, check_flood,
_log_activity, _get_live_users, _get_stats, _add_to_history,
_avg_latency_today,
_is_banned, _ban_user, _unban_user,
_get_maintenance, _set_maintenance,
_is_admin_session, _grant_admin, _revoke_admin,
_admin_state_get, _admin_state_set, _admin_state_clear,
cache_gc,
)
log = logging.getLogger("bot")
# Runtime toggle (local to bot.py — mutated by /backup and admin panel)
BACKUP_ENABLED = BACKUP_ENABLED_DEFAULT
# ══════════════════════════════════════════════════════════════════
# ADMIN RENDERS
# ══════════════════════════════════════════════════════════════════
def admin_menu_kb():
m_on, _ = _get_maintenance()
maint_label = "🔴 Maintenance: ON" if m_on else "🟢 Maintenance: OFF"
backup_label = "📥 Backup: ON" if BACKUP_ENABLED else "📥 Backup: OFF"
return {"inline_keyboard": [
[{"text": "🔴 Live Users", "callback_data": "adm:live"},
{"text": "📈 Stats", "callback_data": "adm:stats"}],
[{"text": "📜 Activity Log", "callback_data": "adm:log:0"},
{"text": "👥 All Users", "callback_data": "adm:users:0"}],
[{"text": "🔍 Top Searches", "callback_data": "adm:top"},
{"text": "🚫 Banned", "callback_data": "adm:banned"}],
[{"text": "🚫 Ban User", "callback_data": "adm:ban"},
{"text": "✅ Unban User", "callback_data": "adm:unban"}],
[{"text": "📢 Broadcast", "callback_data": "adm:broadcast"},
{"text": "📥 Export Log", "callback_data": "adm:export"}],
[{"text": "🔎 Log by Phone", "callback_data": "adm:logphone"},
{"text": maint_label, "callback_data": "adm:maint"}],
[{"text": "🔧 API Status", "callback_data": "adm:apistatus"},
{"text": backup_label, "callback_data": "adm:backuptoggle"}],
[{"text": "🔄 Refresh", "callback_data": "adm:menu"}],
]}
def render_admin_menu():
m_on, reason = _get_maintenance()
m_line = f"🔴 Maintenance ON — {esc(reason)}" if m_on else "🟢 Operational"
b_line = "📥 Backup forwarding: ON" if BACKUP_ENABLED else "📥 Backup forwarding: OFF"
return (f"🛡️ <b>Admin Panel</b> — v{VERSION}\n━━━━━━━━━━━━━━━━━━\n"
f"{m_line}\n{b_line}\n"
f"👥 Users: {len(UNIQUE_USERS)} · 🚫 Banned: {len(BANNED_USERS)}\n\n"
"Tap a button or use commands:\n"
"• /live /stats /log /users /top\n"
"• /ban &lt;id&gt; [reason] · /unban &lt;id&gt;\n"
"• /broadcast &lt;msg&gt;\n"
"• /export · /logphone &lt;num&gt;\n"
"• /maintenance on|off [reason]\n"
"• /apistatus · /backup on|off\n"
"• /reload · /cancel · /logout")
def render_live():
live = _get_live_users()
if not live:
return (f"🔴 <b>Live Users</b>\n\n"