|
| 1 | +""" |
| 2 | +Duplicate message spam detection handler. |
| 3 | +
|
| 4 | +This module detects users who spam by repeatedly posting the same or |
| 5 | +very similar messages within a short time window. When the threshold |
| 6 | +is reached, duplicate messages are deleted and the user is restricted. |
| 7 | +
|
| 8 | +Uses an in-memory rolling window per (group_id, user_id) to track |
| 9 | +recent messages. No database state is needed — restrictions applied |
| 10 | +here are NOT reversible via the DM unrestriction flow (no UserWarning |
| 11 | +record is created). |
| 12 | +""" |
| 13 | + |
| 14 | +import logging |
| 15 | +import re |
| 16 | +import unicodedata |
| 17 | +from collections import deque |
| 18 | +from dataclasses import dataclass |
| 19 | +from datetime import UTC, datetime |
| 20 | +from difflib import SequenceMatcher |
| 21 | + |
| 22 | +from telegram import Update |
| 23 | +from telegram.ext import ApplicationHandlerStop, ContextTypes |
| 24 | + |
| 25 | +from bot.constants import ( |
| 26 | + DUPLICATE_SPAM_RESTRICTION, |
| 27 | + DUPLICATE_SPAM_RESTRICTION_NO_RESTRICT, |
| 28 | + RESTRICTED_PERMISSIONS, |
| 29 | +) |
| 30 | +from bot.group_config import GroupConfig, get_group_config_for_update |
| 31 | +from bot.services.telegram_utils import get_user_mention |
| 32 | + |
| 33 | +logger = logging.getLogger(__name__) |
| 34 | + |
| 35 | +RECENT_MESSAGES_KEY = "duplicate_spam_recent" |
| 36 | + |
| 37 | + |
| 38 | +@dataclass |
| 39 | +class RecentMessage: |
| 40 | + """A recent message entry for duplicate detection.""" |
| 41 | + |
| 42 | + timestamp: datetime |
| 43 | + normalized_text: str |
| 44 | + message_id: int |
| 45 | + |
| 46 | + |
| 47 | +def normalize_text(text: str) -> str: |
| 48 | + """ |
| 49 | + Normalize text for duplicate comparison. |
| 50 | +
|
| 51 | + Lowercases, strips whitespace, collapses runs of whitespace, |
| 52 | + removes emoji/symbol unicode categories, and strips punctuation. |
| 53 | + """ |
| 54 | + text = text.lower() |
| 55 | + text = unicodedata.normalize("NFKC", text) |
| 56 | + text = re.sub(r"\s+", " ", text).strip() |
| 57 | + text = re.sub(r"[^\w\s]", "", text, flags=re.UNICODE) |
| 58 | + return text |
| 59 | + |
| 60 | + |
| 61 | +def is_similar(a: str, b: str, threshold: float = 0.95) -> bool: |
| 62 | + """Check if two normalized texts are similar enough to be considered duplicates.""" |
| 63 | + if a == b: |
| 64 | + return True |
| 65 | + return SequenceMatcher(None, a, b).ratio() >= threshold |
| 66 | + |
| 67 | + |
| 68 | +def _get_recent_messages( |
| 69 | + context: ContextTypes.DEFAULT_TYPE, group_id: int, user_id: int |
| 70 | +) -> deque[RecentMessage]: |
| 71 | + """Get or create the recent messages deque for a (group, user) pair.""" |
| 72 | + store: dict[tuple[int, int], deque[RecentMessage]] = context.bot_data.setdefault( |
| 73 | + RECENT_MESSAGES_KEY, {} |
| 74 | + ) |
| 75 | + key = (group_id, user_id) |
| 76 | + if key not in store: |
| 77 | + store[key] = deque() |
| 78 | + return store[key] |
| 79 | + |
| 80 | + |
| 81 | +def _prune_old_messages( |
| 82 | + dq: deque[RecentMessage], window_seconds: int, now: datetime |
| 83 | +) -> None: |
| 84 | + """Remove messages older than the window from the deque.""" |
| 85 | + while dq and (now - dq[0].timestamp).total_seconds() > window_seconds: |
| 86 | + dq.popleft() |
| 87 | + |
| 88 | + |
| 89 | +def count_similar_in_window( |
| 90 | + dq: deque[RecentMessage], normalized: str, threshold: float = 0.95 |
| 91 | +) -> int: |
| 92 | + """Count how many messages in the deque are similar to the given text.""" |
| 93 | + return sum(1 for m in dq if is_similar(normalized, m.normalized_text, threshold)) |
| 94 | + |
| 95 | + |
| 96 | +async def handle_duplicate_spam( |
| 97 | + update: Update, context: ContextTypes.DEFAULT_TYPE |
| 98 | +) -> None: |
| 99 | + """ |
| 100 | + Detect and handle duplicate message spam. |
| 101 | +
|
| 102 | + Tracks recent messages per (group_id, user_id) in memory. When the |
| 103 | + count of similar messages within the time window reaches the threshold, |
| 104 | + deletes the message and restricts the user. |
| 105 | + """ |
| 106 | + if not update.message or not update.message.from_user: |
| 107 | + return |
| 108 | + |
| 109 | + group_config = get_group_config_for_update(update) |
| 110 | + if group_config is None: |
| 111 | + return |
| 112 | + |
| 113 | + if not group_config.duplicate_spam_enabled: |
| 114 | + return |
| 115 | + |
| 116 | + user = update.message.from_user |
| 117 | + if user.is_bot: |
| 118 | + return |
| 119 | + |
| 120 | + admin_ids = context.bot_data.get("group_admin_ids", {}).get(group_config.group_id, []) |
| 121 | + if user.id in admin_ids: |
| 122 | + return |
| 123 | + |
| 124 | + text = update.message.text or update.message.caption |
| 125 | + if not text: |
| 126 | + return |
| 127 | + |
| 128 | + normalized = normalize_text(text) |
| 129 | + if len(normalized) < group_config.duplicate_spam_min_length: |
| 130 | + return |
| 131 | + |
| 132 | + now = datetime.now(UTC) |
| 133 | + dq = _get_recent_messages(context, group_config.group_id, user.id) |
| 134 | + _prune_old_messages(dq, group_config.duplicate_spam_window_seconds, now) |
| 135 | + |
| 136 | + similar_count = count_similar_in_window(dq, normalized, group_config.duplicate_spam_similarity) |
| 137 | + |
| 138 | + dq.append( |
| 139 | + RecentMessage( |
| 140 | + timestamp=now, |
| 141 | + normalized_text=normalized, |
| 142 | + message_id=update.message.message_id, |
| 143 | + ) |
| 144 | + ) |
| 145 | + |
| 146 | + if similar_count < group_config.duplicate_spam_threshold - 1: |
| 147 | + return |
| 148 | + |
| 149 | + total_count = similar_count + 1 |
| 150 | + user_mention = get_user_mention(user) |
| 151 | + |
| 152 | + logger.info( |
| 153 | + f"Duplicate spam detected: user_id={user.id}, " |
| 154 | + f"group_id={group_config.group_id}, count={total_count}" |
| 155 | + ) |
| 156 | + |
| 157 | + try: |
| 158 | + await update.message.delete() |
| 159 | + logger.info(f"Deleted duplicate spam from user_id={user.id}") |
| 160 | + except Exception: |
| 161 | + logger.error( |
| 162 | + f"Failed to delete duplicate spam: user_id={user.id}", |
| 163 | + exc_info=True, |
| 164 | + ) |
| 165 | + |
| 166 | + await _enforce_restriction(context, group_config, user, user_mention, total_count) |
| 167 | + |
| 168 | + raise ApplicationHandlerStop |
| 169 | + |
| 170 | + |
| 171 | +async def _enforce_restriction( |
| 172 | + context: ContextTypes.DEFAULT_TYPE, |
| 173 | + group_config: GroupConfig, |
| 174 | + user: object, |
| 175 | + user_mention: str, |
| 176 | + count: int, |
| 177 | +) -> None: |
| 178 | + """Restrict the user and send notification to warning topic.""" |
| 179 | + restricted = False |
| 180 | + try: |
| 181 | + await context.bot.restrict_chat_member( |
| 182 | + chat_id=group_config.group_id, |
| 183 | + user_id=user.id, |
| 184 | + permissions=RESTRICTED_PERMISSIONS, |
| 185 | + ) |
| 186 | + restricted = True |
| 187 | + logger.info(f"Restricted user_id={user.id} for duplicate spam") |
| 188 | + except Exception: |
| 189 | + logger.error( |
| 190 | + f"Failed to restrict user for duplicate spam: user_id={user.id}", |
| 191 | + exc_info=True, |
| 192 | + ) |
| 193 | + |
| 194 | + try: |
| 195 | + template = ( |
| 196 | + DUPLICATE_SPAM_RESTRICTION if restricted |
| 197 | + else DUPLICATE_SPAM_RESTRICTION_NO_RESTRICT |
| 198 | + ) |
| 199 | + notification_text = template.format( |
| 200 | + user_mention=user_mention, |
| 201 | + count=count, |
| 202 | + rules_link=group_config.rules_link, |
| 203 | + ) |
| 204 | + await context.bot.send_message( |
| 205 | + chat_id=group_config.group_id, |
| 206 | + message_thread_id=group_config.warning_topic_id, |
| 207 | + text=notification_text, |
| 208 | + parse_mode="Markdown", |
| 209 | + ) |
| 210 | + logger.info(f"Sent duplicate spam notification for user_id={user.id}") |
| 211 | + except Exception: |
| 212 | + logger.error( |
| 213 | + f"Failed to send duplicate spam notification: user_id={user.id}", |
| 214 | + exc_info=True, |
| 215 | + ) |
0 commit comments