Бот для капчи в чатах
Roman Sergienko
11 hours ago 5738a9b08e54bdb7496e36511f223b4737bcd9f5
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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
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_FLOOD_ALARM_MUTE,
    DEF_FLOOD_COUNT,
    DEF_FLOOD_ENABLED,
    DEF_FLOOD_MUTE,
    DEF_FLOOD_WINDOW,
    DEF_MAX_ATTEMPTS,
    DEF_NEW_MEMBER_DAYS,
    DEF_NO_LINKS,
    DEF_SLOW_MODE,
    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",
    "flood_enabled",
    "flood_count",
    "flood_window",
    "flood_mute",
    "flood_alarm_mute",
    "new_member_days",
    "no_links",
    "slow_mode",
)
 
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, "
    "flood_enabled INTEGER DEFAULT 1, "
    "flood_count INTEGER DEFAULT 10, "
    "flood_window INTEGER DEFAULT 5, "
    "flood_mute INTEGER DEFAULT 30, "
    "flood_alarm_mute INTEGER DEFAULT 86400, "
    "new_member_days INTEGER DEFAULT 7, "
    "no_links INTEGER DEFAULT 0, "
    "slow_mode INTEGER DEFAULT 10)",
    "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, "
    "msgs INTEGER DEFAULT 0)",
    "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)",
    "CREATE TABLE IF NOT EXISTS users ("
    "user_id INTEGER PRIMARY KEY, "
    "username TEXT, "
    "first_name TEXT, "
    "last_name TEXT, "
    "updated_at INTEGER)",
    "CREATE TABLE IF NOT EXISTS reports ("
    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "target_id INTEGER, "
    "text TEXT, "
    "created_at INTEGER, "
    "status TEXT DEFAULT 'new', "
    "target_msg_id INTEGER DEFAULT 0, "
    "target_text TEXT DEFAULT '')",
    "CREATE TABLE IF NOT EXISTS report_block ("
    "user_id INTEGER, "
    "chat_id INTEGER, "
    "until INTEGER, "
    "PRIMARY KEY (user_id, chat_id))",
    "CREATE TABLE IF NOT EXISTS alarm ("
    "chat_id INTEGER PRIMARY KEY, "
    "enabled INTEGER DEFAULT 0, "
    "enabled_by INTEGER, "
    "enabled_at INTEGER, "
    "raid_until INTEGER, "
    "until INTEGER DEFAULT 0)",
    "CREATE TABLE IF NOT EXISTS member_join ("
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "joined_at INTEGER, "
    "PRIMARY KEY (chat_id, user_id))",
    "CREATE TABLE IF NOT EXISTS dm_users ("
    "user_id INTEGER PRIMARY KEY, "
    "ts INTEGER)",
    "CREATE TABLE IF NOT EXISTS messages ("
    "id INTEGER PRIMARY KEY AUTOINCREMENT, "
    "chat_id INTEGER, "
    "user_id INTEGER, "
    "name TEXT, "
    "text TEXT, "
    "created_at INTEGER, "
    "tg_msg_id INTEGER DEFAULT 0, "
    "media_type TEXT DEFAULT '', "
    "media_file_id TEXT DEFAULT '', "
    "reply_to_tg INTEGER DEFAULT 0, "
    "reply_to_name TEXT DEFAULT '', "
    "reply_to_text TEXT DEFAULT '')",
)
 
 
@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"):
        add_cols = {
            "warn_limit": "INTEGER DEFAULT 3",
            "warn_action": "TEXT DEFAULT 'mute'",
            "warn_duration": "INTEGER DEFAULT 3600",
            "flood_enabled": "INTEGER DEFAULT 1",
            "flood_count": "INTEGER DEFAULT 10",
            "flood_window": "INTEGER DEFAULT 5",
            "flood_mute": "INTEGER DEFAULT 30",
            "flood_alarm_mute": "INTEGER DEFAULT 86400",
            "new_member_days": "INTEGER DEFAULT 7",
            "no_links": "INTEGER DEFAULT 0",
            "slow_mode": "INTEGER DEFAULT 10",
        }
        for col, ddl in add_cols.items():
            if not await col_exists(db, "chat_cfg", col):
                await db.execute(f"ALTER TABLE chat_cfg ADD COLUMN {col} {ddl}")
    if await tbl_exists(db, "alarm") and not await col_exists(db, "alarm", "until"):
        await db.execute("ALTER TABLE alarm ADD COLUMN until INTEGER DEFAULT 0")
    if await tbl_exists(db, "reports"):
        if not await col_exists(db, "reports", "target_msg_id"):
            await db.execute("ALTER TABLE reports ADD COLUMN target_msg_id INTEGER DEFAULT 0")
        if not await col_exists(db, "reports", "target_text"):
            await db.execute("ALTER TABLE reports ADD COLUMN target_text TEXT DEFAULT ''")
    if await tbl_exists(db, "chats") and not await col_exists(db, "chats", "msgs"):
        await db.execute("ALTER TABLE chats ADD COLUMN msgs INTEGER DEFAULT 0")
    if await tbl_exists(db, "messages"):
        msg_cols = {
            "tg_msg_id": "INTEGER DEFAULT 0",
            "media_type": "TEXT DEFAULT ''",
            "media_file_id": "TEXT DEFAULT ''",
            "reply_to_tg": "INTEGER DEFAULT 0",
            "reply_to_name": "TEXT DEFAULT ''",
            "reply_to_text": "TEXT DEFAULT ''",
        }
        for col, ddl in msg_cols.items():
            if not await col_exists(db, "messages", col):
                await db.execute(f"ALTER TABLE messages ADD COLUMN {col} {ddl}")
 
 
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, msgs) "
            "VALUES (?, ?, ?, ?, ?, 1, 1) "
            "ON CONFLICT(chat_id) DO UPDATE SET "
            "title=excluded.title, type=excluded.type, updated_at=excluded.updated_at, "
            "active=1, msgs=msgs+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,
        "flood_enabled": DEF_FLOOD_ENABLED,
        "flood_count": DEF_FLOOD_COUNT,
        "flood_window": DEF_FLOOD_WINDOW,
        "flood_mute": DEF_FLOOD_MUTE,
        "flood_alarm_mute": DEF_FLOOD_ALARM_MUTE,
        "new_member_days": DEF_NEW_MEMBER_DAYS,
        "no_links": DEF_NO_LINKS,
        "slow_mode": DEF_SLOW_MODE,
    }
 
 
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 stats_scoped(ids, ts: int) -> dict:
    # Статистика только по доступным пользователю чатам (для дашборда).
    result = {"chats": len(ids), "warns": 0, "mutes": 0, "bans": 0, "logs": 0}
    ids = list(ids)
    if not ids:
        return result
    ph = ",".join("?" for _ in ids)
    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]
        result["warns"] = await one(
            f"SELECT COUNT(*) FROM warns WHERE chat_id IN ({ph}) "
            f"AND (expires_at IS NULL OR expires_at > ?)",
            tuple(ids) + (ts,),
        )
        result["mutes"] = await one(
            f"SELECT COUNT(*) FROM punish WHERE chat_id IN ({ph}) AND active=1 AND kind='mute'",
            tuple(ids),
        )
        result["bans"] = await one(
            f"SELECT COUNT(*) FROM punish WHERE chat_id IN ({ph}) AND active=1 AND kind='ban'",
            tuple(ids),
        )
        result["logs"] = await one(
            f"SELECT COUNT(*) FROM mod_log WHERE chat_id IN ({ph})", tuple(ids)
        )
    return result
 
 
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
 
 
# --- Кеш пользователей (для поиска по @username) ---
 
async def upsert_user(user_id: int, username: Optional[str], first_name: Optional[str], last_name: Optional[str], ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO users (user_id, username, first_name, last_name, updated_at) "
            "VALUES (?, ?, ?, ?, ?) "
            "ON CONFLICT(user_id) DO UPDATE SET "
            "username=excluded.username, first_name=excluded.first_name, "
            "last_name=excluded.last_name, updated_at=excluded.updated_at",
            (user_id, username, first_name, last_name, ts),
        )
        await db.commit()
 
 
async def find_user_by_username(username: str) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM users WHERE lower(username)=lower(?) ORDER BY updated_at DESC LIMIT 1",
            (username.lstrip("@"),),
        ) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
async def get_user(user_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM users WHERE user_id=?", (user_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
# --- Репорты ---
 
async def add_report(chat_id: int, user_id: int, target_id: int, text: str, ts: int, target_msg_id: int = 0, target_text: str = "") -> int:
    async with db_conn() as db:
        cur = await db.execute(
            "INSERT INTO reports (chat_id, user_id, target_id, text, created_at, status, target_msg_id, target_text) "
            "VALUES (?, ?, ?, ?, ?, 'new', ?, ?)",
            (chat_id, user_id, target_id, text, ts, target_msg_id, target_text),
        )
        await db.commit()
        return cur.lastrowid
 
 
async def get_report(report_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM reports WHERE id=?", (report_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
async def clr_reports(chat_id: int) -> None:
    async with db_conn() as db:
        await db.execute("DELETE FROM reports WHERE chat_id=?", (chat_id,))
        await db.commit()
 
 
async def list_reports(chat_id: int, limit: int = 200) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM reports WHERE chat_id=? ORDER BY created_at DESC LIMIT ?",
            (chat_id, limit),
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def cnt_reports_since(chat_id: int, user_id: int, since: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT COUNT(*) FROM reports WHERE chat_id=? AND user_id=? AND created_at >= ?",
            (chat_id, user_id, since),
        ) as cur:
            return (await cur.fetchone())[0]
 
 
async def close_report(report_id: int) -> None:
    async with db_conn() as db:
        await db.execute("UPDATE reports SET status='closed' WHERE id=?", (report_id,))
        await db.commit()
 
 
async def report_block_until(chat_id: int, user_id: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT until FROM report_block WHERE chat_id=? AND user_id=?", (chat_id, user_id)
        ) as cur:
            row = await cur.fetchone()
    return row[0] if row else 0
 
 
async def set_report_block(chat_id: int, user_id: int, until: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO report_block (user_id, chat_id, until) VALUES (?, ?, ?) "
            "ON CONFLICT(user_id, chat_id) DO UPDATE SET until=excluded.until",
            (user_id, chat_id, until),
        )
        await db.commit()
 
 
# --- Режим тревоги ---
 
async def get_alarm(chat_id: int) -> dict:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM alarm WHERE chat_id=?", (chat_id,)) as cur:
            row = await cur.fetchone()
    if row:
        return dict(row)
    return {"chat_id": chat_id, "enabled": 0, "enabled_by": 0, "enabled_at": 0, "raid_until": 0, "until": 0}
 
 
async def set_alarm(chat_id: int, enabled: bool, by: int, ts: int, until: int = 0) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO alarm (chat_id, enabled, enabled_by, enabled_at, raid_until, until) "
            "VALUES (?, ?, ?, ?, 0, ?) "
            "ON CONFLICT(chat_id) DO UPDATE SET "
            "enabled=excluded.enabled, enabled_by=excluded.enabled_by, "
            "enabled_at=excluded.enabled_at, until=excluded.until",
            (chat_id, 1 if enabled else 0, by, ts, until if enabled else 0),
        )
        # При выключении сбрасываем авто-кик.
        if not enabled:
            await db.execute("UPDATE alarm SET raid_until=0 WHERE chat_id=?", (chat_id,))
        await db.commit()
 
 
async def set_raid_until(chat_id: int, until: int) -> None:
    async with db_conn() as db:
        await db.execute("UPDATE alarm SET raid_until=? WHERE chat_id=?", (until, chat_id))
        await db.commit()
 
 
async def expired_alarms(ts: int) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM alarm WHERE enabled=1 AND until > 0 AND until <= ?", (ts,)
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
async def list_alarm_chats() -> List[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM alarm WHERE enabled=1") as cur:
            return [dict(r) for r in await cur.fetchall()]
 
 
# --- Время входа и ЛС-подписка ---
 
async def set_join(chat_id: int, user_id: int, ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO member_join (chat_id, user_id, joined_at) VALUES (?, ?, ?) "
            "ON CONFLICT(chat_id, user_id) DO UPDATE SET joined_at=excluded.joined_at",
            (chat_id, user_id, ts),
        )
        await db.commit()
 
 
async def get_join(chat_id: int, user_id: int) -> int:
    async with db_conn() as db:
        async with db.execute(
            "SELECT joined_at FROM member_join WHERE chat_id=? AND user_id=?", (chat_id, user_id)
        ) as cur:
            row = await cur.fetchone()
    return row[0] if row else 0
 
 
async def add_dm(user_id: int, ts: int) -> None:
    async with db_conn() as db:
        await db.execute(
            "INSERT INTO dm_users (user_id, ts) VALUES (?, ?) "
            "ON CONFLICT(user_id) DO UPDATE SET ts=excluded.ts",
            (user_id, ts),
        )
        await db.commit()
 
 
async def has_dm(user_id: int) -> bool:
    async with db_conn() as db:
        async with db.execute("SELECT 1 FROM dm_users WHERE user_id=?", (user_id,)) as cur:
            return await cur.fetchone() is not None
 
 
# --- Последние сообщения чата ---
 
async def add_msg(
    chat_id: int,
    user_id: int,
    name: str,
    text: str,
    ts: int,
    tg_msg_id: int = 0,
    media_type: str = "",
    media_file_id: str = "",
    reply_to_tg: int = 0,
    reply_to_name: str = "",
    reply_to_text: str = "",
    keep: int = 200,
) -> int:
    # Храним последние keep сообщений на чат.
    async with db_conn() as db:
        cur = await db.execute(
            "INSERT INTO messages "
            "(chat_id, user_id, name, text, created_at, tg_msg_id, media_type, media_file_id, reply_to_tg, reply_to_name, reply_to_text) "
            "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
            (chat_id, user_id, name, text, ts, tg_msg_id, media_type, media_file_id, reply_to_tg, reply_to_name, reply_to_text),
        )
        await db.execute(
            "DELETE FROM messages WHERE chat_id=? AND id NOT IN "
            "(SELECT id FROM messages WHERE chat_id=? ORDER BY id DESC LIMIT ?)",
            (chat_id, chat_id, keep),
        )
        await db.commit()
        return cur.lastrowid
 
 
async def get_msg(msg_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute("SELECT * FROM messages WHERE id=?", (msg_id,)) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
async def find_msg_by_tg(chat_id: int, tg_msg_id: int) -> Optional[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM messages WHERE chat_id=? AND tg_msg_id=? ORDER BY id DESC LIMIT 1",
            (chat_id, tg_msg_id),
        ) as cur:
            row = await cur.fetchone()
    return dict(row) if row else None
 
 
async def list_msgs(chat_id: int, limit: int = 100) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM messages WHERE chat_id=? ORDER BY id DESC LIMIT ?", (chat_id, limit)
        ) as cur:
            rows = [dict(r) for r in await cur.fetchall()]
    return rows[::-1]
 
 
async def list_msgs_after(chat_id: int, after_id: int, limit: int = 100) -> List[dict]:
    async with db_conn() as db:
        async with db.execute(
            "SELECT * FROM messages WHERE chat_id=? AND id > ? ORDER BY id ASC LIMIT ?",
            (chat_id, after_id, limit),
        ) as cur:
            return [dict(r) for r in await cur.fetchall()]