Download bot_state.py from Hfzune/Test: direct link, hf CLI and curl.
- Browser
- Download file 19 kB
-
https://huggingface.co/spaces/Hfzune/Test/resolve/main/bot_state.py
- Command line
-
hf download hf://spaces/Hfzune/Test/bot_state.py
-
curl -L -o bot_state.py https://huggingface.co/spaces/Hfzune/Test/resolve/main/bot_state.py
19 kB
| """bot_state.py — Shared state, locks, TG helpers, activity tracking, | |
| bans, maintenance, admin auth, quota, flood, dedup, cache GC. | |
| This module has NO imports from bot.py. | |
| The handler file (bot.py) imports from here and re-exports. | |
| """ | |
| import logging | |
| import threading | |
| import time | |
| from collections import deque, Counter | |
| import httpx | |
| from config import ( | |
| TELEGRAM_API, OWNER_IDS, FORCE_JOIN_CHANNEL, | |
| MEMBERSHIP_CACHE_TTL, PENDING_QUERY_TTL, | |
| FLOOD_WINDOW, FLOOD_MAX, FLOOD_MUTE_SEC, | |
| DAILY_QUOTA, DAILY_QUOTA_ADMIN, | |
| LIVE_WINDOW, HISTORY_LEN, ACTIVITY_LOG_MAX, | |
| ADMIN_SESSION_TTL, ADMIN_PROMPT_TTL, SEARCH_CACHE_TTL, | |
| ) | |
| from engine import esc | |
| log = logging.getLogger("bot_state") | |
| # ══════════════════════════════════════════════════════════════════ | |
| # STATE | |
| # ══════════════════════════════════════════════════════════════════ | |
| ACTIVITY_LOG = deque(maxlen=ACTIVITY_LOG_MAX) | |
| ACTIVE_USERS = {} | |
| UNIQUE_USERS = {} | |
| PHONE_COUNTS = Counter() | |
| PEAK_CONCURRENT = 0 | |
| _activity_lock = threading.Lock() | |
| _admin_lock = threading.Lock() | |
| _admin_sessions = {} | |
| _admin_states = {} | |
| BANNED_USERS = set() | |
| BAN_REASONS = {} | |
| MAINTENANCE_MODE = False | |
| MAINTENANCE_REASON = "" | |
| _state_lock = threading.Lock() | |
| USER_HISTORY = {} | |
| SEARCH_CACHE = {} | |
| SEARCH_CACHE_LOCK = threading.Lock() | |
| USER_LAST = {} | |
| STATS = {"queries": 0, "timeouts": 0, "errors": 0, "backup_sent": 0, | |
| "started": time.time()} | |
| _member_cache = {} | |
| _member_lock = threading.Lock() | |
| _pending_query = {} | |
| _pending_lock = threading.Lock() | |
| _user_daily = {} | |
| _quota_lock = threading.Lock() | |
| _user_msg_times = {} | |
| _muted_until = {} | |
| _flood_lock = threading.Lock() | |
| _seen_updates = {} | |
| _seen_updates_lock = threading.Lock() | |
| # ══════════════════════════════════════════════════════════════════ | |
| # TG HELPERS | |
| # ══════════════════════════════════════════════════════════════════ | |
| async def tg(method, payload, timeout=30): | |
| try: | |
| async with httpx.AsyncClient(timeout=timeout) as cli: | |
| r = await cli.post(f"{TELEGRAM_API}/{method}", json=payload) | |
| return r.json() | |
| except Exception as e: | |
| log.error(f"tg({method}): {e!r}") | |
| return {"ok": False, "error": str(e)} | |
| async def send(chat_id, text, **kw): | |
| kw.setdefault("parse_mode", "HTML") | |
| kw.setdefault("disable_web_page_preview", True) | |
| kw = {k: v for k, v in kw.items() if v is not None} | |
| try: | |
| res = await tg("sendMessage", {"chat_id": chat_id, "text": text, **kw}) | |
| if res.get("ok"): | |
| return res["result"]["message_id"] | |
| log.warning(f"sendMessage failed: {res}") | |
| except Exception as e: | |
| log.error(f"send error: {e!r}") | |
| return None | |
| async def edit(chat_id, message_id, text, **kw): | |
| kw.setdefault("parse_mode", "HTML") | |
| kw.setdefault("disable_web_page_preview", True) | |
| kw = {k: v for k, v in kw.items() if v is not None} | |
| try: | |
| res = await tg("editMessageText", | |
| {"chat_id": chat_id, "message_id": message_id, | |
| "text": text, **kw}) | |
| if not res.get("ok") and "message is not modified" not in str(res): | |
| log.warning(f"editMessageText failed: {res}") | |
| except Exception as e: | |
| log.error(f"edit error: {e!r}") | |
| async def send_document(chat_id, filename, content, caption=""): | |
| try: | |
| files = {"document": (filename, content, "application/octet-stream")} | |
| data = {"chat_id": str(chat_id)} | |
| if caption: | |
| data["caption"] = caption[:1024] | |
| async with httpx.AsyncClient(timeout=60) as cli: | |
| r = await cli.post(f"{TELEGRAM_API}/sendDocument", | |
| data=data, files=files) | |
| res = r.json() | |
| if not res.get("ok"): | |
| log.warning(f"sendDocument failed: {res}") | |
| return res | |
| except Exception as e: | |
| log.error(f"sendDocument error: {e!r}") | |
| return {"ok": False} | |
| # ══════════════════════════════════════════════════════════════════ | |
| # SMALL HELPERS | |
| # ══════════════════════════════════════════════════════════════════ | |
| def _short_user(user_id, user=None): | |
| info = UNIQUE_USERS.get(user_id) or {} | |
| username = (user or {}).get("username") or info.get("username") | |
| first = (user or {}).get("first_name") or info.get("first_name") | |
| if username: | |
| return f"@{username} ({user_id})" | |
| if first: | |
| return f"{first} ({user_id})" | |
| return f"({user_id})" | |
| def _fmt_ts(ts): | |
| return time.strftime("%H:%M:%S", time.localtime(ts)) | |
| def _today_utc(): | |
| return time.strftime("%Y-%m-%d", time.gmtime()) | |
| # ══════════════════════════════════════════════════════════════════ | |
| # UPDATE DEDUP | |
| # ══════════════════════════════════════════════════════════════════ | |
| def is_duplicate_update(update_id): | |
| if not update_id: | |
| return False | |
| now = time.time() | |
| with _seen_updates_lock: | |
| if len(_seen_updates) > 2000: | |
| cutoff = now - 600 | |
| for k in [k for k, v in _seen_updates.items() if v < cutoff]: | |
| del _seen_updates[k] | |
| if update_id in _seen_updates: | |
| return True | |
| _seen_updates[update_id] = now | |
| return False | |
| # ══════════════════════════════════════════════════════════════════ | |
| # FORCE-JOIN | |
| # ══════════════════════════════════════════════════════════════════ | |
| async def _is_channel_member(user_id): | |
| if not FORCE_JOIN_CHANNEL: | |
| return True | |
| now = time.time() | |
| with _member_lock: | |
| c = _member_cache.get(user_id) | |
| if c and now - c[1] < MEMBERSHIP_CACHE_TTL: | |
| return c[0] | |
| is_member = False | |
| try: | |
| res = await tg("getChatMember", | |
| {"chat_id": FORCE_JOIN_CHANNEL, "user_id": user_id}, | |
| timeout=10) | |
| if res.get("ok"): | |
| status = (res.get("result") or {}).get("status", "") | |
| is_member = status in ("member", "administrator", "creator") | |
| except Exception as e: | |
| log.warning(f"[membership] {e!r}") | |
| with _member_lock: | |
| _member_cache[user_id] = (is_member, now) | |
| return is_member | |
| def _join_url(): | |
| if not FORCE_JOIN_CHANNEL: | |
| return "" | |
| if FORCE_JOIN_CHANNEL.startswith("http"): | |
| return FORCE_JOIN_CHANNEL | |
| if FORCE_JOIN_CHANNEL.startswith("@"): | |
| return f"https://t.me/{FORCE_JOIN_CHANNEL.lstrip('@')}" | |
| return "https://t.me/" | |
| async def check_force_join(chat_id, user, text): | |
| if not FORCE_JOIN_CHANNEL: | |
| return True | |
| uid = user.get("id") | |
| if not uid: | |
| return True | |
| if uid in OWNER_IDS: | |
| return True | |
| if _is_admin_session(uid): | |
| return True | |
| if text.startswith(("/start", "/help", "/myid", "/whoami", | |
| "/ping", "/info", "/status")): | |
| return True | |
| if await _is_channel_member(uid): | |
| return True | |
| with _pending_lock: | |
| _pending_query[uid] = (text, chat_id, time.time()) | |
| url = _join_url() | |
| await send(chat_id, | |
| "🔒 <b>Join required</b>\n\n" | |
| "To use this bot, please join our channel first.\n\n" | |
| f"👉 {esc(url)}\n\nAfter joining, tap <b>✅ I Joined</b> below.", | |
| reply_markup={"inline_keyboard": [ | |
| [{"text": "📢 Join Channel", "url": url}], | |
| [{"text": "✅ I Joined", "callback_data": "join:check"}], | |
| ]}) | |
| _log_activity(user, "force_join_block", text[:40], "blocked", "not a member") | |
| return False | |
| # ══════════════════════════════════════════════════════════════════ | |
| # QUOTA | |
| # ══════════════════════════════════════════════════════════════════ | |
| def _is_unlimited(user_id): | |
| return user_id in OWNER_IDS or _is_admin_session(user_id) | |
| def check_quota(user_id): | |
| if _is_unlimited(user_id): | |
| return True, DAILY_QUOTA_ADMIN | |
| today = _today_utc() | |
| with _quota_lock: | |
| e = _user_daily.get(user_id) | |
| if not e or e[0] != today: | |
| _user_daily[user_id] = (today, 0) | |
| return True, DAILY_QUOTA | |
| if e[1] >= DAILY_QUOTA: | |
| return False, 0 | |
| return True, DAILY_QUOTA - e[1] | |
| def incr_quota(user_id): | |
| if _is_unlimited(user_id): | |
| return | |
| today = _today_utc() | |
| with _quota_lock: | |
| e = _user_daily.get(user_id) | |
| if not e or e[0] != today: | |
| _user_daily[user_id] = (today, 1) | |
| else: | |
| _user_daily[user_id] = (today, e[1] + 1) | |
| # ══════════════════════════════════════════════════════════════════ | |
| # FLOOD | |
| # ══════════════════════════════════════════════════════════════════ | |
| def check_flood(user_id): | |
| now = time.time() | |
| with _flood_lock: | |
| until = _muted_until.get(user_id, 0) | |
| if until > now: | |
| return int(until - now) | |
| dq = _user_msg_times.setdefault(user_id, deque(maxlen=FLOOD_MAX)) | |
| dq.append(now) | |
| if len(dq) == FLOOD_MAX and dq[0] >= now - FLOOD_WINDOW: | |
| _muted_until[user_id] = now + FLOOD_MUTE_SEC | |
| return FLOOD_MUTE_SEC | |
| return None | |
| # ══════════════════════════════════════════════════════════════════ | |
| # ACTIVITY | |
| # ══════════════════════════════════════════════════════════════════ | |
| def _log_activity(user, action, input_val, reply_type, summary="", | |
| elapsed_ms=0, source=""): | |
| if not user or "id" not in user: | |
| return | |
| now = time.time() | |
| user_id = user["id"] | |
| with _activity_lock: | |
| info = UNIQUE_USERS.setdefault(user_id, { | |
| "username": None, "first_name": None, "last_name": None, | |
| "count": 0, "first_seen": now, "last_seen": now, | |
| }) | |
| if user.get("username"): | |
| info["username"] = user["username"] | |
| if user.get("first_name"): | |
| info["first_name"] = user["first_name"] | |
| if user.get("last_name"): | |
| info["last_name"] = user["last_name"] | |
| info["count"] += 1 | |
| info["last_seen"] = now | |
| ACTIVE_USERS[user_id] = now | |
| if (action == "search" and isinstance(input_val, str) | |
| and input_val.isdigit() and len(input_val) == 10): | |
| PHONE_COUNTS[input_val] += 1 | |
| ACTIVITY_LOG.append({ | |
| "ts": now, "user_id": user_id, | |
| "username": user.get("username"), | |
| "first_name": user.get("first_name"), | |
| "action": action, "input": (input_val or "")[:80], | |
| "reply_type": reply_type, "summary": (summary or "")[:150], | |
| "elapsed_ms": int(elapsed_ms), "source": source, | |
| }) | |
| def _get_live_users(): | |
| cutoff = time.time() - LIVE_WINDOW | |
| with _activity_lock: | |
| live = [(uid, ts) for uid, ts in ACTIVE_USERS.items() if ts >= cutoff] | |
| live.sort(key=lambda x: -x[1]) | |
| return live | |
| def _get_stats(): | |
| now = time.time() | |
| today_start = now - (now % 86400) | |
| with _activity_lock: | |
| today_users = set() | |
| today_searches = 0 | |
| total_searches = 0 | |
| for e in ACTIVITY_LOG: | |
| if e["action"] == "search": | |
| total_searches += 1 | |
| if e["ts"] >= today_start: | |
| today_searches += 1 | |
| today_users.add(e["user_id"]) | |
| return { | |
| "unique_users": len(UNIQUE_USERS), | |
| "live_users": sum(1 for ts in ACTIVE_USERS.values() | |
| if ts >= now - LIVE_WINDOW), | |
| "today_users": len(today_users), | |
| "today_searches": today_searches, | |
| "total_searches": total_searches, | |
| "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"], | |
| } | |
| def _add_to_history(user_id, phone, count, elapsed, source): | |
| if user_id is None: | |
| return | |
| with _activity_lock: | |
| h = USER_HISTORY.setdefault(user_id, deque(maxlen=HISTORY_LEN)) | |
| h.appendleft({"phone": phone, "ts": time.time(), "count": count, | |
| "elapsed": elapsed, "source": source}) | |
| def _avg_latency_today(): | |
| now = time.time() | |
| today_start = now - (now % 86400) | |
| with _activity_lock: | |
| vals = [e["elapsed_ms"] for e in ACTIVITY_LOG | |
| if e["action"] == "search" and e["ts"] >= today_start | |
| and e["elapsed_ms"] > 0] | |
| return (sum(vals) / len(vals)) / 1000.0 if vals else 0.0 | |
| # ══════════════════════════════════════════════════════════════════ | |
| # BAN / MAINTENANCE | |
| # ══════════════════════════════════════════════════════════════════ | |
| def _is_banned(user_id): | |
| with _state_lock: | |
| return user_id in BANNED_USERS | |
| def _ban_user(user_id, reason=""): | |
| with _state_lock: | |
| BANNED_USERS.add(user_id) | |
| BAN_REASONS[user_id] = reason | |
| def _unban_user(user_id): | |
| with _state_lock: | |
| if user_id in BANNED_USERS: | |
| BANNED_USERS.discard(user_id) | |
| BAN_REASONS.pop(user_id, None) | |
| return True | |
| return False | |
| def _get_maintenance(): | |
| with _state_lock: | |
| return MAINTENANCE_MODE, MAINTENANCE_REASON | |
| def _set_maintenance(on, reason=""): | |
| global MAINTENANCE_MODE, MAINTENANCE_REASON | |
| with _state_lock: | |
| MAINTENANCE_MODE = on | |
| MAINTENANCE_REASON = reason if on else "" | |
| # ══════════════════════════════════════════════════════════════════ | |
| # ADMIN AUTH | |
| # ══════════════════════════════════════════════════════════════════ | |
| def _is_admin_session(user_id): | |
| if user_id is None: | |
| return False | |
| with _admin_lock: | |
| exp = _admin_sessions.get(user_id) | |
| if exp is None: | |
| return False | |
| if time.time() > exp: | |
| _admin_sessions.pop(user_id, None) | |
| return False | |
| return True | |
| def _grant_admin(user_id): | |
| with _admin_lock: | |
| _admin_sessions[user_id] = time.time() + ADMIN_SESSION_TTL | |
| def _revoke_admin(user_id): | |
| with _admin_lock: | |
| _admin_sessions.pop(user_id, None) | |
| def _admin_state_get(user_id): | |
| with _admin_lock: | |
| e = _admin_states.get(user_id) | |
| if e is None: | |
| return None | |
| state, set_at = e | |
| if time.time() - set_at > ADMIN_PROMPT_TTL: | |
| _admin_states.pop(user_id, None) | |
| return None | |
| return state | |
| def _admin_state_set(user_id, state): | |
| with _admin_lock: | |
| _admin_states[user_id] = (state, time.time()) | |
| def _admin_state_clear(user_id): | |
| with _admin_lock: | |
| _admin_states.pop(user_id, None) | |
| # ══════════════════════════════════════════════════════════════════ | |
| # CACHE GC | |
| # ══════════════════════════════════════════════════════════════════ | |
| def cache_gc(): | |
| global PEAK_CONCURRENT | |
| while True: | |
| time.sleep(60) | |
| now = time.time() | |
| with SEARCH_CACHE_LOCK: | |
| dead = [k for k, v in SEARCH_CACHE.items() | |
| if now - v.get("ts", 0) > SEARCH_CACHE_TTL] | |
| for k in dead: | |
| SEARCH_CACHE.pop(k, None) | |
| with _activity_lock: | |
| cutoff = now - LIVE_WINDOW | |
| for uid in list(ACTIVE_USERS.keys()): | |
| if ACTIVE_USERS[uid] < cutoff: | |
| del ACTIVE_USERS[uid] | |
| if len(ACTIVE_USERS) > PEAK_CONCURRENT: | |
| PEAK_CONCURRENT = len(ACTIVE_USERS) | |
| with _member_lock: | |
| for uid, (_, ts) in list(_member_cache.items()): | |
| if now - ts > MEMBERSHIP_CACHE_TTL * 2: | |
| _member_cache.pop(uid, None) | |
| with _pending_lock: | |
| for uid, (_, _, ts) in list(_pending_query.items()): | |
| if now - ts > PENDING_QUERY_TTL: | |
| _pending_query.pop(uid, None) | |
| with _flood_lock: | |
| for uid, until in list(_muted_until.items()): | |
| if until < now - 300: | |
| _muted_until.pop(uid, None) | |
| with _seen_updates_lock: | |
| cutoff = now - 600 | |
| for k in [k for k, v in _seen_updates.items() if v < cutoff]: | |
| del _seen_updates[k] | |
| today = _today_utc() | |
| with _quota_lock: | |
| for uid, (day, _) in list(_user_daily.items()): | |
| if day != today: | |
| _user_daily.pop(uid, None) |