Бот для капчи в чатах
Roman Sergienko
11 hours ago 2dc33598d80358dd4c8b618cb0d42aa2054f2005
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
import re
from collections import defaultdict, deque
from typing import Dict, Tuple
 
from aiogram import types
 
import cfg
import db
from cfg import bot, dp, logger
from mod import apply_mute
from perms import member_status
from util import now_ts
 
# Ссылки/инвайты для фильтра.
LINK_RE = re.compile(r"(https?://\S+|t\.me/\S+|tg://\S+)", re.IGNORECASE)
 
# Антифлуд: (chat_id, user_id) -> метки времени сообщений.
FLOOD: Dict[Tuple[int, int], deque] = defaultdict(deque)
# Копипаста при тревоге: (chat_id, текст) -> deque[(время, user_id)].
DUP: Dict[Tuple[int, str], deque] = defaultdict(deque)
# Ручной «медленный режим»: (chat_id, user_id) -> время последнего сообщения.
SLOW: Dict[Tuple[int, int], int] = {}
# Кэш статуса администратора, чтобы не дёргать Telegram на каждом сообщении.
_STAFF: Dict[Tuple[int, int], Tuple[int, bool]] = {}
_STAFF_TTL = 300
 
 
async def _is_staff(chat_id: int, user_id: int) -> bool:
    # Владельца бота и админов не трогаем никогда.
    if user_id == cfg.OWNER_ID:
        return True
    ts = now_ts()
    cached = _STAFF.get((chat_id, user_id))
    if cached and cached[0] > ts:
        return cached[1]
    status = await member_status(chat_id, user_id)
    if status is None:
        # Не удалось проверить — не наказываем (безопасный режим), не кэшируем.
        return True
    result = status in ("administrator", "creator")
    _STAFF[(chat_id, user_id)] = (ts + _STAFF_TTL, result)
    return result
 
 
async def _del(chat_id: int, msg_id: int) -> None:
    try:
        await bot.delete_message(chat_id, msg_id)
    except Exception:
        pass
 
 
@dp.message.middleware()
async def flood_mw(handler, event: types.Message, data: dict):
    # Антифлуд, фильтр ссылок, копипаста и медленный режим — до обработчиков.
    try:
        await _check(event)
    except Exception as e:
        logger.warning("flood check: %s", e)
    return await handler(event, data)
 
 
async def _check(message: types.Message) -> None:
    chat = message.chat
    if chat.type not in ("group", "supergroup"):
        return
    u = message.from_user
    if u is None or u.is_bot:
        return
 
    chat_id = chat.id
    user_id = u.id
    cfg = await db.get_chat_cfg(chat_id)
    alarm = await db.get_alarm(chat_id)
    on = bool(alarm["enabled"])
    ts = now_ts()
 
    text = message.text or message.caption or ""
 
    # Фильтр ссылок (опционально, по умолчанию выключен).
    if cfg["no_links"] and text and LINK_RE.search(text):
        if not await _is_staff(chat_id, user_id):
            await _del(chat_id, message.message_id)
            return
 
    # Медленный режим во время тревоги (Bot API не умеет slow mode — эмулируем).
    if on and cfg["slow_mode"] > 0:
        last = SLOW.get((chat_id, user_id), 0)
        if last and ts - last < cfg["slow_mode"] and not await _is_staff(chat_id, user_id):
            await _del(chat_id, message.message_id)
        SLOW[(chat_id, user_id)] = ts
 
    # Антифлуд: по параметру чата либо всегда в тревоге.
    if not (cfg["flood_enabled"] or on):
        return
 
    q = FLOOD[(chat_id, user_id)]
    q.append(ts)
    window = max(1, cfg["flood_window"])
    while q and q[0] < ts - window:
        q.popleft()
 
    if len(q) > cfg["flood_count"]:
        q.clear()
        if await _is_staff(chat_id, user_id):
            return
        mute = cfg["flood_mute"]
        if on:
            joined = await db.get_join(chat_id, user_id)
            is_new = joined and (ts - joined) < cfg["new_member_days"] * 86400
            if is_new:
                mute = cfg["flood_alarm_mute"]
        logger.info(
            "antiflood: chat=%s user=%s messages=%s/%ss mute=%ss alarm=%s",
            chat_id, user_id, cfg["flood_count"], cfg["flood_window"], mute, on,
        )
        await apply_mute(chat_id, user_id, u.full_name, mute, 0, "Превышен лимит сообщений")
        return
 
    # Копипаста во время тревоги: одинаковый текст от 3+ разных аккаунтов.
    if on and text and len(text.strip()) >= 8:
        key = (chat_id, text.strip().lower())
        d = DUP[key]
        d.append((ts, user_id))
        while d and d[0][0] < ts - 60:
            d.popleft()
        users = {uid for _, uid in d}
        if len(users) >= 3:
            d.clear()
            logger.info("antiflood: копипаста chat=%s users=%s", chat_id, users)
            for uid in users:
                if not await _is_staff(chat_id, uid):
                    await apply_mute(chat_id, uid, str(uid), cfg["flood_alarm_mute"], 0, "Копипаста при тревоге")