"""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"🛡️ Admin Panel — 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 <id> [reason] · /unban <id>\n"
"• /broadcast <msg>\n"
"• /export · /logphone <num>\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"🔴 Live Users\n\n"
f"No one active in the last {LIVE_WINDOW // 60} minutes.")
lines = [f"🔴 Live Users (last {LIVE_WINDOW // 60} min): "
f"{len(live)}\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 ("📈 Bot Statistics\n━━━━━━━━━━━━━━━━━━\n"
f"⏱️ Uptime: {uptime:.1f} min\n"
f"👥 Unique users: {s['unique_users']}\n"
f"🔴 Live now: {s['live_users']}\n"
f"📅 Active today: {s['today_users']}\n"
f"🔍 Searches today: {s['today_searches']}\n"
f"🔍 Total searches: {s['total_searches']}\n"
f"📊 Peak concurrent: {s['peak_concurrent']}\n"
f"🚫 Banned users: {s['banned_count']}\n"
f"💾 Cached queries: {s['cached_searches']}\n"
f"📥 Backup sent: {s['backup_sent']}\n"
f"📜 Log entries: {s['total_log_entries']}\n"
f"⏰ Timeouts: {STATS['timeouts']}\n"
f"❌ Errors: {STATS['errors']}")
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 "📜 Activity Log\n\nNo activity yet.", None
lines = [f"📜 Activity Log — 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"{_fmt_ts(e['ts'])} · "
f"{esc(name_str)} · {e['user_id']}\n")
block += f" 📥 {esc(e['input'] or '-')}\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 "👥 All Users\n\nNo users yet.", None
lines = [f"👥 All Users — 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"{esc(name_str)}{ban_mark} · "
f"{uid}\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 "🔍 Top Searched Numbers\n\nNo searches yet."
lines = ["🔍 Top Searched Numbers\n"]
for i, (num, cnt) in enumerate(PHONE_COUNTS.most_common(10), 1):
lines.append(f"{i}. {num} — {cnt} time(s)")
return "\n".join(lines)
def render_banned():
with _state_lock:
if not BANNED_USERS:
return "🚫 Banned Users\n\nNo banned users."
lines = [f"🚫 Banned Users ({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"📥 New lookup\n"
f"👤 User: {user.get('id')}"
f"{' (@' + esc(user.get('username')) + ')' if user.get('username') else ''}\n"
f"📱 Mobile: {esc(phone)}\n"
f"📊 Status: {esc(status)} · "
f"📄 Records: {combined_count} · "
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"❌ No record found\n\n"
f"📱 {esc(phone)}\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 = (
"👋 Phone Lookup Bot v{v}\n\n"
"Send me any 10-digit mobile number and I'll return every "
"record we have on file.\n\n"
"📌 Examples\n"
"• 9876543210\n"
"• +91 98765 43210\n"
"• 9876543210,9876543211 (batch)\n\n"
"Commands:\n"
"• /start — this message\n"
"• /info — bot info\n"
"• /status — bot health\n"
"• /history — your last 10 searches\n"
"• /whoami — your profile & quota\n"
"• /daily — today's quota\n"
"• /myid — your Telegram ID\n"
"• /feedback <msg> — send feedback\n"
"• /report <num> — 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"🚫 You are banned.\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, "✅ Admin access granted",
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,
"❌ Invalid token.\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 {tid} — "
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 {phone}.")
return
lines = [f"🔎 Searches for {phone} "
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"{e['user_id']}")
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"🔴 Maintenance ON\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"🛠️ Bot under maintenance\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,
"🔐 Admin access required\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"📊 Bot Status — v{VERSION}\n\n"
f"⏱️ Uptime: {uptime:.1f} min\n"
f"🔌 DuckDB main: {con_ready.is_set()}\n"
f"🔥 Cache warmed: {warmed.is_set()}\n"
f"📂 HiTeck: {len(_cfg.PARQUET_URLS)} · "
f"Flipkart: {len(_cfg.FLIPKART_URLS)}\n"
f"🔗 APIs: 850CR + IndData + ASUR×4\n"
f"🛠️ Maintenance: {m_on}\n"
f"📥 Backup: {BACKUP_ENABLED}\n"
f"🔍 Queries: {STATS['queries']}\n"
f"⏰ Timeouts: {STATS['timeouts']}\n"
f"❌ Errors: {STATS['errors']}")
return
if text == "/info":
uptime = (time.time() - STATS["started"]) / 60
s = _get_stats()
_log_activity(user, "info", "/info", "text")
await send(chat_id,
f"ℹ️ About This Bot\n━━━━━━━━━━━━━━━━━━\n"
f"🤖 Version: {VERSION}\n"
f"📊 Sources: HiTeck (7) + Flipkart (1) + 2 APIs + ASUR×4\n"
f"👥 Unique users: {s['unique_users']}\n"
f"🔍 Searches: {s['total_searches']}\n"
f"⏱️ Avg latency (today): "
f"{_avg_latency_today():.1f}s\n"
f"🕒 Uptime: {uptime:.0f} min\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,
"📭 No history yet\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,
"🕘 Your last searches\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"🆔 Your Telegram ID\n{user_id}")
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 = ["🆔 Your Info", f"• ID: {user_id}"]
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,
"📊 Daily Quota\n\n♾️ Unlimited (admin/owner)")
else:
_, remaining = check_quota(user_id)
used = DAILY_QUOTA - remaining
await send(chat_id,
f"📊 Daily Quota\n\n"
f"Used: {used}/"
f"{DAILY_QUOTA}\n"
f"Remaining: {remaining}")
_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"🏓 Pong!\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: /feedback your message")
return
if BACKUP_CHANNEL_ID:
await send(BACKUP_CHANNEL_ID,
f"💬 Feedback\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: /report 9876543210 [reason]")
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"🚩 Report\n"
f"👤 {_short_user(user_id, user)}\n"
f"📱 {phone}\n"
f"📝 {esc(reason or '(no reason given)')}")
await send(chat_id,
f"✅ Report submitted for {phone}.")
_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,
"❌ Batch format\n\n"
"Example: 9876543210,9876543211")
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: {esc(p)} — {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,
"❌ Invalid input\n\n"
"Send a 10-digit number.\n"
"Also accepts: +91 98765 43210, "
"09876543210, "
"9876543210,9876543211")
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"❌ Daily quota reached\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 {phone}")
if not warmed.is_set():
threading.Thread(target=warm_phone_cache, daemon=True).start()
placeholder = await send(
chat_id,
f"🔍 Searching…\n\n📱 {esc(phone)}\n\n"
f"Fast results appear instantly; database enrich follows.")
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: {esc(str(e)[:200])}")
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("Activity Log",
f"Activity Log{label}", 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 {tid} — "
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 {phone}.")
return
lines = [f"🔎 Searches for {phone} "
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"{e['user_id']}")
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: {st}" +
(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 = ["🔧 API Status\n"]
for name, st in h.items():
icon = "✅" if st.get("ok") else "❌"
lines.append(f"{icon} {name} — "
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"{'ON' if BACKUP_ENABLED else 'OFF'}")
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"🔍 Batch search — {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"📊 Batch results ({len(phones)} numbers) — "
f"{total_elapsed:.1f}s\n"]
for phone, res in zip(phones, results):
if isinstance(res, Exception):
lines.append(f"❌ {phone} — error: "
f"{esc(str(res)[:60])}")
else:
n, ok = res
lines.append(f"✅ {phone} — {n} record(s)"
if ok else
f"❌ {phone} — 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 {len(recipients)} users…")
sent = 0
failed = 0
for uid in recipients:
if _is_banned(uid):
continue
try:
res = await tg("sendMessage",
{"chat_id": uid,
"text": f"📢 Announcement\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"✅ Broadcast complete\n\n"
f"Sent: {sent}\n"
f"Failed: {failed}")
_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,
"✅ Thanks for joining!\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 = ["🔧 API Status\n"]
for name, st in h.items():
icon = "✅" if st.get("ok") else "❌"
lines.append(f"{icon} {name} — "
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"📋 Copy text for page {page + 1}\n\n"
f"
{esc(text[:3500])}")
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",
]