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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|