Hfzune commited on
Commit
058b40c
·
verified ·
1 Parent(s): 1f5e9b2

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -761
app.py DELETED
@@ -1,761 +0,0 @@
1
- import huggingface_hub
2
- if not hasattr(huggingface_hub, "HfFolder"):
3
- class _HfFolder:
4
- @staticmethod
5
- def get_token():
6
- try: return huggingface_hub.get_token()
7
- except: return None
8
- @staticmethod
9
- def save_token(t):
10
- try: huggingface_hub.login(t)
11
- except: pass
12
- @staticmethod
13
- def delete_token():
14
- try: huggingface_hub.logout()
15
- except: pass
16
- huggingface_hub.HfFolder = _HfFolder
17
-
18
- import os, sys, re, io, csv, json, time, html, uuid, asyncio, hashlib, hmac, threading, traceback, logging, urllib.parse
19
- from datetime import datetime, timezone
20
- from collections import deque, Counter
21
- from typing import Optional
22
- import duckdb, httpx, gradio as gr
23
- from fastapi import Request
24
- from fastapi.responses import JSONResponse, HTMLResponse, Response
25
- from starlette.routing import Route as StarletteRoute
26
-
27
- try:
28
- import spaces
29
- _HAS_SPACES = True
30
- except:
31
- _HAS_SPACES = False
32
- class spaces:
33
- @staticmethod
34
- def GPU(*a, **kw):
35
- def deco(f): return f
36
- return deco
37
-
38
- logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)-7s %(message)s", datefmt="%H:%M:%S")
39
- log = logging.getLogger("app")
40
-
41
- # ══ CONFIG ══
42
- BOT_TOKEN = os.environ.get("BOT_TOKEN", "").strip()
43
- HF_TOKEN = os.environ.get("HF_TOKEN", "").strip()
44
- WEBHOOK_SECRET = os.environ.get("WEBHOOK_SECRET", "change_me").strip()
45
- SPACE_URL = os.environ.get("SPACE_URL", "").strip().rstrip("/")
46
- SPACE_HOST = os.environ.get("SPACE_HOST", "").strip().rstrip("/")
47
- ADMIN_TOKEN = os.environ.get("ADMIN_TOKEN", "").strip()
48
- OWNER_IDS = {int(x) for x in os.environ.get("OWNER_IDS", "").split(",") if x.strip().isdigit()}
49
- FORCE_JOIN_CHANNEL = os.environ.get("FORCE_JOIN_CHANNEL", "").strip()
50
- ASUR_KEY = os.environ.get("ASUR_KEY", "@ASUR_ABOUT").strip()
51
- BACKUP_CHANNEL_ID = os.environ.get("BACKUP_CHANNEL_ID", "").strip()
52
- BACKUP_ENABLED = bool(BACKUP_CHANNEL_ID)
53
- TELEGRAM_API = f"https://api.telegram.org/bot{BOT_TOKEN}"
54
- VERSION = "4.1.1"
55
- BOT_NAME = "Phone Lookup Bot"
56
-
57
- HITECK_URLS = [f"https://huggingface.co/datasets/HiTeckGroup/HiTeckgroop/resolve/main/idx_phone.{i}.parquet" for i in range(7)]
58
- FLIPKART_URLS = ["https://huggingface.co/datasets/Hfzune/Flipkart/resolve/main/flipkart.parquet"]
59
- ALL_PARQUET_URLS = HITECK_URLS + FLIPKART_URLS
60
-
61
- API_850CR = "https://tfqdeadlo-850crfastsearch.hf.space/search"
62
- API_INDDATA = "https://tfqdeadlo-inddataapi.hf.space/search"
63
- ASUR_API = {
64
- "num_to_info": "https://num-to-info.asurpapa.workers.dev/api",
65
- "aadhaar_to_info": "https://aadhaar.asurpapa.workers.dev/api",
66
- "aadhaar_family": "https://aadhaar-family.asurpapa.workers.dev/api",
67
- "aadhaar_ration": "https://ration-card.asurpapa.workers.dev/api",
68
- }
69
- ASUR_PARAM_NAMES = {"num_to_info": "number", "aadhaar_to_info": "aadhaar", "aadhaar_family": "aadhaar", "aadhaar_ration": "aadhar"}
70
-
71
- PAGE_SIZE, FETCH_LIMIT, QUERY_TIMEOUT = 4, 40, 90
72
- BATCH_MAX, BATCH_TIMEOUT, HTTP_TIMEOUT = 5, 60, 30
73
- CACHE_TTL, SEARCH_CACHE_TTL, MEMBERSHIP_CACHE_TTL, PENDING_QUERY_TTL = 300, 1800, 300, 600
74
- USER_COOLDOWN, FLOOD_WINDOW, FLOOD_MAX, FLOOD_MUTE_SEC = 5, 10, 5, 60
75
- DAILY_QUOTA, DAILY_QUOTA_ADMIN = 100, 100000
76
- LIVE_WINDOW, HISTORY_LEN, ACTIVITY_LOG_MAX = 300, 10, 10000
77
- ADMIN_SESSION_TTL, ADMIN_PROMPT_TTL = 3600, 180
78
- BROADCAST_DELAY, BROADCAST_MAX_LEN = 0.05, 3800
79
- PHONE_REGEX = re.compile(r"^\d{10}$")
80
- SECRET_TOKEN = hashlib.sha256(WEBHOOK_SECRET.encode()).hexdigest()[:32]
81
-
82
- TRUNC = {"name": 80, "fathersName": 80, "address": 200, "phoneNumber": 40, "aadharNumber": 40, "otherNumber": 40, "district": 40, "pincode": 15, "state": 40, "town": 40, "source": 30}
83
- FIELD_LABELS = [("name", "👤", "Name"), ("fathersName", "👨", "Father"), ("phoneNumber", "📞", "Phone"), ("otherNumber", "📱", "Other"), ("aadharNumber", "🆔", "Aadhaar"), ("address", "🏠", "Address"), ("district", "🏙️", "District"), ("pincode", "📮", "Pincode"), ("state", "🗺️", "State"), ("town", "🌆", "Town"), ("source", "📂", "Source")]
84
- SOURCE_LABEL = {"hiteck": "HiTeck", "flipkart": "Flipkart", "850cr": "850CR Fast", "inddata": "IndData 1.4B", "asur_num": "ASUR NumInfo", "asur_aadhaar": "ASUR AadhaarLink"}
85
-
86
- print(f"=== BOOTING V{VERSION} ===")
87
- print(f"FORCE_JOIN: '{FORCE_JOIN_CHANNEL}' | BACKUP: '{BACKUP_CHANNEL_ID}' | ASUR_KEY: '{ASUR_KEY}'")
88
-
89
- # ══ ENGINE ══
90
- def esc(x): return html.escape(str(x), quote=False) if x is not None else ""
91
- def _tv(v, n):
92
- if v is None: return ""
93
- s = str(v).strip()
94
- if s.lower() in ("", "null", "none", "nan", "n/a", "na"): return ""
95
- return s if len(s) <= n else s[:n-1] + "…"
96
-
97
- _con, _con_lock, _query_lock = None, threading.Lock(), threading.Lock()
98
- con_ready, warmed, _warm_started = threading.Event(), threading.Event(), False
99
-
100
- def get_con():
101
- global _con
102
- with _con_lock:
103
- if _con: return _con
104
- try:
105
- c = duckdb.connect(":memory:")
106
- c.execute("INSTALL httpfs; LOAD httpfs;")
107
- if HF_TOKEN: c.execute(f"CREATE SECRET hf (TYPE HUGGINGFACE, TOKEN '{HF_TOKEN}');")
108
- c.execute("SET enable_object_cache=true; SET preserve_insertion_order=false; SET threads=6; SET memory_limit='12GB';")
109
- _con = c; con_ready.set(); return _con
110
- except Exception as e: log.error(f"DuckDB Init failed: {e!r}"); return None
111
-
112
- def run_search_safe(phone, limit=FETCH_LIMIT, timeout_secs=QUERY_TIMEOUT):
113
- con = get_con()
114
- if not con: return []
115
- with _query_lock:
116
- stop = threading.Event()
117
- def watchdog():
118
- if not stop.wait(timeout_secs):
119
- try: con.interrupt()
120
- except: pass
121
- threading.Thread(target=watchdog, daemon=True).start()
122
- results = []
123
- try:
124
- urls = ", ".join(f"'{u}'" for u in HITECK_URLS)
125
- sql = f"SELECT name, fathersName, phoneNumber, aadharNumber, otherNumber, address, district, pincode, state, town, source FROM read_parquet([{urls}], union_by_name=true) WHERE CAST(phoneNumber AS VARCHAR) = ? LIMIT {limit}"
126
- cur = con.execute(sql, [phone])
127
- cols = [d[0] for d in cur.description]
128
- for r in cur.fetchall():
129
- rec = dict(zip(cols, r))
130
- if not rec.get("source"): rec["source"] = SOURCE_LABEL["hiteck"]
131
- results.append(rec)
132
- fk_urls = ", ".join(f"'{u}'" for u in FLIPKART_URLS)
133
- fk_sql = f"SELECT CustomerName AS name, NULL AS fathersName, CustomerPhone AS phoneNumber, NULL AS aadharNumber, NULL AS otherNumber, CustomerAddress AS address, CustomerCity AS district, CustomerPincode AS pincode, CustomerState AS state, CustomerCity AS town, '{SOURCE_LABEL['flipkart']}' AS source FROM read_parquet([{fk_urls}], union_by_name=true) WHERE RIGHT(REPLACE(REPLACE(REPLACE(CAST(CustomerPhone AS VARCHAR),' ', ''), '-', ''), '+', ''), 10) = ? LIMIT {limit}"
134
- cur = con.execute(fk_sql, [phone])
135
- cols = [d[0] for d in cur.description]
136
- for r in cur.fetchall():
137
- rec = dict(zip(cols, r))
138
- for k in ("name", "address", "district", "state", "town"):
139
- if isinstance(rec.get(k), str) and "%" in rec[k]:
140
- try: rec[k] = urllib.parse.unquote(rec[k])
141
- except: pass
142
- results.append(rec)
143
- return results
144
- except Exception as e: log.error(f"DB Search failed: {e!r}"); return []
145
- finally: stop.set()
146
-
147
- def warm_phone_cache():
148
- global _warm_started
149
- if warmed.is_set(): return
150
- _warm_started = True
151
- con = get_con()
152
- if not con: return
153
- for url in ALL_PARQUET_URLS:
154
- try: con.execute(f"SELECT * FROM read_parquet('{url}') LIMIT 1").fetchall()
155
- except: pass
156
- warmed.set()
157
-
158
- def _is_valid_api_response(name, resp):
159
- if not isinstance(resp, dict) or resp.get("error"): return False
160
- if name == "850cr": return resp.get("success") is True and len(resp.get("results", [])) > 0
161
- if name == "inddata": return resp.get("status") == "success" and isinstance(resp.get("data"), dict)
162
- if name == "num_to_info": return resp.get("status") == "success" and isinstance(resp.get("data"), dict)
163
- if name == "aadhaar_to_info": return resp.get("status") == "success" and len(resp.get("data", [])) > 0
164
- if name == "aadhaar_family": return resp.get("status") is True and len(resp.get("members", [])) > 0
165
- if name == "aadhaar_ration": return resp.get("status") is True and any(resp.get(k) for k in ("head_family", "ration_number", "scheme", "address", "fps_id"))
166
- return False
167
-
168
- def _record_has_content(rec): return any(str(rec.get(k, "")).strip().lower() not in ("", "null", "none") for k in ["name", "fathersName", "phoneNumber", "aadharNumber", "address"])
169
- def _drop_empty_records(records): return [r for r in records if _record_has_content(r)]
170
-
171
- async def _q_cr850_raw(client, number):
172
- try:
173
- r = await client.get(f"{API_850CR}/{number}", timeout=40)
174
- if r.status_code == 200: return r.json()
175
- return None
176
- except Exception as e: log.warning(f"850CR Fail: {e}"); return None
177
-
178
- async def _q_inddata_raw(client, number):
179
- try:
180
- r = await client.get(API_INDDATA, params={"mobile": number}, timeout=30)
181
- if r.status_code == 200: return r.json()
182
- return None
183
- except Exception as e: log.warning(f"IndData Fail: {e}"); return None
184
-
185
- async def search_fast_apis_filtered(phone):
186
- t0 = time.time()
187
- raw_850cr, raw_inddata = None, None
188
- async with httpx.AsyncClient(timeout=60) as cli:
189
- r850, rind = await asyncio.gather(_q_cr850_raw(cli, phone), _q_inddata_raw(cli, phone), return_exceptions=True)
190
- if isinstance(r850, dict): raw_850cr = r850
191
- if isinstance(rind, dict): raw_inddata = rind
192
- records, status, aadhaar = [], {}, None
193
-
194
- if _is_valid_api_response("850cr", raw_850cr):
195
- for item in raw_850cr["results"]:
196
- addr = item.get("address") or {}
197
- full = addr.get("full_address", "").lstrip(", ").strip() if isinstance(addr, dict) else ""
198
- records.append({"name": item.get("name"), "fathersName": item.get("father_name"), "phoneNumber": phone, "otherNumber": item.get("alternate_number"), "address": full, "state": item.get("state"), "source": SOURCE_LABEL["850cr"]})
199
- status["850cr"] = "ok"
200
- else: status["850cr"] = "empty" if raw_850cr is None else "error"
201
-
202
- if _is_valid_api_response("inddata", raw_inddata):
203
- d = raw_inddata["data"]
204
- aadhaar = str(d.get("id") or d.get("aadhar") or d.get("aadhaar") or d.get("aadharNumber") or "").strip()
205
- if len(aadhaar) != 12: aadhaar = None
206
- records.append({"name": d.get("name"), "fathersName": d.get("fname"), "phoneNumber": phone, "aadharNumber": aadhaar, "otherNumber": d.get("alt"), "address": d.get("address"), "town": d.get("circle"), "source": SOURCE_LABEL["inddata"]})
207
- status["inddata"] = "ok"
208
- else: status["inddata"] = "empty" if raw_inddata is None else "error"
209
-
210
- return {"records": _drop_empty_records(records), "source_status": status, "raw": {"850cr": raw_850cr, "inddata": raw_inddata}, "aadhaar": aadhaar, "elapsed": time.time() - t0}
211
-
212
- async def fetch_asurpapa_all(mobile, aadhaar):
213
- results = {}
214
- async with httpx.AsyncClient(timeout=30) as cli:
215
- try:
216
- r = await cli.get(ASUR_API["num_to_info"], params={"key": ASUR_KEY, "number": mobile})
217
- results["num_to_info"] = r.json() if r.status_code == 200 else {"error": f"HTTP {r.status_code}"}
218
- except Exception as e: results["num_to_info"] = {"error": str(e)}
219
-
220
- if not aadhaar:
221
- for k in ("aadhaar_to_info", "aadhaar_family", "aadhaar_ration"): results[k] = {"error": "skipped (no aadhaar)"}
222
- return results
223
-
224
- async def _call(name):
225
- for attempt in range(2): # Retry once if 503
226
- try:
227
- r = await cli.get(ASUR_API[name], params={"key": ASUR_KEY, ASUR_PARAM_NAMES[name]: aadhaar})
228
- if r.status_code == 200:
229
- j = r.json()
230
- log.info(f"ASUR {name}: {j}")
231
- return name, j
232
- elif r.status_code == 503:
233
- await asyncio.sleep(1)
234
- continue
235
- else:
236
- return name, {"error": f"HTTP {r.status_code}"}
237
- except Exception as e:
238
- if attempt == 1: return name, {"error": str(e)}
239
-
240
- gathered = await asyncio.gather(_call("aadhaar_to_info"), _call("aadhaar_family"), _call("aadhaar_ration"))
241
- for name, res in gathered: results[name] = res
242
- return results
243
-
244
- def _format_asur_extras(aadhaar, api_results):
245
- lines = []
246
- if aadhaar: lines.append(f"🆔 <b>Aadhaar:</b> <code>XXXX-XXXX-{esc(aadhaar[-4:])}</code>")
247
- nti = api_results.get("num_to_info")
248
- if _is_valid_api_response("num_to_info", nti):
249
- d = nti["data"]; ex = []
250
- if d.get("email"): ex.append(f"📧 {esc(d['email'])}")
251
- if d.get("alt"): ex.append(f"📱 Alt: {esc(d['alt'])}")
252
- if d.get("circle"): ex.append(f"🌐 {esc(d['circle'])}")
253
- if ex: lines.append(" · ".join(ex))
254
-
255
- fam = api_results.get("aadhaar_family")
256
- if _is_valid_api_response("aadhaar_family", fam):
257
- members = fam.get("members", [])
258
- lines.append(f"👨‍👩‍👧 <b>Family ({len(members)}):</b>")
259
- for m in members[:5]: lines.append(f" • {esc(m.get('name'))} ({esc(m.get('relation'))})")
260
- if len(members) > 5: lines.append(f" <i>… and {len(members)-5} more</i>")
261
-
262
- rat = api_results.get("aadhaar_ration")
263
- if _is_valid_api_response("aadhaar_ration", rat):
264
- bits = []
265
- if rat.get("head_family"): bits.append(f"👤 {esc(rat['head_family'])}")
266
- if rat.get("ration_number"): bits.append(f"🔢 <code>{esc(rat['ration_number'])}</code>")
267
- if rat.get("scheme"): bits.append(f"📋 {esc(rat['scheme'])}")
268
- if bits: lines.append("🍚 <b>Ration:</b> " + " · ".join(bits))
269
-
270
- return ("🪪 <b>ASURPAPA Details</b>\n" + "\n".join(lines)) if lines else ""
271
-
272
- async def asur_lookup_filtered(phone, aadhaar):
273
- t0 = time.time()
274
- api_results = await fetch_asurpapa_all(phone, aadhaar)
275
- records = []
276
- if _is_valid_api_response("num_to_info", api_results.get("num_to_info")):
277
- d = api_results["num_to_info"]["data"]
278
- records.append({"name": d.get("name"), "fathersName": d.get("fname"), "phoneNumber": phone, "otherNumber": d.get("alt"), "address": d.get("address"), "town": d.get("circle"), "source": SOURCE_LABEL["asur_num"]})
279
- if _is_valid_api_response("aadhaar_to_info", api_results.get("aadhaar_to_info")):
280
- for item in api_results["aadhaar_to_info"]["data"]:
281
- records.append({"name": item.get("name"), "phoneNumber": item.get("phoneNumber"), "source": SOURCE_LABEL["asur_aadhaar"]})
282
- return {"records": _drop_empty_records(records), "extras": _format_asur_extras(aadhaar, api_results), "api_results": api_results, "elapsed": time.time() - t0}
283
-
284
- def _norm(s): return re.sub(r"\s+", " ", str(s).strip().lower()) if s else ""
285
- def dedup_records(records):
286
- seen, result = {}, []
287
- for rec in records:
288
- if not isinstance(rec, dict): continue
289
- n, f, a = _norm(rec.get("name")), _norm(rec.get("fathersName")), _norm(rec.get("address"))
290
- an = re.sub(r"[^a-z0-9]+", " ", a).strip()
291
- key = ("na", n, an) if n and an else ("nf", n, f) if n and f else ("a", an) if an else None
292
- if not key: result.append(rec); continue
293
- if key not in seen: seen[key] = len(result); result.append(rec)
294
- else:
295
- idx = seen[key]
296
- if sum(1 for v in rec.values() if v) > sum(1 for v in result[idx].values() if v): result[idx] = rec
297
- return result
298
-
299
- def format_result(idx, row):
300
- lines = [f"<b>━━━ #{idx} ━━━</b>"]
301
- for key, emoji, label in FIELD_LABELS:
302
- v = _tv(row.get(key), TRUNC.get(key, 60))
303
- if v: lines.append(f"{emoji} <b>{label}:</b> <code>{esc(v)}</code>")
304
- return "\n".join(lines)
305
-
306
- def render_page(results, page, total_pages, phone, elapsed, note="", extras=""):
307
- start = page * PAGE_SIZE
308
- chunk = results[start:start + PAGE_SIZE]
309
- head = f"📱 <b>Phone:</b> <code>{esc(phone)}</code>\n📄 <b>Page {page+1}/{total_pages}</b> · {len(results)} result(s) · ⏱️ {elapsed:.1f}s"
310
- if note: head += f"\n⚠️ <i>{esc(note)}</i>"
311
- parts = [head]
312
- if extras and page == 0: parts.append(extras)
313
- parts.append("\n\n".join(format_result(start + i + 1, r) for i, r in enumerate(chunk)) if chunk else "<i>No records to display.</i>")
314
- return "\n\n".join(parts)
315
-
316
- def normalize_phone(text):
317
- digits = "".join(c for c in text.strip() if c.isdigit())
318
- if len(digits) == 11 and digits.startswith("0"): digits = digits[1:]
319
- if len(digits) == 12 and digits.startswith("91"): digits = digits[2:]
320
- elif len(digits) == 11 and digits.startswith("91"): digits = digits[1:]
321
- return (digits, None) if len(digits) == 10 and PHONE_REGEX.match(digits) else (None, f"invalid")
322
-
323
- # ══ BOT STATE ══
324
- ACTIVITY_LOG, ACTIVE_USERS, UNIQUE_USERS, PHONE_COUNTS, PEAK_CONCURRENT = deque(maxlen=ACTIVITY_LOG_MAX), {}, {}, Counter(), 0
325
- _activity_lock, _admin_lock, _state_lock = threading.Lock(), threading.Lock(), threading.Lock()
326
- _admin_sessions, _admin_states = {}, {}
327
- BANNED_USERS, BAN_REASONS, MAINTENANCE_MODE, MAINTENANCE_REASON = set(), {}, False, ""
328
- USER_HISTORY, SEARCH_CACHE, SEARCH_CACHE_LOCK, USER_LAST = {}, {}, threading.Lock(), {}
329
- STATS = {"queries": 0, "timeouts": 0, "errors": 0, "backup_sent": 0, "started": time.time()}
330
- _member_cache, _member_lock, _pending_query, _pending_lock = {}, threading.Lock(), {}, threading.Lock()
331
- _user_daily, _quota_lock, _user_msg_times, _muted_until, _flood_lock = {}, threading.Lock(), {}, {}, threading.Lock()
332
- _seen_updates, _seen_updates_lock = {}, threading.Lock()
333
-
334
- # ══ TELEGRAM HELPERS ══
335
- async def tg(method, payload, timeout=30):
336
- try:
337
- async with httpx.AsyncClient(timeout=timeout) as cli:
338
- return (await cli.post(f"{TELEGRAM_API}/{method}", json=payload)).json()
339
- except Exception as e:
340
- log.error(f"TG API Fail {method}: {e}")
341
- return {"ok": False, "error": str(e)}
342
-
343
- async def send(chat_id, text, **kw):
344
- kw.setdefault("parse_mode", "HTML"); kw.setdefault("disable_web_page_preview", True)
345
- res = await tg("sendMessage", {"chat_id": chat_id, "text": text, **{k: v for k, v in kw.items() if v is not None}})
346
- return res["result"]["message_id"] if res.get("ok") else None
347
-
348
- async def edit(chat_id, msg_id, text, **kw):
349
- kw.setdefault("parse_mode", "HTML"); kw.setdefault("disable_web_page_preview", True)
350
- await tg("editMessageText", {"chat_id": chat_id, "message_id": msg_id, "text": text, **{k: v for k, v in kw.items() if v is not None}})
351
-
352
- async def send_document(chat_id, filename, content, caption=""):
353
- try:
354
- async with httpx.AsyncClient(timeout=60) as cli:
355
- return (await cli.post(f"{TELEGRAM_API}/sendDocument", data={"chat_id": str(chat_id), "caption": caption[:1024]}, files={"document": (filename, content, "application/octet-stream")})).json()
356
- except: return {"ok": False}
357
-
358
- # ══ BOT LOGIC ══
359
- def _short_user(uid, user=None):
360
- u = (user or {}).get("username") or UNIQUE_USERS.get(uid, {}).get("username")
361
- f = (user or {}).get("first_name") or UNIQUE_USERS.get(uid, {}).get("first_name")
362
- return f"@{u}" if u else f if f else f"({uid})"
363
- def _fmt_ts(ts): return time.strftime("%H:%M:%S", time.localtime(ts))
364
- def _today_utc(): return time.strftime("%Y-%m-%d", time.gmtime())
365
-
366
- def is_duplicate_update(update_id):
367
- if not update_id: return False
368
- with _seen_updates_lock:
369
- if len(_seen_updates) > 2000:
370
- for k in [k for k, v in _seen_updates.items() if v < time.time() - 600]: del _seen_updates[k]
371
- if update_id in _seen_updates: return True
372
- _seen_updates[update_id] = time.time(); return False
373
-
374
- async def _is_channel_member(uid):
375
- if not FORCE_JOIN_CHANNEL: return True
376
- with _member_lock:
377
- c = _member_cache.get(uid)
378
- if c and time.time() - c[1] < MEMBERSHIP_CACHE_TTL: return c[0]
379
- is_m = False
380
- res = await tg("getChatMember", {"chat_id": FORCE_JOIN_CHANNEL, "user_id": uid})
381
- if res.get("ok"): is_m = res.get("result", {}).get("status") in ("member", "administrator", "creator")
382
- else: log.warning(f"Force Join Check Failed: {res}")
383
- with _member_lock: _member_cache[uid] = (is_m, time.time())
384
- return is_m
385
-
386
- async def check_force_join(chat_id, user, text):
387
- uid = user.get("id")
388
- if not FORCE_JOIN_CHANNEL or uid in OWNER_IDS or _is_admin_session(uid) or text.startswith(("/start", "/help", "/myid", "/whoami", "/ping", "/info", "/status")): return True
389
- if await _is_channel_member(uid): return True
390
- with _pending_lock: _pending_query[uid] = (text, chat_id, time.time())
391
- url = FORCE_JOIN_CHANNEL if FORCE_JOIN_CHANNEL.startswith("http") else f"https://t.me/{FORCE_JOIN_CHANNEL.lstrip('@')}" if FORCE_JOIN_CHANNEL.startswith("@") else "https://t.me/"
392
- await send(chat_id, f"🔒 <b>Join required</b>\n\n👉 {esc(url)}\n\nTap <b>✅ I Joined</b> below.", reply_markup={"inline_keyboard": [[{"text": "📢 Join", "url": url}], [{"text": "✅ I Joined", "callback_data": "join:check"}]]})
393
- return False
394
-
395
- def _is_unlimited(uid): return uid in OWNER_IDS or _is_admin_session(uid)
396
- def check_quota(uid):
397
- if _is_unlimited(uid): return True, DAILY_QUOTA_ADMIN
398
- today = _today_utc()
399
- with _quota_lock:
400
- e = _user_daily.get(uid)
401
- if not e or e[0] != today: _user_daily[uid] = (today, 0); return True, DAILY_QUOTA
402
- return (False, 0) if e[1] >= DAILY_QUOTA else (True, DAILY_QUOTA - e[1])
403
- def incr_quota(uid):
404
- if _is_unlimited(uid): return
405
- today = _today_utc()
406
- with _quota_lock:
407
- e = _user_daily.get(uid); _user_daily[uid] = (today, 1) if not e or e[0] != today else (today, e[1] + 1)
408
-
409
- def check_flood(uid):
410
- now = time.time()
411
- with _flood_lock:
412
- if _muted_until.get(uid, 0) > now: return int(_muted_until[uid] - now)
413
- dq = _user_msg_times.setdefault(uid, deque(maxlen=FLOOD_MAX)); dq.append(now)
414
- if len(dq) == FLOOD_MAX and dq[0] >= now - FLOOD_WINDOW: _muted_until[uid] = now + FLOOD_MUTE_SEC; return FLOOD_MUTE_SEC
415
- return None
416
-
417
- def _log_activity(user, action, inp, reply, summary="", ms=0, src=""):
418
- if not user or "id" not in user: return
419
- with _activity_lock:
420
- info = UNIQUE_USERS.setdefault(user["id"], {"username": None, "first_name": None, "count": 0, "first_seen": time.time(), "last_seen": time.time()})
421
- info.update({"username": user.get("username"), "first_name": user.get("first_name"), "last_seen": time.time()})
422
- info["count"] += 1; ACTIVE_USERS[user["id"]] = time.time()
423
- if action == "search" and isinstance(inp, str) and len(inp) == 10: PHONE_COUNTS[inp] += 1
424
- ACTIVITY_LOG.append({"ts": time.time(), "user_id": user["id"], "username": user.get("username"), "first_name": user.get("first_name"), "action": action, "input": inp[:80], "reply_type": reply, "summary": summary[:150], "elapsed_ms": int(ms), "source": src})
425
-
426
- def _get_stats():
427
- with _activity_lock:
428
- return {"unique_users": len(UNIQUE_USERS), "live_users": sum(1 for ts in ACTIVE_USERS.values() if ts >= time.time() - LIVE_WINDOW), "today_users": len(set(e["user_id"] for e in ACTIVITY_LOG if e["action"] == "search" and e["ts"] >= time.time() - (time.time() % 86400))), "today_searches": sum(1 for e in ACTIVITY_LOG if e["action"] == "search" and e["ts"] >= time.time() - (time.time() % 86400)), "total_searches": sum(1 for e in ACTIVITY_LOG if e["action"] == "search"), "peak_concurrent": PEAK_CONCURRENT, "total_log_entries": len(ACTIVITY_LOG), "banned_count": len(BANNED_USERS), "maintenance": MAINTENANCE_MODE, "cached_searches": len(SEARCH_CACHE), "backup_sent": STATS["backup_sent"]}
429
-
430
- def _is_banned(uid): return uid in BANNED_USERS
431
- def _ban_user(uid, reason=""): BANNED_USERS.add(uid); BAN_REASONS[uid] = reason
432
- def _unban_user(uid): BANNED_USERS.discard(uid); BAN_REASONS.pop(uid, None)
433
- def _get_maintenance(): return MAINTENANCE_MODE, MAINTENANCE_REASON
434
- def _set_maintenance(on, reason=""): globals().update({"MAINTENANCE_MODE": on, "MAINTENANCE_REASON": reason if on else ""})
435
-
436
- def _is_admin_session(uid): return _admin_sessions.get(uid, 0) > time.time()
437
- def _grant_admin(uid): _admin_sessions[uid] = time.time() + ADMIN_SESSION_TTL
438
- def _revoke_admin(uid): _admin_sessions.pop(uid, None)
439
- def _admin_state_get(uid):
440
- e = _admin_states.get(uid)
441
- if e and time.time() - e[1] < ADMIN_PROMPT_TTL: return e[0]
442
- _admin_states.pop(uid, None); return None
443
- def _admin_state_set(uid, state): _admin_states[uid] = (state, time.time())
444
- def _admin_state_clear(uid): _admin_states.pop(uid, None)
445
-
446
- def _build_backup_payload(user, phone, status, elapsed, fast_data, asur_data, db_results, count):
447
- return {"meta": {"ts_utc": datetime.now(timezone.utc).isoformat(), "bot_version": VERSION, "telegram_user_id": user.get("id"), "username": user.get("username")}, "input": {"mobile": phone}, "status": status, "elapsed_s": round(elapsed, 2), "aadhaar": fast_data.get("aadhaar"), "api_responses_raw": {**(fast_data.get("raw") or {}), **(asur_data.get("api_results") or {})}, "api_status": fast_data.get("source_status"), "db_results": db_results or [], "records_shown": count}
448
- async def forward_to_backup(user, phone, status, elapsed, fast_data, asur_data, db_results, count):
449
- if not BACKUP_CHANNEL_ID or not BACKUP_ENABLED: return
450
- try:
451
- payload = _build_backup_payload(user, phone, status, elapsed, fast_data, asur_data, db_results, count)
452
- res1 = await send(BACKUP_CHANNEL_ID, f"📥 <b>Lookup</b> {phone}\n👤 {user.get('id')} (@{user.get('username')})\n📊 {status} · {count} records · {elapsed:.1f}s")
453
- if not res1: log.warning("Backup text failed to send. Bot in channel?")
454
- res2 = await send_document(BACKUP_CHANNEL_ID, f"lookup_{phone}.json", json.dumps(payload, indent=2).encode(), caption=f"Mobile {phone}")
455
- if not res2.get("ok"): log.warning(f"Backup doc failed: {res2}")
456
- STATS["backup_sent"] += 1
457
- except Exception as e: log.error(f"Backup fail: {e}")
458
-
459
- def page_keyboard(sid, page, total, exp=True):
460
- nav = []
461
- if page > 0: nav.append({"text": "◀ Prev", "callback_data": f"p:{sid}:{page-1}"})
462
- nav.append({"text": f"{page+1} / {total}", "callback_data": "noop"})
463
- if page < total - 1: nav.append({"text": "Next ▶", "callback_data": f"p:{sid}:{page+1}"})
464
- rows = [nav, [{"text": "📋 Copy", "callback_data": f"c:{sid}:{page}"}] + ([{"text": "📥 Export", "callback_data": f"e:{sid}"}] if exp else [])]
465
- return {"inline_keyboard": rows}
466
-
467
- async def _db_search_async(phone, loop):
468
- if not con_ready.is_set(): return []
469
- try: return await asyncio.wait_for(loop.run_in_executor(None, run_search_safe, phone), timeout=QUERY_TIMEOUT + 10)
470
- except: STATS["timeouts"] += 1; return []
471
-
472
- async def _show_progressive(cid, mid, phone, results, elapsed, note="", extras="", asur_snap=None):
473
- sid = uuid.uuid4().hex[:10]; tp = max(1, (len(results) + PAGE_SIZE - 1) // PAGE_SIZE)
474
- SEARCH_CACHE[sid] = {"ts": time.time(), "results": results, "query": phone, "elapsed": elapsed, "source_note": note, "extras_block": extras, "asur_data": asur_snap or {}}
475
- await edit(cid, mid, render_page(results, 0, tp, phone, elapsed, note, extras), reply_markup=page_keyboard(sid, 0, tp))
476
- return sid
477
-
478
- async def _do_progressive_search(phone, cid, mid, user):
479
- t0 = time.time(); loop = asyncio.get_running_loop()
480
- db_task = asyncio.create_task(_db_search_async(phone, loop))
481
- fast_task = asyncio.create_task(search_fast_apis_filtered(phone))
482
-
483
- fast_data = await fast_task
484
- fast_records = dedup_records(fast_data["records"])
485
- aadhaar = fast_data.get("aadhaar")
486
- search_id, extras = None, ""
487
- if fast_records: search_id = await _show_progressive(cid, mid, phone, fast_records, fast_data["elapsed"], "⚡ Fast results…")
488
-
489
- asur_task = asyncio.create_task(asur_lookup_filtered(phone, aadhaar))
490
- asur_data = await asur_task
491
- asur_records = dedup_records(asur_data["records"])
492
- extras = asur_data["extras"]
493
-
494
- if asur_records or extras:
495
- comb = dedup_records(fast_records + asur_records)
496
- snap = {"api_results": asur_data["api_results"]}
497
- if search_id: SEARCH_CACHE[search_id].update({"results": comb, "extras_block": extras, "asur_data": snap, "elapsed": time.time()-t0, "source_note": "🪪 ASUR added…"}); await edit(cid, mid, render_page(comb, 0, max(1, (len(comb)+PAGE_SIZE-1)//PAGE_SIZE), phone, time.time()-t0, "🪪 ASUR added…", extras), reply_markup=page_keyboard(search_id, 0, max(1, (len(comb)+PAGE_SIZE-1)//PAGE_SIZE)))
498
- else: search_id = await _show_progressive(cid, mid, phone, comb, time.time()-t0, "🪪 ASUR added…", extras, snap)
499
-
500
- db_results = await db_task
501
- comb = dedup_records(fast_records + asur_records + db_results)
502
- elapsed = time.time() - t0
503
- tp = max(1, (len(comb) + PAGE_SIZE - 1) // PAGE_SIZE)
504
-
505
- if not comb and not extras:
506
- await edit(cid, mid, f"❌ <b>No record found</b>\n📱 {esc(phone)}")
507
- asyncio.create_task(forward_to_backup(user, phone, "empty", elapsed, fast_data, asur_data, db_results, 0)); return
508
-
509
- note = f"➕ {len(comb)-len(dedup_records(fast_records+asur_records))} more from DB"
510
- if search_id:
511
- SEARCH_CACHE[search_id].update({"results": comb, "elapsed": elapsed, "source_note": note, "ts": time.time()})
512
- await edit(cid, mid, render_page(comb, 0, tp, phone, elapsed, note, extras), reply_markup=page_keyboard(search_id, 0, tp))
513
- else: search_id = await _show_progressive(cid, mid, phone, comb, elapsed, note, extras, {"api_results": asur_data["api_results"]})
514
-
515
- STATS["queries"] += 1
516
- asyncio.create_task(forward_to_backup(user, phone, "success", elapsed, fast_data, asur_data, db_results, len(comb)))
517
-
518
- async def _handle_batch(chat_id, user, phones):
519
- await send(chat_id, f"🔍 Batch {len(phones)} nums…")
520
- res = await asyncio.gather(*[search_fast_apis_filtered(p) for p in phones], return_exceptions=True)
521
- lines = [f"📊 <b>Batch Results</b>"] + [f"✅ {p} — {len(r['records'])} recs" if isinstance(r, dict) else f"❌ {p}" for p, r in zip(phones, res)]
522
- await send(chat_id, "\n".join(lines))
523
-
524
- async def _run_broadcast(cid, msg):
525
- with _activity_lock: recips = list(UNIQUE_USERS.keys())
526
- sent = 0
527
- for uid in recips:
528
- if _is_banned(uid): continue
529
- if (await tg("sendMessage", {"chat_id": uid, "text": f"📢 {msg}", "parse_mode": "HTML"})).get("ok"): sent += 1
530
- await asyncio.sleep(BROADCAST_DELAY)
531
- await send(cid, f"✅ Sent: {sent}/{len(recips)}")
532
-
533
- async def _send_log_export(cid):
534
- buf = io.StringIO(); w = csv.writer(buf)
535
- w.writerow(["ts", "uid", "user", "action", "input", "reply", "ms", "src"])
536
- with _activity_lock:
537
- for e in ACTIVITY_LOG: w.writerow([time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(e["ts"])), e["user_id"], e.get("username") or "", e["action"], e.get("input"), e.get("reply_type"), e.get("elapsed_ms", 0), e.get("source", "")])
538
- await send_document(cid, f"logs.csv", buf.getvalue().encode(), f"{len(ACTIVITY_LOG)} entries")
539
-
540
- # ══ HANDLERS ══
541
- async def handle_message(msg):
542
- try:
543
- cid, user, uid, text = msg["chat"]["id"], msg.get("from") or {}, (msg.get("from") or {}).get("id"), (msg.get("text") or "").strip()
544
- if not text or uid is None: return
545
- if _is_banned(uid): await send(cid, "🚫 Banned."); return
546
-
547
- state = _admin_state_get(uid)
548
- if state == "await_admin_token" and not _is_admin_session(uid):
549
- _admin_state_clear(uid)
550
- if text == ADMIN_TOKEN: _grant_admin(uid); await send(cid, "✅ Admin granted", reply_markup=admin_menu_kb()); await send(cid, render_admin_menu())
551
- else: await send(cid, "❌ Invalid token.")
552
- return
553
- if state and _is_admin_session(uid):
554
- _admin_state_clear(uid)
555
- if state == "await_ban_id": parts=text.split(None,1); _ban_user(int(parts[0]), parts[1] if len(parts)>1 else ""); await send(cid, "🚫 Banned.")
556
- elif state == "await_unban_id": _unban_user(int(text.strip())); await send(cid, "✅ Unbanned.")
557
- elif state == "await_broadcast": asyncio.create_task(_run_broadcast(cid, text)); await send(cid, "Broadcasting…")
558
- return
559
-
560
- m_on, m_r = _get_maintenance()
561
- if m_on and not _is_admin_session(uid) and not text.startswith(("/start","/help","/status","/info","/myid")):
562
- await send(cid, f"🛠️ Maintenance: {esc(m_r)}"); return
563
-
564
- if not await check_force_join(cid, user, text): return
565
-
566
- if text == "/admin":
567
- if _is_admin_session(uid): await send(cid, render_admin_menu(), reply_markup=admin_menu_kb())
568
- else: _admin_state_set(uid, "await_admin_token"); await send(cid, "🔐 Token:")
569
- return
570
- if text == "/logout": _revoke_admin(uid); await send(cid, "Logged out."); return
571
-
572
- if text.startswith("/") and _is_admin_session(uid):
573
- await _handle_admin_command(cid, user, text, uid); return
574
-
575
- if text == "/status":
576
- s = _get_stats()
577
- await send(cid, f"📊 Users: {s['unique_users']} · Searches: {s['total_searches']}\nAPI: 850CR + IndData + ASUR\nDB: {con_ready.is_set()}")
578
- return
579
- if text == "/info": await send(cid, f"ℹ️ Bot v{VERSION}. Send mobile number to search."); return
580
- if text == "/history":
581
- h = USER_HISTORY.get(uid, [])
582
- if not h: await send(cid, "No history.")
583
- else: await send(cid, "🕘 Recent:", reply_markup={"inline_keyboard": [[{"text": x["phone"], "callback_data": f"h:{x['phone']}"}] for x in h]})
584
- return
585
- if text == "/myid": await send(cid, f"🆔 {uid}"); return
586
- if text in ("/start", "/help"):
587
- await send(cid, WELCOME_TEMPLATE.format(v=VERSION))
588
- if not warmed.is_set(): threading.Thread(target=warm_phone_cache, daemon=True).start()
589
- return
590
-
591
- if "," in text:
592
- parts = [p.strip() for p in text.split(",") if p.strip()]
593
- phones = [normalize_phone(p)[0] for p in parts]
594
- if all(phones): await _handle_batch(cid, user, phones); return
595
- await send(cid, "❌ Batch format: 9876543210,9876543211"); return
596
-
597
- phone, err = normalize_phone(text)
598
- if not phone: await send(cid, "❌ Send a 10-digit number."); return
599
-
600
- mute = check_flood(uid)
601
- if mute: await send(cid, f"⏳ Wait {mute}s."); return
602
-
603
- now = time.time()
604
- if now - USER_LAST.get(uid, 0) < USER_COOLDOWN: await send(cid, f"⏳ Wait {int(USER_COOLDOWN-(now-USER_LAST.get(uid,0)))}s."); return
605
- USER_LAST[uid] = now
606
-
607
- ok, rem = check_quota(uid)
608
- if not ok: await send(cid, f"❌ Quota {DAILY_QUOTA} reached."); return
609
- incr_quota(uid)
610
-
611
- if not warmed.is_set(): threading.Thread(target=warm_phone_cache, daemon=True).start()
612
-
613
- mid = await send(cid, f"🔍 Searching <code>{phone}</code>…")
614
- if mid: await _do_progressive_search(phone, cid, mid, user)
615
- except Exception as e: log.error(f"handle_message: {e!r}")
616
-
617
- async def handle_callback(cb):
618
- try:
619
- data, cb_id, msg, user = cb.get("data", ""), cb["id"], cb.get("message") or {}, cb.get("from") or {}
620
- cid, mid, uid = msg.get("chat", {}).get("id"), msg.get("message_id"), user.get("id")
621
- if not cid or not mid: return await tg("answerCallbackQuery", {"callback_query_id": cb_id})
622
-
623
- if data == "join:check":
624
- with _member_lock: _member_cache.pop(uid, None)
625
- if not await _is_channel_member(uid): return await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Not joined", "show_alert": True})
626
- await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "✅ Verified!"})
627
- try: await tg("deleteMessage", {"chat_id": cid, "message_id": mid})
628
- except: pass
629
- with _pending_lock: pending = _pending_query.pop(uid, None)
630
- if pending and time.time() - pending[2] < PENDING_QUERY_TTL: await handle_message({"chat": {"id": cid}, "from": user, "text": pending[0]})
631
- else: await send(cid, "✅ Thanks! Send a number.")
632
- return
633
-
634
- if data.startswith("adm:") and _is_admin_session(uid):
635
- action = data.split(":")[1]
636
- if action == "menu": await edit(cid, mid, render_admin_menu(), reply_markup=admin_menu_kb())
637
- elif action == "live": await edit(cid, mid, render_live(), reply_markup=admin_menu_kb())
638
- elif action == "stats": await edit(cid, mid, render_stats(), reply_markup=admin_menu_kb())
639
- elif action == "log": await edit(cid, mid, *render_log(list(reversed(ACTIVITY_LOG)), int(data.split(":")[2]) if len(data.split(":"))>2 else 0))
640
- elif action == "ban": _admin_state_set(uid, "await_ban_id"); await edit(cid, mid, "Send ID to ban:")
641
- elif action == "unban": _admin_state_set(uid, "await_unban_id"); await edit(cid, mid, "Send ID to unban:")
642
- elif action == "broadcast": _admin_state_set(uid, "await_broadcast"); await edit(cid, mid, "Send message:")
643
- elif action == "export": await _send_log_export(cid)
644
- return await tg("answerCallbackQuery", {"callback_query_id": cb_id})
645
-
646
- if data.startswith("h:"):
647
- await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Searching…"})
648
- return await handle_message({"chat": {"id": cid}, "from": user, "text": data.split(":")[1]})
649
-
650
- if data.startswith("e:") and (sid := data.split(":")[1]) in SEARCH_CACHE:
651
- ent = SEARCH_CACHE[sid]
652
- await send_document(cid, f"results_{ent['query']}.json", json.dumps(ent, indent=2, default=str).encode(), f"{len(ent['results'])} recs")
653
- return await tg("answerCallbackQuery", {"callback_query_id": cb_id, "text": "Sent"})
654
-
655
- if data.startswith("p:") and (parts := data.split(":"))[1] in SEARCH_CACHE:
656
- ent = SEARCH_CACHE[parts[1]]; pg = int(parts[2]); tp = max(1, (len(ent["results"])+PAGE_SIZE-1)//PAGE_SIZE)
657
- await edit(cid, mid, render_page(ent["results"], pg, tp, ent["query"], ent["elapsed"], ent.get("source_note",""), ent.get("extras_block","")), reply_markup=page_keyboard(parts[1], pg, tp))
658
- return await tg("answerCallbackQuery", {"callback_query_id": cb_id})
659
-
660
- await tg("answerCallbackQuery", {"callback_query_id": cb_id})
661
- except: pass
662
-
663
- # ══ ADMIN ══
664
- def admin_menu_kb(): return {"inline_keyboard": [[{"text": "📊 Stats", "callback_data": "adm:stats"}, {"text": "📜 Logs", "callback_data": "adm:log:0"}], [{"text": "🚫 Ban", "callback_data": "adm:ban"}, {"text": "✅ Unban", "callback_data": "adm:unban"}], [{"text": "📢 Broadcast", "callback_data": "adm:broadcast"}, {"text": "📥 Export", "callback_data": "adm:export"}], [{"text": "🔄 Menu", "callback_data": "adm:menu"}]]}
665
- def render_admin_menu(): return f"🛡️ Admin v{VERSION}\nUsers: {len(UNIQUE_USERS)}\nBanned: {len(BANNED_USERS)}"
666
- def render_stats(): return f"📈 Stats\nUsers: {len(UNIQUE_USERS)}\nSearches: {STATS['queries']}"
667
- def render_log(entries, page=0, size=8):
668
- tp = max(1, (len(entries)+size-1)//size); page = max(0, min(page, tp-1))
669
- return "\n".join([f"{_fmt_ts(e['ts'])} {e['action']} {e.get('input','')}" for e in entries[page*size:(page+1)*size]]), {"inline_keyboard": [[{"text": "◀", "callback_data": f"adm:log:{page-1}"}, {"text": f"{page+1}/{tp}", "callback_data": "noop"}, {"text": "▶", "callback_data": f"adm:log:{page+1}"}]]}
670
-
671
- async def _handle_admin_command(cid, user, text, uid):
672
- cmd, args = text.split()[0].lower(), text.split()[1:]
673
- if cmd == "/stats": await send(cid, render_stats())
674
- elif cmd == "/ban" and args: _ban_user(int(args[0]), " ".join(args[1:])); await send(cid, "Banned.")
675
- elif cmd == "/unban" and args: _unban_user(int(args[0])); await send(cid, "Unbanned.")
676
- elif cmd == "/broadcast" and args: asyncio.create_task(_run_broadcast(cid, " ".join(args))); await send(cid, "Broadcasting…")
677
- elif cmd == "/export": await _send_log_export(cid)
678
- elif cmd == "/maintenance" and args: _set_maintenance(args[0]=="on", " ".join(args[1:])); await send(cid, f"Maintenance {args[0]}")
679
- else: await send(cid, render_admin_menu(), reply_markup=admin_menu_kb())
680
-
681
- # ══ WEB ENDPOINTS ══
682
- async def admin_index(req: Request):
683
- for p in ("admin.html", "/app/admin.html"):
684
- if os.path.exists(p): return Response(open(p, "rb").read(), media_type="text/html")
685
- return HTMLResponse("<h1>admin.html not found</h1>", status_code=404)
686
- async def admin_login(req: Request):
687
- if (await req.json()).get("token") == ADMIN_TOKEN:
688
- resp = JSONResponse({"ok": True})
689
- resp.set_cookie("admin_session", "1", max_age=3600, httponly=True, path="/admin")
690
- return resp
691
- return JSONResponse({"error": "invalid"}, status_code=401)
692
- async def api_stats(req): return JSONResponse(_get_stats())
693
- async def api_logs(req): return JSONResponse({"entries": list(reversed(list(ACTIVITY_LOG)))[:100]})
694
- async def api_ban(req): d=await req.json(); _ban_user(d["user_id"], d.get("reason","")); return JSONResponse({"ok":True})
695
- async def api_unban(req): _unban_user((await req.json())["user_id"]); return JSONResponse({"ok":True})
696
-
697
- async def webhook_handler(request: Request):
698
- if SECRET_TOKEN and request.headers.get("x-telegram-bot-api-secret-token") != SECRET_TOKEN: return JSONResponse({"ok": False}, status_code=403)
699
- try: update = await request.json()
700
- except: return JSONResponse({"ok": True})
701
- if "message" in update and not is_duplicate_update(update.get("update_id")): asyncio.create_task(handle_message(update["message"]))
702
- elif "callback_query" in update: asyncio.create_task(handle_callback(update["callback_query"]))
703
- return JSONResponse({"ok": True})
704
-
705
- async def health_handler(req):
706
- return JSONResponse({"status": "ok", "version": VERSION, "con_ready": con_ready.is_set(), "warmed": warmed.is_set()})
707
-
708
- # ══ BOOT ══
709
- def _boot():
710
- demo = gr.Blocks(title="Bot")
711
- with demo:
712
- gr.Markdown(f"# {BOT_NAME} v{VERSION}")
713
- gr.JSON(label="Status", value={"ready": con_ready.is_set()})
714
- if _HAS_SPACES:
715
- @spaces.GPU(duration=10)
716
- def dummy(): return "ok"
717
- gr.Button("init", visible=False).click(fn=dummy, inputs=None, outputs=None)
718
- demo.launch(server_name="0.0.0.0", server_port=7860, share=False, ssr_mode=False, prevent_thread_lock=True)
719
-
720
- app = demo.app
721
- app.router.routes.insert(0, StarletteRoute("/webhook", webhook_handler, methods=["POST"]))
722
- app.router.routes.insert(0, StarletteRoute("/health", health_handler, methods=["GET"]))
723
-
724
- if ADMIN_TOKEN:
725
- app.router.routes.insert(0, StarletteRoute("/admin", admin_index, methods=["GET"]))
726
- app.router.routes.insert(0, StarletteRoute("/admin/login", admin_login, methods=["POST"]))
727
- app.router.routes.insert(0, StarletteRoute("/admin/api/stats", api_stats, methods=["GET"]))
728
- app.router.routes.insert(0, StarletteRoute("/admin/api/logs", api_logs, methods=["GET"]))
729
- app.router.routes.insert(0, StarletteRoute("/admin/api/ban", api_ban, methods=["POST"]))
730
- app.router.routes.insert(0, StarletteRoute("/admin/api/unban", api_unban, methods=["POST"]))
731
-
732
- app.build_middleware_stack()
733
-
734
- threading.Thread(target=warm_phone_cache, daemon=True).start()
735
- threading.Thread(target=cache_gc, daemon=True).start()
736
- threading.Thread(target=_set_webhook, daemon=True).start()
737
-
738
- log.info("✅ Bot Ready")
739
- return demo
740
-
741
- def cache_gc():
742
- while True:
743
- time.sleep(60); now = time.time()
744
- for k in [k for k, v in SEARCH_CACHE.items() if now - v.get("ts", 0) > SEARCH_CACHE_TTL]: SEARCH_CACHE.pop(k, None)
745
- for k in [k for k, v in _seen_updates.items() if v < now - 600]: _seen_updates.pop(k, None)
746
-
747
- def _set_webhook():
748
- if not BOT_TOKEN or not (SPACE_URL or SPACE_HOST): return
749
- url = f"{(SPACE_URL or 'https://'+SPACE_HOST).rstrip('/')}/webhook"
750
- with httpx.Client() as cli:
751
- r = cli.post(f"{TELEGRAM_API}/setWebhook", json={"url": url, "secret_token": SECRET_TOKEN, "allowed_updates": ["message", "callback_query"], "drop_pending_updates": True})
752
- log.info(f"Webhook: {r.json()}")
753
-
754
- WELCOME_TEMPLATE = "👋 <b>Phone Lookup Bot</b> v{v}\n\nSend me any <b>10-digit mobile number</b>."
755
-
756
- if __name__ == "__main__":
757
- try:
758
- demo = _boot()
759
- demo.block_thread()
760
- except Exception as e:
761
- log.critical(f"Boot failed: {e}")