Hfzune commited on
Commit
b4fc8f2
·
verified ·
1 Parent(s): 4311acc

Create bot.py

Browse files
Files changed (1) hide show
  1. bot.py +2038 -0
bot.py ADDED
@@ -0,0 +1,2038 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ══════════════════════════════════════════════════════════════════
2
+ # bot.py — Telegram bot logic
3
+ #
4
+ # Owns:
5
+ # • Telegram helpers (send / edit / send_document)
6
+ # • State: activity, admin, bans, maintenance, quota, flood,
7
+ # membership cache, pending queries, update dedup
8
+ # • Force-join gate (features FORCE_JOIN_CHANNEL)
9
+ # • Backup forwarder (every query → BACKUP_CHANNEL_ID, text + JSON)
10
+ # • Progressive search flow (fast API → ASUR → DB, extras block)
11
+ # • Message handlers (/start /help /info /status /history /myid
12
+ # /ping /whoami /daily /feedback /report
13
+ # /admin … admin commands)
14
+ # • Callback handlers (pagination, copy, export, history, join, admin)
15
+ # • Batch search
16
+ # • Broadcast
17
+ # • cache_gc thread
18
+ #
19
+ # Imports from config.py + engine.py. Never touches gradio.
20
+ # ══════════════════════════════════════════════════════════════════
21
+
22
+ import asyncio
23
+ import csv
24
+ import html
25
+ import io
26
+ import json
27
+ import logging
28
+ import re
29
+ import threading
30
+ import time
31
+ import traceback
32
+ import uuid
33
+ from collections import deque, Counter
34
+ from datetime import datetime, timezone
35
+ from typing import Optional, List
36
+
37
+ import httpx
38
+
39
+ from config import (
40
+ TELEGRAM_API, BOT_TOKEN, ADMIN_TOKEN, OWNER_IDS,
41
+ FORCE_JOIN_CHANNEL, BACKUP_CHANNEL_ID, BACKUP_ENABLED_DEFAULT,
42
+ VERSION, BOT_NAME,
43
+ PAGE_SIZE, FETCH_LIMIT, QUERY_TIMEOUT, USER_COOLDOWN,
44
+ CACHE_TTL, SEARCH_CACHE_TTL,
45
+ MEMBERSHIP_CACHE_TTL, PENDING_QUERY_TTL,
46
+ FLOOD_WINDOW, FLOOD_MAX, FLOOD_MUTE_SEC,
47
+ DAILY_QUOTA, DAILY_QUOTA_ADMIN,
48
+ LIVE_WINDOW, HISTORY_LEN, ACTIVITY_LOG_MAX,
49
+ ADMIN_SESSION_TTL, ADMIN_PROMPT_TTL,
50
+ BROADCAST_DELAY, BROADCAST_MAX_LEN,
51
+ BATCH_MAX, BATCH_TIMEOUT,
52
+ SOURCE_LABEL,
53
+ )
54
+ from engine import (
55
+ run_search_safe, find_aadhaar_by_mobile,
56
+ search_fast_apis_filtered, asur_lookup_filtered,
57
+ search_apis_filtered, search_apis,
58
+ dedup_records, render_page, format_result, _plain_record,
59
+ normalize_phone, check_api_health,
60
+ get_con, get_asur_con, warm_phone_cache, warm_asur_cache,
61
+ con_ready, warmed, esc,
62
+ )
63
+
64
+ log = logging.getLogger("bot")
65
+
66
+
67
+ # ══════════════════════════════════════════════════════════════════
68
+ # 1. STATE
69
+ # ══════════════════════════════════════════════════════════════════
70
+ # ── runtime toggles ──
71
+ BACKUP_ENABLED = BACKUP_ENABLED_DEFAULT
72
+
73
+ # ── activity ──
74
+ ACTIVITY_LOG = deque(maxlen=ACTIVITY_LOG_MAX)
75
+ ACTIVE_USERS = {}
76
+ UNIQUE_USERS = {}
77
+ PHONE_COUNTS = Counter()
78
+ PEAK_CONCURRENT = 0
79
+ _activity_lock = threading.Lock()
80
+
81
+ # ── admin ──
82
+ _admin_lock = threading.Lock()
83
+ _admin_sessions = {} # uid -> expiry
84
+ _admin_states = {} # uid -> (state, set_at)
85
+
86
+ # ── bans / maintenance ──
87
+ BANNED_USERS = set()
88
+ BAN_REASONS = {}
89
+ MAINTENANCE_MODE = False
90
+ MAINTENANCE_REASON = ""
91
+ _state_lock = threading.Lock()
92
+
93
+ # ── history ──
94
+ USER_HISTORY = {}
95
+
96
+ # ── search cache (pagination / copy / export) ──
97
+ SEARCH_CACHE = {}
98
+ SEARCH_CACHE_LOCK = threading.Lock()
99
+
100
+ # ── per-user cooldown ──
101
+ USER_LAST = {}
102
+
103
+ # ── stats ──
104
+ STATS = {"queries": 0, "timeouts": 0, "errors": 0,
105
+ "backup_sent": 0, "started": time.time()}
106
+
107
+ # ── membership cache (force-join) ──
108
+ _member_cache = {} # uid -> (is_member, ts)
109
+ _member_lock = threading.Lock()
110
+
111
+ # ── pending query (user sent query before joining) ──
112
+ _pending_query = {} # uid -> (text, chat_id, ts)
113
+ _pending_lock = threading.Lock()
114
+
115
+ # ── quota ──
116
+ _user_daily = {} # uid -> (yyyy-mm-dd, count)
117
+ _quota_lock = threading.Lock()
118
+
119
+ # ── flood ──
120
+ _user_msg_times = {} # uid -> deque[timestamps]
121
+ _muted_until = {} # uid -> ts
122
+ _flood_lock = threading.Lock()
123
+
124
+ # ── update dedup ──
125
+ _seen_updates = {} # update_id -> ts
126
+ _seen_updates_lock = threading.Lock()
127
+
128
+
129
+ # ══════════════════════════════════════════════════════════════════
130
+ # 2. TELEGRAM HELPERS
131
+ # ══════════════════════════════════════════════════════════════════
132
+ async def tg(method: str, payload: dict, timeout: float = 30) -> dict:
133
+ try:
134
+ async with httpx.AsyncClient(timeout=timeout) as client:
135
+ r = await client.post(f"{TELEGRAM_API}/{method}", json=payload)
136
+ return r.json()
137
+ except Exception as e:
138
+ log.error(f"❌ tg({method}): {e!r}")
139
+ return {"ok": False, "error": str(e)}
140
+
141
+
142
+ async def send(chat_id, text, **kw) -> Optional[int]:
143
+ kw.setdefault("parse_mode", "HTML")
144
+ kw.setdefault("disable_web_page_preview", True)
145
+ kw = {k: v for k, v in kw.items() if v is not None}
146
+ try:
147
+ res = await tg("sendMessage", {"chat_id": chat_id, "text": text, **kw})
148
+ if res.get("ok"):
149
+ return res["result"]["message_id"]
150
+ log.warning(f"⚠️ sendMessage failed: {res}")
151
+ except Exception as e:
152
+ log.error(f"❌ send error: {e!r}")
153
+ return None
154
+
155
+
156
+ async def edit(chat_id, message_id, text, **kw):
157
+ kw.setdefault("parse_mode", "HTML")
158
+ kw.setdefault("disable_web_page_preview", True)
159
+ kw = {k: v for k, v in kw.items() if v is not None}
160
+ try:
161
+ res = await tg("editMessageText",
162
+ {"chat_id": chat_id, "message_id": message_id, "text": text, **kw})
163
+ if not res.get("ok") and "message is not modified" not in str(res):
164
+ log.warning(f"⚠️ editMessageText failed: {res}")
165
+ except Exception as e:
166
+ log.error(f"❌ edit error: {e!r}")
167
+
168
+
169
+ async def send_document(chat_id, filename: str, content: bytes, caption: str = "") -> dict:
170
+ try:
171
+ files = {"document": (filename, content, "application/octet-stream")}
172
+ data = {"chat_id": str(chat_id)}
173
+ if caption:
174
+ data["caption"] = caption[:1024]
175
+ async with httpx.AsyncClient(timeout=60) as client:
176
+ r = await client.post(f"{TELEGRAM_API}/sendDocument", data=data, files=files)
177
+ res = r.json()
178
+ if not res.get("ok"):
179
+ log.warning(f"⚠️ sendDocument failed: {res}")
180
+ return res
181
+ except Exception as e:
182
+ log.error(f"❌ sendDocument error: {e!r}")
183
+ return {"ok": False}
184
+
185
+
186
+ # ══════════════════════════════════════════════════════════════════
187
+ # 3. SMALL HELPERS
188
+ # ══════════════════════════════════════════════════════════════════
189
+ def _short_user(user_id: int, user: dict | None = None) -> str:
190
+ info = UNIQUE_USERS.get(user_id) or {}
191
+ username = (user or {}).get("username") or info.get("username")
192
+ first = (user or {}).get("first_name") or info.get("first_name")
193
+ if username:
194
+ return f"@{username} ({user_id})"
195
+ if first:
196
+ return f"{first} ({user_id})"
197
+ return f"({user_id})"
198
+
199
+
200
+ def _fmt_ts(ts: float) -> str:
201
+ return time.strftime("%H:%M:%S", time.localtime(ts))
202
+
203
+
204
+ def _today_utc() -> str:
205
+ return time.strftime("%Y-%m-%d", time.gmtime())
206
+
207
+
208
+ # ══════════════════════════════════════════════════════════════════
209
+ # 4. UPDATE DEDUP
210
+ # ══════════════════════════════════════════════════════════════════
211
+ def is_duplicate_update(update_id: Optional[int]) -> bool:
212
+ """True if this Telegram update_id was already processed."""
213
+ if not update_id:
214
+ return False
215
+ now = time.time()
216
+ with _seen_updates_lock:
217
+ if len(_seen_updates) > 2000:
218
+ cutoff = now - 600
219
+ for k in [k for k, v in _seen_updates.items() if v < cutoff]:
220
+ del _seen_updates[k]
221
+ if update_id in _seen_updates:
222
+ return True
223
+ _seen_updates[update_id] = now
224
+ return False
225
+
226
+
227
+ # ══════════════════════════════════════════════════════════════════
228
+ # 5. FORCE-JOIN
229
+ # ══════════════════════════════════════════════════════════════════
230
+ async def _is_channel_member(user_id: int) -> bool:
231
+ if not FORCE_JOIN_CHANNEL:
232
+ return True
233
+ now = time.time()
234
+ with _member_lock:
235
+ cached = _member_cache.get(user_id)
236
+ if cached and now - cached[1] < MEMBERSHIP_CACHE_TTL:
237
+ return cached[0]
238
+
239
+ is_member = False
240
+ try:
241
+ res = await tg("getChatMember",
242
+ {"chat_id": FORCE_JOIN_CHANNEL, "user_id": user_id}, timeout=10)
243
+ if res.get("ok"):
244
+ status = (res.get("result") or {}).get("status", "")
245
+ is_member = status in ("member", "administrator", "creator")
246
+ else:
247
+ log.warning(f"[membership] getChatMember failed: {res}")
248
+ except Exception as e:
249
+ log.warning(f"[membership] {e!r}")
250
+
251
+ with _member_lock:
252
+ _member_cache[user_id] = (is_member, now)
253
+ return is_member
254
+
255
+
256
+ def _join_url() -> str:
257
+ if not FORCE_JOIN_CHANNEL:
258
+ return ""
259
+ if FORCE_JOIN_CHANNEL.startswith("http"):
260
+ return FORCE_JOIN_CHANNEL
261
+ if FORCE_JOIN_CHANNEL.startswith("@"):
262
+ return f"https://t.me/{FORCE_JOIN_CHANNEL.lstrip('@')}"
263
+ return "https://t.me/"
264
+
265
+
266
+ async def check_force_join(chat_id: int, user: dict, text: str) -> bool:
267
+ """
268
+ Returns True if the user may proceed.
269
+ Otherwise sends the join prompt (storing pending query) and returns False.
270
+ """
271
+ if not FORCE_JOIN_CHANNEL:
272
+ return True
273
+ uid = user.get("id")
274
+ if not uid:
275
+ return True
276
+ if uid in OWNER_IDS:
277
+ return True
278
+ if _is_admin_session(uid):
279
+ return True
280
+ # Bypass gate for navigation commands so user understands what's happening
281
+ if text.startswith(("/start", "/help", "/myid", "/whoami", "/ping", "/info", "/status")):
282
+ return True
283
+
284
+ if await _is_channel_member(uid):
285
+ return True
286
+
287
+ # Store pending query so it can be replayed after joining
288
+ with _pending_lock:
289
+ _pending_query[uid] = (text, chat_id, time.time())
290
+
291
+ url = _join_url()
292
+ await send(
293
+ chat_id,
294
+ "🔒 <b>Join required</b>\n\n"
295
+ "To use this bot, please join our channel first.\n\n"
296
+ f"👉 {esc(url)}\n\n"
297
+ "After joining, tap <b>✅ I Joined</b> below.",
298
+ reply_markup={
299
+ "inline_keyboard": [
300
+ [{"text": "📢 Join Channel", "url": url}],
301
+ [{"text": "✅ I Joined", "callback_data": "join:check"}],
302
+ ]
303
+ },
304
+ )
305
+ _log_activity(user, "force_join_block", text[:40], "blocked", "not a member")
306
+ return False
307
+
308
+
309
+ # ══════════════════════════════════════════════════════════════════
310
+ # 6. QUOTA
311
+ # ══════════════════════════════════════════════════════════════════
312
+ def _is_unlimited(user_id: int) -> bool:
313
+ return user_id in OWNER_IDS or _is_admin_session(user_id)
314
+
315
+
316
+ def check_quota(user_id: int) -> tuple[bool, int]:
317
+ """Return (allowed, remaining)."""
318
+ if _is_unlimited(user_id):
319
+ return True, DAILY_QUOTA_ADMIN
320
+ today = _today_utc()
321
+ with _quota_lock:
322
+ entry = _user_daily.get(user_id)
323
+ if not entry or entry[0] != today:
324
+ _user_daily[user_id] = (today, 0)
325
+ return True, DAILY_QUOTA
326
+ if entry[1] >= DAILY_QUOTA:
327
+ return False, 0
328
+ return True, DAILY_QUOTA - entry[1]
329
+
330
+
331
+ def incr_quota(user_id: int) -> None:
332
+ if _is_unlimited(user_id):
333
+ return
334
+ today = _today_utc()
335
+ with _quota_lock:
336
+ entry = _user_daily.get(user_id)
337
+ if not entry or entry[0] != today:
338
+ _user_daily[user_id] = (today, 1)
339
+ else:
340
+ _user_daily[user_id] = (today, entry[1] + 1)
341
+
342
+
343
+ # ══════════════════════════════════════════════════════════════════
344
+ # 7. FLOOD
345
+ # ══════════════════════════════════════════════════════════════════
346
+ def check_flood(user_id: int) -> Optional[int]:
347
+ """Returns remaining mute seconds if muted, else None (and records msg)."""
348
+ now = time.time()
349
+ with _flood_lock:
350
+ until = _muted_until.get(user_id, 0)
351
+ if until > now:
352
+ return int(until - now)
353
+ dq = _user_msg_times.setdefault(user_id, deque(maxlen=FLOOD_MAX))
354
+ dq.append(now)
355
+ if len(dq) == FLOOD_MAX and dq[0] >= now - FLOOD_WINDOW:
356
+ _muted_until[user_id] = now + FLOOD_MUTE_SEC
357
+ return FLOOD_MUTE_SEC
358
+ return None
359
+
360
+
361
+ # ══════════════════════════════════════════════════════════════════
362
+ # 8. ACTIVITY TRACKING
363
+ # ══════════════════════════════════════════════════════════════════
364
+ def _log_activity(user: dict, action: str, input_val: str, reply_type: str,
365
+ summary: str = "", elapsed_ms: int = 0, source: str = ""):
366
+ if not user or "id" not in user:
367
+ return
368
+ now = time.time()
369
+ user_id = user["id"]
370
+ with _activity_lock:
371
+ info = UNIQUE_USERS.setdefault(user_id, {
372
+ "username": None, "first_name": None, "last_name": None,
373
+ "count": 0, "first_seen": now, "last_seen": now,
374
+ })
375
+ if user.get("username"): info["username"] = user["username"]
376
+ if user.get("first_name"): info["first_name"] = user["first_name"]
377
+ if user.get("last_name"): info["last_name"] = user["last_name"]
378
+ info["count"] += 1
379
+ info["last_seen"] = now
380
+ ACTIVE_USERS[user_id] = now
381
+
382
+ if (action == "search" and isinstance(input_val, str)
383
+ and input_val.isdigit() and len(input_val) == 10):
384
+ PHONE_COUNTS[input_val] += 1
385
+
386
+ ACTIVITY_LOG.append({
387
+ "ts": now, "user_id": user_id,
388
+ "username": user.get("username"),
389
+ "first_name": user.get("first_name"),
390
+ "action": action, "input": (input_val or "")[:80],
391
+ "reply_type": reply_type, "summary": (summary or "")[:150],
392
+ "elapsed_ms": int(elapsed_ms), "source": source,
393
+ })
394
+
395
+
396
+ def _get_live_users():
397
+ cutoff = time.time() - LIVE_WINDOW
398
+ with _activity_lock:
399
+ live = [(uid, ts) for uid, ts in ACTIVE_USERS.items() if ts >= cutoff]
400
+ live.sort(key=lambda x: -x[1])
401
+ return live
402
+
403
+
404
+ def _get_stats() -> dict:
405
+ now = time.time()
406
+ today_start = now - (now % 86400)
407
+ with _activity_lock:
408
+ today_users = set(); today_searches = 0; total_searches = 0
409
+ for e in ACTIVITY_LOG:
410
+ if e["action"] == "search":
411
+ total_searches += 1
412
+ if e["ts"] >= today_start:
413
+ today_searches += 1; today_users.add(e["user_id"])
414
+ return {
415
+ "unique_users": len(UNIQUE_USERS),
416
+ "live_users": sum(1 for ts in ACTIVE_USERS.values() if ts >= now - LIVE_WINDOW),
417
+ "today_users": len(today_users),
418
+ "today_searches": today_searches,
419
+ "total_searches": total_searches,
420
+ "peak_concurrent": PEAK_CONCURRENT,
421
+ "total_log_entries": len(ACTIVITY_LOG),
422
+ "banned_count": len(BANNED_USERS),
423
+ "maintenance": MAINTENANCE_MODE,
424
+ "cached_searches": len(SEARCH_CACHE),
425
+ "backup_sent": STATS["backup_sent"],
426
+ }
427
+
428
+
429
+ def _add_to_history(user_id: int, phone: str, count: int, elapsed: float, source: str):
430
+ if user_id is None:
431
+ return
432
+ with _activity_lock:
433
+ h = USER_HISTORY.setdefault(user_id, deque(maxlen=HISTORY_LEN))
434
+ h.appendleft({"phone": phone, "ts": time.time(), "count": count,
435
+ "elapsed": elapsed, "source": source})
436
+
437
+
438
+ def _avg_latency_today() -> float:
439
+ now = time.time()
440
+ today_start = now - (now % 86400)
441
+ with _activity_lock:
442
+ vals = [e["elapsed_ms"] for e in ACTIVITY_LOG
443
+ if e["action"] == "search" and e["ts"] >= today_start and e["elapsed_ms"] > 0]
444
+ return (sum(vals) / len(vals)) / 1000.0 if vals else 0.0
445
+
446
+
447
+ # ══════════════════════════════════════════════════════════════════
448
+ # 9. BAN / MAINTENANCE
449
+ # ══════════════════════════════════════════════════════════════════
450
+ def _is_banned(user_id: int) -> bool:
451
+ with _state_lock:
452
+ return user_id in BANNED_USERS
453
+
454
+
455
+ def _ban_user(user_id: int, reason: str = ""):
456
+ with _state_lock:
457
+ BANNED_USERS.add(user_id)
458
+ BAN_REASONS[user_id] = reason
459
+
460
+
461
+ def _unban_user(user_id: int) -> bool:
462
+ with _state_lock:
463
+ if user_id in BANNED_USERS:
464
+ BANNED_USERS.discard(user_id)
465
+ BAN_REASONS.pop(user_id, None)
466
+ return True
467
+ return False
468
+
469
+
470
+ def _get_maintenance() -> tuple[bool, str]:
471
+ with _state_lock:
472
+ return MAINTENANCE_MODE, MAINTENANCE_REASON
473
+
474
+
475
+ def _set_maintenance(on: bool, reason: str = ""):
476
+ global MAINTENANCE_MODE, MAINTENANCE_REASON
477
+ with _state_lock:
478
+ MAINTENANCE_MODE = on
479
+ MAINTENANCE_REASON = reason if on else ""
480
+
481
+
482
+ # ══════════════════════════════════════════════════════════════════
483
+ # 10. ADMIN AUTH + STATE
484
+ # ══════════════════════════════════════════════════════════════════
485
+ def _is_admin_session(user_id: int) -> bool:
486
+ if user_id is None:
487
+ return False
488
+ with _admin_lock:
489
+ exp = _admin_sessions.get(user_id)
490
+ if exp is None:
491
+ return False
492
+ if time.time() > exp:
493
+ _admin_sessions.pop(user_id, None)
494
+ return False
495
+ return True
496
+
497
+
498
+ def _grant_admin(user_id: int):
499
+ with _admin_lock:
500
+ _admin_sessions[user_id] = time.time() + ADMIN_SESSION_TTL
501
+
502
+
503
+ def _revoke_admin(user_id: int):
504
+ with _admin_lock:
505
+ _admin_sessions.pop(user_id, None)
506
+
507
+
508
+ def _admin_state_get(user_id: int):
509
+ with _admin_lock:
510
+ entry = _admin_states.get(user_id)
511
+ if entry is None:
512
+ return None
513
+ state, set_at = entry
514
+ if time.time() - set_at > ADMIN_PROMPT_TTL:
515
+ _admin_states.pop(user_id, None)
516
+ return None
517
+ return state
518
+
519
+
520
+ def _admin_state_set(user_id: int, state: str):
521
+ with _admin_lock:
522
+ _admin_states[user_id] = (state, time.time())
523
+
524
+
525
+ def _admin_state_clear(user_id: int):
526
+ with _admin_lock:
527
+ _admin_states.pop(user_id, None)
528
+
529
+
530
+ # ══════════════════════════════════════════════════════════════════
531
+ # 11. ADMIN RENDERERS
532
+ # ══════════════════════════════════════════════════════════════════
533
+ def admin_menu_kb() -> dict:
534
+ m_on, _ = _get_maintenance()
535
+ maint_label = "🔴 Maintenance: ON" if m_on else "🟢 Maintenance: OFF"
536
+ backup_label = "📥 Backup: ON" if BACKUP_ENABLED else "📥 Backup: OFF"
537
+ return {
538
+ "inline_keyboard": [
539
+ [{"text": "🔴 Live Users", "callback_data": "adm:live"},
540
+ {"text": "📈 Stats", "callback_data": "adm:stats"}],
541
+ [{"text": "📜 Activity Log", "callback_data": "adm:log:0"},
542
+ {"text": "👥 All Users", "callback_data": "adm:users:0"}],
543
+ [{"text": "🔍 Top Searches", "callback_data": "adm:top"},
544
+ {"text": "🚫 Banned", "callback_data": "adm:banned"}],
545
+ [{"text": "🚫 Ban User", "callback_data": "adm:ban"},
546
+ {"text": "✅ Unban User", "callback_data": "adm:unban"}],
547
+ [{"text": "📢 Broadcast", "callback_data": "adm:broadcast"},
548
+ {"text": "📥 Export Log", "callback_data": "adm:export"}],
549
+ [{"text": "🔎 Log by Phone", "callback_data": "adm:logphone"},
550
+ {"text": maint_label, "callback_data": "adm:maint"}],
551
+ [{"text": "🔧 API Status", "callback_data": "adm:apistatus"},
552
+ {"text": backup_label, "callback_data": "adm:backuptoggle"}],
553
+ [{"text": "🔄 Refresh", "callback_data": "adm:menu"}],
554
+ ]
555
+ }
556
+
557
+
558
+ def render_admin_menu() -> str:
559
+ m_on, reason = _get_maintenance()
560
+ m_line = f"🔴 Maintenance ON — {esc(reason)}" if m_on else "🟢 Operational"
561
+ b_line = "📥 Backup forwarding: ON" if BACKUP_ENABLED else "📥 Backup forwarding: OFF"
562
+ return (
563
+ f"🛡️ <b>Admin Panel</b> — v{VERSION}\n"
564
+ "━━━━━━━━━━━━━━━━━━\n"
565
+ f"{m_line}\n"
566
+ f"{b_line}\n"
567
+ f"👥 Users: {len(UNIQUE_USERS)} · 🚫 Banned: {len(BANNED_USERS)}\n\n"
568
+ "Tap a button or use commands:\n"
569
+ "• /live /stats /log /users /top\n"
570
+ "• /ban &lt;id&gt; [reason] · /unban &lt;id&gt;\n"
571
+ "• /broadcast &lt;msg&gt;\n"
572
+ "• /export · /logphone &lt;num&gt;\n"
573
+ "• /maintenance on|off [reason]\n"
574
+ "• /apistatus · /backup on|off\n"
575
+ "• /reload · /cancel · /logout"
576
+ )
577
+
578
+
579
+ def render_live() -> str:
580
+ live = _get_live_users()
581
+ if not live:
582
+ return f"🔴 <b>Live Users</b>\n\nNo one active in the last {LIVE_WINDOW // 60} minutes."
583
+ lines = [f"🔴 <b>Live Users</b> (last {LIVE_WINDOW // 60} min): <b>{len(live)}</b>\n"]
584
+ for uid, ts in live[:25]:
585
+ lines.append(f"• {_short_user(uid)} — {_fmt_ts(ts)}")
586
+ return "\n".join(lines)
587
+
588
+
589
+ def render_stats() -> str:
590
+ s = _get_stats()
591
+ uptime = (time.time() - STATS["started"]) / 60
592
+ return (
593
+ "📈 <b>Bot Statistics</b>\n"
594
+ "━━━━━━━━━━━━━━━━━━\n"
595
+ f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n"
596
+ f"👥 Unique users: <code>{s['unique_users']}</code>\n"
597
+ f"🔴 Live now: <code>{s['live_users']}</code>\n"
598
+ f"📅 Active today: <code>{s['today_users']}</code>\n"
599
+ f"🔍 Searches today: <code>{s['today_searches']}</code>\n"
600
+ f"🔍 Total searches: <code>{s['total_searches']}</code>\n"
601
+ f"📊 Peak concurrent: <code>{s['peak_concurrent']}</code>\n"
602
+ f"🚫 Banned users: <code>{s['banned_count']}</code>\n"
603
+ f"💾 Cached queries: <code>{s['cached_searches']}</code>\n"
604
+ f"📥 Backup sent: <code>{s['backup_sent']}</code>\n"
605
+ f"📜 Log entries: <code>{s['total_log_entries']}</code>\n"
606
+ f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n"
607
+ f"❌ Errors: <code>{STATS['errors']}</code>"
608
+ )
609
+
610
+
611
+ def render_log(entries, page=0, page_size=8):
612
+ total = len(entries)
613
+ total_pages = max(1, (total + page_size - 1) // page_size)
614
+ page = max(0, min(page, total_pages - 1))
615
+ chunk = entries[page * page_size:(page + 1) * page_size]
616
+ if not chunk:
617
+ return "📜 <b>Activity Log</b>\n\nNo activity yet.", None
618
+
619
+ lines = [f"📜 <b>Activity Log</b> — page {page + 1}/{total_pages} ({total} entries)\n"]
620
+ for e in chunk:
621
+ uname = e.get("username"); first = e.get("first_name")
622
+ name_str = f"@{uname}" if uname else (first or "(no name)")
623
+ reply = e.get("summary") or e.get("reply_type") or "-"
624
+ elapsed = e.get("elapsed_ms", 0); source = e.get("source") or ""
625
+ block = f"<code>{_fmt_ts(e['ts'])}</code> · <b>{esc(name_str)}</b> · <code>{e['user_id']}</code>\n"
626
+ block += f" 📥 <code>{esc(e['input'] or '-')}</code>\n"
627
+ reply_line = f" 📤 {esc(reply)}"
628
+ if elapsed: reply_line += f" · {elapsed}ms"
629
+ if source: reply_line += f" · {source}"
630
+ block += reply_line
631
+ lines.append(block)
632
+
633
+ text = "\n\n".join(lines)
634
+ nav = []
635
+ if page > 0:
636
+ nav.append({"text": "◀ Newer", "callback_data": f"adm:log:{page - 1}"})
637
+ nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"})
638
+ if page < total_pages - 1:
639
+ nav.append({"text": "Older ▶", "callback_data": f"adm:log:{page + 1}"})
640
+ kb = {"inline_keyboard": [nav]} if len(nav) > 1 else None
641
+ return text, kb
642
+
643
+
644
+ def render_users(page=0, page_size=8):
645
+ users = sorted(UNIQUE_USERS.items(), key=lambda kv: -kv[1]["last_seen"])
646
+ total = len(users)
647
+ total_pages = max(1, (total + page_size - 1) // page_size)
648
+ page = max(0, min(page, total_pages - 1))
649
+ chunk = users[page * page_size:(page + 1) * page_size]
650
+ if not chunk:
651
+ return "👥 <b>All Users</b>\n\nNo users yet.", None
652
+
653
+ lines = [f"👥 <b>All Users</b> — page {page + 1}/{total_pages} ({total} total)\n"]
654
+ for uid, info in chunk:
655
+ username = info.get("username"); first = info.get("first_name") or ""
656
+ name_str = f"@{username}" if username else (first or "(no name)")
657
+ ban_mark = " 🚫" if _is_banned(uid) else ""
658
+ lines.append(
659
+ f"<b>{esc(name_str)}</b>{ban_mark} · <code>{uid}</code>\n"
660
+ f" Requests: {info['count']} · Last: {_fmt_ts(info['last_seen'])}"
661
+ )
662
+ text = "\n\n".join(lines)
663
+ nav = []
664
+ if page > 0:
665
+ nav.append({"text": "◀ Prev", "callback_data": f"adm:users:{page - 1}"})
666
+ nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"})
667
+ if page < total_pages - 1:
668
+ nav.append({"text": "Next ▶", "callback_data": f"adm:users:{page + 1}"})
669
+ kb = {"inline_keyboard": [nav]} if len(nav) > 1 else None
670
+ return text, kb
671
+
672
+
673
+ def render_top() -> str:
674
+ if not PHONE_COUNTS:
675
+ return "🔍 <b>Top Searched Numbers</b>\n\nNo searches yet."
676
+ lines = ["🔍 <b>Top Searched Numbers</b>\n"]
677
+ for i, (num, cnt) in enumerate(PHONE_COUNTS.most_common(10), 1):
678
+ lines.append(f"{i}. <code>{num}</code> — {cnt} time(s)")
679
+ return "\n".join(lines)
680
+
681
+
682
+ def render_banned() -> str:
683
+ with _state_lock:
684
+ if not BANNED_USERS:
685
+ return "🚫 <b>Banned Users</b>\n\nNo banned users."
686
+ lines = [f"🚫 <b>Banned Users</b> ({len(BANNED_USERS)})\n"]
687
+ for uid in list(BANNED_USERS)[:30]:
688
+ reason = BAN_REASONS.get(uid) or "—"
689
+ lines.append(f"• {_short_user(uid)} — {esc(reason)}")
690
+ return "\n".join(lines)
691
+
692
+
693
+ # ══════════════════════════════════════════════════════════════════
694
+ # 12. BACKUP FORWARDER (every query → BACKUP_CHANNEL_ID)
695
+ # ══════════════════════════════════════════════════════════════════
696
+ def _build_backup_payload(user, phone, status, elapsed,
697
+ fast_data, asur_data, db_results, combined_count) -> dict:
698
+ return {
699
+ "meta": {
700
+ "ts_utc": datetime.now(timezone.utc).isoformat(),
701
+ "bot_version": VERSION,
702
+ "telegram_user_id": user.get("id"),
703
+ "username": user.get("username"),
704
+ "first_name": user.get("first_name"),
705
+ },
706
+ "input": {"mobile": phone},
707
+ "status": status,
708
+ "elapsed_s": round(elapsed, 2),
709
+ "aadhaar_resolution": asur_data.get("aadhaar_res") or {},
710
+ "api_responses_raw": {
711
+ **(fast_data.get("raw") or {}),
712
+ **(asur_data.get("api_results") or {}),
713
+ },
714
+ "api_status": {
715
+ **(fast_data.get("source_status") or {}),
716
+ **(asur_data.get("source_status") or {}),
717
+ },
718
+ "db_results": db_results or [],
719
+ "records_shown": combined_count,
720
+ }
721
+
722
+
723
+ async def forward_to_backup(user, phone, status, elapsed,
724
+ fast_data, asur_data, db_results, combined_count) -> None:
725
+ if not BACKUP_CHANNEL_ID or not BACKUP_ENABLED:
726
+ return
727
+ try:
728
+ payload = _build_backup_payload(
729
+ user, phone, status, elapsed, fast_data, asur_data, db_results, combined_count
730
+ )
731
+ header = (
732
+ f"📥 <b>New lookup</b>\n"
733
+ f"👤 User: <code>{user.get('id')}</code>"
734
+ f"{' (@' + esc(user.get('username')) + ')' if user.get('username') else ''}\n"
735
+ f"📱 Mobile: <code>{esc(phone)}</code>\n"
736
+ f"📊 Status: <b>{esc(status)}</b> · "
737
+ f"📄 Records: <b>{combined_count}</b> · "
738
+ f"⏱️ {elapsed:.1f}s"
739
+ )
740
+ await send(BACKUP_CHANNEL_ID, header)
741
+
742
+ json_str = json.dumps(payload, indent=2, ensure_ascii=False, default=str)
743
+ await send_document(
744
+ BACKUP_CHANNEL_ID,
745
+ f"lookup_{phone}_{int(time.time())}.json",
746
+ json_str.encode("utf-8"),
747
+ caption=f"Mobile {phone} — {status}",
748
+ )
749
+ STATS["backup_sent"] += 1
750
+ except Exception as e:
751
+ log.warning(f"[backup] forward failed: {e!r}")
752
+
753
+
754
+ # ══════════════════════════════════════════════════════════════════
755
+ # 13. SEARCH FLOW
756
+ # ══════════════════════════════════════════════════════════════════
757
+ async def _db_search_async(phone: str, loop) -> list:
758
+ if not con_ready.is_set():
759
+ return []
760
+ try:
761
+ return await asyncio.wait_for(
762
+ loop.run_in_executor(None, run_search_safe, phone, FETCH_LIMIT),
763
+ timeout=QUERY_TIMEOUT + 10,
764
+ )
765
+ except (asyncio.TimeoutError, TimeoutError):
766
+ STATS["timeouts"] += 1
767
+ log.warning(f"⏱️ DB timeout for {phone}")
768
+ return []
769
+ except Exception as e:
770
+ STATS["errors"] += 1
771
+ log.warning(f"⚠️ DB error for {phone}: {e!r}")
772
+ return []
773
+
774
+
775
+ def _compute_status(combined_count: int) -> str:
776
+ return "success" if combined_count > 0 else "empty"
777
+
778
+
779
+ async def _show_progressive(chat_id, message_id, phone, results, elapsed,
780
+ source_note="", extras_block="", asur_data=None) -> str:
781
+ """Create a SEARCH_CACHE entry and edit the placeholder message."""
782
+ search_id = uuid.uuid4().hex[:10]
783
+ total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
784
+ SEARCH_CACHE[search_id] = {
785
+ "ts": time.time(),
786
+ "results": results,
787
+ "query": phone,
788
+ "elapsed": elapsed,
789
+ "source_note": source_note,
790
+ "extras_block": extras_block,
791
+ "asur_data": asur_data or {},
792
+ }
793
+ try:
794
+ await edit(
795
+ chat_id, message_id,
796
+ render_page(results, 0, total_pages, phone, elapsed, source_note, extras_block),
797
+ reply_markup=page_keyboard(search_id, 0, total_pages),
798
+ )
799
+ except Exception as e:
800
+ log.warning(f"⚠️ progressive render failed: {e!r}")
801
+ return search_id
802
+
803
+
804
+ async def _do_progressive_search(phone: str, chat_id: int, placeholder_id: int, user: dict):
805
+ """
806
+ 3-phase progressive flow:
807
+ 1. Fast APIs (850CR + IndData)
808
+ 2. ASUR (aadhaar resolution + 4 APIs) — hides dead sources
809
+ 3. DuckDB (HiTeck + Flipkart)
810
+ Every phase edits the SAME message. Final result forwarded to backup.
811
+ """
812
+ t0 = time.time()
813
+ loop = asyncio.get_running_loop()
814
+
815
+ db_task = asyncio.create_task(_db_search_async(phone, loop))
816
+ fast_task = asyncio.create_task(search_fast_apis_filtered(phone))
817
+ asur_task = asyncio.create_task(asur_lookup_filtered(phone))
818
+
819
+ # ── Phase 1: fast APIs ──
820
+ fast_data = {"records": [], "source_status": {}, "raw": {}, "elapsed": 0.0}
821
+ try:
822
+ fast_data = await asyncio.wait_for(fast_task, timeout=75)
823
+ except asyncio.TimeoutError:
824
+ log.warning(f"⏱️ Fast API timeout for {phone}")
825
+ except Exception as e:
826
+ log.warning(f"⚠️ Fast API error for {phone}: {e!r}")
827
+
828
+ fast_records = dedup_records(fast_data.get("records") or [])
829
+ search_id = None
830
+ extras_block = ""
831
+ asur_data: dict = {"records": [], "extras": "", "aadhaar_res": {},
832
+ "api_results": {}, "source_status": {}, "elapsed": 0.0}
833
+
834
+ if fast_records:
835
+ search_id = await _show_progressive(
836
+ chat_id, placeholder_id, phone, fast_records, fast_data.get("elapsed", 0.0),
837
+ source_note="⚡ Fast results — enriching…",
838
+ )
839
+
840
+ # ── Phase 2: ASUR ──
841
+ try:
842
+ asur_data = await asyncio.wait_for(asur_task, timeout=90)
843
+ except asyncio.TimeoutError:
844
+ log.warning(f"⏱️ ASUR timeout for {phone}")
845
+ except Exception as e:
846
+ log.warning(f"⚠️ ASUR error for {phone}: {e!r}")
847
+
848
+ asur_records = dedup_records(asur_data.get("records") or [])
849
+ extras_block = asur_data.get("extras") or ""
850
+
851
+ # Show intermediate state if ASUR added something new
852
+ if (asur_records or extras_block) and (fast_records or search_id):
853
+ combined_sofar = dedup_records(fast_records + asur_records)
854
+ elapsed = time.time() - t0
855
+ note = "🪪 ASUR data added — database query ongoing…"
856
+ if search_id:
857
+ SEARCH_CACHE[search_id]["results"] = combined_sofar
858
+ SEARCH_CACHE[search_id]["extras_block"] = extras_block
859
+ SEARCH_CACHE[search_id]["asur_data"] = {
860
+ "aadhaar_res": asur_data.get("aadhaar_res"),
861
+ "api_results": asur_data.get("api_results"),
862
+ "source_status": asur_data.get("source_status"),
863
+ }
864
+ SEARCH_CACHE[search_id]["elapsed"] = elapsed
865
+ SEARCH_CACHE[search_id]["source_note"] = note
866
+ SEARCH_CACHE[search_id]["ts"] = time.time()
867
+ total_pages = max(1, (len(combined_sofar) + PAGE_SIZE - 1) // PAGE_SIZE)
868
+ try:
869
+ await edit(
870
+ chat_id, placeholder_id,
871
+ render_page(combined_sofar, 0, total_pages, phone, elapsed, note, extras_block),
872
+ reply_markup=page_keyboard(search_id, 0, total_pages),
873
+ )
874
+ except Exception as e:
875
+ log.warning(f"⚠️ ASUR phase render failed: {e!r}")
876
+ else:
877
+ search_id = await _show_progressive(
878
+ chat_id, placeholder_id, phone, combined_sofar, elapsed,
879
+ source_note=note, extras_block=extras_block,
880
+ asur_data={
881
+ "aadhaar_res": asur_data.get("aadhaar_res"),
882
+ "api_results": asur_data.get("api_results"),
883
+ "source_status": asur_data.get("source_status"),
884
+ },
885
+ )
886
+
887
+ # ── Phase 3: DB ──
888
+ db_results: list = []
889
+ try:
890
+ db_results = await db_task
891
+ except Exception as e:
892
+ log.warning(f"⚠️ DB task raised for {phone}: {e!r}")
893
+
894
+ elapsed = time.time() - t0
895
+ combined = dedup_records(fast_records + asur_records + (db_results or []))
896
+ new_from_db = max(0, len(combined) - len(dedup_records(fast_records + asur_records)))
897
+
898
+ # ── Determine source label ──
899
+ if fast_records and (asur_records or extras_block) and db_results:
900
+ source = "hybrid"
901
+ elif db_results:
902
+ source = "duckdb"
903
+ elif fast_records or asur_records or extras_block:
904
+ source = "api"
905
+ else:
906
+ source = "empty"
907
+
908
+ # ── No results anywhere ──
909
+ if not combined and not extras_block:
910
+ _log_activity(user, "search", phone, "no_results",
911
+ "no records", int(elapsed * 1000), source)
912
+ try:
913
+ await edit(
914
+ chat_id, placeholder_id,
915
+ f"❌ <b>No record found</b>\n\n"
916
+ f"📱 <code>{esc(phone)}</code>\n"
917
+ f"⏱️ {elapsed:.1f}s",
918
+ )
919
+ except Exception:
920
+ pass
921
+ # Backup forward anyway
922
+ asyncio.create_task(forward_to_backup(
923
+ user, phone, "empty", elapsed,
924
+ fast_data, asur_data, db_results, 0,
925
+ ))
926
+ return 0, elapsed, source
927
+
928
+ # ── Final render ──
929
+ note = ""
930
+ if new_from_db > 0 and (fast_records or asur_records):
931
+ note = f"➕ {new_from_db} more from database"
932
+ total_pages = max(1, (len(combined) + PAGE_SIZE - 1) // PAGE_SIZE)
933
+
934
+ asur_snapshot = {
935
+ "aadhaar_res": asur_data.get("aadhaar_res"),
936
+ "api_results": asur_data.get("api_results"),
937
+ "source_status": asur_data.get("source_status"),
938
+ }
939
+
940
+ if search_id:
941
+ SEARCH_CACHE[search_id]["results"] = combined
942
+ SEARCH_CACHE[search_id]["elapsed"] = elapsed
943
+ SEARCH_CACHE[search_id]["source_note"] = note
944
+ SEARCH_CACHE[search_id]["extras_block"] = extras_block
945
+ SEARCH_CACHE[search_id]["asur_data"] = asur_snapshot
946
+ SEARCH_CACHE[search_id]["ts"] = time.time()
947
+ try:
948
+ await edit(
949
+ chat_id, placeholder_id,
950
+ render_page(combined, 0, total_pages, phone, elapsed, note, extras_block),
951
+ reply_markup=page_keyboard(search_id, 0, total_pages),
952
+ )
953
+ except Exception as e:
954
+ log.warning(f"⚠️ final render failed: {e!r}")
955
+ else:
956
+ search_id = await _show_progressive(
957
+ chat_id, placeholder_id, phone, combined, elapsed,
958
+ source_note=note, extras_block=extras_block,
959
+ asur_data=asur_snapshot,
960
+ )
961
+
962
+ STATS["queries"] += 1
963
+ _add_to_history(user.get("id"), phone, len(combined), elapsed, source)
964
+ _log_activity(user, "search", phone, "results",
965
+ f"{len(combined)} result(s) (+{new_from_db} new)",
966
+ int(elapsed * 1000), source)
967
+
968
+ # ── Backup forward ──
969
+ asyncio.create_task(forward_to_backup(
970
+ user, phone, _compute_status(len(combined)), elapsed,
971
+ fast_data, asur_data, db_results, len(combined),
972
+ ))
973
+ return len(combined), elapsed, source
974
+
975
+
976
+ async def _search_quiet(phone: str) -> tuple[int, bool]:
977
+ """Batch-mode — no UI, returns (count, ok)."""
978
+ loop = asyncio.get_running_loop()
979
+ api_task = asyncio.create_task(search_apis_filtered(phone))
980
+ db_task = asyncio.create_task(_db_search_async(phone, loop))
981
+
982
+ api_res, db_res = [], []
983
+ try:
984
+ r = await asyncio.wait_for(api_task, timeout=25)
985
+ api_res = r.get("records") or []
986
+ except Exception:
987
+ pass
988
+ try:
989
+ db_res = await asyncio.wait_for(db_task, timeout=max(5, BATCH_TIMEOUT - 25))
990
+ except Exception:
991
+ pass
992
+
993
+ combined = dedup_records(api_res + (db_res or []))
994
+ return len(combined), len(combined) > 0
995
+
996
+
997
+ # ══════════════════════════════════════════════════════════════════
998
+ # 14. PAGE KEYBOARD
999
+ # ══════════════════════════════════════════════════════════════════
1000
+ def page_keyboard(search_id, page, total_pages, has_export=True):
1001
+ nav = []
1002
+ if page > 0:
1003
+ nav.append({"text": "◀ Prev", "callback_data": f"p:{search_id}:{page-1}"})
1004
+ nav.append({"text": f"{page+1} / {total_pages}", "callback_data": "noop"})
1005
+ if page < total_pages - 1:
1006
+ nav.append({"text": "Next ▶", "callback_data": f"p:{search_id}:{page+1}"})
1007
+ rows = [nav]
1008
+ extras = [{"text": "📋 Copy page", "callback_data": f"c:{search_id}:{page}"}]
1009
+ if has_export:
1010
+ extras.append({"text": "📥 Export", "callback_data": f"e:{search_id}"})
1011
+ rows.append(extras)
1012
+ return {"inline_keyboard": rows}
1013
+
1014
+
1015
+ # ══════════════════════════════════════════════════════════════════
1016
+ # 15. WELCOME
1017
+ # ══════════════════════════════════════════════════════════════════
1018
+ WELCOME_TEMPLATE = (
1019
+ "👋 <b>Phone Lookup Bot</b> v{v}\n\n"
1020
+ "Send me any <b>10-digit mobile number</b> and I'll return every "
1021
+ "record we have on file.\n\n"
1022
+ "📌 <b>Examples</b>\n"
1023
+ "• <code>9876543210</code>\n"
1024
+ "• <code>+91 98765 43210</code>\n"
1025
+ "• <code>9876543210,9876543211</code> (batch)\n\n"
1026
+ "<i>Commands:</i>\n"
1027
+ "• /start — this message\n"
1028
+ "• /info — bot info &amp; credits\n"
1029
+ "• /status — bot health\n"
1030
+ "• /history — your last 10 searches\n"
1031
+ "• /whoami — your profile &amp; quota\n"
1032
+ "• /daily — today's quota\n"
1033
+ "• /myid — your Telegram ID\n"
1034
+ "• /feedback &lt;msg&gt; — send feedback\n"
1035
+ "• /report &lt;num&gt; — flag wrong data"
1036
+ )
1037
+
1038
+
1039
+ # ══════════════════════════════════════════════════════════════════
1040
+ # 16. MESSAGE HANDLER
1041
+ # ══════════════════════════════════════════════════════════════════
1042
+ async def handle_message(msg: dict):
1043
+ try:
1044
+ chat_id = msg["chat"]["id"]
1045
+ user = msg.get("from") or {}
1046
+ user_id = user.get("id")
1047
+ text = (msg.get("text") or "").strip()
1048
+ log.info(f"💬 Message from {user_id}: {text[:50]!r}")
1049
+
1050
+ if not text or user_id is None:
1051
+ return
1052
+
1053
+ # ── Ban check ──
1054
+ if _is_banned(user_id):
1055
+ with _state_lock:
1056
+ reason = BAN_REASONS.get(user_id) or "no reason given"
1057
+ await send(chat_id, f"🚫 <b>You are banned.</b>\n\nReason: {esc(reason)}")
1058
+ _log_activity(user, "banned_hit", text[:40], "blocked", reason)
1059
+ return
1060
+
1061
+ # ── Admin token input ──
1062
+ state = _admin_state_get(user_id)
1063
+ if state == "await_admin_token" and not _is_admin_session(user_id):
1064
+ _admin_state_clear(user_id)
1065
+ if ADMIN_TOKEN and text == ADMIN_TOKEN:
1066
+ _grant_admin(user_id)
1067
+ _log_activity(user, "admin_login", "***", "granted", "session started")
1068
+ await send(chat_id, "✅ <b>Admin access granted</b>",
1069
+ reply_markup=admin_menu_kb())
1070
+ await send(chat_id, render_admin_menu())
1071
+ else:
1072
+ _log_activity(user, "admin_login", "***", "denied", "invalid token")
1073
+ await send(chat_id, "❌ <b>Invalid token.</b>\nTry /admin again.")
1074
+ return
1075
+
1076
+ # ── Admin input capture ──
1077
+ if state and _is_admin_session(user_id):
1078
+ _admin_state_clear(user_id)
1079
+
1080
+ if state == "await_ban_id":
1081
+ parts = text.split(None, 1)
1082
+ target = parts[0].lstrip("@")
1083
+ reason = parts[1] if len(parts) > 1 else ""
1084
+ try:
1085
+ tid = int(target)
1086
+ except ValueError:
1087
+ await send(chat_id, "❗ Invalid user ID.")
1088
+ return
1089
+ _ban_user(tid, reason)
1090
+ _log_activity(user, "admin", f"/ban {tid}", "banned", reason or "no reason")
1091
+ await send(chat_id, f"🚫 Banned <code>{tid}</code> — {esc(reason or 'no reason')}")
1092
+ return
1093
+
1094
+ if state == "await_unban_id":
1095
+ try:
1096
+ tid = int(text.strip())
1097
+ except ValueError:
1098
+ await send(chat_id, "❗ Invalid user ID.")
1099
+ return
1100
+ ok = _unban_user(tid)
1101
+ _log_activity(user, "admin", f"/unban {tid}", "unbanned")
1102
+ await send(chat_id, "✅ Unbanned." if ok else "ℹ️ User was not banned.")
1103
+ return
1104
+
1105
+ if state == "await_broadcast":
1106
+ asyncio.create_task(_run_broadcast(chat_id, text))
1107
+ _log_activity(user, "admin", "/broadcast", "sending", f"{len(text)} chars")
1108
+ return
1109
+
1110
+ if state == "await_logphone":
1111
+ phone, hint = normalize_phone(text)
1112
+ if not phone:
1113
+ await send(chat_id, f"❗ {hint}")
1114
+ return
1115
+ entries = [e for e in ACTIVITY_LOG
1116
+ if e["action"] == "search" and e["input"] == phone]
1117
+ entries.reverse()
1118
+ if not entries:
1119
+ await send(chat_id, f"🔎 No searches logged for <code>{phone}</code>.")
1120
+ return
1121
+ lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> ({len(entries)} total)\n"]
1122
+ for e in entries[:20]:
1123
+ uname = e.get("username"); first = e.get("first_name")
1124
+ nm = f"@{uname}" if uname else (first or "(anon)")
1125
+ lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · <code>{e['user_id']}</code>")
1126
+ await send(chat_id, "\n".join(lines))
1127
+ _log_activity(user, "admin", f"logphone {phone}", "text")
1128
+ return
1129
+
1130
+ if state == "await_maint_reason":
1131
+ _set_maintenance(True, text[:100])
1132
+ _log_activity(user, "admin", "maintenance on", "state", text[:100])
1133
+ await send(chat_id, f"🔴 <b>Maintenance ON</b>\nReason: {esc(text[:100])}")
1134
+ return
1135
+
1136
+ # ── Maintenance gate ──
1137
+ m_on, m_reason = _get_maintenance()
1138
+ if m_on and not _is_admin_session(user_id):
1139
+ if text in ("/start", "/help", "/status", "/info", "/myid"):
1140
+ pass
1141
+ else:
1142
+ await send(chat_id, f"🛠️ <b>Bot under maintenance</b>\n\n{esc(m_reason)}")
1143
+ _log_activity(user, "maintenance_block", text[:40], "blocked")
1144
+ return
1145
+
1146
+ # ── Force-join gate ──
1147
+ if not await check_force_join(chat_id, user, text):
1148
+ return
1149
+
1150
+ # ── /admin ──
1151
+ if text == "/admin":
1152
+ if not ADMIN_TOKEN:
1153
+ await send(chat_id, "⚠️ Admin panel is not configured.")
1154
+ return
1155
+ if _is_admin_session(user_id):
1156
+ _log_activity(user, "admin", "/admin", "menu")
1157
+ await send(chat_id, render_admin_menu(), reply_markup=admin_menu_kb())
1158
+ else:
1159
+ _admin_state_set(user_id, "await_admin_token")
1160
+ await send(chat_id, "🔐 <b>Admin access required</b>\n\n"
1161
+ "Send the admin token to continue. "
1162
+ "It expires in 3 minutes.")
1163
+ return
1164
+
1165
+ # ── /logout ──
1166
+ if text == "/logout":
1167
+ if _is_admin_session(user_id):
1168
+ _revoke_admin(user_id)
1169
+ _log_activity(user, "admin_logout", "/logout", "revoked")
1170
+ await send(chat_id, "✅ Admin session ended.")
1171
+ else:
1172
+ await send(chat_id, "You are not logged in as admin.")
1173
+ return
1174
+
1175
+ # ── Admin commands ──
1176
+ if text.startswith("/") and _is_admin_session(user_id):
1177
+ await _handle_admin_command(chat_id, user, text, user_id)
1178
+ return
1179
+
1180
+ # ── /status ──
1181
+ if text == "/status":
1182
+ uptime = (time.time() - STATS["started"]) / 60
1183
+ m_on, _ = _get_maintenance()
1184
+ _log_activity(user, "status", "/status", "text")
1185
+ await send(chat_id, (
1186
+ f"<b>📊 Bot Status</b> — v{VERSION}\n\n"
1187
+ f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n"
1188
+ f"🔌 DuckDB main: <code>{con_ready.is_set()}</code>\n"
1189
+ f"🔥 Cache warmed: <code>{warmed.is_set()}</code>\n"
1190
+ f"📂 HiTeck: <code>{len(__import__('config').PARQUET_URLS)}</code> · "
1191
+ f"Flipkart: <code>{len(__import__('config').FLIPKART_URLS)}</code>\n"
1192
+ f"🔗 APIs: <code>850CR + IndData + ASUR×4</code>\n"
1193
+ f"🛠️ Maintenance: <code>{m_on}</code>\n"
1194
+ f"📥 Backup: <code>{BACKUP_ENABLED}</code>\n"
1195
+ f"🔍 Queries: <code>{STATS['queries']}</code>\n"
1196
+ f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n"
1197
+ f"❌ Errors: <code>{STATS['errors']}</code>"
1198
+ ))
1199
+ return
1200
+
1201
+ # ── /info ──
1202
+ if text == "/info":
1203
+ uptime = (time.time() - STATS["started"]) / 60
1204
+ s = _get_stats()
1205
+ _log_activity(user, "info", "/info", "text")
1206
+ await send(chat_id, (
1207
+ f"ℹ️ <b>About This Bot</b>\n"
1208
+ "━━━━━━━━━━━━━━━━━━\n"
1209
+ f"🤖 Version: <code>{VERSION}</code>\n"
1210
+ f"📊 Sources: HiTeck (7) + Flipkart (1) + 2 APIs + ASUR×4\n"
1211
+ f"👥 Unique users: <code>{s['unique_users']}</code>\n"
1212
+ f"🔍 Searches: <code>{s['total_searches']}</code>\n"
1213
+ f"⏱️ Avg latency (today): <code>{_avg_latency_today():.1f}s</code>\n"
1214
+ f"🕒 Uptime: <code>{uptime:.0f} min</code>\n"
1215
+ "━━━━━━━━━━━━━━━━━━\n"
1216
+ "Built with ❤️ for fast, private lookups."
1217
+ ))
1218
+ return
1219
+
1220
+ # ── /history ──
1221
+ if text == "/history":
1222
+ with _activity_lock:
1223
+ h = list(USER_HISTORY.get(user_id, []))
1224
+ _log_activity(user, "history", "/history", "text")
1225
+ if not h:
1226
+ await send(chat_id, "📭 <b>No history yet</b>\n\nSearch a number to start.")
1227
+ return
1228
+ rows = []
1229
+ for i, item in enumerate(h, 1):
1230
+ rows.append([{
1231
+ "text": f"{i}. {item['phone']} ({item['count']} res)",
1232
+ "callback_data": f"h:{item['phone']}"
1233
+ }])
1234
+ await send(chat_id,
1235
+ "🕘 <b>Your last searches</b>\n\nTap to search again:",
1236
+ reply_markup={"inline_keyboard": rows})
1237
+ return
1238
+
1239
+ # ── /myid ──
1240
+ if text == "/myid":
1241
+ _log_activity(user, "myid", "/myid", "text")
1242
+ await send(chat_id, f"🆔 <b>Your Telegram ID</b>\n<code>{user_id}</code>")
1243
+ return
1244
+
1245
+ # ── /whoami ──
1246
+ if text == "/whoami":
1247
+ quota_ok, remaining = check_quota(user_id)
1248
+ banned = _is_banned(user_id)
1249
+ admin = _is_admin_session(user_id)
1250
+ owner = user_id in OWNER_IDS
1251
+ with _activity_lock:
1252
+ info = UNIQUE_USERS.get(user_id, {})
1253
+ first_seen = info.get("first_seen")
1254
+ count = info.get("count", 0)
1255
+ lines = ["🆔 <b>Your Info</b>", f"• ID: <code>{user_id}</code>"]
1256
+ if user.get("username"):
1257
+ lines.append(f"• Username: @{esc(user['username'])}")
1258
+ if user.get("first_name"):
1259
+ lines.append(f"• Name: {esc(user['first_name'])}")
1260
+ if first_seen:
1261
+ lines.append(f"• First seen: {time.strftime('%Y-%m-%d %H:%M', time.gmtime(first_seen))}")
1262
+ lines.append(f"• Total requests: {count}")
1263
+ if _is_unlimited(user_id):
1264
+ lines.append("• Daily quota: ∞")
1265
+ else:
1266
+ lines.append(f"• Daily quota: {DAILY_QUOTA - remaining}/{DAILY_QUOTA} remaining")
1267
+ if owner:
1268
+ lines.append("• Status: 👑 Owner")
1269
+ elif admin:
1270
+ lines.append("• Status: 🛡️ Admin")
1271
+ if banned:
1272
+ with _state_lock:
1273
+ reason = BAN_REASONS.get(user_id) or "no reason"
1274
+ lines.append(f"• Status: 🚫 Banned ({esc(reason)})")
1275
+ _log_activity(user, "whoami", "/whoami", "text")
1276
+ await send(chat_id, "\n".join(lines))
1277
+ return
1278
+
1279
+ # ── /daily ──
1280
+ if text == "/daily":
1281
+ if _is_unlimited(user_id):
1282
+ await send(chat_id, "📊 <b>Daily Quota</b>\n\n♾️ Unlimited (admin/owner)")
1283
+ else:
1284
+ _, remaining = check_quota(user_id)
1285
+ used = DAILY_QUOTA - remaining
1286
+ await send(chat_id,
1287
+ f"📊 <b>Daily Quota</b>\n\n"
1288
+ f"Used: <code>{used}</code>/<code>{DAILY_QUOTA}</code>\n"
1289
+ f"Remaining: <code>{remaining}</code>")
1290
+ _log_activity(user, "daily", "/daily", "text")
1291
+ return
1292
+
1293
+ # ── /ping ──
1294
+ if text == "/ping":
1295
+ uptime = (time.time() - STATS["started"]) / 60
1296
+ _log_activity(user, "ping", "/ping", "text")
1297
+ await send(chat_id,
1298
+ f"🏓 <b>Pong!</b>\n\n"
1299
+ f"⏱️ Uptime: {uptime:.1f} min\n"
1300
+ f"🕐 {time.strftime('%H:%M:%S', time.gmtime())} UTC")
1301
+ return
1302
+
1303
+ # ── /feedback ──
1304
+ if text.startswith("/feedback"):
1305
+ fb = text[len("/feedback"):].strip()
1306
+ if not fb:
1307
+ await send(chat_id, "❌ Usage: <code>/feedback your message</code>")
1308
+ return
1309
+ if BACKUP_CHANNEL_ID:
1310
+ await send(
1311
+ BACKUP_CHANNEL_ID,
1312
+ f"💬 <b>Feedback</b>\n"
1313
+ f"👤 {_short_user(user_id, user)}\n\n"
1314
+ f"{esc(fb[:3000])}",
1315
+ )
1316
+ await send(chat_id, "✅ Thanks for your feedback!")
1317
+ _log_activity(user, "feedback", fb[:60], "text")
1318
+ return
1319
+
1320
+ # ── /report ──
1321
+ if text.startswith("/report"):
1322
+ arg = text[len("/report"):].strip()
1323
+ if not arg:
1324
+ await send(chat_id, "❌ Usage: <code>/report 9876543210 [reason]</code>")
1325
+ return
1326
+ parts = arg.split(None, 1)
1327
+ phone, hint = normalize_phone(parts[0])
1328
+ if not phone:
1329
+ await send(chat_id, f"❌ Invalid number: {hint}")
1330
+ return
1331
+ reason = parts[1] if len(parts) > 1 else ""
1332
+ if BACKUP_CHANNEL_ID:
1333
+ await send(
1334
+ BACKUP_CHANNEL_ID,
1335
+ f"🚩 <b>Report</b>\n"
1336
+ f"👤 {_short_user(user_id, user)}\n"
1337
+ f"📱 <code>{phone}</code>\n"
1338
+ f"📝 {esc(reason or '(no reason given)')}",
1339
+ )
1340
+ await send(chat_id, f"✅ Report submitted for <code>{phone}</code>.")
1341
+ _log_activity(user, "report", phone, "text", reason[:80])
1342
+ return
1343
+
1344
+ # ── /start /help ──
1345
+ if text in ("/start", "/help"):
1346
+ _log_activity(user, "start", text, "text")
1347
+ await send(chat_id, WELCOME_TEMPLATE.format(v=VERSION))
1348
+ if not warmed.is_set():
1349
+ threading.Thread(target=warm_phone_cache, daemon=True).start()
1350
+ return
1351
+
1352
+ # ── Batch search ──
1353
+ if "," in text:
1354
+ parts = [p.strip() for p in text.split(",") if p.strip()]
1355
+ if len(parts) < 2:
1356
+ await send(chat_id,
1357
+ "❌ <b>Batch format</b>\n\n"
1358
+ "Example: <code>9876543210,9876543211</code>")
1359
+ return
1360
+ if len(parts) > BATCH_MAX:
1361
+ await send(chat_id, f"❌ Max {BATCH_MAX} numbers per batch.")
1362
+ return
1363
+ phones = []
1364
+ for p in parts:
1365
+ ph, hint = normalize_phone(p)
1366
+ if not ph:
1367
+ await send(chat_id, f"❌ Invalid: <code>{esc(p)}</code> — {hint}")
1368
+ return
1369
+ phones.append(ph)
1370
+ await _handle_batch(chat_id, user, phones)
1371
+ return
1372
+
1373
+ # ── Single search ──
1374
+ phone, hint = normalize_phone(text)
1375
+ if not phone:
1376
+ _log_activity(user, "invalid", text, "error", hint)
1377
+ await send(chat_id,
1378
+ "❌ <b>Invalid input</b>\n\n"
1379
+ "Send a 10-digit number.\n"
1380
+ "Also accepts: <code>+91 98765 43210</code>, "
1381
+ "<code>09876543210</code>, <code>9876543210,9876543211</code>")
1382
+ return
1383
+
1384
+ # Flood check (only for searches)
1385
+ remaining_mute = check_flood(user_id)
1386
+ if remaining_mute:
1387
+ await send(chat_id, f"⏳ Slow down! Try again in {remaining_mute}s.")
1388
+ _log_activity(user, "flood_muted", phone, "blocked", f"{remaining_mute}s")
1389
+ return
1390
+
1391
+ # Cooldown
1392
+ now = time.time()
1393
+ if now - USER_LAST.get(user_id, 0) < USER_COOLDOWN:
1394
+ wait = USER_COOLDOWN - (now - USER_LAST.get(user_id, 0))
1395
+ _log_activity(user, "cooldown", phone, "text", f"wait {wait:.0f}s")
1396
+ await send(chat_id, f"⏳ Wait {wait:.0f}s before next search.")
1397
+ return
1398
+ USER_LAST[user_id] = now
1399
+
1400
+ # Quota
1401
+ ok, remaining = check_quota(user_id)
1402
+ if not ok:
1403
+ await send(chat_id,
1404
+ f"❌ <b>Daily quota reached</b>\n\n"
1405
+ f"You've used all {DAILY_QUOTA} queries for today.\n"
1406
+ f"Resets at 00:00 UTC.")
1407
+ _log_activity(user, "quota_exceeded", phone, "blocked")
1408
+ return
1409
+ incr_quota(user_id)
1410
+
1411
+ # Hint if phone was normalized
1412
+ if text.strip() != phone and not text.strip().isdigit():
1413
+ await send(chat_id, f"ℹ�� Interpreted as <code>{phone}</code>")
1414
+
1415
+ if not warmed.is_set():
1416
+ threading.Thread(target=warm_phone_cache, daemon=True).start()
1417
+
1418
+ placeholder = await send(
1419
+ chat_id,
1420
+ f"🔍 <b>Searching…</b>\n\n📱 <code>{esc(phone)}</code>\n\n"
1421
+ f"<i>Fast results appear instantly; database enrich follows.</i>",
1422
+ )
1423
+ if placeholder is None:
1424
+ return
1425
+
1426
+ try:
1427
+ await _do_progressive_search(phone, chat_id, placeholder, user)
1428
+ except asyncio.TimeoutError:
1429
+ STATS["timeouts"] += 1
1430
+ _log_activity(user, "search", phone, "timeout", "progressive timeout")
1431
+ await edit(chat_id, placeholder, "⏱️ Timed out. Try again.")
1432
+ except Exception as e:
1433
+ STATS["errors"] += 1
1434
+ log.error(f"❌ progressive search error: {e!r}\n{traceback.format_exc()}")
1435
+ _log_activity(user, "search", phone, "error", str(e)[:100])
1436
+ await edit(chat_id, placeholder, f"❌ Error: <code>{esc(str(e)[:200])}</code>")
1437
+
1438
+ except Exception as e:
1439
+ log.error(f"❌ handle_message fatal: {e!r}\n{traceback.format_exc()}")
1440
+
1441
+
1442
+ # ══════════════════════════════════════════════════════════════════
1443
+ # 17. ADMIN COMMANDS
1444
+ # ══════════════════════════════════════════════════════════════════
1445
+ async def _handle_admin_command(chat_id: int, user: dict, text: str, user_id: int):
1446
+ cmd = text.split()[0].lower()
1447
+ args = text.split()[1:]
1448
+
1449
+ if cmd == "/live":
1450
+ _log_activity(user, "admin", "/live", "text")
1451
+ await send(chat_id, render_live()); return
1452
+ if cmd == "/stats":
1453
+ _log_activity(user, "admin", "/stats", "text")
1454
+ await send(chat_id, render_stats()); return
1455
+ if cmd == "/users":
1456
+ _log_activity(user, "admin", "/users", "text")
1457
+ t, kb = render_users(0)
1458
+ await send(chat_id, t, reply_markup=kb); return
1459
+ if cmd == "/top":
1460
+ _log_activity(user, "admin", "/top", "text")
1461
+ await send(chat_id, render_top()); return
1462
+ if cmd == "/log":
1463
+ entries = list(ACTIVITY_LOG); entries.reverse()
1464
+ label = ""
1465
+ if args:
1466
+ try:
1467
+ tid = int(args[0])
1468
+ entries = [e for e in entries if e["user_id"] == tid]
1469
+ label = f" (user {tid})"
1470
+ except ValueError:
1471
+ target = args[0].lstrip("@").lower()
1472
+ entries = [e for e in entries
1473
+ if (e.get("username") or "").lower() == target]
1474
+ label = f" (@{target})"
1475
+ _log_activity(user, "admin", text, "log_view")
1476
+ t, kb = render_log(entries, 0)
1477
+ if label:
1478
+ t = t.replace("<b>Activity Log</b>", f"<b>Activity Log{label}</b>", 1)
1479
+ await send(chat_id, t, reply_markup=kb); return
1480
+ if cmd == "/banned":
1481
+ _log_activity(user, "admin", "/banned", "text")
1482
+ await send(chat_id, render_banned()); return
1483
+ if cmd == "/ban":
1484
+ if not args:
1485
+ _admin_state_set(user_id, "await_ban_id")
1486
+ await send(chat_id, "Send user ID (and optional reason):")
1487
+ return
1488
+ tid_s = args[0].lstrip("@")
1489
+ reason = " ".join(args[1:]) if len(args) > 1 else ""
1490
+ try:
1491
+ tid = int(tid_s)
1492
+ except ValueError:
1493
+ await send(chat_id, "❗ Invalid user ID."); return
1494
+ _ban_user(tid, reason)
1495
+ _log_activity(user, "admin", f"/ban {tid}", "banned", reason or "no reason")
1496
+ await send(chat_id, f"🚫 Banned <code>{tid}</code> — {esc(reason or 'no reason')}")
1497
+ return
1498
+ if cmd == "/unban":
1499
+ if not args:
1500
+ _admin_state_set(user_id, "await_unban_id")
1501
+ await send(chat_id, "Send user ID to unban:")
1502
+ return
1503
+ try:
1504
+ tid = int(args[0])
1505
+ except ValueError:
1506
+ await send(chat_id, "❗ Invalid user ID."); return
1507
+ ok = _unban_user(tid)
1508
+ _log_activity(user, "admin", f"/unban {tid}", "unbanned")
1509
+ await send(chat_id, "✅ Unbanned." if ok else "ℹ️ User was not banned.")
1510
+ return
1511
+ if cmd == "/broadcast":
1512
+ if not args:
1513
+ _admin_state_set(user_id, "await_broadcast")
1514
+ await send(chat_id, "Send the message to broadcast to all users:")
1515
+ return
1516
+ await send(chat_id, "ℹ️ Use /broadcast with no args, then send the message.")
1517
+ return
1518
+ if cmd == "/export":
1519
+ _log_activity(user, "admin", "/export", "file")
1520
+ await _send_log_export(chat_id); return
1521
+ if cmd == "/logphone":
1522
+ if not args:
1523
+ _admin_state_set(user_id, "await_logphone")
1524
+ await send(chat_id, "Send a 10-digit number to search the log:")
1525
+ return
1526
+ phone, hint = normalize_phone(args[0])
1527
+ if not phone:
1528
+ await send(chat_id, f"❗ {hint}"); return
1529
+ entries = [e for e in ACTIVITY_LOG
1530
+ if e["action"] == "search" and e["input"] == phone]
1531
+ entries.reverse()
1532
+ if not entries:
1533
+ await send(chat_id, f"🔎 No searches for <code>{phone}</code>."); return
1534
+ lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> ({len(entries)})\n"]
1535
+ for e in entries[:20]:
1536
+ uname = e.get("username"); first = e.get("first_name")
1537
+ nm = f"@{uname}" if uname else (first or "(anon)")
1538
+ lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · <code>{e['user_id']}</code>")
1539
+ await send(chat_id, "\n".join(lines)); return
1540
+ if cmd == "/maintenance":
1541
+ if not args:
1542
+ m_on, m_reason = _get_maintenance()
1543
+ st = "ON" if m_on else "OFF"
1544
+ await send(chat_id, f"🛠️ Maintenance: <b>{st}</b>"
1545
+ + (f"\nReason: {esc(m_reason)}" if m_on else ""))
1546
+ return
1547
+ mode = args[0].lower()
1548
+ if mode == "on":
1549
+ reason = " ".join(args[1:]) if len(args) > 1 else ""
1550
+ if reason:
1551
+ _set_maintenance(True, reason)
1552
+ _log_activity(user, "admin", "maintenance on", "state", reason)
1553
+ await send(chat_id, f"🔴 Maintenance ON — {esc(reason)}")
1554
+ else:
1555
+ _admin_state_set(user_id, "await_maint_reason")
1556
+ await send(chat_id, "Send a short reason for maintenance:")
1557
+ return
1558
+ elif mode == "off":
1559
+ _set_maintenance(False)
1560
+ _log_activity(user, "admin", "maintenance off", "state")
1561
+ await send(chat_id, "🟢 Maintenance OFF"); return
1562
+ await send(chat_id, "Usage: /maintenance on|off [reason]"); return
1563
+ if cmd == "/apistatus":
1564
+ await send(chat_id, "🔍 Pinging APIs…")
1565
+ h = await check_api_health()
1566
+ lines = ["🔧 <b>API Status</b>\n"]
1567
+ for name, st in h.items():
1568
+ icon = "✅" if st.get("ok") else "❌"
1569
+ lines.append(f"{icon} <code>{name}</code> — {st.get('latency_ms', '?')}ms")
1570
+ await send(chat_id, "\n".join(lines))
1571
+ _log_activity(user, "admin", "/apistatus", "text")
1572
+ return
1573
+ if cmd == "/backup":
1574
+ global BACKUP_ENABLED
1575
+ if not args:
1576
+ st = "ON" if BACKUP_ENABLED else "OFF"
1577
+ await send(chat_id, f"📥 Backup forwarding: <b>{st}</b>")
1578
+ return
1579
+ mode = args[0].lower()
1580
+ if mode == "on":
1581
+ BACKUP_ENABLED = True
1582
+ _log_activity(user, "admin", "backup on", "state")
1583
+ await send(chat_id, "✅ Backup forwarding ON")
1584
+ elif mode == "off":
1585
+ BACKUP_ENABLED = False
1586
+ _log_activity(user, "admin", "backup off", "state")
1587
+ await send(chat_id, "🚫 Backup forwarding OFF")
1588
+ else:
1589
+ await send(chat_id, "Usage: /backup on|off")
1590
+ return
1591
+ if cmd == "/reload":
1592
+ with _member_lock: _member_cache.clear()
1593
+ with _pending_lock: _pending_query.clear()
1594
+ with _seen_updates_lock: _seen_updates.clear()
1595
+ SEARCH_CACHE.clear()
1596
+ _log_activity(user, "admin", "/reload", "state")
1597
+ await send(chat_id, "✅ Caches cleared")
1598
+ return
1599
+ if cmd == "/cancel":
1600
+ _admin_state_clear(user_id)
1601
+ _log_activity(user, "admin", "/cancel", "state")
1602
+ await send(chat_id, "✅ Pending prompt cancelled")
1603
+ return
1604
+ # Unknown admin command → show menu
1605
+ await send(chat_id, render_admin_menu(), reply_markup=admin_menu_kb())
1606
+
1607
+
1608
+ # ══════════════════════════════════════════════════════════════════
1609
+ # 18. BATCH
1610
+ # ══════════════════════════════════════════════════════════════════
1611
+ async def _handle_batch(chat_id, user, phones):
1612
+ await send(chat_id, f"🔍 <b>Batch search</b> — {len(phones)} number(s)…")
1613
+ t0 = time.time()
1614
+ tasks = [asyncio.create_task(_search_quiet(p)) for p in phones]
1615
+ results = await asyncio.gather(*tasks, return_exceptions=True)
1616
+ total_elapsed = time.time() - t0
1617
+
1618
+ lines = [f"📊 <b>Batch results</b> ({len(phones)} numbers) — {total_elapsed:.1f}s\n"]
1619
+ for phone, res in zip(phones, results):
1620
+ if isinstance(res, Exception):
1621
+ lines.append(f"❌ <code>{phone}</code> — error: {esc(str(res)[:60])}")
1622
+ else:
1623
+ n, ok = res
1624
+ lines.append(f"{'✅' if ok else '❌'} <code>{phone}</code> — "
1625
+ f"{n} record(s)" if ok else f"❌ <code>{phone}</code> — no results")
1626
+
1627
+ kb_rows = [[{"text": f"View {p}", "callback_data": f"h:{p}"}] for p in phones]
1628
+ _log_activity(user, "batch_search", ",".join(phones), "text",
1629
+ f"{len(phones)} nums in {total_elapsed:.1f}s")
1630
+ await send(chat_id, "\n".join(lines),
1631
+ reply_markup={"inline_keyboard": kb_rows})
1632
+
1633
+
1634
+ # ══════════════════════════════════════════════════════════════════
1635
+ # 19. BROADCAST
1636
+ # ══════════════════════════════════════════════════════════════════
1637
+ async def _run_broadcast(admin_chat_id: int, message: str):
1638
+ with _activity_lock:
1639
+ recipients = list(UNIQUE_USERS.keys())
1640
+ if not recipients:
1641
+ await send(admin_chat_id, "📭 No users to broadcast to.")
1642
+ return
1643
+ message = message[:BROADCAST_MAX_LEN]
1644
+ await send(admin_chat_id, f"📢 Broadcasting to <b>{len(recipients)}</b> users…")
1645
+ sent = failed = 0
1646
+ for uid in recipients:
1647
+ if _is_banned(uid):
1648
+ continue
1649
+ try:
1650
+ res = await tg("sendMessage", {
1651
+ "chat_id": uid,
1652
+ "text": f"📢 <b>Announcement</b>\n\n{message}",
1653
+ "parse_mode": "HTML",
1654
+ "disable_web_page_preview": True,
1655
+ }, timeout=15)
1656
+ if res.get("ok"):
1657
+ sent += 1
1658
+ else:
1659
+ failed += 1
1660
+ except Exception:
1661
+ failed += 1
1662
+ await asyncio.sleep(BROADCAST_DELAY)
1663
+ await send(admin_chat_id,
1664
+ f"✅ <b>Broadcast complete</b>\n\n"
1665
+ f"Sent: <code>{sent}</code>\n"
1666
+ f"Failed: <code>{failed}</code>")
1667
+ _log_activity({"id": 0}, "admin", "broadcast", "done",
1668
+ f"sent={sent} failed={failed}")
1669
+
1670
+
1671
+ # ══════════════════════════════════════════════════════════════════
1672
+ # 20. LOG EXPORT
1673
+ # ══════════════════════════════════════════════════════════════════
1674
+ async def _send_log_export(chat_id: int):
1675
+ entries = list(ACTIVITY_LOG)
1676
+ if not entries:
1677
+ await send(chat_id, "📭 No activity to export.")
1678
+ return
1679
+ buf = io.StringIO()
1680
+ w = csv.writer(buf)
1681
+ w.writerow(["timestamp", "user_id", "username", "first_name",
1682
+ "action", "input", "reply_type", "summary", "elapsed_ms", "source"])
1683
+ for e in entries:
1684
+ w.writerow([
1685
+ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["ts"])),
1686
+ e["user_id"], e.get("username") or "", e.get("first_name") or "",
1687
+ e["action"], e.get("input", ""), e.get("reply_type", ""),
1688
+ e.get("summary", ""), e.get("elapsed_ms", 0), e.get("source", ""),
1689
+ ])
1690
+ csv_bytes = buf.getvalue().encode("utf-8")
1691
+ ts = time.strftime("%Y%m%d_%H%M%S")
1692
+ await send_document(chat_id, f"activity_log_{ts}.csv", csv_bytes,
1693
+ caption=f"📥 Activity log — {len(entries)} entries")
1694
+
1695
+
1696
+ # ══════════════════════════════════════════════════════════════════
1697
+ # 21. CALLBACK HANDLER
1698
+ # ══════════════════════════════════════════════════════════════════
1699
+ async def handle_callback(cb: dict):
1700
+ try:
1701
+ data = cb.get("data", "")
1702
+ cb_id = cb["id"]
1703
+ msg = cb.get("message") or {}
1704
+ chat_id = msg.get("chat", {}).get("id")
1705
+ message_id = msg.get("message_id")
1706
+ user = cb.get("from") or {}
1707
+ user_id = user.get("id")
1708
+
1709
+ if not chat_id or not message_id:
1710
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1711
+ return
1712
+
1713
+ if _is_banned(user_id):
1714
+ await tg("answerCallbackQuery", {
1715
+ "callback_query_id": cb_id, "text": "🚫 You are banned.",
1716
+ "show_alert": True,
1717
+ }); return
1718
+
1719
+ # ── Force-join re-check ──
1720
+ if data == "join:check":
1721
+ with _member_lock:
1722
+ _member_cache.pop(user_id, None)
1723
+ ok = await _is_channel_member(user_id)
1724
+ if not ok:
1725
+ await tg("answerCallbackQuery", {
1726
+ "callback_query_id": cb_id,
1727
+ "text": "You haven't joined yet. Please join first.",
1728
+ "show_alert": True,
1729
+ })
1730
+ return
1731
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id,
1732
+ "text": "✅ Verified!"})
1733
+ # Delete the join prompt
1734
+ try:
1735
+ await tg("deleteMessage", {"chat_id": chat_id, "message_id": message_id})
1736
+ except Exception:
1737
+ pass
1738
+ # Replay pending query
1739
+ with _pending_lock:
1740
+ pending = _pending_query.pop(user_id, None)
1741
+ if pending:
1742
+ text, _, ts = pending
1743
+ if time.time() - ts < PENDING_QUERY_TTL:
1744
+ fake_msg = {"chat": {"id": chat_id}, "from": user, "text": text}
1745
+ await handle_message(fake_msg)
1746
+ _log_activity(user, "join_verified", text[:40], "replay")
1747
+ return
1748
+ await send(chat_id, "✅ <b>Thanks for joining!</b>\n\n"
1749
+ "Send a 10-digit mobile number to start.")
1750
+ _log_activity(user, "join_verified", "-", "ok")
1751
+ return
1752
+
1753
+ # ── Admin callbacks ──
1754
+ if data.startswith("adm:"):
1755
+ if not _is_admin_session(user_id):
1756
+ await tg("answerCallbackQuery", {
1757
+ "callback_query_id": cb_id,
1758
+ "text": "Admin session expired — send /admin again.",
1759
+ "show_alert": True,
1760
+ }); return
1761
+ parts = data.split(":")
1762
+ action = parts[1] if len(parts) > 1 else "menu"
1763
+
1764
+ global BACKUP_ENABLED
1765
+ if action == "menu":
1766
+ await edit(chat_id, message_id, render_admin_menu(), reply_markup=admin_menu_kb())
1767
+ elif action == "live":
1768
+ await edit(chat_id, message_id, render_live(), reply_markup=admin_menu_kb())
1769
+ elif action == "stats":
1770
+ await edit(chat_id, message_id, render_stats(), reply_markup=admin_menu_kb())
1771
+ elif action == "top":
1772
+ await edit(chat_id, message_id, render_top(), reply_markup=admin_menu_kb())
1773
+ elif action == "banned":
1774
+ await edit(chat_id, message_id, render_banned(), reply_markup=admin_menu_kb())
1775
+ elif action == "log":
1776
+ page = int(parts[2]) if len(parts) > 2 else 0
1777
+ entries = list(ACTIVITY_LOG); entries.reverse()
1778
+ t, kb = render_log(entries, page)
1779
+ await edit(chat_id, message_id, t, reply_markup=kb)
1780
+ elif action == "users":
1781
+ page = int(parts[2]) if len(parts) > 2 else 0
1782
+ t, kb = render_users(page)
1783
+ await edit(chat_id, message_id, t, reply_markup=kb)
1784
+ elif action == "ban":
1785
+ _admin_state_set(user_id, "await_ban_id")
1786
+ await edit(chat_id, message_id, "🚫 Send user ID (and optional reason):")
1787
+ elif action == "unban":
1788
+ _admin_state_set(user_id, "await_unban_id")
1789
+ await edit(chat_id, message_id, "✅ Send user ID to unban:")
1790
+ elif action == "broadcast":
1791
+ _admin_state_set(user_id, "await_broadcast")
1792
+ await edit(chat_id, message_id, "📢 Send the message to broadcast:")
1793
+ elif action == "export":
1794
+ await edit(chat_id, message_id, "📥 Generating export…",
1795
+ reply_markup=admin_menu_kb())
1796
+ await _send_log_export(chat_id)
1797
+ elif action == "logphone":
1798
+ _admin_state_set(user_id, "await_logphone")
1799
+ await edit(chat_id, message_id, "🔎 Send a 10-digit number:")
1800
+ elif action == "maint":
1801
+ m_on, _ = _get_maintenance()
1802
+ if m_on:
1803
+ _set_maintenance(False)
1804
+ await edit(chat_id, message_id, "🟢 Maintenance OFF",
1805
+ reply_markup=admin_menu_kb())
1806
+ else:
1807
+ _admin_state_set(user_id, "await_maint_reason")
1808
+ await edit(chat_id, message_id, "Send a short maintenance reason:")
1809
+ elif action == "apistatus":
1810
+ await edit(chat_id, message_id, "🔍 Pinging APIs…")
1811
+ h = await check_api_health()
1812
+ lines = ["🔧 <b>API Status</b>\n"]
1813
+ for name, st in h.items():
1814
+ icon = "✅" if st.get("ok") else "❌"
1815
+ lines.append(f"{icon} <code>{name}</code> — {st.get('latency_ms', '?')}ms")
1816
+ await edit(chat_id, message_id, "\n".join(lines),
1817
+ reply_markup=admin_menu_kb())
1818
+ elif action == "backuptoggle":
1819
+ BACKUP_ENABLED = not BACKUP_ENABLED
1820
+ await edit(chat_id, message_id, render_admin_menu(),
1821
+ reply_markup=admin_menu_kb())
1822
+ elif action == "noop":
1823
+ pass
1824
+
1825
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1826
+ _log_activity(user, "admin", data, "menu")
1827
+ return
1828
+
1829
+ # ── History re-run ──
1830
+ if data.startswith("h:"):
1831
+ phone = data.split(":", 1)[1]
1832
+ await tg("answerCallbackQuery", {
1833
+ "callback_query_id": cb_id,
1834
+ "text": f"Searching {phone}…",
1835
+ })
1836
+ fake_msg = {"chat": {"id": chat_id}, "from": user, "text": phone}
1837
+ await handle_message(fake_msg)
1838
+ return
1839
+
1840
+ # ── Copy page ──
1841
+ if data.startswith("c:"):
1842
+ try:
1843
+ _, sid, page_s = data.split(":")
1844
+ page = int(page_s)
1845
+ except Exception:
1846
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1847
+ return
1848
+ with SEARCH_CACHE_LOCK:
1849
+ entry = SEARCH_CACHE.get(sid)
1850
+ if not entry:
1851
+ await tg("answerCallbackQuery", {
1852
+ "callback_query_id": cb_id,
1853
+ "text": "Session expired.", "show_alert": True,
1854
+ }); return
1855
+ results = entry["results"]
1856
+ total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
1857
+ page = max(0, min(page, total_pages - 1))
1858
+ start = page * PAGE_SIZE
1859
+ chunk = results[start:start + PAGE_SIZE]
1860
+ text = "\n\n".join(_plain_record(start + i + 1, r)
1861
+ for i, r in enumerate(chunk))
1862
+ await send(chat_id, f"<b>📋 Copy text for page {page + 1}</b>\n\n"
1863
+ f"<pre>{esc(text[:3500])}</pre>")
1864
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id,
1865
+ "text": "Sent as copyable message"})
1866
+ _log_activity(user, "copy", entry["query"], "text")
1867
+ return
1868
+
1869
+ # ── Export ──
1870
+ if data.startswith("e:"):
1871
+ sid = data.split(":", 1)[1]
1872
+ with SEARCH_CACHE_LOCK:
1873
+ entry = SEARCH_CACHE.get(sid)
1874
+ if not entry:
1875
+ await tg("answerCallbackQuery", {
1876
+ "callback_query_id": cb_id,
1877
+ "text": "Session expired.", "show_alert": True,
1878
+ }); return
1879
+ phone = entry["query"]
1880
+ results = entry["results"]
1881
+ payload = json.dumps({
1882
+ "phone": phone,
1883
+ "records": results,
1884
+ "extras": entry.get("extras_block", ""),
1885
+ "source_note": entry.get("source_note", ""),
1886
+ "elapsed_s": entry.get("elapsed", 0),
1887
+ "asurpapa": entry.get("asur_data", {}),
1888
+ }, indent=2, ensure_ascii=False, default=str).encode("utf-8")
1889
+ await send_document(chat_id, f"results_{phone}.json", payload,
1890
+ caption=f"📥 {len(results)} record(s) for {phone}")
1891
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id,
1892
+ "text": "Sent as file"})
1893
+ _log_activity(user, "export", phone, "file", f"{len(results)} records")
1894
+ return
1895
+
1896
+ # ── Pagination ──
1897
+ if data == "noop" or not data.startswith("p:"):
1898
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1899
+ return
1900
+
1901
+ try:
1902
+ _, search_id, page_str = data.split(":")
1903
+ page = int(page_str)
1904
+ except Exception:
1905
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1906
+ return
1907
+
1908
+ with SEARCH_CACHE_LOCK:
1909
+ entry = SEARCH_CACHE.get(search_id)
1910
+ if not entry:
1911
+ await tg("answerCallbackQuery", {
1912
+ "callback_query_id": cb_id,
1913
+ "text": "Session expired — search again.", "show_alert": True,
1914
+ }); return
1915
+
1916
+ results = entry["results"]
1917
+ total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
1918
+ page = max(0, min(page, total_pages - 1))
1919
+
1920
+ await edit(
1921
+ chat_id, message_id,
1922
+ render_page(results, page, total_pages, entry["query"],
1923
+ entry["elapsed"], entry.get("source_note", ""),
1924
+ entry.get("extras_block", "")),
1925
+ reply_markup=page_keyboard(search_id, page, total_pages),
1926
+ )
1927
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1928
+ _log_activity(user, "paginate", entry["query"], "page",
1929
+ f"page {page + 1}/{total_pages}")
1930
+ except Exception as e:
1931
+ log.error(f"❌ handle_callback fatal: {e!r}\n{traceback.format_exc()}")
1932
+
1933
+
1934
+ # ══════════════════════════════════════════════════════════════════
1935
+ # 22. CACHE GC
1936
+ # ══════════════════════════════════════════════════════════════════
1937
+ def cache_gc():
1938
+ global PEAK_CONCURRENT
1939
+ while True:
1940
+ time.sleep(60)
1941
+ now = time.time()
1942
+
1943
+ # SEARCH_CACHE entries past TTL
1944
+ with SEARCH_CACHE_LOCK:
1945
+ dead = [k for k, v in SEARCH_CACHE.items()
1946
+ if now - v.get("ts", 0) > SEARCH_CACHE_TTL]
1947
+ for k in dead:
1948
+ SEARCH_CACHE.pop(k, None)
1949
+
1950
+ # Live-user tracking
1951
+ with _activity_lock:
1952
+ cutoff = now - LIVE_WINDOW
1953
+ for uid in list(ACTIVE_USERS.keys()):
1954
+ if ACTIVE_USERS[uid] < cutoff:
1955
+ del ACTIVE_USERS[uid]
1956
+ if len(ACTIVE_USERS) > PEAK_CONCURRENT:
1957
+ PEAK_CONCURRENT = len(ACTIVE_USERS)
1958
+
1959
+ # Membership cache
1960
+ with _member_lock:
1961
+ for uid, (_, ts) in list(_member_cache.items()):
1962
+ if now - ts > MEMBERSHIP_CACHE_TTL * 2:
1963
+ _member_cache.pop(uid, None)
1964
+
1965
+ # Pending queries
1966
+ with _pending_lock:
1967
+ for uid, (_, _, ts) in list(_pending_query.items()):
1968
+ if now - ts > PENDING_QUERY_TTL:
1969
+ _pending_query.pop(uid, None)
1970
+
1971
+ # Flood mutes
1972
+ with _flood_lock:
1973
+ for uid, until in list(_muted_until.items()):
1974
+ if until < now - 300:
1975
+ _muted_until.pop(uid, None)
1976
+
1977
+ # Update dedup
1978
+ with _seen_updates_lock:
1979
+ cutoff = now - 600
1980
+ for k in [k for k, v in _seen_updates.items() if v < cutoff]:
1981
+ del _seen_updates[k]
1982
+
1983
+ # Quota — drop entries from previous days
1984
+ today = _today_utc()
1985
+ with _quota_lock:
1986
+ for uid, (day, _) in list(_user_daily.items()):
1987
+ if day != today:
1988
+ _user_daily.pop(uid, None)
1989
+
1990
+
1991
+ # ══════════════════════════════════════════════════════════════════
1992
+ # 23. PUBLIC EXPORTS (used by app.py)
1993
+ # ══════════════════════════════════════════════════════════════════
1994
+ __all__ = [
1995
+ # Helpers / state
1996
+ "handle_message", "handle_callback",
1997
+ "is_duplicate_update", "cache_gc",
1998
+ # Telegram helpers
1999
+ "tg", "send", "edit", "send_document",
2000
+ # Admin
2001
+ "_is_admin_session",
2002
+ # Stats
2003
+ "_get_stats", "_get_live_users",
2004
+ # State refs for web panel
2005
+ "ACTIVITY_LOG", "UNIQUE_USERS", "ACTIVE_USERS",
2006
+ "BANNED_USERS", "BAN_REASONS",
2007
+ "SEARCH_CACHE", "STATS",
2008
+ "_ban_user", "_unban_user",
2009
+ "_set_maintenance", "_get_maintenance",
2010
+ "_revoke_admin",
2011
+ ]
2012
+
2013
+
2014
+ # ══════════════════════════════════════════════════════════════════
2015
+ # SELF-TEST
2016
+ # ══════════════════════════════════════════════════════════════════
2017
+ if __name__ == "__main__":
2018
+ logging.basicConfig(level=logging.INFO,
2019
+ format="%(asctime)s %(levelname)s %(message)s")
2020
+ print("── normalize_phone tests ──")
2021
+ for raw in ("9876543210", "+91 98765 43210", "09876543210", "12345"):
2022
+ print(f" {raw!r:22} → {normalize_phone(raw)}")
2023
+
2024
+ print("\n── quota tests ──")
2025
+ print(" unlimited check (uid=1):", check_quota(1))
2026
+ print(" regular check (uid=42):", check_quota(42))
2027
+
2028
+ print("\n── flood test (10 rapid msgs from uid=999) ──")
2029
+ for i in range(10):
2030
+ print(f" msg {i+1}: mute={check_flood(999)}")
2031
+
2032
+ print("\n── update dedup ──")
2033
+ print(" first 1001:", is_duplicate_update(1001))
2034
+ print(" repeat 1001:", is_duplicate_update(1001))
2035
+ print(" new 1002:", is_duplicate_update(1002))
2036
+
2037
+ print("\n── stats snapshot ──")
2038
+ print(" ", _get_stats())