Hfzune commited on
Commit
033ba70
·
verified ·
1 Parent(s): d0e59aa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +1391 -421
app.py CHANGED
@@ -1,486 +1,1456 @@
1
- # ══════════════════════════════════════════════════════════════════
2
- # app.py — Entry point (v2.0.1 — defensive boot)
3
- #
4
- # Fixes vs v2.0.0:
5
- # • _verify_bot_module() — fails fast with clear message if bot.py
6
- # is truncated or any required attribute is missing
7
- # • _safe_start() — one failing daemon thread no longer kills boot
8
- # • All thread starts guarded
9
- # • Route injection also guarded per-route
10
- # • Boot never aborts silently — logs exactly what's missing
11
- #
12
- # Responsibility:
13
- # • HfFolder monkey-patch (MUST be line 1, before any gradio import)
14
- # • Imports gradio + sub-modules (config → engine → bot → admin_panel)
15
- # • Gradio UI (health JSON + hidden ZeroGPU registration button)
16
- # • demo.launch(ssr_mode=False, prevent_thread_lock=True)
17
- # • Route injection at index 0:
18
- # POST /webhook ← Telegram webhook
19
- # GET /health ← liveness probe
20
- # /admin/* ← web panel (only if ADMIN_TOKEN set)
21
- # • Startup threads (all wrapped):
22
- # get_con, warm_phone_cache, get_asur_con, warm_asur_cache
23
- # cache_gc, set_webhook, api_health_poller
24
- # • demo.block_thread() ← keeps process alive
25
- # ══════════════════════════════════════════════════════════════════
26
-
27
- # ══════════════════════════════════════════════════════════════════
28
- # STEP 0: MONKEY-PATCH HfFolder BEFORE ANY GRADIO/HF IMPORT
29
- # ══════════════════════════════════════════════════════════════════
30
- import huggingface_hub
31
-
32
- if not hasattr(huggingface_hub, "HfFolder"):
33
- class _HfFolder:
34
- @staticmethod
35
- def get_token():
36
- try:
37
- return huggingface_hub.get_token()
38
- except Exception:
39
- return None
40
-
41
- @staticmethod
42
- def save_token(token):
43
- try:
44
- huggingface_hub.login(token)
45
- except Exception:
46
- pass
47
-
48
- @staticmethod
49
- def delete_token():
50
- try:
51
- huggingface_hub.logout()
52
- except Exception:
53
- pass
54
-
55
- huggingface_hub.HfFolder = _HfFolder
56
 
57
- # ══════════════════════════════════════════════════════════════════
58
- # STEP 1: STANDARD LIB
59
- # ══════════════════════════════════════════════════════════════════
60
  import asyncio
 
 
 
61
  import logging
62
  import threading
63
  import time
64
  import traceback
 
 
65
 
66
- # ══════════════════════════════════════════════════════════════════
67
- # STEP 2: THIRD-PARTY
68
- # ══════════════════════════════════════════════════════════════════
69
- import gradio as gr
70
- from fastapi import Request
71
- from fastapi.responses import JSONResponse
72
- from starlette.routing import Route as StarletteRoute
73
-
74
- # ZeroGPU optional — HF Spaces provide it, local dev doesn't
75
- try:
76
- import spaces
77
- _HAS_SPACES = True
78
- except ImportError:
79
- _HAS_SPACES = False
80
- class spaces:
81
- @staticmethod
82
- def GPU(*_a, **_kw):
83
- def deco(f):
84
- return f
85
- return deco
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
 
87
  # ══════════════════════════════════════════════════════════════════
88
- # STEP 3: PROJECT MODULES (order matters)
89
  # ══════════════════════════════════════════════════════════════════
90
- import config
91
- import engine
92
- import bot
93
- import admin_panel
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  # ══════════════════════════════════════════════════════════════════
96
- # STEP 4: LOGGING
97
  # ══════════════════════════════════════════════════════════════════
98
- logging.basicConfig(
99
- level=logging.INFO,
100
- format="%(asctime)s %(levelname)-7s [%(name)s] %(message)s",
101
- datefmt="%H:%M:%S",
102
- )
103
- log = logging.getLogger("app")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
 
105
  # ══════════════════════════════════════════════════════════════════
106
- # STEP 5: ROUTE HANDLERS (webhook + health)
107
  # ══════════════════════════════════════════════════════════════════
108
- async def webhook_handler(request: Request):
109
- """Telegram webhook. Returns 200 immediately; dispatches work in tasks."""
110
- # ── Header secret check ──
111
- if config.SECRET_TOKEN:
112
- got = request.headers.get("x-telegram-bot-api-secret-token", "")
113
- if got != config.SECRET_TOKEN:
114
- log.warning(f"[webhook] bad secret header: {got[:8]}…")
115
- return JSONResponse({"ok": False, "reason": "bad_header"}, status_code=403)
 
 
 
 
 
 
 
 
116
 
 
 
 
 
 
 
 
 
 
117
  try:
118
- update = await request.json()
119
- except Exception:
120
- return JSONResponse({"ok": True})
 
 
 
 
121
 
122
- # ── Dedup by update_id ──
123
- update_id = update.get("update_id")
124
- if bot.is_duplicate_update(update_id):
125
- log.debug(f"[webhook] duplicate update_id={update_id}")
126
- return JSONResponse({"ok": True})
127
 
128
- # ── Dispatch ──
 
 
 
 
 
 
 
129
  try:
130
- if "message" in update:
131
- asyncio.create_task(bot.handle_message(update["message"]))
132
- elif "callback_query" in update:
133
- asyncio.create_task(bot.handle_callback(update["callback_query"]))
134
- except RuntimeError:
135
- threading.Thread(
136
- target=lambda: asyncio.run(_dispatch_sync(update)),
137
- daemon=True,
138
- ).start()
139
 
140
- return JSONResponse({"ok": True})
 
 
 
 
141
 
 
 
 
 
 
142
 
143
- async def _dispatch_sync(update: dict):
144
- """Fallback if create_task fails."""
145
  try:
146
- if "message" in update:
147
- await bot.handle_message(update["message"])
148
- elif "callback_query" in update:
149
- await bot.handle_callback(update["callback_query"])
150
  except Exception as e:
151
- log.error(f"[webhook] dispatch: {e!r}\n{traceback.format_exc()}")
152
-
153
-
154
- async def health_handler(request: Request):
155
- """Liveness probe — cheap, no API calls."""
156
- return JSONResponse({
157
- "status": "ok",
158
- "version": config.VERSION,
159
- "time": time.time(),
160
- "duckdb_ready": engine.con_ready.is_set(),
161
- "warmed": engine.warmed.is_set(),
162
- "files": len(config.ALL_PARQUET_URLS),
163
- "hiteck_files": len(config.PARQUET_URLS),
164
- "flipkart_files": len(config.FLIPKART_URLS),
165
- "cached_searches": len(bot.SEARCH_CACHE),
166
- "unique_users": len(bot.UNIQUE_USERS),
167
- "live_users": bot._get_stats()["live_users"],
168
- "maintenance": bot.MAINTENANCE_MODE,
169
- "force_join": bool(config.FORCE_JOIN_CHANNEL),
170
- "backup_enabled": bot.BACKUP_ENABLED,
171
- "admin_panel": bool(config.ADMIN_TOKEN),
172
- "apis": {
173
- "cr850": config.API_850CR,
174
- "inddata": config.API_INDDATA,
175
- "asur": list(config.ASUR_API.values()),
176
- },
177
- "stats": bot.STATS,
178
- })
179
 
 
 
180
 
181
- # ══════════════════════════════════════════════════════════════════
182
- # STEP 6: GRADIO UI
183
- # ══════════════════════════════════════════════════════════════════
184
- def _build_gradio() -> gr.Blocks:
185
- with gr.Blocks(title=f"{config.BOT_NAME} v{config.VERSION}") as demo:
186
- gr.Markdown(f"# 🤖 {config.BOT_NAME} v{config.VERSION}")
187
- gr.Markdown(
188
- "This Space runs a **Telegram bot**.\n\n"
189
- "**Endpoints**\n"
190
- "- `GET /health` — liveness\n"
191
- "- `POST /webhook` — Telegram webhook\n"
192
- + ("- `GET /admin` — web admin panel\n" if config.ADMIN_TOKEN else "")
193
- )
194
-
195
- status_box = gr.JSON(label="Health")
196
- refresh_btn = gr.Button("🔄 Refresh health", variant="secondary")
197
-
198
- def _health_snapshot():
199
  try:
200
- s = bot._get_stats()
201
- return {
202
- "status": "ok",
203
- "version": config.VERSION,
204
- "duckdb_ready": engine.con_ready.is_set(),
205
- "warmed": engine.warmed.is_set(),
206
- "files": len(config.ALL_PARQUET_URLS),
207
- "cached_searches": len(bot.SEARCH_CACHE),
208
- "unique_users": s["unique_users"],
209
- "live_users": s["live_users"],
210
- "backup_enabled": bot.BACKUP_ENABLED,
211
- "maintenance": s["maintenance"],
212
- }
213
  except Exception as e:
214
- return {"error": str(e)}
 
 
 
 
 
215
 
216
- refresh_btn.click(fn=_health_snapshot, inputs=None, outputs=status_box)
217
- demo.load(fn=_health_snapshot, inputs=None, outputs=status_box)
 
 
 
218
 
219
- # Hidden ZeroGPU registration button
220
- if _HAS_SPACES:
221
- try:
222
- @spaces.GPU(duration=10)
223
- def _zerogpu_register():
224
- return "gpu-ready"
225
 
226
- _zgpu_btn = gr.Button("init-gpu", visible=False)
227
- _zgpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
228
- log.info("✅ ZeroGPU registered")
229
- except Exception as e:
230
- log.warning(f"⚠️ ZeroGPU registration failed: {e!r}")
 
 
 
231
 
232
- return demo
 
 
 
 
 
 
 
 
 
 
 
 
233
 
 
 
 
 
 
 
 
234
 
235
- # ══════════════════════════════════════════════════════════════════
236
- # STEP 7: WEBHOOK REGISTRATION (background thread, async impl)
237
- # ══════════════════════════════════════════════════════════════════
238
- async def _set_webhook_async_impl():
239
- if not config.BOT_TOKEN:
240
- log.warning("[setwebhook] BOT_TOKEN missing — skipped")
241
- return
242
- space_url = config.SPACE_URL or (f"https://{config.SPACE_HOST}" if config.SPACE_HOST else "")
243
- if not space_url:
244
- log.warning("[setwebhook] SPACE_URL/SPACE_HOST missing — skipped")
245
- return
246
-
247
- url = f"{space_url.rstrip('/')}/webhook"
248
- payload = {
249
- "url": url,
250
- "secret_token": config.SECRET_TOKEN,
251
- "allowed_updates": ["message", "callback_query"],
252
- "drop_pending_updates": True,
253
- }
254
- import httpx
255
- for attempt in range(1, 4):
256
  try:
257
- async with httpx.AsyncClient(timeout=30) as cli:
258
- r = await cli.post(f"{config.TELEGRAM_API}/setWebhook", json=payload)
259
- data = r.json()
260
- log.info(f"[setwebhook] attempt {attempt}: {data}")
261
- if data.get("ok"):
262
- return
263
  except Exception as e:
264
- log.warning(f"[setwebhook] attempt {attempt}: {e!r}")
265
- await asyncio.sleep(3)
266
- log.error("[setwebhook] gave up after 3 attempts")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
267
 
268
 
269
- def _set_webhook_async():
 
 
 
 
270
  try:
271
- loop = asyncio.new_event_loop()
272
- asyncio.set_event_loop(loop)
273
- loop.run_until_complete(_set_webhook_async_impl())
274
- except Exception as e:
275
- log.warning(f"[setwebhook] fatal: {e!r}")
 
 
 
 
 
 
276
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
 
278
  # ══════════════════════════════════════════════════════════════════
279
- # STEP 8: API HEALTH POLLER
280
  # ══════════════════════════════════════════════════════════════════
281
- def _api_health_poller():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  try:
283
- loop = asyncio.new_event_loop()
284
- asyncio.set_event_loop(loop)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
285
 
286
- async def _loop_forever():
287
- await asyncio.sleep(30) # initial delay
288
- while True:
 
 
 
289
  try:
290
- await engine.check_api_health()
291
- log.debug("[health-poller] tick ok")
292
- except Exception as e:
293
- log.warning(f"[health-poller] {e!r}")
294
- await asyncio.sleep(config.API_HEALTH_INTERVAL)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
295
 
296
- loop.run_until_complete(_loop_forever())
297
- except Exception as e:
298
- log.warning(f"[health-poller] fatal: {e!r}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
 
301
  # ══════════════════════════════════════════════════════════════════
302
- # STEP 9: BOOT — defensive
303
  # ══════════════════════════════════════════════════════════════════
 
 
 
 
304
 
305
- # Every attribute app.py (and admin_panel.py, indirectly) needs from bot.
306
- # If any is missing → module is truncated and boot must abort with a clear message.
307
- _BOT_REQUIRED_ATTRS = [
308
- # handlers
309
- "handle_message", "handle_callback", "is_duplicate_update",
310
- # threads
311
- "cache_gc",
312
- # stats / state (read by health_handler + admin_panel)
313
- "_get_stats", "_get_live_users",
314
- "SEARCH_CACHE", "UNIQUE_USERS", "ACTIVE_USERS", "STATS",
315
- "ACTIVITY_LOG", "BANNED_USERS", "BAN_REASONS",
316
- "MAINTENANCE_MODE", "BACKUP_ENABLED",
317
- # mutators (used by admin_panel)
318
- "_ban_user", "_unban_user",
319
- "_set_maintenance", "_get_maintenance",
320
- "_revoke_admin", "_is_admin_session",
321
- # internal locks referenced by admin_panel
322
- "_activity_lock", "_state_lock",
323
- ]
324
-
325
-
326
- def _verify_bot_module() -> bool:
327
- """Return True if bot.py exports everything app.py + admin_panel need."""
328
- missing = [n for n in _BOT_REQUIRED_ATTRS if not hasattr(bot, n)]
329
- if missing:
330
- log.error("╔══════════════════════════════════════════════════════════╗")
331
- log.error("║ ❌ bot module is INCOMPLETE — missing attributes: ║")
332
- log.error("╚══════════════════════════════════════════════════════════╝")
333
- for m in missing:
334
- log.error(f" • bot.{m}")
335
- log.error("")
336
- log.error(" Likely cause: bot.py was truncated during save.")
337
- log.error(" Expected: ~950 lines, ending with:")
338
- log.error(' if __name__ == "__main__":')
339
- log.error(" ...")
340
- log.error("")
341
- log.error(" Fix: re-save bot.py in full, then restart the Space.")
342
- return False
343
- log.info(f"✅ bot module OK ({len(_BOT_REQUIRED_ATTRS)} attributes present)")
344
- return True
345
-
346
-
347
- def _safe_start(name: str, target, *args):
348
- """Start a daemon thread — never raise."""
349
- if target is None:
350
- log.error(f"⚠️ thread '{name}': target is None — NOT started")
351
  return
352
- if not callable(target):
353
- log.error(f"⚠️ thread '{name}': target is not callable — NOT started")
 
354
  return
355
- try:
356
- threading.Thread(target=target, args=args, daemon=True, name=name).start()
357
- log.info(f"✅ thread started: {name}")
358
- except Exception as e:
359
- log.error(f"❌ thread '{name}' failed: {e!r}")
360
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
 
362
- def _safe_inject(live_app, route, description: str):
363
- """Insert a route at index 0 — never raise."""
364
- try:
365
- live_app.router.routes.insert(0, route)
366
- return True
367
- except Exception as e:
368
- log.error(f"❌ route inject failed ({description}): {e!r}")
369
- return False
370
-
371
-
372
- def _boot():
373
- # ── 9.0 Verify bot module FIRST ──
374
- if not _verify_bot_module():
375
- log.critical("❌ Aborting boot — fix bot.py and restart the Space.")
376
- time.sleep(5)
377
- raise RuntimeError("bot module incomplete — see log for missing attributes")
378
-
379
- # ── 9.1 Sanity + config dump ──
380
- print()
381
- print(config.summary())
382
- warnings = config._sanity_check()
383
- if warnings:
384
- print("\n⚠️ Config warnings:")
385
- for w in warnings:
386
- print(f" • {w}")
387
- print()
388
-
389
- # ── 9.2 Build Gradio ──
390
- log.info("[boot] building Gradio app…")
391
- demo = _build_gradio()
392
-
393
- # ── 9.3 Launch Gradio ──
394
- log.info("[boot] launching Gradio (ssr_mode=False, prevent_thread_lock=True)…")
395
- demo.launch(
396
- server_name="0.0.0.0",
397
- server_port=7860,
398
- share=False,
399
- ssr_mode=False,
400
- prevent_thread_lock=True,
401
- show_error=True,
402
- )
403
-
404
- # ── 9.4 Inject routes ──
405
- log.info("[boot] injecting /webhook, /health, /admin/* at index 0…")
406
- live_app = demo.app
407
-
408
- _safe_inject(
409
- live_app,
410
- StarletteRoute("/webhook", webhook_handler, methods=["POST"]),
411
- "POST /webhook",
412
- )
413
- _safe_inject(
414
- live_app,
415
- StarletteRoute("/health", health_handler, methods=["GET"]),
416
- "GET /health",
417
- )
418
-
419
- # ── 9.5 Admin panel ──
420
- admin_route_count = 0
421
- try:
422
- admin_routes = admin_panel.get_admin_routes()
423
- for route in admin_routes:
424
- if _safe_inject(live_app, route, getattr(route, "path", "?")):
425
- admin_route_count += 1
426
- if admin_route_count:
427
- log.info(f"✅ injected {admin_route_count} admin routes at /admin/*")
428
  else:
429
- log.info("ℹ️ admin routes not injected (ADMIN_TOKEN unset)")
430
- except Exception as e:
431
- log.warning(f"⚠️ admin_panel injection failed: {e!r}\n{traceback.format_exc()}")
 
 
 
 
 
 
 
432
 
433
- # ── 9.6 Rebuild middleware ──
434
- try:
435
- live_app.build_middleware_stack()
436
- log.info("✅ middleware stack rebuilt")
437
- except Exception as e:
438
- log.warning(f"⚠️ middleware stack rebuild: {e!r}")
439
-
440
- # ── 9.7 Log routes ──
441
- log.info("📋 First 10 routes:")
442
- for route in live_app.router.routes[:10]:
443
- path = getattr(route, "path", "?")
444
- methods = getattr(route, "methods", None)
445
- ms = f"{sorted(methods)}" if methods else "?"
446
- log.info(f" {ms:30s} {path}")
447
-
448
- # ── 9.8 Warm-up threads (engine) ──
449
- log.info("[boot] starting warm-up threads…")
450
- _safe_start("con", getattr(engine, "get_con", None))
451
- _safe_start("warm", getattr(engine, "warm_phone_cache", None))
452
- _safe_start("asur-con", getattr(engine, "get_asur_con", None))
453
- _safe_start("asur-warm", getattr(engine, "warm_asur_cache", None))
454
-
455
- # ── 9.9 Background daemons ──
456
- log.info("[boot] starting background daemons…")
457
- _safe_start("gc", bot.cache_gc)
458
- _safe_start("setwh", _set_webhook_async)
459
- _safe_start("health", _api_health_poller)
460
-
461
- # ── 9.10 Ready ──
462
- log.info("[boot] ✅ ready — blocking main thread")
463
- print()
464
- print("═" * 60)
465
- print(f" {config.BOT_NAME} v{config.VERSION} — ONLINE")
466
- print(f" Webhook : {config.SPACE_URL or config.SPACE_HOST or '(local)'}/webhook")
467
- print(f" Health : /health")
468
- print(f" Admin : {'/admin' if config.ADMIN_TOKEN else '(disabled — ADMIN_TOKEN unset)'}")
469
- print("═" * 60)
470
- print()
471
-
472
- return demo
473
 
474
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
475
  # ══════════════════════════════════════════════════════════════════
476
- # STEP 10: MAIN
477
  # ══════════════════════════════════════════════════════════════════
478
- if __name__ == "__main__":
 
479
  try:
480
- demo = _boot()
481
- demo.block_thread()
482
- except KeyboardInterrupt:
483
- log.info("shutting down…")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
484
  except Exception as e:
485
- log.critical(f"❌ boot failed: {e!r}\n{traceback.format_exc()}")
486
- raise
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """bot.py — Handlers, progressive search, admin commands, callbacks.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ State lives in bot_state.py. This file re-exports everything so
4
+ `import bot; bot.cache_gc` etc. continue to work.
5
+ """
6
  import asyncio
7
+ import csv
8
+ import io
9
+ import json
10
  import logging
11
  import threading
12
  import time
13
  import traceback
14
+ import uuid
15
+ from datetime import datetime, timezone
16
 
17
+ from config import (
18
+ BACKUP_ENABLED_DEFAULT, BACKUP_CHANNEL_ID, VERSION,
19
+ PAGE_SIZE, FETCH_LIMIT, QUERY_TIMEOUT, USER_COOLDOWN,
20
+ BATCH_MAX, BATCH_TIMEOUT, ADMIN_TOKEN, OWNER_IDS,
21
+ BROADCAST_DELAY, BROADCAST_MAX_LEN,
22
+ DAILY_QUOTA,
23
+ )
24
+ from engine import (
25
+ run_search_safe, search_fast_apis_filtered, asur_lookup_filtered,
26
+ search_apis_filtered, dedup_records, render_page, _plain_record,
27
+ normalize_phone, check_api_health, warm_phone_cache,
28
+ con_ready, warmed, esc,
29
+ )
30
+ from bot_state import (
31
+ ACTIVITY_LOG, ACTIVE_USERS, UNIQUE_USERS, BANNED_USERS, BAN_REASONS,
32
+ MAINTENANCE_MODE, SEARCH_CACHE, SEARCH_CACHE_LOCK, USER_HISTORY,
33
+ USER_LAST, STATS, PHONE_COUNTS,
34
+ _activity_lock, _state_lock,
35
+ tg, send, edit, send_document,
36
+ _short_user, _fmt_ts, _today_utc,
37
+ is_duplicate_update,
38
+ check_force_join,
39
+ _is_unlimited, check_quota, incr_quota, check_flood,
40
+ _log_activity, _get_live_users, _get_stats, _add_to_history,
41
+ _avg_latency_today,
42
+ _is_banned, _ban_user, _unban_user,
43
+ _get_maintenance, _set_maintenance,
44
+ _is_admin_session, _grant_admin, _revoke_admin,
45
+ _admin_state_get, _admin_state_set, _admin_state_clear,
46
+ cache_gc,
47
+ )
48
+
49
+ log = logging.getLogger("bot")
50
+
51
+ # Runtime toggle (local to bot.py — mutated by /backup and admin panel)
52
+ BACKUP_ENABLED = BACKUP_ENABLED_DEFAULT
53
 
54
  # ══════════════════════════════════════════════════════════════════
55
+ # ADMIN RENDERS
56
  # ══════════════════════════════════════════════════════════════════
57
+ def admin_menu_kb():
58
+ m_on, _ = _get_maintenance()
59
+ maint_label = "🔴 Maintenance: ON" if m_on else "🟢 Maintenance: OFF"
60
+ backup_label = "📥 Backup: ON" if BACKUP_ENABLED else "📥 Backup: OFF"
61
+ return {"inline_keyboard": [
62
+ [{"text": "🔴 Live Users", "callback_data": "adm:live"},
63
+ {"text": "📈 Stats", "callback_data": "adm:stats"}],
64
+ [{"text": "📜 Activity Log", "callback_data": "adm:log:0"},
65
+ {"text": "👥 All Users", "callback_data": "adm:users:0"}],
66
+ [{"text": "🔍 Top Searches", "callback_data": "adm:top"},
67
+ {"text": "🚫 Banned", "callback_data": "adm:banned"}],
68
+ [{"text": "🚫 Ban User", "callback_data": "adm:ban"},
69
+ {"text": "✅ Unban User", "callback_data": "adm:unban"}],
70
+ [{"text": "📢 Broadcast", "callback_data": "adm:broadcast"},
71
+ {"text": "📥 Export Log", "callback_data": "adm:export"}],
72
+ [{"text": "🔎 Log by Phone", "callback_data": "adm:logphone"},
73
+ {"text": maint_label, "callback_data": "adm:maint"}],
74
+ [{"text": "🔧 API Status", "callback_data": "adm:apistatus"},
75
+ {"text": backup_label, "callback_data": "adm:backuptoggle"}],
76
+ [{"text": "🔄 Refresh", "callback_data": "adm:menu"}],
77
+ ]}
78
+
79
+
80
+ def render_admin_menu():
81
+ m_on, reason = _get_maintenance()
82
+ m_line = f"🔴 Maintenance ON — {esc(reason)}" if m_on else "🟢 Operational"
83
+ b_line = "📥 Backup forwarding: ON" if BACKUP_ENABLED else "📥 Backup forwarding: OFF"
84
+ return (f"🛡️ <b>Admin Panel</b> — v{VERSION}\n━━━━━━━━━━━━━━━━━━\n"
85
+ f"{m_line}\n{b_line}\n"
86
+ f"👥 Users: {len(UNIQUE_USERS)} · 🚫 Banned: {len(BANNED_USERS)}\n\n"
87
+ "Tap a button or use commands:\n"
88
+ "• /live /stats /log /users /top\n"
89
+ "• /ban &lt;id&gt; [reason] · /unban &lt;id&gt;\n"
90
+ "• /broadcast &lt;msg&gt;\n"
91
+ "• /export · /logphone &lt;num&gt;\n"
92
+ "• /maintenance on|off [reason]\n"
93
+ "• /apistatus · /backup on|off\n"
94
+ "• /reload · /cancel · /logout")
95
+
96
+
97
+ def render_live():
98
+ live = _get_live_users()
99
+ if not live:
100
+ return (f"🔴 <b>Live Users</b>\n\n"
101
+ f"No one active in the last {LIVE_WINDOW // 60} minutes.")
102
+ lines = [f"🔴 <b>Live Users</b> (last {LIVE_WINDOW // 60} min): "
103
+ f"<b>{len(live)}</b>\n"]
104
+ for uid, ts in live[:25]:
105
+ lines.append(f"• {_short_user(uid)} — {_fmt_ts(ts)}")
106
+ return "\n".join(lines)
107
+
108
+
109
+ def render_stats():
110
+ s = _get_stats()
111
+ uptime = (time.time() - STATS["started"]) / 60
112
+ return ("📈 <b>Bot Statistics</b>\n━━━━━━━━━━━━━━━━━━\n"
113
+ f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n"
114
+ f"👥 Unique users: <code>{s['unique_users']}</code>\n"
115
+ f"🔴 Live now: <code>{s['live_users']}</code>\n"
116
+ f"📅 Active today: <code>{s['today_users']}</code>\n"
117
+ f"🔍 Searches today: <code>{s['today_searches']}</code>\n"
118
+ f"🔍 Total searches: <code>{s['total_searches']}</code>\n"
119
+ f"📊 Peak concurrent: <code>{s['peak_concurrent']}</code>\n"
120
+ f"🚫 Banned users: <code>{s['banned_count']}</code>\n"
121
+ f"💾 Cached queries: <code>{s['cached_searches']}</code>\n"
122
+ f"📥 Backup sent: <code>{s['backup_sent']}</code>\n"
123
+ f"📜 Log entries: <code>{s['total_log_entries']}</code>\n"
124
+ f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n"
125
+ f"❌ Errors: <code>{STATS['errors']}</code>")
126
+
127
+
128
+ def render_log(entries, page=0, page_size=8):
129
+ total = len(entries)
130
+ total_pages = max(1, (total + page_size - 1) // page_size)
131
+ page = max(0, min(page, total_pages - 1))
132
+ chunk = entries[page * page_size:(page + 1) * page_size]
133
+ if not chunk:
134
+ return "📜 <b>Activity Log</b>\n\nNo activity yet.", None
135
+ lines = [f"📜 <b>Activity Log</b> — page {page + 1}/{total_pages} "
136
+ f"({total} entries)\n"]
137
+ for e in chunk:
138
+ uname = e.get("username")
139
+ first = e.get("first_name")
140
+ name_str = f"@{uname}" if uname else (first or "(no name)")
141
+ reply = e.get("summary") or e.get("reply_type") or "-"
142
+ elapsed = e.get("elapsed_ms", 0)
143
+ source = e.get("source") or ""
144
+ block = (f"<code>{_fmt_ts(e['ts'])}</code> · "
145
+ f"<b>{esc(name_str)}</b> · <code>{e['user_id']}</code>\n")
146
+ block += f" 📥 <code>{esc(e['input'] or '-')}</code>\n"
147
+ reply_line = f" 📤 {esc(reply)}"
148
+ if elapsed:
149
+ reply_line += f" · {elapsed}ms"
150
+ if source:
151
+ reply_line += f" · {source}"
152
+ lines.append(block + reply_line)
153
+ text = "\n\n".join(lines)
154
+ nav = []
155
+ if page > 0:
156
+ nav.append({"text": "◀ Newer", "callback_data": f"adm:log:{page - 1}"})
157
+ nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"})
158
+ if page < total_pages - 1:
159
+ nav.append({"text": "Older ▶", "callback_data": f"adm:log:{page + 1}"})
160
+ return text, ({"inline_keyboard": [nav]} if len(nav) > 1 else None)
161
+
162
+
163
+ def render_users(page=0, page_size=8):
164
+ users = sorted(UNIQUE_USERS.items(), key=lambda kv: -kv[1]["last_seen"])
165
+ total = len(users)
166
+ total_pages = max(1, (total + page_size - 1) // page_size)
167
+ page = max(0, min(page, total_pages - 1))
168
+ chunk = users[page * page_size:(page + 1) * page_size]
169
+ if not chunk:
170
+ return "👥 <b>All Users</b>\n\nNo users yet.", None
171
+ lines = [f"👥 <b>All Users</b> — page {page + 1}/{total_pages} "
172
+ f"({total} total)\n"]
173
+ for uid, info in chunk:
174
+ username = info.get("username")
175
+ first = info.get("first_name") or ""
176
+ name_str = f"@{username}" if username else (first or "(no name)")
177
+ ban_mark = " 🚫" if _is_banned(uid) else ""
178
+ lines.append(f"<b>{esc(name_str)}</b>{ban_mark} · "
179
+ f"<code>{uid}</code>\n"
180
+ f" Requests: {info['count']} · "
181
+ f"Last: {_fmt_ts(info['last_seen'])}")
182
+ text = "\n\n".join(lines)
183
+ nav = []
184
+ if page > 0:
185
+ nav.append({"text": "◀ Prev", "callback_data": f"adm:users:{page - 1}"})
186
+ nav.append({"text": f"{page + 1}/{total_pages}", "callback_data": "adm:noop"})
187
+ if page < total_pages - 1:
188
+ nav.append({"text": "Next ▶", "callback_data": f"adm:users:{page + 1}"})
189
+ return text, ({"inline_keyboard": [nav]} if len(nav) > 1 else None)
190
+
191
+
192
+ def render_top():
193
+ if not PHONE_COUNTS:
194
+ return "🔍 <b>Top Searched Numbers</b>\n\nNo searches yet."
195
+ lines = ["🔍 <b>Top Searched Numbers</b>\n"]
196
+ for i, (num, cnt) in enumerate(PHONE_COUNTS.most_common(10), 1):
197
+ lines.append(f"{i}. <code>{num}</code> — {cnt} time(s)")
198
+ return "\n".join(lines)
199
+
200
+
201
+ def render_banned():
202
+ with _state_lock:
203
+ if not BANNED_USERS:
204
+ return "🚫 <b>Banned Users</b>\n\nNo banned users."
205
+ lines = [f"🚫 <b>Banned Users</b> ({len(BANNED_USERS)})\n"]
206
+ for uid in list(BANNED_USERS)[:30]:
207
+ reason = BAN_REASONS.get(uid) or "—"
208
+ lines.append(f"• {_short_user(uid)} — {esc(reason)}")
209
+ return "\n".join(lines)
210
 
211
  # ══════════════════════════════════════════════════════════════════
212
+ # BACKUP FORWARDER
213
  # ══════════════════════════════════════════════════════════════════
214
+ def _build_backup_payload(user, phone, status, elapsed, fast_data,
215
+ asur_data, db_results, combined_count):
216
+ return {
217
+ "meta": {"ts_utc": datetime.now(timezone.utc).isoformat(),
218
+ "bot_version": VERSION,
219
+ "telegram_user_id": user.get("id"),
220
+ "username": user.get("username"),
221
+ "first_name": user.get("first_name")},
222
+ "input": {"mobile": phone},
223
+ "status": status,
224
+ "elapsed_s": round(elapsed, 2),
225
+ "aadhaar_resolution": asur_data.get("aadhaar_res") or {},
226
+ "api_responses_raw": {**(fast_data.get("raw") or {}),
227
+ **(asur_data.get("api_results") or {})},
228
+ "api_status": {**(fast_data.get("source_status") or {}),
229
+ **(asur_data.get("source_status") or {})},
230
+ "db_results": db_results or [],
231
+ "records_shown": combined_count,
232
+ }
233
+
234
+
235
+ async def forward_to_backup(user, phone, status, elapsed, fast_data,
236
+ asur_data, db_results, combined_count):
237
+ if not BACKUP_CHANNEL_ID or not BACKUP_ENABLED:
238
+ return
239
+ try:
240
+ payload = _build_backup_payload(user, phone, status, elapsed,
241
+ fast_data, asur_data,
242
+ db_results, combined_count)
243
+ header = (f"📥 <b>New lookup</b>\n"
244
+ f"👤 User: <code>{user.get('id')}</code>"
245
+ f"{' (@' + esc(user.get('username')) + ')' if user.get('username') else ''}\n"
246
+ f"📱 Mobile: <code>{esc(phone)}</code>\n"
247
+ f"📊 Status: <b>{esc(status)}</b> · "
248
+ f"📄 Records: <b>{combined_count}</b> · "
249
+ f"⏱️ {elapsed:.1f}s")
250
+ await send(BACKUP_CHANNEL_ID, header)
251
+ json_str = json.dumps(payload, indent=2, ensure_ascii=False,
252
+ default=str)
253
+ await send_document(BACKUP_CHANNEL_ID,
254
+ f"lookup_{phone}_{int(time.time())}.json",
255
+ json_str.encode("utf-8"),
256
+ caption=f"Mobile {phone} — {status}")
257
+ STATS["backup_sent"] += 1
258
+ except Exception as e:
259
+ log.warning(f"[backup] forward failed: {e!r}")
260
 
261
  # ══════════════════════════════════════════════════════════════════
262
+ # SEARCH FLOW
263
  # ══════════════════════════════════════════════════════════════════
264
+ async def _db_search_async(phone, loop):
265
+ if not con_ready.is_set():
266
+ return []
267
+ try:
268
+ return await asyncio.wait_for(
269
+ loop.run_in_executor(None, run_search_safe, phone, FETCH_LIMIT),
270
+ timeout=QUERY_TIMEOUT + 10)
271
+ except (asyncio.TimeoutError, TimeoutError):
272
+ STATS["timeouts"] += 1
273
+ log.warning(f"DB timeout for {phone}")
274
+ return []
275
+ except Exception as e:
276
+ STATS["errors"] += 1
277
+ log.warning(f"DB error for {phone}: {e!r}")
278
+ return []
279
+
280
 
281
+ async def _show_progressive(chat_id, message_id, phone, results, elapsed,
282
+ source_note="", extras_block="", asur_data=None):
283
+ search_id = uuid.uuid4().hex[:10]
284
+ total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
285
+ SEARCH_CACHE[search_id] = {
286
+ "ts": time.time(), "results": results, "query": phone,
287
+ "elapsed": elapsed, "source_note": source_note,
288
+ "extras_block": extras_block, "asur_data": asur_data or {},
289
+ }
290
  try:
291
+ await edit(chat_id, message_id,
292
+ render_page(results, 0, total_pages, phone,
293
+ elapsed, source_note, extras_block),
294
+ reply_markup=page_keyboard(search_id, 0, total_pages))
295
+ except Exception as e:
296
+ log.warning(f"progressive render failed: {e!r}")
297
+ return search_id
298
 
 
 
 
 
 
299
 
300
+ async def _do_progressive_search(phone, chat_id, placeholder_id, user):
301
+ t0 = time.time()
302
+ loop = asyncio.get_running_loop()
303
+ db_task = asyncio.create_task(_db_search_async(phone, loop))
304
+ fast_task = asyncio.create_task(search_fast_apis_filtered(phone))
305
+ asur_task = asyncio.create_task(asur_lookup_filtered(phone))
306
+
307
+ fast_data = {"records": [], "source_status": {}, "raw": {}, "elapsed": 0.0}
308
  try:
309
+ fast_data = await asyncio.wait_for(fast_task, timeout=75)
310
+ except asyncio.TimeoutError:
311
+ log.warning(f"Fast API timeout for {phone}")
312
+ except Exception as e:
313
+ log.warning(f"Fast API error for {phone}: {e!r}")
 
 
 
 
314
 
315
+ fast_records = dedup_records(fast_data.get("records") or [])
316
+ search_id = None
317
+ extras_block = ""
318
+ asur_data = {"records": [], "extras": "", "aadhaar_res": {},
319
+ "api_results": {}, "source_status": {}, "elapsed": 0.0}
320
 
321
+ if fast_records:
322
+ search_id = await _show_progressive(
323
+ chat_id, placeholder_id, phone, fast_records,
324
+ fast_data.get("elapsed", 0.0),
325
+ source_note="⚡ Fast results — enriching…")
326
 
 
 
327
  try:
328
+ asur_data = await asyncio.wait_for(asur_task, timeout=90)
329
+ except asyncio.TimeoutError:
330
+ log.warning(f"ASUR timeout for {phone}")
 
331
  except Exception as e:
332
+ log.warning(f"ASUR error for {phone}: {e!r}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
 
334
+ asur_records = dedup_records(asur_data.get("records") or [])
335
+ extras_block = asur_data.get("extras") or ""
336
 
337
+ if (asur_records or extras_block) and (fast_records or search_id):
338
+ combined_sofar = dedup_records(fast_records + asur_records)
339
+ elapsed = time.time() - t0
340
+ note = "🪪 ASUR data added — database query ongoing…"
341
+ asur_snapshot = {"aadhaar_res": asur_data.get("aadhaar_res"),
342
+ "api_results": asur_data.get("api_results"),
343
+ "source_status": asur_data.get("source_status")}
344
+ if search_id:
345
+ SEARCH_CACHE[search_id].update({
346
+ "results": combined_sofar, "extras_block": extras_block,
347
+ "asur_data": asur_snapshot, "elapsed": elapsed,
348
+ "source_note": note, "ts": time.time(),
349
+ })
350
+ total_pages = max(1, (len(combined_sofar) + PAGE_SIZE - 1) // PAGE_SIZE)
 
 
 
 
351
  try:
352
+ await edit(chat_id, placeholder_id,
353
+ render_page(combined_sofar, 0, total_pages, phone,
354
+ elapsed, note, extras_block),
355
+ reply_markup=page_keyboard(search_id, 0, total_pages))
 
 
 
 
 
 
 
 
 
356
  except Exception as e:
357
+ log.warning(f"ASUR phase render failed: {e!r}")
358
+ else:
359
+ search_id = await _show_progressive(
360
+ chat_id, placeholder_id, phone, combined_sofar, elapsed,
361
+ source_note=note, extras_block=extras_block,
362
+ asur_data=asur_snapshot)
363
 
364
+ db_results = []
365
+ try:
366
+ db_results = await db_task
367
+ except Exception as e:
368
+ log.warning(f"DB task raised for {phone}: {e!r}")
369
 
370
+ elapsed = time.time() - t0
371
+ combined = dedup_records(fast_records + asur_records + (db_results or []))
372
+ new_from_db = max(0, len(combined) - len(dedup_records(fast_records + asur_records)))
 
 
 
373
 
374
+ if fast_records and (asur_records or extras_block) and db_results:
375
+ source = "hybrid"
376
+ elif db_results:
377
+ source = "duckdb"
378
+ elif fast_records or asur_records or extras_block:
379
+ source = "api"
380
+ else:
381
+ source = "empty"
382
 
383
+ if not combined and not extras_block:
384
+ _log_activity(user, "search", phone, "no_results",
385
+ "no records", int(elapsed * 1000), source)
386
+ try:
387
+ await edit(chat_id, placeholder_id,
388
+ f"❌ <b>No record found</b>\n\n"
389
+ f"📱 <code>{esc(phone)}</code>\n"
390
+ f"⏱️ {elapsed:.1f}s")
391
+ except Exception:
392
+ pass
393
+ asyncio.create_task(forward_to_backup(
394
+ user, phone, "empty", elapsed, fast_data, asur_data, db_results, 0))
395
+ return 0, elapsed, source
396
 
397
+ note = ""
398
+ if new_from_db > 0 and (fast_records or asur_records):
399
+ note = f"➕ {new_from_db} more from database"
400
+ total_pages = max(1, (len(combined) + PAGE_SIZE - 1) // PAGE_SIZE)
401
+ asur_snapshot = {"aadhaar_res": asur_data.get("aadhaar_res"),
402
+ "api_results": asur_data.get("api_results"),
403
+ "source_status": asur_data.get("source_status")}
404
 
405
+ if search_id:
406
+ SEARCH_CACHE[search_id].update({
407
+ "results": combined, "elapsed": elapsed, "source_note": note,
408
+ "extras_block": extras_block, "asur_data": asur_snapshot,
409
+ "ts": time.time(),
410
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
411
  try:
412
+ await edit(chat_id, placeholder_id,
413
+ render_page(combined, 0, total_pages, phone,
414
+ elapsed, note, extras_block),
415
+ reply_markup=page_keyboard(search_id, 0, total_pages))
 
 
416
  except Exception as e:
417
+ log.warning(f"final render failed: {e!r}")
418
+ else:
419
+ search_id = await _show_progressive(
420
+ chat_id, placeholder_id, phone, combined, elapsed,
421
+ source_note=note, extras_block=extras_block,
422
+ asur_data=asur_snapshot)
423
+
424
+ STATS["queries"] += 1
425
+ _add_to_history(user.get("id"), phone, len(combined), elapsed, source)
426
+ _log_activity(user, "search", phone, "results",
427
+ f"{len(combined)} result(s) (+{new_from_db} new)",
428
+ int(elapsed * 1000), source)
429
+ status = "success" if len(combined) > 0 else "empty"
430
+ asyncio.create_task(forward_to_backup(
431
+ user, phone, status, elapsed, fast_data, asur_data, db_results,
432
+ len(combined)))
433
+ return len(combined), elapsed, source
434
 
435
 
436
+ async def _search_quiet(phone):
437
+ loop = asyncio.get_running_loop()
438
+ api_task = asyncio.create_task(search_apis_filtered(phone))
439
+ db_task = asyncio.create_task(_db_search_async(phone, loop))
440
+ api_res, db_res = [], []
441
  try:
442
+ r = await asyncio.wait_for(api_task, timeout=25)
443
+ api_res = r.get("records") or []
444
+ except Exception:
445
+ pass
446
+ try:
447
+ db_res = await asyncio.wait_for(db_task,
448
+ timeout=max(5, BATCH_TIMEOUT - 25))
449
+ except Exception:
450
+ pass
451
+ combined = dedup_records(api_res + (db_res or []))
452
+ return len(combined), len(combined) > 0
453
 
454
+ # ══════════════════════════════════════════════════════════════════
455
+ # PAGE KEYBOARD
456
+ # ══════════════════════════════════════════════════════════════════
457
+ def page_keyboard(search_id, page, total_pages, has_export=True):
458
+ nav = []
459
+ if page > 0:
460
+ nav.append({"text": "◀ Prev",
461
+ "callback_data": f"p:{search_id}:{page-1}"})
462
+ nav.append({"text": f"{page+1} / {total_pages}",
463
+ "callback_data": "noop"})
464
+ if page < total_pages - 1:
465
+ nav.append({"text": "Next ▶",
466
+ "callback_data": f"p:{search_id}:{page+1}"})
467
+ rows = [nav]
468
+ extras = [{"text": "📋 Copy page",
469
+ "callback_data": f"c:{search_id}:{page}"}]
470
+ if has_export:
471
+ extras.append({"text": "📥 Export",
472
+ "callback_data": f"e:{search_id}"})
473
+ rows.append(extras)
474
+ return {"inline_keyboard": rows}
475
 
476
  # ══════════════════════════════════════════════════════════════════
477
+ # WELCOME
478
  # ══════════════════════════════════════════════════════════════════
479
+ WELCOME_TEMPLATE = (
480
+ "👋 <b>Phone Lookup Bot</b> v{v}\n\n"
481
+ "Send me any <b>10-digit mobile number</b> and I'll return every "
482
+ "record we have on file.\n\n"
483
+ "📌 <b>Examples</b>\n"
484
+ "• <code>9876543210</code>\n"
485
+ "• <code>+91 98765 43210</code>\n"
486
+ "• <code>9876543210,9876543211</code> (batch)\n\n"
487
+ "<i>Commands:</i>\n"
488
+ "• /start — this message\n"
489
+ "• /info — bot info\n"
490
+ "• /status — bot health\n"
491
+ "• /history — your last 10 searches\n"
492
+ "• /whoami — your profile &amp; quota\n"
493
+ "• /daily — today's quota\n"
494
+ "• /myid — your Telegram ID\n"
495
+ "• /feedback &lt;msg&gt; — send feedback\n"
496
+ "• /report &lt;num&gt; — flag wrong data")
497
+
498
+ # ══════════════════════════════════════════════════════════════════
499
+ # MESSAGE HANDLER
500
+ # ══════════════════════════════════════════════════════════════════
501
+ async def handle_message(msg):
502
  try:
503
+ chat_id = msg["chat"]["id"]
504
+ user = msg.get("from") or {}
505
+ user_id = user.get("id")
506
+ text = (msg.get("text") or "").strip()
507
+ log.info(f"Message from {user_id}: {text[:50]!r}")
508
+ if not text or user_id is None:
509
+ return
510
+
511
+ if _is_banned(user_id):
512
+ with _state_lock:
513
+ reason = BAN_REASONS.get(user_id) or "no reason given"
514
+ await send(chat_id,
515
+ f"🚫 <b>You are banned.</b>\n\nReason: {esc(reason)}")
516
+ _log_activity(user, "banned_hit", text[:40], "blocked", reason)
517
+ return
518
+
519
+ state = _admin_state_get(user_id)
520
+ if state == "await_admin_token" and not _is_admin_session(user_id):
521
+ _admin_state_clear(user_id)
522
+ if ADMIN_TOKEN and text == ADMIN_TOKEN:
523
+ _grant_admin(user_id)
524
+ _log_activity(user, "admin_login", "***", "granted",
525
+ "session started")
526
+ await send(chat_id, "✅ <b>Admin access granted</b>",
527
+ reply_markup=admin_menu_kb())
528
+ await send(chat_id, render_admin_menu())
529
+ else:
530
+ _log_activity(user, "admin_login", "***", "denied",
531
+ "invalid token")
532
+ await send(chat_id,
533
+ "❌ <b>Invalid token.</b>\nTry /admin again.")
534
+ return
535
 
536
+ if state and _is_admin_session(user_id):
537
+ _admin_state_clear(user_id)
538
+ if state == "await_ban_id":
539
+ parts = text.split(None, 1)
540
+ target = parts[0].lstrip("@")
541
+ reason = parts[1] if len(parts) > 1 else ""
542
  try:
543
+ tid = int(target)
544
+ except ValueError:
545
+ await send(chat_id, "❗ Invalid user ID.")
546
+ return
547
+ _ban_user(tid, reason)
548
+ _log_activity(user, "admin", f"/ban {tid}", "banned",
549
+ reason or "no reason")
550
+ await send(chat_id,
551
+ f"🚫 Banned <code>{tid}</code> — "
552
+ f"{esc(reason or 'no reason')}")
553
+ return
554
+ if state == "await_unban_id":
555
+ try:
556
+ tid = int(text.strip())
557
+ except ValueError:
558
+ await send(chat_id, "❗ Invalid user ID.")
559
+ return
560
+ ok = _unban_user(tid)
561
+ _log_activity(user, "admin", f"/unban {tid}", "unbanned")
562
+ await send(chat_id,
563
+ "✅ Unbanned." if ok else "ℹ️ User was not banned.")
564
+ return
565
+ if state == "await_broadcast":
566
+ asyncio.create_task(_run_broadcast(chat_id, text))
567
+ _log_activity(user, "admin", "/broadcast", "sending",
568
+ f"{len(text)} chars")
569
+ return
570
+ if state == "await_logphone":
571
+ phone, hint = normalize_phone(text)
572
+ if not phone:
573
+ await send(chat_id, f"❗ {hint}")
574
+ return
575
+ entries = [e for e in ACTIVITY_LOG
576
+ if e["action"] == "search" and e["input"] == phone]
577
+ entries.reverse()
578
+ if not entries:
579
+ await send(chat_id,
580
+ f"🔎 No searches logged for <code>{phone}</code>.")
581
+ return
582
+ lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> "
583
+ f"({len(entries)} total)\n"]
584
+ for e in entries[:20]:
585
+ uname = e.get("username")
586
+ first = e.get("first_name")
587
+ nm = f"@{uname}" if uname else (first or "(anon)")
588
+ lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · "
589
+ f"<code>{e['user_id']}</code>")
590
+ await send(chat_id, "\n".join(lines))
591
+ _log_activity(user, "admin", f"logphone {phone}", "text")
592
+ return
593
+ if state == "await_maint_reason":
594
+ _set_maintenance(True, text[:100])
595
+ _log_activity(user, "admin", "maintenance on", "state",
596
+ text[:100])
597
+ await send(chat_id,
598
+ f"🔴 <b>Maintenance ON</b>\n"
599
+ f"Reason: {esc(text[:100])}")
600
+ return
601
 
602
+ m_on, m_reason = _get_maintenance()
603
+ if m_on and not _is_admin_session(user_id):
604
+ if text in ("/start", "/help", "/status", "/info", "/myid"):
605
+ pass
606
+ else:
607
+ await send(chat_id,
608
+ f"🛠️ <b>Bot under maintenance</b>\n\n{esc(m_reason)}")
609
+ _log_activity(user, "maintenance_block", text[:40], "blocked")
610
+ return
611
+
612
+ if not await check_force_join(chat_id, user, text):
613
+ return
614
+
615
+ if text == "/admin":
616
+ if not ADMIN_TOKEN:
617
+ await send(chat_id, "⚠️ Admin panel is not configured.")
618
+ return
619
+ if _is_admin_session(user_id):
620
+ _log_activity(user, "admin", "/admin", "menu")
621
+ await send(chat_id, render_admin_menu(),
622
+ reply_markup=admin_menu_kb())
623
+ else:
624
+ _admin_state_set(user_id, "await_admin_token")
625
+ await send(chat_id,
626
+ "🔐 <b>Admin access required</b>\n\n"
627
+ "Send the admin token to continue. "
628
+ "It expires in 3 minutes.")
629
+ return
630
+
631
+ if text == "/logout":
632
+ if _is_admin_session(user_id):
633
+ _revoke_admin(user_id)
634
+ _log_activity(user, "admin_logout", "/logout", "revoked")
635
+ await send(chat_id, "✅ Admin session ended.")
636
+ else:
637
+ await send(chat_id, "You are not logged in as admin.")
638
+ return
639
+
640
+ if text.startswith("/") and _is_admin_session(user_id):
641
+ await _handle_admin_command(chat_id, user, text, user_id)
642
+ return
643
+
644
+ if text == "/status":
645
+ uptime = (time.time() - STATS["started"]) / 60
646
+ m_on, _ = _get_maintenance()
647
+ _log_activity(user, "status", "/status", "text")
648
+ import config as _cfg
649
+ await send(chat_id,
650
+ f"<b>📊 Bot Status</b> — v{VERSION}\n\n"
651
+ f"⏱️ Uptime: <code>{uptime:.1f} min</code>\n"
652
+ f"🔌 DuckDB main: <code>{con_ready.is_set()}</code>\n"
653
+ f"🔥 Cache warmed: <code>{warmed.is_set()}</code>\n"
654
+ f"📂 HiTeck: <code>{len(_cfg.PARQUET_URLS)}</code> · "
655
+ f"Flipkart: <code>{len(_cfg.FLIPKART_URLS)}</code>\n"
656
+ f"🔗 APIs: <code>850CR + IndData + ASUR×4</code>\n"
657
+ f"🛠️ Maintenance: <code>{m_on}</code>\n"
658
+ f"📥 Backup: <code>{BACKUP_ENABLED}</code>\n"
659
+ f"🔍 Queries: <code>{STATS['queries']}</code>\n"
660
+ f"⏰ Timeouts: <code>{STATS['timeouts']}</code>\n"
661
+ f"❌ Errors: <code>{STATS['errors']}</code>")
662
+ return
663
+
664
+ if text == "/info":
665
+ uptime = (time.time() - STATS["started"]) / 60
666
+ s = _get_stats()
667
+ _log_activity(user, "info", "/info", "text")
668
+ await send(chat_id,
669
+ f"ℹ️ <b>About This Bot</b>\n━━━━━━━━━━━━━━━━━━\n"
670
+ f"🤖 Version: <code>{VERSION}</code>\n"
671
+ f"📊 Sources: HiTeck (7) + Flipkart (1) + 2 APIs + ASUR×4\n"
672
+ f"👥 Unique users: <code>{s['unique_users']}</code>\n"
673
+ f"🔍 Searches: <code>{s['total_searches']}</code>\n"
674
+ f"⏱️ Avg latency (today): "
675
+ f"<code>{_avg_latency_today():.1f}s</code>\n"
676
+ f"🕒 Uptime: <code>{uptime:.0f} min</code>\n"
677
+ "━━━━━━━━━━━━━━━━━━\n"
678
+ "Built with ❤️ for fast, private lookups.")
679
+ return
680
+
681
+ if text == "/history":
682
+ with _activity_lock:
683
+ h = list(USER_HISTORY.get(user_id, []))
684
+ _log_activity(user, "history", "/history", "text")
685
+ if not h:
686
+ await send(chat_id,
687
+ "📭 <b>No history yet</b>\n\n"
688
+ "Search a number to start.")
689
+ return
690
+ rows = [[{"text": f"{i}. {item['phone']} ({item['count']} res)",
691
+ "callback_data": f"h:{item['phone']}"}]
692
+ for i, item in enumerate(h, 1)]
693
+ await send(chat_id,
694
+ "🕘 <b>Your last searches</b>\n\nTap to search again:",
695
+ reply_markup={"inline_keyboard": rows})
696
+ return
697
+
698
+ if text == "/myid":
699
+ _log_activity(user, "myid", "/myid", "text")
700
+ await send(chat_id,
701
+ f"🆔 <b>Your Telegram ID</b>\n<code>{user_id}</code>")
702
+ return
703
+
704
+ if text == "/whoami":
705
+ _, remaining = check_quota(user_id)
706
+ banned = _is_banned(user_id)
707
+ admin = _is_admin_session(user_id)
708
+ owner = user_id in OWNER_IDS
709
+ with _activity_lock:
710
+ info = UNIQUE_USERS.get(user_id, {})
711
+ first_seen = info.get("first_seen")
712
+ count = info.get("count", 0)
713
+ lines = ["🆔 <b>Your Info</b>", f"• ID: <code>{user_id}</code>"]
714
+ if user.get("username"):
715
+ lines.append(f"• Username: @{esc(user['username'])}")
716
+ if user.get("first_name"):
717
+ lines.append(f"• Name: {esc(user['first_name'])}")
718
+ if first_seen:
719
+ lines.append("• First seen: " +
720
+ time.strftime('%Y-%m-%d %H:%M',
721
+ time.gmtime(first_seen)))
722
+ lines.append(f"• Total requests: {count}")
723
+ if _is_unlimited(user_id):
724
+ lines.append("• Daily quota: ∞")
725
+ else:
726
+ lines.append(f"• Daily quota: {DAILY_QUOTA - remaining}/"
727
+ f"{DAILY_QUOTA} remaining")
728
+ if owner:
729
+ lines.append("• Status: 👑 Owner")
730
+ elif admin:
731
+ lines.append("• Status: 🛡️ Admin")
732
+ if banned:
733
+ with _state_lock:
734
+ reason = BAN_REASONS.get(user_id) or "no reason"
735
+ lines.append(f"• Status: 🚫 Banned ({esc(reason)})")
736
+ _log_activity(user, "whoami", "/whoami", "text")
737
+ await send(chat_id, "\n".join(lines))
738
+ return
739
+
740
+ if text == "/daily":
741
+ if _is_unlimited(user_id):
742
+ await send(chat_id,
743
+ "📊 <b>Daily Quota</b>\n\n♾️ Unlimited (admin/owner)")
744
+ else:
745
+ _, remaining = check_quota(user_id)
746
+ used = DAILY_QUOTA - remaining
747
+ await send(chat_id,
748
+ f"📊 <b>Daily Quota</b>\n\n"
749
+ f"Used: <code>{used}</code>/"
750
+ f"<code>{DAILY_QUOTA}</code>\n"
751
+ f"Remaining: <code>{remaining}</code>")
752
+ _log_activity(user, "daily", "/daily", "text")
753
+ return
754
+
755
+ if text == "/ping":
756
+ uptime = (time.time() - STATS["started"]) / 60
757
+ _log_activity(user, "ping", "/ping", "text")
758
+ await send(chat_id,
759
+ f"🏓 <b>Pong!</b>\n\n⏱️ Uptime: {uptime:.1f} min\n"
760
+ f"🕐 {time.strftime('%H:%M:%S', time.gmtime())} UTC")
761
+ return
762
+
763
+ if text.startswith("/feedback"):
764
+ fb = text[len("/feedback"):].strip()
765
+ if not fb:
766
+ await send(chat_id,
767
+ "❌ Usage: <code>/feedback your message</code>")
768
+ return
769
+ if BACKUP_CHANNEL_ID:
770
+ await send(BACKUP_CHANNEL_ID,
771
+ f"💬 <b>Feedback</b>\n"
772
+ f"👤 {_short_user(user_id, user)}\n\n"
773
+ f"{esc(fb[:3000])}")
774
+ await send(chat_id, "✅ Thanks for your feedback!")
775
+ _log_activity(user, "feedback", fb[:60], "text")
776
+ return
777
+
778
+ if text.startswith("/report"):
779
+ arg = text[len("/report"):].strip()
780
+ if not arg:
781
+ await send(chat_id,
782
+ "❌ Usage: <code>/report 9876543210 [reason]</code>")
783
+ return
784
+ parts = arg.split(None, 1)
785
+ phone, hint = normalize_phone(parts[0])
786
+ if not phone:
787
+ await send(chat_id, f"❌ Invalid number: {hint}")
788
+ return
789
+ reason = parts[1] if len(parts) > 1 else ""
790
+ if BACKUP_CHANNEL_ID:
791
+ await send(BACKUP_CHANNEL_ID,
792
+ f"🚩 <b>Report</b>\n"
793
+ f"👤 {_short_user(user_id, user)}\n"
794
+ f"📱 <code>{phone}</code>\n"
795
+ f"📝 {esc(reason or '(no reason given)')}")
796
+ await send(chat_id,
797
+ f"✅ Report submitted for <code>{phone}</code>.")
798
+ _log_activity(user, "report", phone, "text", reason[:80])
799
+ return
800
+
801
+ if text in ("/start", "/help"):
802
+ _log_activity(user, "start", text, "text")
803
+ await send(chat_id, WELCOME_TEMPLATE.format(v=VERSION))
804
+ if not warmed.is_set():
805
+ threading.Thread(target=warm_phone_cache, daemon=True).start()
806
+ return
807
+
808
+ if "," in text:
809
+ parts = [p.strip() for p in text.split(",") if p.strip()]
810
+ if len(parts) < 2:
811
+ await send(chat_id,
812
+ "❌ <b>Batch format</b>\n\n"
813
+ "Example: <code>9876543210,9876543211</code>")
814
+ return
815
+ if len(parts) > BATCH_MAX:
816
+ await send(chat_id,
817
+ f"❌ Max {BATCH_MAX} numbers per batch.")
818
+ return
819
+ phones = []
820
+ for p in parts:
821
+ ph, hint = normalize_phone(p)
822
+ if not ph:
823
+ await send(chat_id,
824
+ f"❌ Invalid: <code>{esc(p)}</code> — {hint}")
825
+ return
826
+ phones.append(ph)
827
+ await _handle_batch(chat_id, user, phones)
828
+ return
829
+
830
+ phone, hint = normalize_phone(text)
831
+ if not phone:
832
+ _log_activity(user, "invalid", text, "error", hint)
833
+ await send(chat_id,
834
+ "❌ <b>Invalid input</b>\n\n"
835
+ "Send a 10-digit number.\n"
836
+ "Also accepts: <code>+91 98765 43210</code>, "
837
+ "<code>09876543210</code>, "
838
+ "<code>9876543210,9876543211</code>")
839
+ return
840
+
841
+ remaining_mute = check_flood(user_id)
842
+ if remaining_mute:
843
+ await send(chat_id,
844
+ f"⏳ Slow down! Try again in {remaining_mute}s.")
845
+ _log_activity(user, "flood_muted", phone, "blocked",
846
+ f"{remaining_mute}s")
847
+ return
848
+
849
+ now = time.time()
850
+ if now - USER_LAST.get(user_id, 0) < USER_COOLDOWN:
851
+ wait = USER_COOLDOWN - (now - USER_LAST.get(user_id, 0))
852
+ _log_activity(user, "cooldown", phone, "text",
853
+ f"wait {wait:.0f}s")
854
+ await send(chat_id, f"⏳ Wait {wait:.0f}s before next search.")
855
+ return
856
+ USER_LAST[user_id] = now
857
+
858
+ ok, remaining = check_quota(user_id)
859
+ if not ok:
860
+ await send(chat_id,
861
+ f"❌ <b>Daily quota reached</b>\n\n"
862
+ f"You've used all {DAILY_QUOTA} queries for today.\n"
863
+ f"Resets at 00:00 UTC.")
864
+ _log_activity(user, "quota_exceeded", phone, "blocked")
865
+ return
866
+ incr_quota(user_id)
867
 
868
+ if text.strip() != phone and not text.strip().isdigit():
869
+ await send(chat_id, f"ℹ️ Interpreted as <code>{phone}</code>")
870
+ if not warmed.is_set():
871
+ threading.Thread(target=warm_phone_cache, daemon=True).start()
872
+
873
+ placeholder = await send(
874
+ chat_id,
875
+ f"🔍 <b>Searching…</b>\n\n📱 <code>{esc(phone)}</code>\n\n"
876
+ f"<i>Fast results appear instantly; database enrich follows.</i>")
877
+ if placeholder is None:
878
+ return
879
+
880
+ try:
881
+ await _do_progressive_search(phone, chat_id, placeholder, user)
882
+ except asyncio.TimeoutError:
883
+ STATS["timeouts"] += 1
884
+ _log_activity(user, "search", phone, "timeout",
885
+ "progressive timeout")
886
+ await edit(chat_id, placeholder, "⏱️ Timed out. Try again.")
887
+ except Exception as e:
888
+ STATS["errors"] += 1
889
+ log.error(f"progressive search error: {e!r}\n"
890
+ f"{traceback.format_exc()}")
891
+ _log_activity(user, "search", phone, "error", str(e)[:100])
892
+ await edit(chat_id, placeholder,
893
+ f"❌ Error: <code>{esc(str(e)[:200])}</code>")
894
+ except Exception as e:
895
+ log.error(f"handle_message fatal: {e!r}\n{traceback.format_exc()}")
896
 
897
  # ══════════════════════════════════════════════════════════════════
898
+ # ADMIN COMMANDS
899
  # ══════════════════════════════════════════════════════════════════
900
+ async def _handle_admin_command(chat_id, user, text, user_id):
901
+ global BACKUP_ENABLED
902
+ cmd = text.split()[0].lower()
903
+ args = text.split()[1:]
904
 
905
+ if cmd == "/live":
906
+ _log_activity(user, "admin", "/live", "text")
907
+ await send(chat_id, render_live())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
908
  return
909
+ if cmd == "/stats":
910
+ _log_activity(user, "admin", "/stats", "text")
911
+ await send(chat_id, render_stats())
912
  return
913
+ if cmd == "/users":
914
+ _log_activity(user, "admin", "/users", "text")
915
+ t, kb = render_users(0)
916
+ await send(chat_id, t, reply_markup=kb)
917
+ return
918
+ if cmd == "/top":
919
+ _log_activity(user, "admin", "/top", "text")
920
+ await send(chat_id, render_top())
921
+ return
922
+ if cmd == "/log":
923
+ entries = list(ACTIVITY_LOG)
924
+ entries.reverse()
925
+ label = ""
926
+ if args:
927
+ try:
928
+ tid = int(args[0])
929
+ entries = [e for e in entries if e["user_id"] == tid]
930
+ label = f" (user {tid})"
931
+ except ValueError:
932
+ target = args[0].lstrip("@").lower()
933
+ entries = [e for e in entries
934
+ if (e.get("username") or "").lower() == target]
935
+ label = f" (@{target})"
936
+ _log_activity(user, "admin", text, "log_view")
937
+ t, kb = render_log(entries, 0)
938
+ if label:
939
+ t = t.replace("<b>Activity Log</b>",
940
+ f"<b>Activity Log{label}</b>", 1)
941
+ await send(chat_id, t, reply_markup=kb)
942
+ return
943
+ if cmd == "/banned":
944
+ _log_activity(user, "admin", "/banned", "text")
945
+ await send(chat_id, render_banned())
946
+ return
947
+ if cmd == "/ban":
948
+ if not args:
949
+ _admin_state_set(user_id, "await_ban_id")
950
+ await send(chat_id, "Send user ID (and optional reason):")
951
+ return
952
+ try:
953
+ tid = int(args[0].lstrip("@"))
954
+ except ValueError:
955
+ await send(chat_id, "❗ Invalid user ID.")
956
+ return
957
+ reason = " ".join(args[1:]) if len(args) > 1 else ""
958
+ _ban_user(tid, reason)
959
+ _log_activity(user, "admin", f"/ban {tid}", "banned",
960
+ reason or "no reason")
961
+ await send(chat_id,
962
+ f"🚫 Banned <code>{tid}</code> — "
963
+ f"{esc(reason or 'no reason')}")
964
+ return
965
+ if cmd == "/unban":
966
+ if not args:
967
+ _admin_state_set(user_id, "await_unban_id")
968
+ await send(chat_id, "Send user ID to unban:")
969
+ return
970
+ try:
971
+ tid = int(args[0])
972
+ except ValueError:
973
+ await send(chat_id, "❗ Invalid user ID.")
974
+ return
975
+ ok = _unban_user(tid)
976
+ _log_activity(user, "admin", f"/unban {tid}", "unbanned")
977
+ await send(chat_id,
978
+ "✅ Unbanned." if ok else "ℹ️ User was not banned.")
979
+ return
980
+ if cmd == "/broadcast":
981
+ if not args:
982
+ _admin_state_set(user_id, "await_broadcast")
983
+ await send(chat_id,
984
+ "Send the message to broadcast to all users:")
985
+ return
986
+ await send(chat_id,
987
+ "ℹ️ Use /broadcast with no args, then send the message.")
988
+ return
989
+ if cmd == "/export":
990
+ _log_activity(user, "admin", "/export", "file")
991
+ await _send_log_export(chat_id)
992
+ return
993
+ if cmd == "/logphone":
994
+ if not args:
995
+ _admin_state_set(user_id, "await_logphone")
996
+ await send(chat_id, "Send a 10-digit number to search the log:")
997
+ return
998
+ phone, hint = normalize_phone(args[0])
999
+ if not phone:
1000
+ await send(chat_id, f"❗ {hint}")
1001
+ return
1002
+ entries = [e for e in ACTIVITY_LOG
1003
+ if e["action"] == "search" and e["input"] == phone]
1004
+ entries.reverse()
1005
+ if not entries:
1006
+ await send(chat_id, f"🔎 No searches for <code>{phone}</code>.")
1007
+ return
1008
+ lines = [f"🔎 <b>Searches for</b> <code>{phone}</code> "
1009
+ f"({len(entries)})\n"]
1010
+ for e in entries[:20]:
1011
+ uname = e.get("username")
1012
+ first = e.get("first_name")
1013
+ nm = f"@{uname}" if uname else (first or "(anon)")
1014
+ lines.append(f"• {_fmt_ts(e['ts'])} · {esc(nm)} · "
1015
+ f"<code>{e['user_id']}</code>")
1016
+ await send(chat_id, "\n".join(lines))
1017
+ return
1018
+ if cmd == "/maintenance":
1019
+ if not args:
1020
+ m_on, m_reason = _get_maintenance()
1021
+ st = "ON" if m_on else "OFF"
1022
+ await send(chat_id, f"🛠️ Maintenance: <b>{st}</b>" +
1023
+ (f"\nReason: {esc(m_reason)}" if m_on else ""))
1024
+ return
1025
+ mode = args[0].lower()
1026
+ if mode == "on":
1027
+ reason = " ".join(args[1:]) if len(args) > 1 else ""
1028
+ if reason:
1029
+ _set_maintenance(True, reason)
1030
+ _log_activity(user, "admin", "maintenance on", "state",
1031
+ reason)
1032
+ await send(chat_id, f"🔴 Maintenance ON — {esc(reason)}")
1033
+ else:
1034
+ _admin_state_set(user_id, "await_maint_reason")
1035
+ await send(chat_id, "Send a short reason for maintenance:")
1036
+ return
1037
+ elif mode == "off":
1038
+ _set_maintenance(False)
1039
+ _log_activity(user, "admin", "maintenance off", "state")
1040
+ await send(chat_id, "🟢 Maintenance OFF")
1041
+ return
1042
+ await send(chat_id, "Usage: /maintenance on|off [reason]")
1043
+ return
1044
+ if cmd == "/apistatus":
1045
+ await send(chat_id, "🔍 Pinging APIs…")
1046
+ h = await check_api_health()
1047
+ lines = ["🔧 <b>API Status</b>\n"]
1048
+ for name, st in h.items():
1049
+ icon = "✅" if st.get("ok") else "❌"
1050
+ lines.append(f"{icon} <code>{name}</code> — "
1051
+ f"{st.get('latency_ms', '?')}ms")
1052
+ await send(chat_id, "\n".join(lines))
1053
+ _log_activity(user, "admin", "/apistatus", "text")
1054
+ return
1055
+ if cmd == "/backup":
1056
+ if not args:
1057
+ await send(chat_id,
1058
+ f"📥 Backup forwarding: "
1059
+ f"<b>{'ON' if BACKUP_ENABLED else 'OFF'}</b>")
1060
+ return
1061
+ mode = args[0].lower()
1062
+ if mode == "on":
1063
+ BACKUP_ENABLED = True
1064
+ _log_activity(user, "admin", "backup on", "state")
1065
+ await send(chat_id, "✅ Backup forwarding ON")
1066
+ elif mode == "off":
1067
+ BACKUP_ENABLED = False
1068
+ _log_activity(user, "admin", "backup off", "state")
1069
+ await send(chat_id, "🚫 Backup forwarding OFF")
1070
+ else:
1071
+ await send(chat_id, "Usage: /backup on|off")
1072
+ return
1073
+ if cmd == "/reload":
1074
+ from bot_state import (_member_cache, _pending_query, _seen_updates,
1075
+ _member_lock, _pending_lock, _seen_updates_lock)
1076
+ with _member_lock:
1077
+ _member_cache.clear()
1078
+ with _pending_lock:
1079
+ _pending_query.clear()
1080
+ with _seen_updates_lock:
1081
+ _seen_updates.clear()
1082
+ SEARCH_CACHE.clear()
1083
+ _log_activity(user, "admin", "/reload", "state")
1084
+ await send(chat_id, "✅ Caches cleared")
1085
+ return
1086
+ if cmd == "/cancel":
1087
+ _admin_state_clear(user_id)
1088
+ _log_activity(user, "admin", "/cancel", "state")
1089
+ await send(chat_id, "✅ Pending prompt cancelled")
1090
+ return
1091
+ await send(chat_id, render_admin_menu(), reply_markup=admin_menu_kb())
1092
 
1093
+ # ══════════════════════════════════════════════════════════════════
1094
+ # BATCH / BROADCAST / EXPORT
1095
+ # ══════════════════════════════════════════════════════════════════
1096
+ async def _handle_batch(chat_id, user, phones):
1097
+ await send(chat_id,
1098
+ f"🔍 <b>Batch search</b> — {len(phones)} number(s)…")
1099
+ t0 = time.time()
1100
+ tasks = [asyncio.create_task(_search_quiet(p)) for p in phones]
1101
+ results = await asyncio.gather(*tasks, return_exceptions=True)
1102
+ total_elapsed = time.time() - t0
1103
+ lines = [f"📊 <b>Batch results</b> ({len(phones)} numbers) — "
1104
+ f"{total_elapsed:.1f}s\n"]
1105
+ for phone, res in zip(phones, results):
1106
+ if isinstance(res, Exception):
1107
+ lines.append(f"❌ <code>{phone}</code> — error: "
1108
+ f"{esc(str(res)[:60])}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1109
  else:
1110
+ n, ok = res
1111
+ lines.append(f"✅ <code>{phone}</code> — {n} record(s)"
1112
+ if ok else
1113
+ f"❌ <code>{phone}</code> — no results")
1114
+ kb_rows = [[{"text": f"View {p}", "callback_data": f"h:{p}"}]
1115
+ for p in phones]
1116
+ _log_activity(user, "batch_search", ",".join(phones), "text",
1117
+ f"{len(phones)} nums in {total_elapsed:.1f}s")
1118
+ await send(chat_id, "\n".join(lines),
1119
+ reply_markup={"inline_keyboard": kb_rows})
1120
 
1121
+
1122
+ async def _run_broadcast(admin_chat_id, message):
1123
+ with _activity_lock:
1124
+ recipients = list(UNIQUE_USERS.keys())
1125
+ if not recipients:
1126
+ await send(admin_chat_id, "📭 No users to broadcast to.")
1127
+ return
1128
+ message = message[:BROADCAST_MAX_LEN]
1129
+ await send(admin_chat_id,
1130
+ f"📢 Broadcasting to <b>{len(recipients)}</b> users…")
1131
+ sent = 0
1132
+ failed = 0
1133
+ for uid in recipients:
1134
+ if _is_banned(uid):
1135
+ continue
1136
+ try:
1137
+ res = await tg("sendMessage",
1138
+ {"chat_id": uid,
1139
+ "text": f"📢 <b>Announcement</b>\n\n{message}",
1140
+ "parse_mode": "HTML",
1141
+ "disable_web_page_preview": True},
1142
+ timeout=15)
1143
+ if res.get("ok"):
1144
+ sent += 1
1145
+ else:
1146
+ failed += 1
1147
+ except Exception:
1148
+ failed += 1
1149
+ await asyncio.sleep(BROADCAST_DELAY)
1150
+ await send(admin_chat_id,
1151
+ f"✅ <b>Broadcast complete</b>\n\n"
1152
+ f"Sent: <code>{sent}</code>\n"
1153
+ f"Failed: <code>{failed}</code>")
1154
+ _log_activity({"id": 0}, "admin", "broadcast", "done",
1155
+ f"sent={sent} failed={failed}")
 
 
 
 
 
1156
 
1157
 
1158
+ async def _send_log_export(chat_id):
1159
+ entries = list(ACTIVITY_LOG)
1160
+ if not entries:
1161
+ await send(chat_id, "📭 No activity to export.")
1162
+ return
1163
+ buf = io.StringIO()
1164
+ w = csv.writer(buf)
1165
+ w.writerow(["timestamp", "user_id", "username", "first_name",
1166
+ "action", "input", "reply_type", "summary",
1167
+ "elapsed_ms", "source"])
1168
+ for e in entries:
1169
+ w.writerow([
1170
+ time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["ts"])),
1171
+ e["user_id"], e.get("username") or "",
1172
+ e.get("first_name") or "", e["action"],
1173
+ e.get("input", ""), e.get("reply_type", ""),
1174
+ e.get("summary", ""), e.get("elapsed_ms", 0),
1175
+ e.get("source", ""),
1176
+ ])
1177
+ csv_bytes = buf.getvalue().encode("utf-8")
1178
+ ts = time.strftime("%Y%m%d_%H%M%S")
1179
+ await send_document(chat_id, f"activity_log_{ts}.csv", csv_bytes,
1180
+ caption=f"📥 Activity log — {len(entries)} entries")
1181
+
1182
  # ══════════════════════════════════════════════════════════════════
1183
+ # CALLBACK HANDLER
1184
  # ══════════════════════════════════════════════════════════════════
1185
+ async def handle_callback(cb):
1186
+ global BACKUP_ENABLED
1187
  try:
1188
+ data = cb.get("data", "")
1189
+ cb_id = cb["id"]
1190
+ msg = cb.get("message") or {}
1191
+ chat_id = msg.get("chat", {}).get("id")
1192
+ message_id = msg.get("message_id")
1193
+ user = cb.get("from") or {}
1194
+ user_id = user.get("id")
1195
+ if not chat_id or not message_id:
1196
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1197
+ return
1198
+ if _is_banned(user_id):
1199
+ await tg("answerCallbackQuery",
1200
+ {"callback_query_id": cb_id,
1201
+ "text": "🚫 You are banned.",
1202
+ "show_alert": True})
1203
+ return
1204
+
1205
+ if data == "join:check":
1206
+ from bot_state import (_member_cache, _member_lock,
1207
+ _pending_query, _pending_lock)
1208
+ with _member_lock:
1209
+ _member_cache.pop(user_id, None)
1210
+ ok = await _is_channel_member(user_id)
1211
+ if not ok:
1212
+ await tg("answerCallbackQuery",
1213
+ {"callback_query_id": cb_id,
1214
+ "text": "You haven't joined yet. Please join first.",
1215
+ "show_alert": True})
1216
+ return
1217
+ await tg("answerCallbackQuery",
1218
+ {"callback_query_id": cb_id, "text": "✅ Verified!"})
1219
+ try:
1220
+ await tg("deleteMessage",
1221
+ {"chat_id": chat_id, "message_id": message_id})
1222
+ except Exception:
1223
+ pass
1224
+ with _pending_lock:
1225
+ pending = _pending_query.pop(user_id, None)
1226
+ if pending:
1227
+ ptext, _, pts = pending
1228
+ from config import PENDING_QUERY_TTL
1229
+ if time.time() - pts < PENDING_QUERY_TTL:
1230
+ await handle_message({"chat": {"id": chat_id},
1231
+ "from": user, "text": ptext})
1232
+ _log_activity(user, "join_verified", ptext[:40], "replay")
1233
+ return
1234
+ await send(chat_id,
1235
+ "✅ <b>Thanks for joining!</b>\n\n"
1236
+ "Send a 10-digit mobile number to start.")
1237
+ _log_activity(user, "join_verified", "-", "ok")
1238
+ return
1239
+
1240
+ if data.startswith("adm:"):
1241
+ if not _is_admin_session(user_id):
1242
+ await tg("answerCallbackQuery",
1243
+ {"callback_query_id": cb_id,
1244
+ "text": "Admin session expired — send /admin again.",
1245
+ "show_alert": True})
1246
+ return
1247
+ parts = data.split(":")
1248
+ action = parts[1] if len(parts) > 1 else "menu"
1249
+ if action == "menu":
1250
+ await edit(chat_id, message_id, render_admin_menu(),
1251
+ reply_markup=admin_menu_kb())
1252
+ elif action == "live":
1253
+ await edit(chat_id, message_id, render_live(),
1254
+ reply_markup=admin_menu_kb())
1255
+ elif action == "stats":
1256
+ await edit(chat_id, message_id, render_stats(),
1257
+ reply_markup=admin_menu_kb())
1258
+ elif action == "top":
1259
+ await edit(chat_id, message_id, render_top(),
1260
+ reply_markup=admin_menu_kb())
1261
+ elif action == "banned":
1262
+ await edit(chat_id, message_id, render_banned(),
1263
+ reply_markup=admin_menu_kb())
1264
+ elif action == "log":
1265
+ page = int(parts[2]) if len(parts) > 2 else 0
1266
+ entries = list(ACTIVITY_LOG)
1267
+ entries.reverse()
1268
+ t, kb = render_log(entries, page)
1269
+ await edit(chat_id, message_id, t, reply_markup=kb)
1270
+ elif action == "users":
1271
+ page = int(parts[2]) if len(parts) > 2 else 0
1272
+ t, kb = render_users(page)
1273
+ await edit(chat_id, message_id, t, reply_markup=kb)
1274
+ elif action == "ban":
1275
+ _admin_state_set(user_id, "await_ban_id")
1276
+ await edit(chat_id, message_id,
1277
+ "🚫 Send user ID (and optional reason):")
1278
+ elif action == "unban":
1279
+ _admin_state_set(user_id, "await_unban_id")
1280
+ await edit(chat_id, message_id,
1281
+ "✅ Send user ID to unban:")
1282
+ elif action == "broadcast":
1283
+ _admin_state_set(user_id, "await_broadcast")
1284
+ await edit(chat_id, message_id,
1285
+ "📢 Send the message to broadcast:")
1286
+ elif action == "export":
1287
+ await edit(chat_id, message_id, "📥 Generating export…",
1288
+ reply_markup=admin_menu_kb())
1289
+ await _send_log_export(chat_id)
1290
+ elif action == "logphone":
1291
+ _admin_state_set(user_id, "await_logphone")
1292
+ await edit(chat_id, message_id,
1293
+ "🔎 Send a 10-digit number:")
1294
+ elif action == "maint":
1295
+ m_on, _ = _get_maintenance()
1296
+ if m_on:
1297
+ _set_maintenance(False)
1298
+ await edit(chat_id, message_id,
1299
+ "🟢 Maintenance OFF",
1300
+ reply_markup=admin_menu_kb())
1301
+ else:
1302
+ _admin_state_set(user_id, "await_maint_reason")
1303
+ await edit(chat_id, message_id,
1304
+ "Send a short maintenance reason:")
1305
+ elif action == "apistatus":
1306
+ await edit(chat_id, message_id, "🔍 Pinging APIs…")
1307
+ h = await check_api_health()
1308
+ lines = ["🔧 <b>API Status</b>\n"]
1309
+ for name, st in h.items():
1310
+ icon = "✅" if st.get("ok") else "❌"
1311
+ lines.append(f"{icon} <code>{name}</code> — "
1312
+ f"{st.get('latency_ms', '?')}ms")
1313
+ await edit(chat_id, message_id, "\n".join(lines),
1314
+ reply_markup=admin_menu_kb())
1315
+ elif action == "backuptoggle":
1316
+ BACKUP_ENABLED = not BACKUP_ENABLED
1317
+ await edit(chat_id, message_id, render_admin_menu(),
1318
+ reply_markup=admin_menu_kb())
1319
+ elif action == "noop":
1320
+ pass
1321
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1322
+ _log_activity(user, "admin", data, "menu")
1323
+ return
1324
+
1325
+ if data.startswith("h:"):
1326
+ phone = data.split(":", 1)[1]
1327
+ await tg("answerCallbackQuery",
1328
+ {"callback_query_id": cb_id,
1329
+ "text": f"Searching {phone}…"})
1330
+ await handle_message({"chat": {"id": chat_id},
1331
+ "from": user, "text": phone})
1332
+ return
1333
+
1334
+ if data.startswith("c:"):
1335
+ try:
1336
+ _, sid, page_s = data.split(":")
1337
+ page = int(page_s)
1338
+ except Exception:
1339
+ await tg("answerCallbackQuery",
1340
+ {"callback_query_id": cb_id})
1341
+ return
1342
+ with SEARCH_CACHE_LOCK:
1343
+ entry = SEARCH_CACHE.get(sid)
1344
+ if not entry:
1345
+ await tg("answerCallbackQuery",
1346
+ {"callback_query_id": cb_id,
1347
+ "text": "Session expired.",
1348
+ "show_alert": True})
1349
+ return
1350
+ results = entry["results"]
1351
+ total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
1352
+ page = max(0, min(page, total_pages - 1))
1353
+ start = page * PAGE_SIZE
1354
+ chunk = results[start:start + PAGE_SIZE]
1355
+ text = "\n\n".join(_plain_record(start + i + 1, r)
1356
+ for i, r in enumerate(chunk))
1357
+ await send(chat_id,
1358
+ f"<b>📋 Copy text for page {page + 1}</b>\n\n"
1359
+ f"<pre>{esc(text[:3500])}</pre>")
1360
+ await tg("answerCallbackQuery",
1361
+ {"callback_query_id": cb_id,
1362
+ "text": "Sent as copyable message"})
1363
+ _log_activity(user, "copy", entry["query"], "text")
1364
+ return
1365
+
1366
+ if data.startswith("e:"):
1367
+ sid = data.split(":", 1)[1]
1368
+ with SEARCH_CACHE_LOCK:
1369
+ entry = SEARCH_CACHE.get(sid)
1370
+ if not entry:
1371
+ await tg("answerCallbackQuery",
1372
+ {"callback_query_id": cb_id,
1373
+ "text": "Session expired.",
1374
+ "show_alert": True})
1375
+ return
1376
+ phone = entry["query"]
1377
+ results = entry["results"]
1378
+ payload = json.dumps({
1379
+ "phone": phone,
1380
+ "records": results,
1381
+ "extras": entry.get("extras_block", ""),
1382
+ "source_note": entry.get("source_note", ""),
1383
+ "elapsed_s": entry.get("elapsed", 0),
1384
+ "asurpapa": entry.get("asur_data", {}),
1385
+ }, indent=2, ensure_ascii=False,
1386
+ default=str).encode("utf-8")
1387
+ await send_document(chat_id, f"results_{phone}.json", payload,
1388
+ caption=f"📥 {len(results)} record(s) "
1389
+ f"for {phone}")
1390
+ await tg("answerCallbackQuery",
1391
+ {"callback_query_id": cb_id, "text": "Sent as file"})
1392
+ _log_activity(user, "export", phone, "file",
1393
+ f"{len(results)} records")
1394
+ return
1395
+
1396
+ if data == "noop" or not data.startswith("p:"):
1397
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1398
+ return
1399
+
1400
+ try:
1401
+ _, search_id, page_str = data.split(":")
1402
+ page = int(page_str)
1403
+ except Exception:
1404
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1405
+ return
1406
+
1407
+ with SEARCH_CACHE_LOCK:
1408
+ entry = SEARCH_CACHE.get(search_id)
1409
+ if not entry:
1410
+ await tg("answerCallbackQuery",
1411
+ {"callback_query_id": cb_id,
1412
+ "text": "Session expired — search again.",
1413
+ "show_alert": True})
1414
+ return
1415
+ results = entry["results"]
1416
+ total_pages = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
1417
+ page = max(0, min(page, total_pages - 1))
1418
+ await edit(chat_id, message_id,
1419
+ render_page(results, page, total_pages, entry["query"],
1420
+ entry["elapsed"],
1421
+ entry.get("source_note", ""),
1422
+ entry.get("extras_block", "")),
1423
+ reply_markup=page_keyboard(search_id, page, total_pages))
1424
+ await tg("answerCallbackQuery", {"callback_query_id": cb_id})
1425
+ _log_activity(user, "paginate", entry["query"], "page",
1426
+ f"page {page + 1}/{total_pages}")
1427
  except Exception as e:
1428
+ log.error(f"handle_callback fatal: {e!r}\n{traceback.format_exc()}")
1429
+
1430
+ # ══════════════════════════════════════════════════════════════════
1431
+ # RE-EXPORTS — everything app.py and admin_panel.py need
1432
+ # ══════════════════════════════════════════════════════════════════
1433
+ __all__ = [
1434
+ "handle_message", "handle_callback", "is_duplicate_update", "cache_gc",
1435
+ "tg", "send", "edit", "send_document",
1436
+ "ACTIVITY_LOG", "UNIQUE_USERS", "ACTIVE_USERS", "BANNED_USERS",
1437
+ "BAN_REASONS", "MAINTENANCE_MODE", "SEARCH_CACHE", "STATS",
1438
+ "BACKUP_ENABLED", "USER_HISTORY", "USER_LAST", "PHONE_COUNTS",
1439
+ "_activity_lock", "_state_lock", "SEARCH_CACHE_LOCK",
1440
+ "_ban_user", "_unban_user",
1441
+ "_set_maintenance", "_get_maintenance",
1442
+ "_revoke_admin", "_is_admin_session", "_grant_admin",
1443
+ "_get_stats", "_get_live_users",
1444
+ "_short_user", "_fmt_ts", "_today_utc",
1445
+ "_log_activity", "_add_to_history",
1446
+ "_is_banned", "_is_unlimited",
1447
+ "check_quota", "incr_quota", "check_flood",
1448
+ "check_force_join",
1449
+ "_admin_state_get", "_admin_state_set", "_admin_state_clear",
1450
+ "_db_search_async", "_show_progressive", "_do_progressive_search",
1451
+ "page_keyboard", "WELCOME_TEMPLATE",
1452
+ "forward_to_backup", "_build_backup_payload",
1453
+ "_handle_batch", "_run_broadcast", "_send_log_export",
1454
+ "admin_menu_kb", "render_admin_menu", "render_live", "render_stats",
1455
+ "render_log", "render_users", "render_top", "render_banned",
1456
+ ]