Бот для капчи в чатах
Roman Sergienko
2026-10-10 c3f15480f581df8799eeead71987956db11e85b9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
import os
import secrets
from contextlib import asynccontextmanager
from typing import AsyncIterator, Dict, List, Optional
 
import aiosqlite
 
from cfg import (
    DB_DIR,
    DB_PATH,
    DEF_BTN_COUNT,
    DEF_MAX_ATTEMPTS,
    DEF_TIMEOUT,
    DEF_WARN_ACTION,
    DEF_WARN_DURATION,
    DEF_WARN_EXPIRE,
    DEF_WARN_LIMIT,
)
 
# Колонки настроек чата, которые можно менять.
CFG_COLS = (
    "btn_count",
    "timeout",
    "max_attempts",
    "warn_limit",
    "warn_action",
    "warn_duration",
)
 
SQL_TABLES = (
    "CREATE TABLE IF NOT EXISTS chat_cfg ("
    "chat_id INTEGER PRIMARY KEY, "
    "btn_count INTEGER DEFAULT 3, "
    "timeout INTEGER DEFAULT 30, "
    "max_attempts INTEGER DEFAULT 3, "
    "warn_limit INTEGER DEFAULT 3, "
    "warn_action TEXT DEFAULT 'mute', "
    "warn_duration INTEGER DEFAULT 3600)",
    "CREATE TABLE IF NOT EXISTS chats ("
    "chat_id INTEGER PRIMARY KEY, "
    "title TEXT, "
    "type TEXT, "
    "added_at INTEGER, "
    "updated_at INTEGER, "
    "active INTEGER DEFAULT 1)",
    "CREATE TABLE IF NOT EXISTS usr_fails ("
    "user_id INTEGER, "
    "chat_id INTEGER, "
    "fail_count INTEGER DEFAULT 0, "
    "PRIMARY KEY (user_id, chat_id))",
    "CREATE TABLE IF NOT EXISTS warns ("
    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "admin_id INTEGER, "
    "reason TEXT, "
    "created_at INTEGER, "
    "expires_at INTEGER)",
    "CREATE TABLE IF NOT EXISTS punish ("
    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "kind TEXT, "
    "admin_id INTEGER, "
    "reason TEXT, "
    "created_at INTEGER, "
    "until INTEGER, "
    "active INTEGER DEFAULT 1)",
    "CREATE TABLE IF NOT EXISTS mod_log ("
    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
    "chat_id INTEGER, "
    "admin_id INTEGER, "
    "target_id INTEGER, "
    "action TEXT, "
    "reason TEXT, "
    "created_at INTEGER)",
    "CREATE TABLE IF NOT EXISTS adm_perms ("
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "perm TEXT, "
    "allow INTEGER, "
    "PRIMARY KEY (chat_id, user_id, perm))",
    "CREATE TABLE IF NOT EXISTS web_sessions ("
    "token TEXT PRIMARY KEY, "
    "user_id INTEGER, "
    "created_at INTEGER, "
    "expires_at INTEGER)",
    "CREATE TABLE IF NOT EXISTS web_users ("
    "user_id INTEGER PRIMARY KEY, "
    "first_name TEXT, "
    "last_name TEXT, "
    "username TEXT, "
    "photo_url TEXT, "
    "last_login INTEGER)",
)
 
 
@asynccontextmanager
async def db_conn() -> AsyncIterator[aiosqlite.Connection]:
    # busy_timeout предотвращает ошибку "database is locked" при параллельных апдейтах.
    conn = await aiosqlite.connect(DB_PATH)
    conn.row_factory = aiosqlite.Row
    try:
        await conn.execute("PRAGMA busy_timeout=5000")
        yield conn
    finally:
        await conn.close()
 
 
async def tbl_exists(db: aiosqlite.Connection, name: str) -> bool:
    async with db.execute(
        "SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (name,)
    ) as cur:
        return await cur.fetchone() is not None
 
 
async def col_exists(db: aiosqlite.Connection, table: str, col: str) -> bool:
    async with db.execute(f"PRAGMA table_info({table})") as cur:
        cols = [r[1] for r in await cur.fetchall()]
    return col in cols
 
 
async def migrate_db(db: aiosqlite.Connection) -> None:
    # Обратная совместимость: таблицы переименованы при рефакторинге.
    if await tbl_exists(db, "chat_settings") and not await tbl_exists(db, "chat_cfg"):
        await db.execute("ALTER TABLE chat_settings RENAME TO chat_cfg")
    if await tbl_exists(db, "user_violations") and not await tbl_exists(db, "usr_fails"):
        await db.execute("ALTER TABLE user_violations RENAME TO usr_fails")
    # Дополняем chat_cfg колонками системы предупреждений.
    if await tbl_exists(db, "chat_cfg"):
        if not await col_exists(db, "chat_cfg", "warn_limit"):
            await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_limit INTEGER DEFAULT 3")
        if not await col_exists(db, "chat_cfg", "warn_action"):
            await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_action TEXT DEFAULT 'mute'")
        if not await col_exists(db, "chat_cfg", "warn_duration"):
            await db.execute("ALTER TABLE chat_cfg ADD COLUMN warn_duration INTEGER DEFAULT 3600")
 
 
async def init_db() -> None:
    # Создание каталога обязательно: без него sqlite не откроет файл БД.
    os.makedirs(DB_DIR, exist_ok=True)
    async with aiosqlite.connect(DB_PATH) as db:
        await db.execute("PRAGMA journal_mode=WAL")
        await migrate_db(db)
        for sql in SQL_TABLES:
            await db.execute(sql)
        await db.commit()
 
 
# --- Чаты ---
 
async def upsert_chat(chat_id: int, title: Optional[str], ctype: Optional[str], ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO chats (chat_id, title, type, added_at, updated_at, active) "
            "VALUES (?, ?, ?, ?, ?, 1) "
            "ON CONFLICT(chat_id) DO UPDATE SET "
            "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, active=1",
            (chat_id, title, ctype, ts, ts),
        )
        await db.commit()
 
 
async def set_chat_active(chat_id: int, active: int) -> None:
    async with db_conn() as db:
        await db.execute("UPDATE chats SET active=? WHERE chat_id=?", (active, chat_id))
        await db.commit()
 
 
async def list_chats(active_only: bool = True) -> List[dict]:
    q = "SELECT * FROM chats"
    if active_only:
        q += " WHERE active=1"
    q += " ORDER BY title COLLATE NOCASE"
    async with db_conn() as db:
        async with db.execute(q) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def get_chat(chat_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM chats WHERE chat_id=?", (chat_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
# --- Настройки чата ---
 
def _cfg_defaults() -> Dict:
    return {
        "btn_count": DEF_BTN_COUNT,
        "timeout": DEF_TIMEOUT,
        "max_attempts": DEF_MAX_ATTEMPTS,
        "warn_limit": DEF_WARN_LIMIT,
        "warn_action": DEF_WARN_ACTION,
        "warn_duration": DEF_WARN_DURATION,
    }
 
 
async def get_chat_cfg(chat_id: int) -> Dict:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM chat_cfg WHERE chat_id=?", (chat_id,)) as cur:
            row = await cur.fetchone()
    cfg = _cfg_defaults()
    if row:
        for key in CFG_COLS:
            if row[key] is not None:
                cfg[key] = row[key]
    return cfg
 
 
async def save_chat_cfg(chat_id: int, **fields) -> None:
    # Частичный upsert: обновляются только переданные колонки.
    data = {k: v for k, v in fields.items() if k in CFG_COLS}
    if not data:
        return
    cols = ["chat_id"] + list(data)
    marks = ",".join("?" for _ in cols)
    updates = ",".join(f"{k}=excluded.{k}" for k in data)
    async with db_conn() as db:
        await db.execute(
            f"INSERT INTO chat_cfg ({','.join(cols)}) VALUES ({marks}) "
            f"ON CONFLICT(chat_id) DO UPDATE SET {updates}",
            [chat_id] + list(data.values()),
        )
        await db.commit()
 
 
# --- Нарушения капчи ---
 
async def get_fail_cnt(user_id: int, chat_id: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT fail_count FROM usr_fails WHERE user_id=? AND chat_id=?",
            (user_id, chat_id),
        ) as cur:
            row = await cur.fetchone()
    return row[0] if row else 0
 
 
async def inc_fail_cnt(user_id: int, chat_id: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO usr_fails (user_id, chat_id, fail_count) VALUES (?, ?, 1) "
            "ON CONFLICT(user_id, chat_id) DO UPDATE SET fail_count = fail_count + 1",
            (user_id, chat_id),
        )
        await db.commit()
 
 
async def rst_fail_cnt(user_id: int, chat_id: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "DELETE FROM usr_fails WHERE user_id=? AND chat_id=?", (user_id, chat_id)
        )
        await db.commit()
 
 
# --- Варны ---
 
async def add_warn(chat_id: int, user_id: int, admin_id: int, reason: str, ts: int, expire: int) -> int:
    async with db_conn() as db:
        cur = await db.execute(
            "INSERT INTO warns (chat_id, user_id, admin_id, reason, created_at, expires_at) "
            "VALUES (?, ?, ?, ?, ?, ?)",
            (chat_id, user_id, admin_id, reason, ts, ts + expire),
        )
        await db.commit()
        return cur.lastrowid
 
 
async def cnt_warns(chat_id: int, user_id: int, ts: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT COUNT(*) FROM warns WHERE chat_id=? AND user_id=? AND (expires_at IS NULL OR expires_at > ?)",
            (chat_id, user_id, ts),
        ) as cur:
            return (await cur.fetchone())[0]
 
 
async def list_warns(chat_id: int, user_id: Optional[int] = None) -> List[dict]:
    q = "SELECT * FROM warns WHERE chat_id=?"
    args: list = [chat_id]
    if user_id is not None:
        q += " AND user_id=?"
        args.append(user_id)
    q += " ORDER BY created_at DESC"
    async with db_conn() as db:
        async with db.execute(q, args) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def del_last_warn(chat_id: int, user_id: int) -> bool:
    async with db_conn() as db:
        async with db.execute(
            "SELECT id FROM warns WHERE chat_id=? AND user_id=? ORDER BY created_at DESC, id DESC LIMIT 1",
            (chat_id, user_id),
        ) as cur:
            row = await cur.fetchone()
        if not row:
            return False
        await db.execute("DELETE FROM warns WHERE id=?", (row["id"],))
        await db.commit()
        return True
 
 
async def clr_warns(chat_id: int, user_id: int) -> None:
    async with db_conn() as db:
        await db.execute("DELETE FROM warns WHERE chat_id=? AND user_id=?", (chat_id, user_id))
        await db.commit()
 
 
async def exp_warns(ts: int) -> None:
    # Уборка просроченных варнов.
    async with db_conn() as db:
        await db.execute("DELETE FROM warns WHERE expires_at IS NOT NULL AND expires_at <= ?", (ts,))
        await db.commit()
 
 
# --- Наказания (муты/баны) ---
 
async def add_punish(chat_id: int, user_id: int, kind: str, admin_id: int, reason: str, ts: int, until: Optional[int]) -> int:
    async with db_conn() as db:
        await db.execute(
            "UPDATE punish SET active=0 WHERE chat_id=? AND user_id=? AND kind=? AND active=1",
            (chat_id, user_id, kind),
        )
        cur = await db.execute(
            "INSERT INTO punish (chat_id, user_id, kind, admin_id, reason, created_at, until, active) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, 1)",
            (chat_id, user_id, kind, admin_id, reason, ts, until),
        )
        await db.commit()
        return cur.lastrowid
 
 
async def end_punish(chat_id: int, user_id: int, kind: str) -> None:
    async with db_conn() as db:
        await db.execute(
            "UPDATE punish SET active=0 WHERE chat_id=? AND user_id=? AND kind=? AND active=1",
            (chat_id, user_id, kind),
        )
        await db.commit()
 
 
async def get_punish(chat_id: int, user_id: int, kind: str) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM punish WHERE chat_id=? AND user_id=? AND kind=? AND active=1 "
            "ORDER BY id DESC LIMIT 1",
            (chat_id, user_id, kind),
        ) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
async def list_punish(chat_id: Optional[int] = None, active_only: bool = True) -> List[dict]:
    q = "SELECT * FROM punish WHERE 1=1"
    args: list = []
    if chat_id is not None:
        q += " AND chat_id=?"
        args.append(chat_id)
    if active_only:
        q += " AND active=1"
    q += " ORDER BY created_at DESC"
    async with db_conn() as db:
        async with db.execute(q, args) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def due_unbans(ts: int) -> List[dict]:
    # Активные наказания, срок которых истёк и которые нужно снять.
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM punish WHERE active=1 AND until IS NOT NULL AND until <= ?", (ts,)
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def hist_punish(chat_id: int, user_id: int) -> List[dict]:
    # Полная история мутов/банов пользователя в чате.
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM punish WHERE chat_id=? AND user_id=? ORDER BY created_at DESC",
            (chat_id, user_id),
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def stats(ts: int) -> dict:
    # Сводная статистика для дашборда панели.
    async with db_conn() as db:
        async def one(q: str, args: tuple = ()):
            async with db.execute(q, args) as cur:
                return (await cur.fetchone())[0]
        return {
            "chats": await one("SELECT COUNT(*) FROM chats WHERE active=1"),
            "warns": await one(
                "SELECT COUNT(*) FROM warns WHERE expires_at IS NULL OR expires_at > ?", (ts,)
            ),
            "mutes": await one("SELECT COUNT(*) FROM punish WHERE active=1 AND kind='mute'"),
            "bans": await one("SELECT COUNT(*) FROM punish WHERE active=1 AND kind='ban'"),
            "logs": await one("SELECT COUNT(*) FROM mod_log"),
            "web_users": await one("SELECT COUNT(*) FROM web_users"),
        }
 
 
async def add_log(chat_id: int, admin_id: int, target_id: int, action: str, reason: str, ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO mod_log (chat_id, admin_id, target_id, action, reason, created_at) "
            "VALUES (?, ?, ?, ?, ?, ?)",
            (chat_id, admin_id, target_id, action, reason or "", ts),
        )
        await db.commit()
 
 
async def list_log(chat_id: Optional[int] = None, limit: int = 100) -> List[dict]:
    if chat_id is None:
        q = "SELECT * FROM mod_log ORDER BY created_at DESC LIMIT ?"
        args: list = [limit]
    else:
        q = "SELECT * FROM mod_log WHERE chat_id=? ORDER BY created_at DESC LIMIT ?"
        args = [chat_id, limit]
    async with db_conn() as db:
        async with db.execute(q, args) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
# --- Права администраторов ---
 
async def set_perm(chat_id: int, user_id: int, perm: str, allow: bool) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO adm_perms (chat_id, user_id, perm, allow) VALUES (?, ?, ?, ?) "
            "ON CONFLICT(chat_id, user_id, perm) DO UPDATE SET allow=excluded.allow",
            (chat_id, user_id, perm, 1 if allow else 0),
        )
        await db.commit()
 
 
async def get_perm_row(chat_id: int, user_id: int, perm: str) -> Optional[int]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT allow FROM adm_perms WHERE chat_id=? AND user_id=? AND perm=?",
            (chat_id, user_id, perm),
        ) as cur:
            row = await cur.fetchone()
    return row[0] if row else None
 
 
async def list_perm_rows(chat_id: int) -> List[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM adm_perms WHERE chat_id=?", (chat_id,)) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def del_user_perms(chat_id: int, user_id: int) -> None:
    async with db_conn() as db:
        await db.execute("DELETE FROM adm_perms WHERE chat_id=? AND user_id=?", (chat_id, user_id))
        await db.commit()
 
 
# --- Веб-сессии и пользователи панели ---
 
async def create_sess(user_id: int, ts: int, ttl: int) -> str:
    token = secrets.token_urlsafe(32)
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO web_sessions (token, user_id, created_at, expires_at) VALUES (?, ?, ?, ?)",
            (token, user_id, ts, ts + ttl),
        )
        await db.commit()
    return token
 
 
async def get_sess(token: str, ts: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM web_sessions WHERE token=? AND expires_at > ?", (token, ts)
        ) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
async def del_sess(token: str) -> None:
    async with db_conn() as db:
        await db.execute("DELETE FROM web_sessions WHERE token=?", (token,))
        await db.commit()
 
 
async def upsert_web_user(user_id: int, first_name: str, last_name: str, username: str, photo_url: str, ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO web_users (user_id, first_name, last_name, username, photo_url, last_login) "
            "VALUES (?, ?, ?, ?, ?, ?) "
            "ON CONFLICT(user_id) DO UPDATE SET "
            "first_name=excluded.first_name, last_name=excluded.last_name, "
            "username=excluded.username, photo_url=excluded.photo_url, last_login=excluded.last_login",
            (user_id, first_name, last_name, username, photo_url, ts),
        )
        await db.commit()
 
 
async def get_web_user(user_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM web_users WHERE user_id=?", (user_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None