Hfzune commited on
Commit
2c4f66a
·
verified ·
1 Parent(s): 403e043

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +412 -322
app.py CHANGED
@@ -1,77 +1,46 @@
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
@@ -80,20 +49,11 @@ except ImportError:
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,
@@ -103,29 +63,301 @@ logging.basicConfig(
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"]))
@@ -133,137 +365,115 @@ async def webhook_handler(request: Request):
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():
@@ -272,111 +482,12 @@ def _set_webhook_async():
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()
@@ -386,101 +497,80 @@ def _boot():
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
+ # app.py — Diagnostic + degraded-mode entry point (v2.0.2)
2
+ # If bot.py is broken/truncated, this file keeps the Space ALIVE,
3
+ # logs EXACTLY what's wrong, and serves /debug for browser inspection.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  # ══════════════════════════════════════════════════════════════════
6
+ # STEP 0: HfFolder monkey-patch (MUST be first)
7
  # ══════════════════════════════════════════════════════════════════
8
  import huggingface_hub
 
9
  if not hasattr(huggingface_hub, "HfFolder"):
10
  class _HfFolder:
11
  @staticmethod
12
  def get_token():
13
+ try: return huggingface_hub.get_token()
14
+ except Exception: return None
 
 
 
15
  @staticmethod
16
+ def save_token(t):
17
+ try: huggingface_hub.login(t)
18
+ except Exception: pass
 
 
 
19
  @staticmethod
20
  def delete_token():
21
+ try: huggingface_hub.logout()
22
+ except Exception: pass
 
 
 
23
  huggingface_hub.HfFolder = _HfFolder
24
 
25
  # ══════════════════════════════════════════════════════════════════
26
+ # STEP 1: stdlib
27
  # ══════════════════════════════════════════════════════════════════
28
  import asyncio
29
  import logging
30
+ import os
31
+ import sys
32
  import threading
33
  import time
34
  import traceback
35
 
36
  # ══════════════════════════════════════════════════════════════════
37
+ # STEP 2: third-party
38
  # ══════════════════════════════════════════════════════════════════
39
  import gradio as gr
40
  from fastapi import Request
41
  from fastapi.responses import JSONResponse
42
  from starlette.routing import Route as StarletteRoute
43
 
 
44
  try:
45
  import spaces
46
  _HAS_SPACES = True
 
49
  class spaces:
50
  @staticmethod
51
  def GPU(*_a, **_kw):
52
+ def deco(f): return f
 
53
  return deco
54
 
55
  # ══════════════════════════════════════════════════════════════════
56
+ # STEP 3: logging
 
 
 
 
 
 
 
 
57
  # ══════════════════════════════════════════════════════════════════
58
  logging.basicConfig(
59
  level=logging.INFO,
 
63
  log = logging.getLogger("app")
64
 
65
  # ══════════════════════════════════════════════════════════════════
66
+ # STEP 4: project modules
67
+ # ══════════════════════════════════════════════════════════════════
68
+ import config
69
+ import engine
70
+
71
+ # ── bot — wrapped so we can diagnose instead of crashing ──
72
+ _BOT_IMPORT_ERROR = None
73
+ _BOT_LOADED = False
74
+ try:
75
+ import bot
76
+ except Exception as _e:
77
+ _BOT_IMPORT_ERROR = f"{type(_e).__name__}: {_e}"
78
+ log.error(f"❌ import bot failed: {_BOT_IMPORT_ERROR}")
79
+ log.error(traceback.format_exc())
80
+ # Create an empty stand-in module
81
+ import types
82
+ bot = types.ModuleType("bot")
83
+ sys.modules["bot"] = bot
84
+
85
+ # ══════════════════════════════════════════════════════════════════
86
+ # STEP 5: bot module verification + diagnostics
87
+ # ══════════════════════════════════════════════════════════════════
88
+ REQUIRED_ATTRS = [
89
+ "handle_message", "handle_callback", "is_duplicate_update", "cache_gc",
90
+ "SEARCH_CACHE", "UNIQUE_USERS", "ACTIVE_USERS", "STATS",
91
+ "ACTIVITY_LOG", "BANNED_USERS", "BAN_REASONS", "MAINTENANCE_MODE",
92
+ "BACKUP_ENABLED", "_ban_user", "_unban_user",
93
+ "_set_maintenance", "_get_maintenance",
94
+ "_revoke_admin", "_is_admin_session",
95
+ "_activity_lock", "_state_lock",
96
+ "_get_stats", "_get_live_users",
97
+ ]
98
+
99
+
100
+ def _inspect_bot_file() -> dict:
101
+ """Read bot.py from disk and report lines/size/first+last lines."""
102
+ info = {"path": None, "exists": False, "lines": 0, "size": 0,
103
+ "first_5": [], "last_5": []}
104
+ for candidate in ("/app/bot.py", os.path.join(os.getcwd(), "bot.py"), "bot.py"):
105
+ if os.path.exists(candidate):
106
+ info["path"] = os.path.abspath(candidate)
107
+ info["exists"] = True
108
+ break
109
+ if not info["exists"]:
110
+ return info
111
+ try:
112
+ with open(info["path"], "r", encoding="utf-8") as f:
113
+ content = f.read()
114
+ info["size"] = len(content.encode("utf-8"))
115
+ lines = content.splitlines()
116
+ info["lines"] = len(lines)
117
+ info["first_5"] = lines[:5]
118
+ info["last_5"] = lines[-5:] if len(lines) >= 5 else lines
119
+ except Exception as e:
120
+ info["error"] = str(e)
121
+ return info
122
+
123
+
124
+ def _inspect_bot_module() -> dict:
125
+ """Report what Python actually loaded for the `bot` module."""
126
+ try:
127
+ module_file = getattr(bot, "__file__", None)
128
+ attrs = [a for a in dir(bot) if not a.startswith("__")]
129
+ return {
130
+ "module_file": module_file,
131
+ "module_name": getattr(bot, "__name__", None),
132
+ "attr_count": len(attrs),
133
+ "attrs_sample": attrs[:50],
134
+ }
135
+ except Exception as e:
136
+ return {"error": str(e)}
137
+
138
+
139
+ def _check_bot() -> dict:
140
+ """Return diagnostic dict + set _BOT_LOADED."""
141
+ global _BOT_LOADED
142
+ missing = [a for a in REQUIRED_ATTRS if not hasattr(bot, a)]
143
+ diag = {
144
+ "import_error": _BOT_IMPORT_ERROR,
145
+ "module": _inspect_bot_module(),
146
+ "file": _inspect_bot_file(),
147
+ "missing_attrs": missing,
148
+ "ok": (not missing) and (not _BOT_IMPORT_ERROR),
149
+ }
150
+ _BOT_LOADED = diag["ok"]
151
+ return diag
152
+
153
+
154
+ def _install_bot_stubs():
155
+ """Fill in every missing attribute so downstream code doesn't crash."""
156
+ if _BOT_LOADED:
157
+ return
158
+
159
+ def _noop_async(*a, **kw):
160
+ return None
161
+
162
+ async def _offline_reply(*a, **kw):
163
+ """Placeholder handler — tells user the bot is under repair."""
164
+ try:
165
+ chat_id = kw.get("chat_id")
166
+ if chat_id:
167
+ await bot.send(chat_id,
168
+ "⚠️ <b>Bot is being repaired</b>\n\n"
169
+ "The bot module failed to load. Admin has been notified.\n"
170
+ "Please try again in a few minutes.")
171
+ except Exception:
172
+ pass
173
+
174
+ async def _offline_send(chat_id, text, **kw):
175
+ """Minimal Telegram send that bypasses bot module entirely."""
176
+ try:
177
+ import httpx
178
+ payload = {"chat_id": chat_id, "text": text,
179
+ "parse_mode": "HTML",
180
+ "disable_web_page_preview": True}
181
+ payload.update({k: v for k, v in kw.items() if v is not None})
182
+ async with httpx.AsyncClient(timeout=15) as cli:
183
+ r = await cli.post(
184
+ f"{config.TELEGRAM_API}/sendMessage", json=payload)
185
+ return r.json().get("result", {}).get("message_id")
186
+ except Exception as e:
187
+ log.warning(f"[stub-send] {e!r}")
188
+ return None
189
+
190
+ # Locks
191
+ if not hasattr(bot, "_activity_lock"):
192
+ bot._activity_lock = threading.Lock()
193
+ if not hasattr(bot, "_state_lock"):
194
+ bot._state_lock = threading.Lock()
195
+
196
+ # State containers
197
+ defaults = {
198
+ "SEARCH_CACHE": {}, "UNIQUE_USERS": {}, "ACTIVE_USERS": {},
199
+ "ACTIVITY_LOG": [], "BANNED_USERS": set(), "BAN_REASONS": {},
200
+ "MAINTENANCE_MODE": False, "BACKUP_ENABLED": False,
201
+ "USER_HISTORY": {}, "USER_LAST": {}, "PHONE_COUNTS": {},
202
+ "STATS": {"queries": 0, "timeouts": 0, "errors": 0,
203
+ "backup_sent": 0, "started": time.time()},
204
+ }
205
+ for k, v in defaults.items():
206
+ if not hasattr(bot, k):
207
+ setattr(bot, k, v)
208
+
209
+ # Handlers
210
+ if not hasattr(bot, "send"):
211
+ bot.send = _offline_send
212
+ if not hasattr(bot, "edit"):
213
+ async def _offline_edit(chat_id, message_id, text, **kw):
214
+ return None
215
+ bot.edit = _offline_edit
216
+ if not hasattr(bot, "tg"):
217
+ async def _offline_tg(method, payload, timeout=15):
218
+ return {"ok": False, "error": "bot offline"}
219
+ bot.tg = _offline_tg
220
+ if not hasattr(bot, "send_document"):
221
+ async def _offline_doc(chat_id, filename, content, caption=""):
222
+ return {"ok": False}
223
+ bot.send_document = _offline_doc
224
+
225
+ if not hasattr(bot, "handle_message"):
226
+ async def _stub_handle_message(msg):
227
+ log.warning("[stub] handle_message called but bot is offline")
228
+ try:
229
+ chat_id = (msg.get("chat") or {}).get("id")
230
+ if chat_id:
231
+ await _offline_send(chat_id,
232
+ "⚠️ <b>Bot is being repaired</b>\n\n"
233
+ "Your message was received but the bot module "
234
+ "isn't loaded. Admin has been notified.\n"
235
+ "Try again in a few minutes.")
236
+ except Exception:
237
+ pass
238
+ bot.handle_message = _stub_handle_message
239
+
240
+ if not hasattr(bot, "handle_callback"):
241
+ async def _stub_handle_callback(cb):
242
+ log.warning("[stub] handle_callback called but bot is offline")
243
+ try:
244
+ cb_id = cb.get("id")
245
+ if cb_id:
246
+ import httpx
247
+ async with httpx.AsyncClient(timeout=10) as cli:
248
+ await cli.post(
249
+ f"{config.TELEGRAM_API}/answerCallbackQuery",
250
+ json={"callback_query_id": cb_id,
251
+ "text": "Bot is offline. Try later.",
252
+ "show_alert": True})
253
+ except Exception:
254
+ pass
255
+ bot.handle_callback = _stub_handle_callback
256
+
257
+ if not hasattr(bot, "is_duplicate_update"):
258
+ bot.is_duplicate_update = lambda update_id: False
259
+
260
+ if not hasattr(bot, "cache_gc"):
261
+ def _stub_gc():
262
+ while True:
263
+ time.sleep(3600)
264
+ bot.cache_gc = _stub_gc
265
+
266
+ # Admin helpers
267
+ for name, retval in (
268
+ ("_get_stats", lambda: {"unique_users": 0, "live_users": 0,
269
+ "today_users": 0, "today_searches": 0,
270
+ "total_searches": 0, "peak_concurrent": 0,
271
+ "total_log_entries": 0, "banned_count": 0,
272
+ "maintenance": False, "cached_searches": 0,
273
+ "backup_sent": 0}),
274
+ ("_get_live_users", lambda: []),
275
+ ("_get_maintenance", lambda: (False, "")),
276
+ ("_is_admin_session", lambda uid: False),
277
+ ("_is_banned", lambda uid: False),
278
+ ("_is_unlimited", lambda uid: False),
279
+ ("check_quota", lambda uid: (True, 100)),
280
+ ("_today_utc", lambda: time.strftime("%Y-%m-%d", time.gmtime())),
281
+ ("_fmt_ts", lambda ts: time.strftime("%H:%M:%S", time.localtime(ts))),
282
+ ("_short_user", lambda uid, user=None: f"({uid})"),
283
+ ):
284
+ if not hasattr(bot, name):
285
+ setattr(bot, name, retval)
286
+
287
+ # No-ops
288
+ for name in ("_ban_user", "_unban_user", "incr_quota",
289
+ "_set_maintenance", "_revoke_admin",
290
+ "_admin_state_clear", "_log_activity",
291
+ "_add_to_history", "_grant_admin"):
292
+ if not hasattr(bot, name):
293
+ setattr(bot, name, lambda *a, **kw: None)
294
+
295
+ for name in ("_admin_state_get",):
296
+ if not hasattr(bot, name):
297
+ setattr(bot, name, lambda uid: None)
298
+
299
+ log.info("🔧 bot stubs installed (degraded mode)")
300
+
301
+
302
+ # Run diagnostics, then stub if needed
303
+ _BOT_DIAG = _check_bot()
304
+ _install_bot_stubs()
305
+
306
+ if _BOT_LOADED:
307
+ log.info(f"✅ bot module OK ({len(REQUIRED_ATTRS)} attributes present)")
308
+ else:
309
+ log.error("╔══════════════════════════════════════════════════════════╗")
310
+ log.error("║ ⚠️ bot module is INCOMPLETE — running in DEGRADED mode ║")
311
+ log.error("╚══════════════════════════════════════════════════════════╝")
312
+ _f = _BOT_DIAG["file"]
313
+ log.error(f" bot.__file__ : {_BOT_DIAG['module'].get('module_file')}")
314
+ log.error(f" bot attr count : {_BOT_DIAG['module'].get('attr_count')}")
315
+ log.error(f" bot.py on disk : {_f.get('path')}")
316
+ log.error(f" bot.py exists : {_f.get('exists')}")
317
+ log.error(f" bot.py lines : {_f.get('lines')} ← if < 100, TRUNCATED")
318
+ log.error(f" bot.py size : {_f.get('size')} bytes")
319
+ log.error(f" bot.py first 3 : {_f.get('first_5', [])[:3]}")
320
+ log.error(f" bot.py last 3 : {_f.get('last_5', [])[-3:]}")
321
+ log.error(f" MISSING attrs : {_BOT_DIAG['missing_attrs']}")
322
+ log.error(f" import_error : {_BOT_DIAG['import_error']}")
323
+ log.error(" ⤷ Space will stay UP. Fix bot.py to restore full service.")
324
+ log.error(" ⤷ Open /debug in browser for full JSON diagnostic.")
325
+
326
+ # ══════════════════════════════════════════════════════════════════
327
+ # STEP 6: admin_panel (import after stubs so it doesn't crash)
328
+ # ══════════════════════════════════════════════════════════════════
329
+ try:
330
+ import admin_panel
331
+ _ADMIN_LOADED = True
332
+ except Exception as e:
333
+ _ADMIN_LOADED = False
334
+ log.warning(f"⚠️ admin_panel import failed: {e!r}")
335
+ log.warning(traceback.format_exc())
336
+ import types
337
+ admin_panel = types.ModuleType("admin_panel")
338
+ admin_panel.get_admin_routes = lambda: []
339
+
340
+ # ══════════════════════════════════════════════════════════════════
341
+ # STEP 7: route handlers
342
  # ══════════════════════════════════════════════════════════════════
343
  async def webhook_handler(request: Request):
 
 
344
  if config.SECRET_TOKEN:
345
  got = request.headers.get("x-telegram-bot-api-secret-token", "")
346
  if got != config.SECRET_TOKEN:
347
+ return JSONResponse({"ok": False, "reason": "bad_header"},
348
+ status_code=403)
 
349
  try:
350
  update = await request.json()
351
  except Exception:
352
  return JSONResponse({"ok": True})
353
 
 
354
  update_id = update.get("update_id")
355
+ try:
356
+ if bot.is_duplicate_update(update_id):
357
+ return JSONResponse({"ok": True})
358
+ except Exception:
359
+ pass
360
 
 
361
  try:
362
  if "message" in update:
363
  asyncio.create_task(bot.handle_message(update["message"]))
 
365
  asyncio.create_task(bot.handle_callback(update["callback_query"]))
366
  except RuntimeError:
367
  threading.Thread(
368
+ target=lambda: asyncio.run(_dispatch(update)), daemon=True
 
369
  ).start()
370
 
371
  return JSONResponse({"ok": True})
372
 
373
 
374
+ async def _dispatch(update):
 
375
  try:
376
  if "message" in update:
377
  await bot.handle_message(update["message"])
378
  elif "callback_query" in update:
379
  await bot.handle_callback(update["callback_query"])
380
  except Exception as e:
381
+ log.error(f"dispatch: {e!r}")
382
 
383
 
384
  async def health_handler(request: Request):
385
+ s = bot._get_stats() if _BOT_LOADED else {}
386
  return JSONResponse({
387
+ "status": "ok" if _BOT_LOADED else "degraded",
388
+ "version": config.VERSION,
389
+ "time": time.time(),
390
+ "bot_loaded": _BOT_LOADED,
391
+ "admin_loaded": _ADMIN_LOADED,
392
+ "missing_attrs": _BOT_DIAG["missing_attrs"],
393
+ "bot_py_lines": _BOT_DIAG["file"].get("lines"),
394
+ "bot_py_size": _BOT_DIAG["file"].get("size"),
395
+ "duckdb_ready": engine.con_ready.is_set(),
396
+ "warmed": engine.warmed.is_set(),
 
 
 
 
 
 
 
 
 
 
 
397
  })
398
 
399
 
400
+ async def debug_handler(request: Request):
401
+ """Full diagnostic — open /debug in browser, paste JSON back."""
402
+ return JSONResponse({
403
+ "version": config.VERSION,
404
+ "bot_loaded": _BOT_LOADED,
405
+ "admin_loaded": _ADMIN_LOADED,
406
+ "diagnostic": _BOT_DIAG,
407
+ "cwd": os.getcwd(),
408
+ "sys_path_first_5": sys.path[:5],
409
+ "bot_module_file": getattr(bot, "__file__", None),
410
+ })
411
+
412
  # ══════════════════════════════════════════════════════════════════
413
+ # STEP 8: Gradio UI
414
  # ══════════════════════════════════════════════════════════════════
415
+ def _build_gradio():
416
  with gr.Blocks(title=f"{config.BOT_NAME} v{config.VERSION}") as demo:
417
  gr.Markdown(f"# 🤖 {config.BOT_NAME} v{config.VERSION}")
418
+ status_md = gr.Markdown("Loading…")
419
+
420
+ def _snapshot():
421
+ if _BOT_LOADED:
422
+ return "✅ **Bot is operational**"
423
+ missing = _BOT_DIAG["missing_attrs"]
424
+ f = _BOT_DIAG["file"]
425
+ return (
426
+ f"⚠️ **Bot is in DEGRADED mode**\n\n"
427
+ f"- `bot.py` line count: **{f.get('lines')}**\n"
428
+ f"- Missing attributes: **{len(missing)}**\n"
429
+ f"- First missing: `{missing[0] if missing else '(none)'}`\n\n"
430
+ f"**Fix:** re-save `bot.py` in full. "
431
+ f"Open `/debug` in browser for details."
432
+ )
433
+
434
+ demo.load(fn=_snapshot, inputs=None, outputs=status_md)
435
+ gr.Button("🔄 Refresh").click(fn=_snapshot, inputs=None, outputs=status_md)
 
 
 
 
 
 
 
 
 
 
436
 
 
 
 
 
437
  if _HAS_SPACES:
438
  try:
439
  @spaces.GPU(duration=10)
440
+ def _zgpu(): return "ok"
441
+ _b = gr.Button("init-gpu", visible=False)
442
+ _b.click(fn=_zgpu, inputs=None, outputs=None)
443
+ except Exception:
444
+ pass
 
 
 
445
 
446
  return demo
447
 
 
448
  # ══════════════════════════════════════════════════════════════════
449
+ # STEP 9: webhook registration
450
  # ══════════════════════════════════════════════════════════════════
451
  async def _set_webhook_async_impl():
452
  if not config.BOT_TOKEN:
 
453
  return
454
+ space_url = (config.SPACE_URL or
455
+ (f"https://{config.SPACE_HOST}" if config.SPACE_HOST else ""))
456
  if not space_url:
 
457
  return
 
458
  url = f"{space_url.rstrip('/')}/webhook"
459
  payload = {
460
+ "url": url, "secret_token": config.SECRET_TOKEN,
461
+ "allowed_updates": ["message", "callback_query"],
 
462
  "drop_pending_updates": True,
463
  }
464
  import httpx
465
  for attempt in range(1, 4):
466
  try:
467
  async with httpx.AsyncClient(timeout=30) as cli:
468
+ r = await cli.post(f"{config.TELEGRAM_API}/setWebhook",
469
+ json=payload)
470
  data = r.json()
471
+ log.info(f"[setwebhook] {attempt}: {data}")
472
  if data.get("ok"):
473
  return
474
  except Exception as e:
475
+ log.warning(f"[setwebhook] {attempt}: {e!r}")
476
  await asyncio.sleep(3)
 
477
 
478
 
479
  def _set_webhook_async():
 
482
  asyncio.set_event_loop(loop)
483
  loop.run_until_complete(_set_webhook_async_impl())
484
  except Exception as e:
485
+ log.warning(f"[setwebhook] {e!r}")
 
486
 
487
  # ══════════════════════════════════════════════════════════════════
488
+ # STEP 10: boot
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
489
  # ══════════════════════════════════════════════════════════════════
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
  def _boot():
 
 
 
 
 
 
 
491
  print()
492
  print(config.summary())
493
  warnings = config._sanity_check()
 
497
  print(f" • {w}")
498
  print()
499
 
 
500
  log.info("[boot] building Gradio app…")
501
  demo = _build_gradio()
502
 
503
+ log.info("[boot] launching Gradio…")
504
+ demo.launch(server_name="0.0.0.0", server_port=7860, share=False,
505
+ ssr_mode=False, prevent_thread_lock=True, show_error=True)
506
+
507
+ log.info("[boot] injecting routes…")
 
 
 
 
 
 
 
 
508
  live_app = demo.app
509
 
510
+ live_app.router.routes.insert(
511
+ 0, StarletteRoute("/webhook", webhook_handler, methods=["POST"]))
512
+ live_app.router.routes.insert(
513
+ 0, StarletteRoute("/health", health_handler, methods=["GET"]))
514
+ live_app.router.routes.insert(
515
+ 0, StarletteRoute("/debug", debug_handler, methods=["GET"]))
516
+
517
+ # Admin routes
518
+ admin_count = 0
 
 
 
 
519
  try:
520
+ for route in admin_panel.get_admin_routes():
521
+ live_app.router.routes.insert(0, route)
522
+ admin_count += 1
523
+ if admin_count:
524
+ log.info(f"✅ injected {admin_count} admin routes")
 
525
  else:
526
+ log.info("ℹ️ no admin routes (ADMIN_TOKEN unset)")
527
  except Exception as e:
528
+ log.warning(f"⚠️ admin injection: {e!r}")
529
 
 
530
  try:
531
  live_app.build_middleware_stack()
532
+ except Exception:
533
+ pass
534
+
535
+ # Warm-up threads (safe)
536
+ for name, target in (
537
+ ("con", engine.get_con),
538
+ ("warm", engine.warm_phone_cache),
539
+ ("asur-con", getattr(engine, "get_asur_con", None)),
540
+ ("asur-warm", getattr(engine, "warm_asur_cache", None)),
541
+ ("gc", bot.cache_gc),
542
+ ("setwh", _set_webhook_async),
543
+ ):
544
+ if target and callable(target):
545
+ try:
546
+ threading.Thread(target=target, daemon=True, name=name).start()
547
+ log.info(f"✅ thread: {name}")
548
+ except Exception as e:
549
+ log.warning(f"⚠️ thread '{name}': {e!r}")
550
+
 
 
 
 
 
 
 
 
551
  print()
552
  print("═" * 60)
553
+ status = "ONLINE ✅" if _BOT_LOADED else "DEGRADED ⚠️"
554
+ print(f" {config.BOT_NAME} v{config.VERSION} — {status}")
555
  print(f" Health : /health")
556
+ print(f" Debug : /debug ← open this in browser")
557
+ print(f" Admin : {'/admin' if config.ADMIN_TOKEN else '(disabled)'}")
558
+ if not _BOT_LOADED:
559
+ print(f" ⚠️ bot.py has {_BOT_DIAG['file'].get('lines')} lines — TRUNCATED")
560
+ print(f" ⚠️ Missing {len(_BOT_DIAG['missing_attrs'])} attributes")
561
  print("═" * 60)
562
  print()
 
563
  return demo
564
 
 
565
  # ══════════════════════════════════════════════════════════════════
566
+ # STEP 11: main
567
  # ══════════════════════════════════════════════════════════════════
568
  if __name__ == "__main__":
569
  try:
570
  demo = _boot()
571
  demo.block_thread()
572
  except KeyboardInterrupt:
573
+ log.info("shutting down")
574
  except Exception as e:
575
+ log.critical(f"boot failed: {e!r}\n{traceback.format_exc()}")
576
  raise