Hfzune commited on
Commit
0636ffd
·
verified ·
1 Parent(s): fd26440

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +400 -1104
app.py CHANGED
@@ -1,1148 +1,444 @@
1
- # =====================================================================
2
- # 0. HF FOLDER PATCH
3
- # =====================================================================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
  import huggingface_hub
 
5
  if not hasattr(huggingface_hub, "HfFolder"):
6
  class _HfFolder:
7
  @staticmethod
8
- def get_token(): return huggingface_hub.get_token()
 
 
 
 
 
9
  @staticmethod
10
- def save_token(token): huggingface_hub.login(token)
 
 
 
 
 
11
  @staticmethod
12
- def delete_token(): huggingface_hub.logout()
 
 
 
 
 
13
  huggingface_hub.HfFolder = _HfFolder
14
 
15
- # =====================================================================
16
- # 1. IMPORTS
17
- # =====================================================================
18
- import spaces
19
- import os, json, time, asyncio, secrets, sqlite3, threading, traceback, base64, hmac, hashlib, collections, queue
20
- import httpx
 
 
 
 
 
 
21
  import gradio as gr
22
- from datetime import datetime
23
- from fastapi import FastAPI, Request, HTTPException, Header, Query
24
- from fastapi.responses import JSONResponse, HTMLResponse, Response
25
  from starlette.routing import Route as StarletteRoute
26
- from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup, Bot
27
- from telegram.error import BadRequest
28
-
29
- # =====================================================================
30
- # 2. CONFIG
31
- # =====================================================================
32
- BOT_TOKEN = os.getenv("BOT_TOKEN")
33
- CHANNEL_ID = os.getenv("CHANNEL_ID")
34
- LOG_CHANNEL_ID = os.getenv("LOG_CHANNEL_ID")
35
- ADMIN_ID = int(os.getenv("ADMIN_ID", "0"))
36
- ADMIN_PASSWORD = os.getenv("ADMIN_PASSWORD", "SuperSecret123")
37
- ADMIN_SECRET = (os.getenv("ADMIN_SECRET") or secrets.token_urlsafe(32)).encode()
38
- API_BASE = os.getenv("URL")
39
- API_HEALTH = os.getenv("URLH")
40
- TOKEN_TTL = 8 * 3600
41
- DB_FILE = "users.json"
42
- ACTIVITY_DB = "activity.db"
43
-
44
- def _norm_chat(cid):
45
- if not cid: return None
46
- cid = str(cid).strip()
47
- return int(cid) if cid.lstrip("-").isdigit() else cid
48
-
49
- LOG_CHANNEL_ID = _norm_chat(LOG_CHANNEL_ID)
50
-
51
- bot = Bot(token=BOT_TOKEN)
52
-
53
- USER_DB = {}
54
- seen_users = set()
55
- MAINTENANCE_MODE = False
56
-
57
- ASK_NUMBER, ASK_MESSAGE, ASK_COUNT = range(1, 4)
58
- WAITING_FOR_ADMIN_PASS = 99
59
-
60
- def default_user():
61
- return {
62
- "accepted": False, "verified": False, "state": None, "is_admin": False,
63
- "banned": False, "ban_reason": "", "warnings": 0, "is_vip": False,
64
- "daily_requests": 0, "last_reset": str(datetime.now().date()),
65
- "last_attack_time": 0, "claim_time": 0,
66
- "stats": {"requests": 0, "sent": 0},
67
- }
68
-
69
- # =====================================================================
70
- # 3. ACTIVITY LOGGER (SQLite + ring + Telegram mirror)
71
- # =====================================================================
72
- _DB = sqlite3.connect(ACTIVITY_DB, check_same_thread=False)
73
- _DB.row_factory = sqlite3.Row
74
- _DB.execute("PRAGMA journal_mode=WAL")
75
- _DB.executescript("""
76
- CREATE TABLE IF NOT EXISTS activity (
77
- id INTEGER PRIMARY KEY AUTOINCREMENT,
78
- ts REAL NOT NULL,
79
- user_id INTEGER,
80
- username TEXT,
81
- event TEXT NOT NULL,
82
- level TEXT NOT NULL,
83
- data TEXT,
84
- admin_id INTEGER,
85
- ip TEXT
86
- );
87
- CREATE INDEX IF NOT EXISTS idx_ts ON activity(ts);
88
- CREATE INDEX IF NOT EXISTS idx_user_ts ON activity(user_id, ts);
89
- CREATE INDEX IF NOT EXISTS idx_event ON activity(event, ts);
90
- CREATE INDEX IF NOT EXISTS idx_level ON activity(level, ts);
91
- """)
92
- _DB.commit()
93
- _DB_LOCK = threading.Lock()
94
- _RING = collections.deque(maxlen=500)
95
- _MIRROR_Q = queue.Queue()
96
-
97
- async def _mirror_to_channel(row):
98
- if not LOG_CHANNEL_ID:
99
- return
100
- try:
101
- icon = {"warn": "⚠️", "error": "🔥", "critical": "🚨", "audit": "📋"}.get(row["level"], "📝")
102
- ts_str = datetime.fromtimestamp(row["ts"]).strftime("%H:%M:%S")
103
- user = f"<code>{row['user_id']}</code>" if row["user_id"] else "—"
104
- data_str = json.dumps(row["data"], ensure_ascii=False)[:180]
105
- text = f"{icon} <b>{row['event'].upper()}</b> · {row['level']}\n{user} · {ts_str}\n<code>{data_str}</code>"
106
- await bot.send_message(chat_id=LOG_CHANNEL_ID, text=text, parse_mode="HTML", disable_web_page_preview=True)
107
- except Exception as e:
108
- print(f"❌ mirror error: {e!r}")
109
-
110
- def _mirror_worker():
111
- loop = asyncio.new_event_loop()
112
- asyncio.set_event_loop(loop)
113
- while True:
114
- try:
115
- row = _MIRROR_Q.get(timeout=2)
116
- if row is None: continue
117
- loop.run_until_complete(_mirror_to_channel(row))
118
- except queue.Empty:
119
- continue
120
- except Exception as e:
121
- print(f"❌ mirror worker: {e!r}")
122
-
123
- threading.Thread(target=_mirror_worker, daemon=True).start()
124
-
125
- def log_event(event, *, user_id=None, username=None, level="info", data=None, admin_id=None, ip=None):
126
- ts = time.time()
127
- payload = json.dumps(data or {}, separators=(",", ":"), ensure_ascii=False, default=str)
128
- with _DB_LOCK:
129
- cur = _DB.execute(
130
- "INSERT INTO activity(ts,user_id,username,event,level,data,admin_id,ip) VALUES (?,?,?,?,?,?,?,?)",
131
- (ts, user_id, username, event, level, payload, admin_id, ip),
132
- )
133
- _DB.commit()
134
- rid = cur.lastrowid
135
- row = {"id": rid, "ts": ts, "user_id": user_id, "username": username,
136
- "event": event, "level": level, "data": data or {}, "admin_id": admin_id, "ip": ip}
137
- _RING.append(row)
138
- if level in ("warn", "error", "critical", "audit"):
139
- _MIRROR_Q.put(row)
140
- return rid
141
-
142
- def _fetch_logs(since_id=None, before_id=None, user_id=None, event=None, level=None,
143
- q=None, from_ts=None, to_ts=None, page=1, per_page=100):
144
- where, params = [], []
145
- if since_id is not None:
146
- where.append("id > ?"); params.append(since_id)
147
- if before_id is not None:
148
- where.append("id < ?"); params.append(before_id)
149
- if user_id is not None:
150
- where.append("user_id = ?"); params.append(user_id)
151
- if event:
152
- where.append("event = ?"); params.append(event)
153
- if level:
154
- where.append("level = ?"); params.append(level)
155
- if q:
156
- where.append("(data LIKE ? OR username LIKE ? OR CAST(user_id AS TEXT) LIKE ?)")
157
- like = f"%{q}%"; params += [like, like, like]
158
- if from_ts: where.append("ts >= ?"); params.append(from_ts)
159
- if to_ts: where.append("ts <= ?"); params.append(to_ts)
160
- wsql = (" WHERE " + " AND ".join(where)) if where else ""
161
- order = "ASC" if since_id is not None else "DESC"
162
- offset = 0 if since_id is not None else (page - 1) * per_page
163
- sql = f"SELECT * FROM activity{wsql} ORDER BY id {order} LIMIT ? OFFSET ?"
164
- with _DB_LOCK:
165
- rows = _DB.execute(sql, params + [per_page, offset]).fetchall()
166
- out = []
167
- for r in rows:
168
- d = dict(r)
169
- try: d["data"] = json.loads(d["data"]) if d["data"] else {}
170
- except: d["data"] = {}
171
- out.append(d)
172
- return out
173
-
174
- def _count_logs(**kw):
175
- r = _fetch_logs(per_page=1, **kw)
176
- return len(_RING) if not r else None
177
 
178
- # =====================================================================
179
- # 4. AUTH HELPERS
180
- # =====================================================================
181
- def _b64(b): return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
182
- def _unb64(s): return base64.urlsafe_b64decode(s + "=" * (-len(s) % 4))
183
-
184
- def mint_token(admin_id):
185
- payload = json.dumps({"sub": admin_id, "exp": int(time.time()) + TOKEN_TTL, "scope": "admin"},
186
- separators=(",", ":")).encode()
187
- sig = hmac.new(ADMIN_SECRET, payload, hashlib.sha256).digest()
188
- return f"{_b64(payload)}.{_b64(sig)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
189
 
190
- def verify_token(token):
191
  try:
192
- p, s = token.split(".")
193
- payload = _unb64(p)
194
- if not hmac.compare_digest(_unb64(s), hmac.new(ADMIN_SECRET, payload, hashlib.sha256).digest()):
195
- return None
196
- d = json.loads(payload)
197
- return d if d["exp"] >= time.time() else None
198
  except Exception:
199
- return None
200
-
201
- _LOGIN_FAILS = collections.defaultdict(list)
202
- _LOGIN_LOCK = threading.Lock()
203
-
204
- def _rl_ok(ip):
205
- now = time.time()
206
- with _LOGIN_LOCK:
207
- _LOGIN_FAILS[ip] = [t for t in _LOGIN_FAILS[ip] if now - t < 300]
208
- return len(_LOGIN_FAILS[ip]) < 5
209
-
210
- def _rl_fail(ip):
211
- with _LOGIN_LOCK:
212
- _LOGIN_FAILS[ip].append(time.time())
213
-
214
- def require_admin(authorization: str = Header("")):
215
- if not authorization.startswith("Bearer "):
216
- raise HTTPException(401, "missing token")
217
- data = verify_token(authorization[7:])
218
- if not data:
219
- raise HTTPException(401, "invalid or expired token")
220
- return data["sub"]
221
-
222
- # =====================================================================
223
- # 5. DB PERSISTENCE
224
- # =====================================================================
225
- def save_db():
226
- try:
227
- with open(DB_FILE, "w") as f:
228
- json.dump(USER_DB, f, default=str)
229
- except Exception as e:
230
- print(f"❌ DB save: {e}")
231
 
232
- def load_db():
233
- global USER_DB
234
- if os.path.exists(DB_FILE):
235
- try:
236
- with open(DB_FILE, "r") as f:
237
- data = json.load(f)
238
- USER_DB = {int(k): v for k, v in data.items()}
239
- print(f"✅ Loaded {len(USER_DB)} users")
240
- except Exception as e:
241
- print(f"❌ DB load: {e}")
242
-
243
- def _bg_saver():
244
- while True:
245
- time.sleep(300)
246
- save_db()
247
-
248
- threading.Thread(target=_bg_saver, daemon=True).start()
249
- load_db()
250
-
251
- # =====================================================================
252
- # 6. ZEROGPU
253
- # =====================================================================
254
- @spaces.GPU(duration=10)
255
- def _zerogpu_register():
256
- return "gpu-ready"
257
-
258
- # =====================================================================
259
- # 7. HELPERS
260
- # =====================================================================
261
- def get_user(uid):
262
- if uid not in USER_DB:
263
- USER_DB[uid] = default_user()
264
- return USER_DB[uid]
265
-
266
- async def check_channel_membership(user_id: int) -> bool:
267
- try:
268
- m = await bot.get_chat_member(chat_id=CHANNEL_ID, user_id=user_id)
269
- return m.status not in ("left", "kicked", "restricted")
270
- except Exception:
271
- return True
272
 
273
- async def safe_edit(user_id, msg_id, text, reply_markup=None):
274
  try:
275
- await bot.edit_message_text(chat_id=user_id, message_id=msg_id, text=text,
276
- reply_markup=reply_markup, parse_mode="HTML",
277
- disable_web_page_preview=True)
278
- except BadRequest as e:
279
- if "not modified" not in str(e): print(f"edit: {e}")
280
-
281
- def _status_line(u):
282
- if MAINTENANCE_MODE: return "🛠️ Maintenance mode"
283
- if u.get("banned"): return f"🚫 Banned · {u.get('ban_reason') or 'no reason'}"
284
- rem = int(30 - (time.time() - u.get("last_attack_time", 0)))
285
- if rem > 0: return f"⏳ Cooldown · {rem}s"
286
- if u.get("is_vip"): return "👑 VIP · unlimited"
287
- return f"🟢 {u.get('daily_requests', 0)}/5 today"
288
-
289
- # =====================================================================
290
- # 8. KEYBOARDS
291
- # =====================================================================
292
- def kb_main():
293
- return InlineKeyboardMarkup([
294
- [InlineKeyboardButton("🚀 New Attack", callback_data="menu_attack")],
295
- [InlineKeyboardButton("👤 Profile", callback_data="menu_profile"),
296
- InlineKeyboardButton("🎁 Claim", callback_data="menu_claim")],
297
- [InlineKeyboardButton("📡 Health", callback_data="menu_health"),
298
- InlineKeyboardButton("📖 Help", callback_data="menu_help")],
299
- ])
300
-
301
- def kb_back():
302
- return InlineKeyboardMarkup([[InlineKeyboardButton("⬅️ Back to Menu", callback_data="menu_main")]])
303
-
304
- def kb_cancel():
305
- return InlineKeyboardMarkup([[InlineKeyboardButton("❌ Cancel", callback_data="menu_main")]])
306
-
307
- def kb_confirm():
308
- return InlineKeyboardMarkup([
309
- [InlineKeyboardButton("✅ Send", callback_data="confirm_attack"),
310
- InlineKeyboardButton("❌ Cancel", callback_data="menu_main")],
311
- ])
312
-
313
- def kb_admin():
314
- return InlineKeyboardMarkup([
315
- [InlineKeyboardButton("👥 User Stats", callback_data="admin_users"),
316
- InlineKeyboardButton("📊 Global Stats", callback_data="admin_stats")],
317
- [InlineKeyboardButton("🛑 Toggle Maintenance", callback_data="admin_maintenance")],
318
- [InlineKeyboardButton("⬅️ Back", callback_data="menu_main")],
319
- ])
320
-
321
- # =====================================================================
322
- # 9. BOT LOGIC
323
- # =====================================================================
324
- async def process_update(update: Update):
325
- global MAINTENANCE_MODE
326
  try:
327
- user = update.effective_user
328
- if not user: return
329
- uid = user.id
330
- uname = user.username
331
- msg = update.message
332
- cb = update.callback_query
333
-
334
- db_user = get_user(uid)
335
-
336
- # generic message / callback log
337
- if msg and msg.text:
338
- log_event("message", user_id=uid, username=uname, data={"text": msg.text[:200]})
339
- if cb:
340
- log_event("callback", user_id=uid, username=uname, data={"data": cb.data})
341
-
342
- if db_user.get("banned"):
343
- if msg:
344
- await bot.send_message(uid, f"🚫 <b>Banned.</b>\n{db_user.get('ban_reason')}", parse_mode="HTML")
345
- return
346
-
347
- # --- TEXT ---
348
- if msg and msg.text:
349
- text = msg.text.strip()
350
- if text.startswith("/"):
351
- db_user["state"] = None
352
- log_event("command", user_id=uid, username=uname,
353
- data={"cmd": text.split()[0]})
354
-
355
- if text == "/start":
356
- if uid not in seen_users:
357
- seen_users.add(uid)
358
- log_event("new_user", user_id=uid, username=uname)
359
- if uid != ADMIN_ID and not await check_channel_membership(uid):
360
- await bot.send_message(
361
- uid,
362
- "🔒 <b>Join required</b>\nJoin the channel to continue.",
363
- parse_mode="HTML",
364
- reply_markup=InlineKeyboardMarkup([[
365
- InlineKeyboardButton("📢 Join Channel",
366
- url=f"https://t.me/{CHANNEL_ID.replace('@', '')}")
367
- ]]),
368
- )
369
- return
370
- db_user["verified"] = True
371
- if not db_user["accepted"]:
372
- disc = (
373
- "⚠️ <b>LEGAL DISCLAIMER</b>\n"
374
- "━━━━━━━━━━━━━━━━━━━━\n"
375
- "<b>1. Educational only</b>\nStrictly for testing. Do not harass.\n\n"
376
- "<b>2. Consent</b>\nYou confirm the target owner gave permission.\n\n"
377
- "<b>3. Logging</b>\nAll actions are logged.\n\n"
378
- "<i>By clicking Accept you agree.</i>"
379
- )
380
- await bot.send_message(
381
- uid, disc, parse_mode="HTML",
382
- reply_markup=InlineKeyboardMarkup([[
383
- InlineKeyboardButton("✅ I Accept", callback_data="accept_disclaimer")
384
- ]]),
385
- )
386
- return
387
- await bot.send_message(
388
- uid,
389
- f"👋 Welcome, <b>{user.first_name}</b>!\n<i>{_status_line(db_user)}</i>",
390
- parse_mode="HTML", reply_markup=kb_main(),
391
- )
392
- return
393
-
394
- if text == "/cancel":
395
- db_user["state"] = None
396
- await bot.send_message(uid, "❎ Cancelled.", reply_markup=kb_main())
397
- return
398
-
399
- if text == "/status":
400
- stats = db_user["stats"]
401
- rem = max(0, int(30 - (time.time() - db_user.get("last_attack_time", 0))))
402
- txt = (
403
- f"<b>📊 Your Status</b>\n"
404
- f"━━━━━━━━━━━━━━━━━━━━\n"
405
- f"Rank · {'👑 VIP' if db_user.get('is_vip') else '👤 Standard'}\n"
406
- f"Attacks · {stats['requests']}\n"
407
- f"Messages · {stats['sent']}\n"
408
- f"Daily · {db_user.get('daily_requests', 0)}/5\n"
409
- f"Cooldown · {rem}s\n"
410
- f"Warnings · {db_user.get('warnings', 0)}/3\n"
411
- f"━━━━━━━━━━━━━━━━━━━━\n"
412
- f"<i>{_status_line(db_user)}</i>"
413
- )
414
- await bot.send_message(uid, txt, parse_mode="HTML", reply_markup=kb_main())
415
- return
416
-
417
- if text == "/send":
418
- if not db_user["accepted"] or not db_user["verified"]:
419
- await bot.send_message(uid, "❌ Use /start first.")
420
- return
421
- if MAINTENANCE_MODE and not db_user.get("is_admin"):
422
- await bot.send_message(uid, "🛠️ Maintenance.")
423
- return
424
- db_user["state"] = ASK_NUMBER
425
- await bot.send_message(uid, "📱 Enter 10-digit target number:", reply_markup=kb_cancel())
426
- return
427
-
428
- if text == "/admin":
429
- if uid == ADMIN_ID:
430
- tok = mint_token(uid)
431
- host = os.getenv("SPACE_HOST", "")
432
- if host:
433
- url = f"https://{host}/admin?t={tok}"
434
- log_event("admin_login", user_id=uid, level="audit",
435
- data={"channel": "tg_link"})
436
- await bot.send_message(
437
- uid,
438
- f"🖥 <b>Admin Panel</b>\n<a href='{url}'>Open panel</a>",
439
- parse_mode="HTML", disable_web_page_preview=True,
440
- )
441
- else:
442
- db_user["state"] = WAITING_FOR_ADMIN_PASS
443
- await bot.send_message(uid, "🔐 Enter admin password:")
444
- else:
445
- db_user["state"] = WAITING_FOR_ADMIN_PASS
446
- await bot.send_message(uid, "🔐 Enter admin password:")
447
- return
448
-
449
- if text == "/admin_panel":
450
- if db_user.get("is_admin"):
451
- await bot.send_message(
452
- uid, "👑 <b>Admin</b>\nChoose an option:",
453
- parse_mode="HTML", reply_markup=kb_admin(),
454
- )
455
- return
456
-
457
- if text == "/delete_history":
458
- await bot.send_message(uid, "✅ <b>Scheduled</b>\nData purged in 24h.", parse_mode="HTML")
459
- return
460
-
461
- # Legacy admin commands
462
- if text.startswith("/ban ") and db_user.get("is_admin"):
463
- parts = text.split(" ", 2)
464
- try: target = int(parts[1])
465
- except: await bot.send_message(uid, "Usage: /ban <id> <reason>"); return
466
- reason = parts[2] if len(parts) > 2 else "No reason"
467
- get_user(target)["banned"] = True
468
- get_user(target)["ban_reason"] = reason
469
- log_event("ban", user_id=target, admin_id=uid, level="audit",
470
- data={"reason": reason})
471
- await bot.send_message(uid, f"✅ Banned {target}")
472
- return
473
-
474
- if text.startswith("/unban ") and db_user.get("is_admin"):
475
- try: target = int(text.split(" ")[1])
476
- except: await bot.send_message(uid, "Usage: /unban <id>"); return
477
- get_user(target)["banned"] = False
478
- log_event("unban", user_id=target, admin_id=uid, level="audit")
479
- await bot.send_message(uid, f"✅ Unbanned {target}")
480
- return
481
-
482
- if text.startswith("/setvip ") and db_user.get("is_admin"):
483
- try: target = int(text.split(" ")[1])
484
- except: await bot.send_message(uid, "Usage: /setvip <id>"); return
485
- u = get_user(target)
486
- u["is_vip"] = not u.get("is_vip", False)
487
- log_event("vip", user_id=target, admin_id=uid, level="audit",
488
- data={"value": u["is_vip"]})
489
- await bot.send_message(uid, f"✅ VIP={u['is_vip']} for {target}")
490
- return
491
-
492
- if text.startswith("/warn ") and db_user.get("is_admin"):
493
- parts = text.split(" ", 2)
494
- try: target = int(parts[1])
495
- except: await bot.send_message(uid, "Usage: /warn <id> <reason>"); return
496
- reason = parts[2] if len(parts) > 2 else "No reason"
497
- tu = get_user(target)
498
- tu["warnings"] = tu.get("warnings", 0) + 1
499
- log_event("warn", user_id=target, admin_id=uid, level="audit",
500
- data={"reason": reason, "count": tu["warnings"]})
501
- if tu["warnings"] >= 3:
502
- tu["banned"] = True
503
- tu["ban_reason"] = "3 warnings"
504
- log_event("ban", user_id=target, admin_id=uid, level="audit",
505
- data={"reason": "3 warnings"})
506
- await bot.send_message(uid, f"🚫 Auto-banned {target}")
507
- else:
508
- await bot.send_message(uid, f"⚠️ Warned {target} ({tu['warnings']}/3)")
509
- return
510
-
511
- if text.startswith("/broadcast ") and db_user.get("is_admin"):
512
- body = text.replace("/broadcast ", "")
513
- ok = 0
514
- for u2 in list(USER_DB.keys()):
515
- try:
516
- await bot.send_message(u2, body)
517
- ok += 1
518
- except: pass
519
- log_event("broadcast", admin_id=uid, level="audit",
520
- data={"text": body[:80], "sent": ok})
521
- await bot.send_message(uid, f"✅ Sent to {ok} users")
522
- return
523
-
524
- # --- STATE MACHINE ---
525
- if db_user.get("state") is not None:
526
- st = db_user["state"]
527
-
528
- if st == WAITING_FOR_ADMIN_PASS:
529
- if text == ADMIN_PASSWORD:
530
- db_user["is_admin"] = True
531
- db_user["state"] = None
532
- log_event("admin_login", user_id=uid, level="audit",
533
- data={"channel": "tg_password"})
534
- await bot.send_message(uid, "✅ <b>Admin enabled.</b>", parse_mode="HTML", reply_markup=kb_main())
535
- else:
536
- db_user["state"] = None
537
- log_event("admin_login_fail", user_id=uid, level="warn")
538
- await bot.send_message(uid, "❌ Wrong password.")
539
- return
540
-
541
- if st == ASK_NUMBER:
542
- if not text.isdigit() or len(text) != 10:
543
- await bot.send_message(uid, "❌ Invalid. Enter 10 digits:", reply_markup=kb_cancel())
544
- return
545
- db_user["target_number"] = text
546
- db_user["state"] = ASK_MESSAGE
547
- save_db()
548
- await bot.send_message(uid, "�� Enter the message:", reply_markup=kb_cancel())
549
- return
550
-
551
- if st == ASK_MESSAGE:
552
- db_user["target_msg"] = text
553
- db_user["state"] = ASK_COUNT
554
- save_db()
555
- await bot.send_message(uid, "🔢 How many times? (1-10):", reply_markup=kb_cancel())
556
- return
557
-
558
- if st == ASK_COUNT:
559
- try:
560
- cnt = int(text)
561
- if not 1 <= cnt <= 10: raise ValueError
562
- except:
563
- await bot.send_message(uid, "❌ Enter 1-10:", reply_markup=kb_cancel())
564
- return
565
- # daily reset (fixed: applies to VIP too)
566
- today = str(datetime.now().date())
567
- if db_user.get("last_reset") != today:
568
- db_user["daily_requests"] = 0
569
- db_user["last_reset"] = today
570
- if not db_user.get("is_admin") and not db_user.get("is_vip"):
571
- if db_user.get("daily_requests", 0) >= 5:
572
- db_user["state"] = None
573
- await bot.send_message(uid, "❌ Daily limit (5/5).", reply_markup=kb_main())
574
- return
575
- gap = time.time() - db_user.get("last_attack_time", 0)
576
- if gap < 30:
577
- await bot.send_message(uid, f"⏳ Wait {int(30-gap)}s.", reply_markup=kb_cancel())
578
- return
579
- db_user["pending_count"] = cnt
580
- db_user["state"] = None
581
- save_db()
582
- await bot.send_message(
583
- uid,
584
- f"<b>🧾 Confirm Attack</b>\n━━━━━━━━━━━━━━━━━━━━\n"
585
- f"Target · <code>{db_user['target_number']}</code>\n"
586
- f"Message · <i>{(db_user['target_msg'][:60])}</i>\n"
587
- f"Count · {cnt}",
588
- parse_mode="HTML", reply_markup=kb_confirm(),
589
- )
590
- return
591
- return
592
-
593
- # --- CALLBACKS ---
594
- if cb:
595
- try: await bot.answer_callback_query(cb.id)
596
- except: pass
597
- data = cb.data
598
-
599
- if data in ["menu_main", "accept_disclaimer", "menu_attack", "menu_profile",
600
- "menu_claim", "menu_health", "menu_help", "confirm_attack"]:
601
- db_user["state"] = None
602
-
603
- if data == "accept_disclaimer":
604
- db_user["accepted"] = True
605
- db_user["verified"] = True
606
- await safe_edit(uid, cb.message.message_id,
607
- f"👋 Welcome!\n<i>{_status_line(db_user)}</i>", kb_main())
608
-
609
- elif data == "menu_main":
610
- await safe_edit(uid, cb.message.message_id,
611
- f"<b>🏠 Main Menu</b>\n<i>{_status_line(db_user)}</i>", kb_main())
612
-
613
- elif data == "menu_attack":
614
- if MAINTENANCE_MODE and not db_user.get("is_admin"):
615
- await safe_edit(uid, cb.message.message_id,
616
- "🛠️ Under maintenance.", kb_main())
617
- return
618
- db_user["state"] = ASK_NUMBER
619
- await bot.send_message(uid, "📱 Enter 10-digit target number:", reply_markup=kb_cancel())
620
-
621
- elif data == "confirm_attack":
622
- target = db_user.get("target_number")
623
- tmsg = db_user.get("target_msg")
624
- cnt = db_user.get("pending_count", 1)
625
- if not target or not tmsg:
626
- await safe_edit(uid, cb.message.message_id, "❌ No pending attack.", kb_main())
627
- return
628
- # rate limits
629
- today = str(datetime.now().date())
630
- if db_user.get("last_reset") != today:
631
- db_user["daily_requests"] = 0
632
- db_user["last_reset"] = today
633
- if not db_user.get("is_admin") and not db_user.get("is_vip"):
634
- if db_user.get("daily_requests", 0) >= 5:
635
- await safe_edit(uid, cb.message.message_id, "❌ Daily limit (5/5).", kb_main())
636
- return
637
- db_user["daily_requests"] += 1
638
- db_user["last_attack_time"] = time.time()
639
- save_db()
640
- log_event("attack_start", user_id=uid, username=uname,
641
- data={"number": target, "count": cnt, "msg": tmsg[:60]})
642
- await safe_edit(uid, cb.message.message_id, "⏳ Sending...", None)
643
- url = f"{API_BASE}?count={cnt}&msg={tmsg}&number={target}"
644
- async with httpx.AsyncClient(timeout=30.0) as cli:
645
- try:
646
- r = await cli.get(url)
647
- d = r.json()
648
- if r.status_code == 200 and d.get("ok"):
649
- sent = d.get("sent", 0)
650
- db_user["stats"]["requests"] += 1
651
- db_user["stats"]["sent"] += sent
652
- save_db()
653
- log_event("attack_ok", user_id=uid, username=uname,
654
- data={"number": target, "sent": sent,
655
- "elapsed": d.get("elapsedSec")})
656
- await safe_edit(
657
- uid, cb.message.message_id,
658
- f"<b>✅ Attack OK</b>\n━━━━━━━━━━━━━━━━━━━━\n"
659
- f"Target · <code>{target}</code>\n"
660
- f"Rounds · {cnt}\n"
661
- f"Fired · {sent}\n"
662
- f"Time · {d.get('elapsedSec')}s\n"
663
- f"━━━━━━━━━━━━━━━━━━━━\n"
664
- f"<i>{_status_line(db_user)}</i>",
665
- kb_main(),
666
- )
667
- else:
668
- log_event("attack_fail", user_id=uid, level="warn",
669
- data={"number": target, "status": r.status_code})
670
- await safe_edit(uid, cb.message.message_id, "❌ API error.", kb_main())
671
- except Exception as e:
672
- log_event("attack_error", user_id=uid, level="error",
673
- data={"number": target, "error": str(e)})
674
- await safe_edit(uid, cb.message.message_id, "❌ Network error.", kb_main())
675
-
676
- elif data == "menu_profile":
677
- s = db_user["stats"]
678
- vip = "👑 VIP" if db_user.get("is_vip") else "👤 Standard"
679
- txt = (
680
- f"<b>👤 Profile</b>\n━━━━━━━━━━━━━━━━━━━━\n"
681
- f"<b>{user.first_name}</b>\n"
682
- f"<blockquote>Rank · {vip}\n"
683
- f"Attacks · {s['requests']}\n"
684
- f"Messages · {s['sent']}\n"
685
- f"Daily · {db_user.get('daily_requests', 0)}/5\n"
686
- f"Warnings · {db_user.get('warnings', 0)}/3</blockquote>\n"
687
- f"━━━━━━━━━━━━━━━━━━━━\n"
688
- f"<i>{_status_line(db_user)}</i>"
689
- )
690
- await safe_edit(uid, cb.message.message_id, txt, kb_main())
691
-
692
- elif data == "menu_claim":
693
- now = time.time()
694
- if now - db_user.get("claim_time", 0) < 86400:
695
- rem = int(86400 - (now - db_user.get("claim_time", 0)))
696
- await safe_edit(uid, cb.message.message_id,
697
- f"⏳ Claim in {rem//3600}h {(rem%3600)//60}m.", kb_main())
698
- return
699
- await safe_edit(uid, cb.message.message_id, "🔄 Rolling...", None)
700
- await asyncio.sleep(0.4)
701
- await safe_edit(uid, cb.message.message_id, "🎁 Unboxing...", None)
702
- await asyncio.sleep(0.4)
703
- db_user["claim_time"] = now
704
- db_user["daily_requests"] = max(0, db_user.get("daily_requests", 0) - 1)
705
- save_db()
706
- log_event("claim", user_id=uid)
707
- await safe_edit(uid, cb.message.message_id,
708
- "🎉 <b>+1 attack</b>", kb_main())
709
-
710
- elif data == "menu_health":
711
- await safe_edit(uid, cb.message.message_id, "📡 Pinging...", None)
712
- try:
713
- async with httpx.AsyncClient() as cli:
714
- r = await cli.get(API_HEALTH, timeout=5)
715
- d = r.json()
716
- if d.get("ok"):
717
- txt = (f"<b>📡 API Status</b>\n━━━━━━━━━━━━━━━━━━━━\n"
718
- f"🟢 Online\n"
719
- f"Nodes · {d.get('dbs', '?')}\n"
720
- f"Devices · {d.get('cachedDevices', '?')}")
721
- else:
722
- txt = "🔴 API down"
723
- except:
724
- txt = "🔴 Unreachable"
725
- await safe_edit(uid, cb.message.message_id, txt, kb_back())
726
-
727
- elif data == "menu_help":
728
- txt = (
729
- "<b>📖 Help</b>\n━━━━━━━━━━━━━━━━━━━━\n"
730
- "<blockquote expandable>"
731
- "/start — Main menu\n"
732
- "/status — Your stats\n"
733
- "/send — Start an attack\n"
734
- "/cancel — Cancel current action\n"
735
- "/health — API status\n"
736
- "/delete_history — Schedule wipe</blockquote>"
737
- )
738
- await safe_edit(uid, cb.message.message_id, txt, kb_main())
739
-
740
- elif data == "admin_users":
741
- if not db_user.get("is_admin"): return
742
- t = (f"<b>👥 Users</b>\n━━━━━━━━━━━━━━━━━━━━\n"
743
- f"Total · {len(USER_DB)}\n"
744
- f"Banned · {sum(1 for u in USER_DB.values() if u.get('banned'))}\n"
745
- f"VIPs · {sum(1 for u in USER_DB.values() if u.get('is_vip'))}")
746
- await safe_edit(uid, cb.message.message_id, t, kb_admin())
747
-
748
- elif data == "admin_stats":
749
- if not db_user.get("is_admin"): return
750
- tr = sum(u.get("stats", {}).get("requests", 0) for u in USER_DB.values())
751
- ts = sum(u.get("stats", {}).get("sent", 0) for u in USER_DB.values())
752
- t = (f"<b>📊 Global</b>\n━━━━━━━━━━━━━━━━━━━━\n"
753
- f"Attacks · {tr}\n"
754
- f"Messages · {ts}")
755
- await safe_edit(uid, cb.message.message_id, t, kb_admin())
756
-
757
- elif data == "admin_maintenance":
758
- if not db_user.get("is_admin"): return
759
- MAINTENANCE_MODE = not MAINTENANCE_MODE
760
- log_event("maintenance", admin_id=uid, level="audit",
761
- data={"value": MAINTENANCE_MODE})
762
- await safe_edit(uid, cb.message.message_id,
763
- f"🛠️ Maintenance: {'ON' if MAINTENANCE_MODE else 'OFF'}",
764
- kb_admin())
765
- return
766
-
767
- except Exception as e:
768
- log_event("error", level="critical",
769
- data={"where": "process_update", "error": str(e),
770
- "trace": traceback.format_exc()[-800:]})
771
- print(f"🔥 {e}")
772
- traceback.print_exc()
773
-
774
- # =====================================================================
775
- # 10. WEBHOOK + HEALTH
776
- # =====================================================================
777
- async def telegram_webhook(request: Request):
778
- try:
779
- data = await request.json()
780
- update = Update.de_json(data, bot)
781
- await process_update(update)
782
  except Exception as e:
783
- log_event("error", level="critical",
784
- data={"where": "webhook", "error": str(e)})
785
- return JSONResponse({"status": "ok"})
786
-
787
- async def health_check(request: Request):
788
- return JSONResponse({"status": "ok", "bot": "running"})
789
-
790
- # =====================================================================
791
- # 11. ADMIN API
792
- # =====================================================================
793
- from fastapi import APIRouter
794
- admin = APIRouter()
795
-
796
- @admin.post("/login")
797
- async def api_login(request: Request):
798
- ip = request.client.host if request.client else "unknown"
799
- if not _rl_ok(ip):
800
- raise HTTPException(429, "Too many attempts")
801
- try:
802
- body = await request.json()
803
- except:
804
- raise HTTPException(400, "bad json")
805
- pw = body.get("password", "")
806
- if not pw or not hmac.compare_digest(pw, ADMIN_PASSWORD):
807
- _rl_fail(ip)
808
- log_event("admin_login_fail", level="warn", ip=ip, data={"reason": "bad_password"})
809
- raise HTTPException(401, "Invalid password")
810
- tok = mint_token(ADMIN_ID)
811
- log_event("admin_login", user_id=ADMIN_ID, level="audit", ip=ip, data={"channel": "web"})
812
- return {"token": tok, "expires_at": int(time.time()) + TOKEN_TTL}
 
 
 
 
 
 
 
 
 
 
 
 
 
813
 
814
- @admin.get("/me")
815
- async def api_me(admin_id: int = __import__("fastapi").Depends(require_admin)):
816
- return {"admin_id": admin_id, "scope": "admin"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
817
 
818
- @admin.get("/stats")
819
- async def api_stats(admin_id: int = __import__("fastapi").Depends(require_admin)):
820
- now = time.time()
821
- day = now - 86400
822
- with _DB_LOCK:
823
- atk24 = _DB.execute("SELECT COUNT(*) c FROM activity WHERE event='attack_ok' AND ts>=?", (day,)).fetchone()["c"]
824
- atk_total = _DB.execute("SELECT COUNT(*) c FROM activity WHERE event='attack_ok'").fetchone()["c"]
825
- active24 = _DB.execute("SELECT COUNT(DISTINCT user_id) c FROM activity WHERE ts>=? AND user_id IS NOT NULL", (day,)).fetchone()["c"]
826
- msgs24 = _DB.execute("SELECT COALESCE(SUM(CAST(json_extract(data,'$.sent') AS INTEGER)),0) s FROM activity WHERE event='attack_ok' AND ts>=?", (day,)).fetchone()["s"]
827
- return {
828
- "users_total": len(USER_DB),
829
- "banned": sum(1 for u in USER_DB.values() if u.get("banned")),
830
- "vip": sum(1 for u in USER_DB.values() if u.get("is_vip")),
831
- "attacks_24h": atk24,
832
- "attacks_total": atk_total,
833
- "active_24h": active24,
834
- "msgs_24h": msgs24,
835
- "maintenance": MAINTENANCE_MODE,
836
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
837
 
838
- @admin.get("/stats/timeseries")
839
- async def api_ts(days: int = 7, admin_id: int = __import__("fastapi").Depends(require_admin)):
840
- since = time.time() - days * 86400
841
- with _DB_LOCK:
842
- rows = _DB.execute(
843
- "SELECT date(ts,'unixepoch') d, COUNT(*) c FROM activity "
844
- "WHERE event='attack_ok' AND ts>=? GROUP BY d ORDER BY d", (since,)
845
- ).fetchall()
846
- return [{"date": r["d"], "count": r["c"]} for r in rows]
847
-
848
- @admin.get("/stats/targets")
849
- async def api_targets(limit: int = 10, admin_id: int = __import__("fastapi").Depends(require_admin)):
850
- with _DB_LOCK:
851
- rows = _DB.execute(
852
- "SELECT json_extract(data,'$.number') t, COUNT(*) c FROM activity "
853
- "WHERE event='attack_ok' GROUP BY t ORDER BY c DESC LIMIT ?", (limit,)
854
- ).fetchall()
855
- return [{"target": r["t"], "count": r["c"]} for r in rows]
856
-
857
- @admin.get("/users")
858
- async def api_users(
859
- q: str = "", banned: str = "", vip: str = "",
860
- page: int = 1, per_page: int = 20,
861
- admin_id: int = __import__("fastapi").Depends(require_admin),
862
- ):
863
- out = []
864
- for uid, u in USER_DB.items():
865
- if q:
866
- ql = q.lower()
867
- if str(uid) != q and ql not in (str(u.get("username", "")) + str(uid)).lower():
868
- continue
869
- if banned == "1" and not u.get("banned"): continue
870
- if banned == "0" and u.get("banned"): continue
871
- if vip == "1" and not u.get("is_vip"): continue
872
- if vip == "0" and u.get("is_vip"): continue
873
- out.append({
874
- "id": uid,
875
- "accepted": u.get("accepted", False),
876
- "verified": u.get("verified", False),
877
- "banned": u.get("banned", False),
878
- "ban_reason": u.get("ban_reason", ""),
879
- "is_vip": u.get("is_vip", False),
880
- "is_admin": u.get("is_admin", False),
881
- "warnings": u.get("warnings", 0),
882
- "daily_requests": u.get("daily_requests", 0),
883
- "last_attack_time": u.get("last_attack_time", 0),
884
- "claim_time": u.get("claim_time", 0),
885
- "stats": u.get("stats", {}),
886
- })
887
- out.sort(key=lambda x: x["last_attack_time"], reverse=True)
888
- total = len(out)
889
- start = (page - 1) * per_page
890
- return {"total": total, "page": page, "per_page": per_page,
891
- "users": out[start:start + per_page]}
892
-
893
- @admin.get("/users/{uid}")
894
- async def api_user_detail(uid: int, admin_id: int = __import__("fastapi").Depends(require_admin)):
895
- if uid not in USER_DB:
896
- raise HTTPException(404, "not found")
897
- u = dict(USER_DB[uid])
898
- recent = _fetch_logs(user_id=uid, per_page=100)
899
- return {"user": {"id": uid, **u}, "recent": recent}
900
-
901
- @admin.post("/users/{uid}/ban")
902
- async def api_ban(uid: int, request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
903
- body = await request.json()
904
- reason = body.get("reason", "No reason")
905
- u = get_user(uid)
906
- u["banned"] = True
907
- u["ban_reason"] = reason
908
- save_db()
909
- log_event("ban", user_id=uid, admin_id=admin_id, level="audit",
910
- data={"reason": reason})
911
- return {"ok": True}
912
-
913
- @admin.post("/users/{uid}/unban")
914
- async def api_unban(uid: int, admin_id: int = __import__("fastapi").Depends(require_admin)):
915
- u = get_user(uid)
916
- u["banned"] = False
917
- u["ban_reason"] = ""
918
- save_db()
919
- log_event("unban", user_id=uid, admin_id=admin_id, level="audit")
920
- return {"ok": True}
921
-
922
- @admin.post("/users/{uid}/warn")
923
- async def api_warn(uid: int, request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
924
- body = await request.json()
925
- reason = body.get("reason", "No reason")
926
- u = get_user(uid)
927
- u["warnings"] = u.get("warnings", 0) + 1
928
- log_event("warn", user_id=uid, admin_id=admin_id, level="audit",
929
- data={"reason": reason, "count": u["warnings"]})
930
- if u["warnings"] >= 3:
931
- u["banned"] = True
932
- u["ban_reason"] = "3 warnings"
933
- log_event("ban", user_id=uid, admin_id=admin_id, level="audit",
934
- data={"reason": "3 warnings"})
935
- save_db()
936
- return {"ok": True, "warnings": u["warnings"], "banned": u["banned"]}
937
-
938
- @admin.post("/users/{uid}/vip")
939
- async def api_vip(uid: int, request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
940
- body = await request.json()
941
- val = bool(body.get("value"))
942
- u = get_user(uid)
943
- u["is_vip"] = val
944
- save_db()
945
- log_event("vip", user_id=uid, admin_id=admin_id, level="audit",
946
- data={"value": val})
947
- return {"ok": True, "vip": val}
948
 
949
- @admin.post("/users/{uid}/message")
950
- async def api_dm(uid: int, request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
951
- body = await request.json()
952
- text = body.get("text", "").strip()
953
- if not text:
954
- raise HTTPException(400, "empty")
955
  try:
956
- await bot.send_message(uid, text)
 
 
957
  except Exception as e:
958
- raise HTTPException(500, f"send failed: {e}")
959
- log_event("dm_sent", user_id=uid, admin_id=admin_id, level="audit",
960
- data={"text": text[:80]})
961
- return {"ok": True}
962
-
963
- @admin.post("/users/{uid}/reset-cooldown")
964
- async def api_reset_cd(uid: int, admin_id: int = __import__("fastapi").Depends(require_admin)):
965
- get_user(uid)["last_attack_time"] = 0
966
- save_db()
967
- log_event("reset_cooldown", user_id=uid, admin_id=admin_id, level="audit")
968
- return {"ok": True}
969
-
970
- @admin.post("/users/{uid}/reset-daily")
971
- async def api_reset_daily(uid: int, admin_id: int = __import__("fastapi").Depends(require_admin)):
972
- get_user(uid)["daily_requests"] = 0
973
- save_db()
974
- log_event("reset_daily", user_id=uid, admin_id=admin_id, level="audit")
975
- return {"ok": True}
976
-
977
- @admin.post("/users/{uid}/clear-state")
978
- async def api_clear_state(uid: int, admin_id: int = __import__("fastapi").Depends(require_admin)):
979
- get_user(uid)["state"] = None
980
- save_db()
981
- log_event("clear_state", user_id=uid, admin_id=admin_id, level="audit")
982
- return {"ok": True}
983
-
984
- @admin.delete("/users/{uid}")
985
- async def api_delete_user(uid: int, request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
986
- body = await request.json()
987
- if body.get("confirm") != "DELETE":
988
- raise HTTPException(400, "confirm required")
989
- USER_DB.pop(uid, None)
990
- save_db()
991
- log_event("user_deleted", user_id=uid, admin_id=admin_id, level="critical")
992
- return {"ok": True}
993
 
994
- @admin.get("/logs")
995
- async def api_logs(
996
- since_id: int = None, before_id: int = None, user_id: int = None,
997
- event: str = None, level: str = None, q: str = None,
998
- from_ts: float = None, to_ts: float = None,
999
- page: int = 1, per_page: int = 100,
1000
- admin_id: int = __import__("fastapi").Depends(require_admin),
1001
- ):
1002
- return _fetch_logs(since_id=since_id, before_id=before_id, user_id=user_id,
1003
- event=event, level=level, q=q, from_ts=from_ts, to_ts=to_ts,
1004
- page=page, per_page=per_page)
1005
 
1006
- @admin.get("/logs/stream")
1007
- async def api_stream(since_id: int = 0, admin_id: int = __import__("fastapi").Depends(require_admin)):
1008
- return _fetch_logs(since_id=since_id, per_page=200)
1009
-
1010
- @admin.get("/logs/export")
1011
- async def api_export(admin_id: int = __import__("fastapi").Depends(require_admin)):
1012
- rows = _fetch_logs(per_page=10000)
1013
- lines = ["id,ts,iso,user_id,username,event,level,data"]
1014
- for r in rows:
1015
- lines.append(f"{r['id']},{r['ts']},{datetime.fromtimestamp(r['ts']).isoformat()},"
1016
- f"{r['user_id'] or ''},{r['username'] or ''},{r['event']},{r['level']},"
1017
- f"\"{json.dumps(r['data'], ensure_ascii=False).replace(chr(34), chr(39))}\"")
1018
- return Response("\n".join(lines), media_type="text/csv",
1019
- headers={"Content-Disposition": "attachment; filename=logs.csv"})
1020
-
1021
- @admin.get("/audit")
1022
- async def api_audit(page: int = 1, admin_id: int = __import__("fastapi").Depends(require_admin)):
1023
- return _fetch_logs(level="audit", page=page, per_page=100)
1024
 
1025
- @admin.post("/broadcast")
1026
- async def api_broadcast(request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
1027
- body = await request.json()
1028
- text = body.get("text", "").strip()
1029
- filt = body.get("filter", "all")
1030
- if not text:
1031
- raise HTTPException(400, "empty text")
1032
- targets = []
1033
- for uid, u in list(USER_DB.items()):
1034
- if filt == "vip" and not u.get("is_vip"): continue
1035
- if filt == "nonbanned" and u.get("banned"): continue
1036
- targets.append(uid)
1037
- sent = 0
1038
- for uid in targets:
1039
  try:
1040
- await bot.send_message(uid, text)
1041
- sent += 1
1042
- await asyncio.sleep(0.05)
1043
- except: pass
1044
- log_event("broadcast", admin_id=admin_id, level="audit",
1045
- data={"text": text[:80], "sent": sent, "filter": filt})
1046
- return {"ok": True, "sent": sent, "targeted": len(targets)}
 
 
 
1047
 
1048
- @admin.get("/maintenance")
1049
- async def api_maint(admin_id: int = __import__("fastapi").Depends(require_admin)):
1050
- return {"maintenance": MAINTENANCE_MODE}
1051
 
1052
- @admin.post("/maintenance")
1053
- async def api_set_maint(request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
1054
- global MAINTENANCE_MODE
1055
- body = await request.json()
1056
- MAINTENANCE_MODE = bool(body.get("value"))
1057
- log_event("maintenance", admin_id=admin_id, level="audit",
1058
- data={"value": MAINTENANCE_MODE})
1059
- return {"maintenance": MAINTENANCE_MODE}
1060
 
1061
- @admin.get("/health")
1062
- async def api_health(admin_id: int = __import__("fastapi").Depends(require_admin)):
1063
- try:
1064
- async with httpx.AsyncClient() as c:
1065
- r = await c.get(API_HEALTH, timeout=5)
1066
- return {"ok": True, "status": r.status_code, "data": r.json()}
1067
- except Exception as e:
1068
- return {"ok": False, "error": str(e)}
 
 
1069
 
1070
- @admin.get("/bot/webhook-info")
1071
- async def api_wh_info(admin_id: int = __import__("fastapi").Depends(require_admin)):
1072
  try:
1073
- info = await bot.get_webhook_info()
1074
- return {"url": info.url, "has_custom_certificate": info.has_custom_certificate,
1075
- "pending_update_count": info.pending_update_count,
1076
- "last_error_date": info.last_error_date,
1077
- "last_error_message": info.last_error_message}
1078
  except Exception as e:
1079
- raise HTTPException(500, str(e))
1080
-
1081
- @admin.post("/bot/set-webhook")
1082
- async def api_set_wh(request: Request, admin_id: int = __import__("fastapi").Depends(require_admin)):
1083
- body = await request.json()
1084
- url = body.get("url", "").strip()
1085
- if not url.startswith("https://"):
1086
- raise HTTPException(400, "https:// required")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1087
  try:
1088
- ok = await bot.set_webhook(url=url)
1089
- log_event("webhook_set", admin_id=admin_id, level="audit", data={"url": url})
1090
- return {"ok": ok}
 
 
 
 
1091
  except Exception as e:
1092
- raise HTTPException(500, str(e))
1093
-
1094
- @admin.post("/bot/test-log")
1095
- async def api_test_log(admin_id: int = __import__("fastapi").Depends(require_admin)):
1096
- log_event("test_log", admin_id=admin_id, level="audit",
1097
- data={"msg": "Manual test from web panel"})
1098
- return {"ok": True}
1099
 
1100
- # =====================================================================
1101
- # 12. PANEL ROUTE
1102
- # =====================================================================
1103
- async def serve_panel(request: Request):
1104
  try:
1105
- with open("panel.html", "r", encoding="utf-8") as f:
1106
- return HTMLResponse(f.read(), headers={"Cache-Control": "no-store"})
1107
  except Exception as e:
1108
- return HTMLResponse(f"<h1>panel.html not found</h1><pre>{e}</pre>", status_code=500)
1109
-
1110
- # =====================================================================
1111
- # 13. LAUNCH
1112
- # =====================================================================
1113
- with gr.Blocks(title="Bot Host") as demo:
1114
- gr.Markdown("# 🤖 Bot is Running\n\nAdmin panel → `/admin`")
1115
- _b = gr.Button("init-gpu", visible=False)
1116
- _b.click(fn=_zerogpu_register, inputs=None, outputs=None)
1117
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1118
  if __name__ == "__main__":
1119
- demo.launch(server_name="0.0.0.0", server_port=7860,
1120
- share=False, ssr_mode=False, prevent_thread_lock=True)
1121
-
1122
- live_app = demo.app
1123
- live_app.include_router(admin, prefix="/api/admin")
1124
- live_app.router.routes.insert(0, StarletteRoute("/admin", serve_panel, methods=["GET"]))
1125
- live_app.router.routes.insert(0, StarletteRoute("/webhook", telegram_webhook, methods=["POST"]))
1126
- live_app.router.routes.insert(0, StarletteRoute("/health", health_check, methods=["GET"]))
1127
- live_app.build_middleware_stack()
1128
-
1129
- # verify log channel after startup
1130
- async def _verify_log():
1131
- await asyncio.sleep(2)
1132
- if not LOG_CHANNEL_ID:
1133
- print("⚠️ LOG_CHANNEL_ID not set")
1134
- return
1135
- try:
1136
- chat = await bot.get_chat(LOG_CHANNEL_ID)
1137
- print(f"✅ Log channel OK: {chat.title} ({chat.id})")
1138
- await bot.send_message(LOG_CHANNEL_ID, "🚀 Admin panel online. /admin")
1139
- except Exception as e:
1140
- print(f"❌ LOG CHANNEL BROKEN: {e!r}")
1141
-
1142
  try:
1143
- loop = asyncio.get_event_loop()
1144
- loop.create_task(_verify_log())
 
 
1145
  except Exception as e:
1146
- print(f"startup warn: {e}")
1147
-
1148
- demo.block_thread()
 
1
+ # ══════════════════════════════════════════════════════════════════
2
+ # app.py — Entry point
3
+ #
4
+ # Responsibility:
5
+ # • HfFolder monkey-patch (MUST be line 1, before any gradio import)
6
+ # • Imports gradio + sub-modules (config → engine → bot → admin_panel)
7
+ # • Gradio UI (health JSON + hidden ZeroGPU registration button)
8
+ # • demo.launch(ssr_mode=False, prevent_thread_lock=True)
9
+ # • Route injection at index 0:
10
+ # POST /webhook ← Telegram webhook
11
+ # GET /health ← liveness probe
12
+ # /admin/* ← web panel (21 routes, only if ADMIN_TOKEN set)
13
+ # • Startup threads:
14
+ # get_con, warm_phone_cache, get_asur_con, warm_asur_cache
15
+ # cache_gc, set_webhook, api_health_poller
16
+ # • demo.block_thread() ← keeps process alive
17
+ #
18
+ # All heavy lifting lives in engine.py / bot.py / admin_panel.py.
19
+ # This file is intentionally thin.
20
+ # ══════════════════════════════════════════════════════════════════
21
+
22
+ # ══════════════════════════════════════════════════════════════════
23
+ # STEP 0: MONKEY-PATCH HfFolder BEFORE ANY GRADIO/HF IMPORT
24
+ # (This must be the very first executable code — Gradio's oauth.py
25
+ # imports HfFolder at module level and crashes on new huggingface_hub.)
26
+ # ══════════════════════════════════════════════════════════════════
27
  import huggingface_hub
28
+
29
  if not hasattr(huggingface_hub, "HfFolder"):
30
  class _HfFolder:
31
  @staticmethod
32
+ def get_token():
33
+ try:
34
+ return huggingface_hub.get_token()
35
+ except Exception:
36
+ return None
37
+
38
  @staticmethod
39
+ def save_token(token):
40
+ try:
41
+ huggingface_hub.login(token)
42
+ except Exception:
43
+ pass
44
+
45
  @staticmethod
46
+ def delete_token():
47
+ try:
48
+ huggingface_hub.logout()
49
+ except Exception:
50
+ pass
51
+
52
  huggingface_hub.HfFolder = _HfFolder
53
 
54
+ # ══════════════════════════════════════════════════════════════════
55
+ # STEP 1: STANDARD LIB
56
+ # ══════════════════════════════════════════════════════════════════
57
+ import asyncio
58
+ import logging
59
+ import threading
60
+ import time
61
+ import traceback
62
+
63
+ # ══════════════════════════════════════════════════════════════════
64
+ # STEP 2: THIRD-PARTY
65
+ # ══════════════════════════════════════════════════════════════════
66
  import gradio as gr
67
+ from fastapi import Request
68
+ from fastapi.responses import JSONResponse
 
69
  from starlette.routing import Route as StarletteRoute
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
 
71
+ # ZeroGPU optional — Gradio Spaces have it, local dev does not
72
+ try:
73
+ import spaces
74
+ _HAS_SPACES = True
75
+ except ImportError:
76
+ _HAS_SPACES = False
77
+ class spaces:
78
+ @staticmethod
79
+ def GPU(*_a, **_kw):
80
+ def deco(f):
81
+ return f
82
+ return deco
83
+
84
+ # ══════════════════════════════════════════════════════════════════
85
+ # STEP 3: PROJECT MODULES (order matters)
86
+ # ══════════════════════════════════════════════════════════════════
87
+ import config
88
+ import engine
89
+ import bot
90
+ import admin_panel
91
+
92
+ # ══════════════════════════════════════════════════════════════════
93
+ # STEP 4: LOGGING
94
+ # ══════════════════════════════════════════════════════════════════
95
+ logging.basicConfig(
96
+ level=logging.INFO,
97
+ format="%(asctime)s %(levelname)-7s [%(name)s] %(message)s",
98
+ datefmt="%H:%M:%S",
99
+ )
100
+ log = logging.getLogger("app")
101
+
102
+ # ══════════════════════════════════════════════════════════════════
103
+ # STEP 5: ROUTE HANDLERS (webhook + health)
104
+ # ══════════════════════════════════════════════════════════════════
105
+ async def webhook_handler(request: Request):
106
+ """
107
+ Telegram webhook. Returns 200 immediately; dispatches work in tasks.
108
+ """
109
+ # ── Header secret check (Telegram echoes back SECRET_TOKEN) ──
110
+ if config.SECRET_TOKEN:
111
+ got = request.headers.get("x-telegram-bot-api-secret-token", "")
112
+ if got != config.SECRET_TOKEN:
113
+ log.warning(f"[webhook] bad secret header: {got[:8]}…")
114
+ return JSONResponse({"ok": False, "reason": "bad_header"}, status_code=403)
115
 
 
116
  try:
117
+ update = await request.json()
 
 
 
 
 
118
  except Exception:
119
+ # Swallow malformed JSON so Telegram doesn't retry
120
+ return JSONResponse({"ok": True})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
+ # ── Dedup by update_id (guards against retries) ──
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
+ # We ignore edited_message, inline_query, etc.
135
+ except RuntimeError:
136
+ # No running loop — extremely rare, but guard anyway
137
+ threading.Thread(
138
+ target=lambda: asyncio.run(_dispatch_sync(update)),
139
+ daemon=True,
140
+ ).start()
141
+
142
+ return JSONResponse({"ok": True})
143
+
144
+
145
+ async def _dispatch_sync(update: dict):
146
+ """Fallback if create_task fails."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  try:
148
+ if "message" in update:
149
+ await bot.handle_message(update["message"])
150
+ elif "callback_query" in update:
151
+ await bot.handle_callback(update["callback_query"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  except Exception as e:
153
+ log.error(f"[webhook] dispatch: {e!r}\n{traceback.format_exc()}")
154
+
155
+
156
+ async def health_handler(request: Request):
157
+ """Liveness probe — cheap, no API calls."""
158
+ return JSONResponse({
159
+ "status": "ok",
160
+ "version": config.VERSION,
161
+ "time": time.time(),
162
+ "duckdb_ready": engine.con_ready.is_set(),
163
+ "warmed": engine.warmed.is_set(),
164
+ "files": len(config.ALL_PARQUET_URLS),
165
+ "hiteck_files": len(config.PARQUET_URLS),
166
+ "flipkart_files": len(config.FLIPKART_URLS),
167
+ "cached_searches": len(bot.SEARCH_CACHE),
168
+ "unique_users": len(bot.UNIQUE_USERS),
169
+ "live_users": bot._get_stats()["live_users"],
170
+ "maintenance": bot.MAINTENANCE_MODE,
171
+ "force_join": bool(config.FORCE_JOIN_CHANNEL),
172
+ "backup_enabled": bot.BACKUP_ENABLED,
173
+ "admin_panel": bool(config.ADMIN_TOKEN),
174
+ "apis": {
175
+ "cr850": config.API_850CR,
176
+ "inddata": config.API_INDDATA,
177
+ "asur": list(config.ASUR_API.values()),
178
+ },
179
+ "stats": bot.STATS,
180
+ })
181
+
182
+
183
+ # ═════════���════════════════════════════════════════════════════════
184
+ # STEP 6: GRADIO UI (hidden ZeroGPU scanner button + health view)
185
+ # ══════════════════════════════════════════════════════════════════
186
+ def _build_gradio() -> gr.Blocks:
187
+ with gr.Blocks(title=f"{config.BOT_NAME} v{config.VERSION}") as demo:
188
+ gr.Markdown(f"# 🤖 {config.BOT_NAME} v{config.VERSION}")
189
+ gr.Markdown(
190
+ "This Space runs a **Telegram bot**. Open Telegram and interact with the bot.\n\n"
191
+ "**Endpoints**\n"
192
+ "- `GET /health` — liveness\n"
193
+ "- `POST /webhook` — Telegram webhook\n"
194
+ + ("- `GET /admin` — web admin panel\n" if config.ADMIN_TOKEN else "")
195
+ )
196
 
197
+ # Live health JSON — reloaded when user presses the button
198
+ status_box = gr.JSON(label="Health")
199
+ refresh_btn = gr.Button("🔄 Refresh health", variant="secondary")
200
+
201
+ def _health_snapshot():
202
+ try:
203
+ s = bot._get_stats()
204
+ return {
205
+ "status": "ok",
206
+ "version": config.VERSION,
207
+ "duckdb_ready": engine.con_ready.is_set(),
208
+ "warmed": engine.warmed.is_set(),
209
+ "files": len(config.ALL_PARQUET_URLS),
210
+ "cached_searches": len(bot.SEARCH_CACHE),
211
+ "unique_users": s["unique_users"],
212
+ "live_users": s["live_users"],
213
+ "backup_enabled": bot.BACKUP_ENABLED,
214
+ "maintenance": s["maintenance"],
215
+ }
216
+ except Exception as e:
217
+ return {"error": str(e)}
218
+
219
+ refresh_btn.click(fn=_health_snapshot, inputs=None, outputs=status_box)
220
+ demo.load(fn=_health_snapshot, inputs=None, outputs=status_box)
221
+
222
+ # ── Hidden ZeroGPU registration (Space scanner requirement) ──
223
+ if _HAS_SPACES:
224
+ try:
225
+ @spaces.GPU(duration=10)
226
+ def _zerogpu_register():
227
+ return "gpu-ready"
228
+
229
+ _zgpu_btn = gr.Button("init-gpu", visible=False)
230
+ _zgpu_btn.click(fn=_zerogpu_register, inputs=None, outputs=None)
231
+ log.info("✅ ZeroGPU registered")
232
+ except Exception as e:
233
+ log.warning(f"⚠️ ZeroGPU registration failed: {e!r}")
234
+
235
+ return demo
236
+
237
+
238
+ # ══════════════════════════════════════════════════════════════════
239
+ # STEP 7: WEBHOOK REGISTRATION (background thread)
240
+ # ══════════════════════════════════════════════════════════════════
241
+ def _set_webhook():
242
+ if not config.BOT_TOKEN:
243
+ log.warning("[setwebhook] BOT_TOKEN missing — skipped")
244
+ return
245
+ space_url = config.SPACE_URL or (f"https://{config.SPACE_HOST}" if config.SPACE_HOST else "")
246
+ if not space_url:
247
+ log.warning("[setwebhook] SPACE_URL/SPACE_HOST missing — skipped")
248
+ return
249
 
250
+ url = f"{space_url.rstrip('/')}/webhook"
251
+ payload = {
252
+ "url": url,
253
+ "secret_token": config.SECRET_TOKEN,
254
+ "allowed_updates": ["message", "callback_query"],
255
+ "drop_pending_updates": True,
 
 
 
 
 
 
 
 
 
 
 
 
256
  }
257
+ for attempt in range(1, 4):
258
+ try:
259
+ import httpx
260
+ with httpx.Client(timeout=30) as cli:
261
+ r = cli.post(f"{config.TELEGRAM_API}/setWebhook", json=payload)
262
+ data = r.json()
263
+ log.info(f"[setwebhook] attempt {attempt}: {data}")
264
+ if data.get("ok"):
265
+ return
266
+ except Exception as e:
267
+ log.warning(f"[setwebhook] attempt {attempt}: {e!r}")
268
+ time.sleep(3)
269
+ log.error("[setwebhook] gave up after 3 attempts")
270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
 
272
+ def _set_webhook_async():
273
+ """Wrap _set_webhook in its own event loop so it can be a thread target."""
 
 
 
 
274
  try:
275
+ loop = asyncio.new_event_loop()
276
+ asyncio.set_event_loop(loop)
277
+ loop.run_until_complete(_set_webhook_async_impl())
278
  except Exception as e:
279
+ log.warning(f"[setwebhook] fatal: {e!r}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
280
 
 
 
 
 
 
 
 
 
 
 
 
281
 
282
+ async def _set_webhook_async_impl():
283
+ """Async version — cleaner with httpx.AsyncClient."""
284
+ if not config.BOT_TOKEN:
285
+ log.warning("[setwebhook] BOT_TOKEN missing — skipped")
286
+ return
287
+ space_url = config.SPACE_URL or (f"https://{config.SPACE_HOST}" if config.SPACE_HOST else "")
288
+ if not space_url:
289
+ log.warning("[setwebhook] SPACE_URL/SPACE_HOST missing — skipped")
290
+ return
 
 
 
 
 
 
 
 
 
291
 
292
+ url = f"{space_url.rstrip('/')}/webhook"
293
+ payload = {
294
+ "url": url,
295
+ "secret_token": config.SECRET_TOKEN,
296
+ "allowed_updates": ["message", "callback_query"],
297
+ "drop_pending_updates": True,
298
+ }
299
+ import httpx
300
+ for attempt in range(1, 4):
 
 
 
 
 
301
  try:
302
+ async with httpx.AsyncClient(timeout=30) as cli:
303
+ r = await cli.post(f"{config.TELEGRAM_API}/setWebhook", json=payload)
304
+ data = r.json()
305
+ log.info(f"[setwebhook] attempt {attempt}: {data}")
306
+ if data.get("ok"):
307
+ return
308
+ except Exception as e:
309
+ log.warning(f"[setwebhook] attempt {attempt}: {e!r}")
310
+ await asyncio.sleep(3)
311
+ log.error("[setwebhook] gave up after 3 attempts")
312
 
 
 
 
313
 
314
+ # ══════════════════════════════════════════════════════════════════
315
+ # STEP 8: API HEALTH POLLER (warms the admin dashboard cache)
316
+ # ══════════════════════════════════════════════════════════════════
317
+ def _api_health_poller():
318
+ loop = asyncio.new_event_loop()
319
+ asyncio.set_event_loop(loop)
 
 
320
 
321
+ async def _loop_forever():
322
+ # initial delay — let DB + webhook settle first
323
+ await asyncio.sleep(30)
324
+ while True:
325
+ try:
326
+ await engine.check_api_health()
327
+ log.debug("[health-poller] tick ok")
328
+ except Exception as e:
329
+ log.warning(f"[health-poller] {e!r}")
330
+ await asyncio.sleep(config.API_HEALTH_INTERVAL)
331
 
 
 
332
  try:
333
+ loop.run_until_complete(_loop_forever())
 
 
 
 
334
  except Exception as e:
335
+ log.warning(f"[health-poller] fatal: {e!r}")
336
+
337
+
338
+ # ══════════════════════════════════════════════════════════════════
339
+ # STEP 9: BOOT — SEQUENCE
340
+ # ══════════════════════════════════════════════════════════════════
341
+ def _boot():
342
+ # ── 9.1 Sanity check + config dump ──
343
+ print()
344
+ print(config.summary())
345
+ warnings = config._sanity_check()
346
+ if warnings:
347
+ print("\n⚠️ Config warnings:")
348
+ for w in warnings:
349
+ print(f" • {w}")
350
+ print()
351
+
352
+ # ── 9.2 Build Gradio app ──
353
+ log.info("[boot] building Gradio app…")
354
+ demo = _build_gradio()
355
+
356
+ # ── 9.3 Launch Gradio ──
357
+ log.info("[boot] launching Gradio (ssr_mode=False, prevent_thread_lock=True)…")
358
+ demo.launch(
359
+ server_name="0.0.0.0",
360
+ server_port=7860,
361
+ share=False,
362
+ ssr_mode=False, # disables Node SSR proxy so /webhook is reachable
363
+ prevent_thread_lock=True, # returns live app immediately
364
+ show_error=True,
365
+ )
366
+
367
+ # ── 9.4 Inject routes at index 0 ──
368
+ log.info("[boot] injecting /webhook, /health, /admin/* at index 0…")
369
+ live_app = demo.app # NOT demo.server.app (gradio 4/5 difference)
370
+
371
+ # Webhook + health first
372
+ live_app.router.routes.insert(
373
+ 0, StarletteRoute("/webhook", webhook_handler, methods=["POST"])
374
+ )
375
+ live_app.router.routes.insert(
376
+ 0, StarletteRoute("/health", health_handler, methods=["GET"])
377
+ )
378
+
379
+ # Admin panel (optional — skipped if ADMIN_TOKEN unset)
380
  try:
381
+ admin_routes = admin_panel.get_admin_routes()
382
+ for route in admin_routes:
383
+ live_app.router.routes.insert(0, route)
384
+ if admin_routes:
385
+ log.info(f"✅ injected {len(admin_routes)} admin routes at /admin/*")
386
+ else:
387
+ log.info("ℹ️ admin routes not injected (ADMIN_TOKEN unset)")
388
  except Exception as e:
389
+ log.warning(f"⚠️ admin_panel injection failed: {e!r}\n{traceback.format_exc()}")
 
 
 
 
 
 
390
 
391
+ # Rebuild middleware stack after inserting routes
 
 
 
392
  try:
393
+ live_app.build_middleware_stack()
394
+ log.info("✅ middleware stack rebuilt")
395
  except Exception as e:
396
+ log.warning(f"⚠️ middleware stack rebuild: {e!r}")
397
+
398
+ # Log the first few routes for debugging
399
+ log.info("📋 First 10 routes:")
400
+ for route in live_app.router.routes[:10]:
401
+ path = getattr(route, "path", "?")
402
+ methods = getattr(route, "methods", None)
403
+ ms = f"{sorted(methods)}" if methods else "?"
404
+ log.info(f" {ms:30s} {path}")
405
+
406
+ # ── 9.5 Warm-up threads ──
407
+ log.info("[boot] starting warm-up threads…")
408
+ threading.Thread(target=engine.get_con, daemon=True, name="con").start()
409
+ threading.Thread(target=engine.warm_phone_cache, daemon=True, name="warm").start()
410
+ threading.Thread(target=engine.get_asur_con, daemon=True, name="asur-con").start()
411
+ threading.Thread(target=engine.warm_asur_cache, daemon=True, name="asur-warm").start()
412
+
413
+ # ── 9.6 Background maintenance threads ──
414
+ log.info("[boot] starting background daemons…")
415
+ threading.Thread(target=bot.cache_gc, daemon=True, name="gc").start()
416
+ threading.Thread(target=_set_webhook_async, daemon=True, name="setwh").start()
417
+ threading.Thread(target=_api_health_poller, daemon=True, name="health").start()
418
+
419
+ # ── 9.7 Ready ──
420
+ log.info("[boot] ✅ ready — blocking main thread")
421
+ print()
422
+ print("═" * 60)
423
+ print(f" {config.BOT_NAME} v{config.VERSION} — ONLINE")
424
+ print(f" Webhook : {config.SPACE_URL or config.SPACE_HOST or '(local)'}/webhook")
425
+ print(f" Health : /health")
426
+ print(f" Admin : {'/admin' if config.ADMIN_TOKEN else '(disabled)'}")
427
+ print("═" * 60)
428
+ print()
429
+
430
+ return demo
431
+
432
+
433
+ # ══════════════════════════════════════════════════════════════════
434
+ # STEP 10: MAIN
435
+ # ══════════════════════════════════════════════════════════════════
436
  if __name__ == "__main__":
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  try:
438
+ demo = _boot()
439
+ demo.block_thread() # ← keeps process alive
440
+ except KeyboardInterrupt:
441
+ log.info("shutting down…")
442
  except Exception as e:
443
+ log.critical(f"❌ boot failed: {e!r}\n{traceback.format_exc()}")
444
+ raise