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, ts + 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), ts + cfg["flood_alarm_mute"], 0, "Копипаста при тревоге")