diff --git a/locale/ja_JP/LC_MESSAGES/BetterForward.mo b/locale/ja_JP/LC_MESSAGES/BetterForward.mo index 4959cea..3cd3c04 100644 Binary files a/locale/ja_JP/LC_MESSAGES/BetterForward.mo and b/locale/ja_JP/LC_MESSAGES/BetterForward.mo differ diff --git a/locale/ja_JP/LC_MESSAGES/BetterForward.po b/locale/ja_JP/LC_MESSAGES/BetterForward.po index 43c3378..dd4c5bb 100644 --- a/locale/ja_JP/LC_MESSAGES/BetterForward.po +++ b/locale/ja_JP/LC_MESSAGES/BetterForward.po @@ -884,6 +884,10 @@ msgstr "このスレッドを削除" msgid "User banned" msgstr "ユーザーを禁止された" +#: src/utils/helpers.py +msgid "You have been banned." +msgstr "あなたは禁止されています。" + #: src/handlers/command_handler.py:128 src/handlers/command_handler.py:162 #: src/handlers/command_handler.py:165 msgid "User unbanned" diff --git a/locale/zh_CN/LC_MESSAGES/BetterForward.mo b/locale/zh_CN/LC_MESSAGES/BetterForward.mo index caf47f9..0d3a066 100644 Binary files a/locale/zh_CN/LC_MESSAGES/BetterForward.mo and b/locale/zh_CN/LC_MESSAGES/BetterForward.mo differ diff --git a/locale/zh_CN/LC_MESSAGES/BetterForward.po b/locale/zh_CN/LC_MESSAGES/BetterForward.po index f41cc14..b50727b 100644 --- a/locale/zh_CN/LC_MESSAGES/BetterForward.po +++ b/locale/zh_CN/LC_MESSAGES/BetterForward.po @@ -872,6 +872,10 @@ msgstr "删除该会话" msgid "User banned" msgstr "用户已被封禁" +#: src/utils/helpers.py +msgid "You have been banned." +msgstr "你已被封禁。" + #: src/handlers/command_handler.py:128 src/handlers/command_handler.py:162 #: src/handlers/command_handler.py:165 msgid "User unbanned" diff --git a/src/handlers/callback_handler.py b/src/handlers/callback_handler.py index 319a1b2..0be82f2 100644 --- a/src/handlers/callback_handler.py +++ b/src/handlers/callback_handler.py @@ -6,6 +6,7 @@ from telebot import types from src.config import logger, _ +from src.utils.helpers import blocked_user_notice, is_user_blocked class CallbackHandler: @@ -72,6 +73,8 @@ def _handle_verify_button(self, call: types.CallbackQuery, data: dict): show_alert=True, ) return + if self._reject_banned_verification(call, user_id): + return if not self.captcha_manager.is_current_callback(user_id, "button", call.message.message_id): self.bot.answer_callback_query( @@ -99,6 +102,8 @@ def _handle_verify_emoji(self, call: types.CallbackQuery, data: dict): show_alert=True, ) return + if self._reject_banned_verification(call, user_id): + return if not self.captcha_manager.is_current_callback(user_id, "emoji", call.message.message_id): self.bot.answer_callback_query( call.id, _("This verification has expired. Send a message to request a new challenge."), @@ -119,6 +124,16 @@ def _handle_verify_emoji(self, call: types.CallbackQuery, data: dict): self.bot.send_message(user_id, _("Verification successful, you can now send messages")) self.bot.delete_message(call.message.chat.id, call.message.message_id) + def _reject_banned_verification(self, call: types.CallbackQuery, user_id: int) -> bool: + """Refuse captcha completion for banned users. Returns True when rejected.""" + with sqlite3.connect(self.db_path) as db: + if not is_user_blocked(db, user_id): + return False + self.captcha_manager.clear_pending(user_id) + self.bot.answer_callback_query( + call.id, blocked_user_notice(self.captcha_manager.cache), show_alert=True) + return True + def _handle_admin_callback(self, call: types.CallbackQuery, action: str, data: dict): """Handle admin callbacks.""" markup = types.InlineKeyboardMarkup() diff --git a/src/handlers/command_handler.py b/src/handlers/command_handler.py index 318c8fc..10006de 100644 --- a/src/handlers/command_handler.py +++ b/src/handlers/command_handler.py @@ -20,7 +20,14 @@ from src.config import logger, _ from src.utils.captcha import VERIFICATION_DAYS_SETTING, verification_days -from src.utils.helpers import build_user_info_pin_text, parse_start_payload, send_and_pin_user_info, to_html +from src.utils.helpers import ( + blocked_user_notice, + build_user_info_pin_text, + is_user_blocked, + parse_start_payload, + send_and_pin_user_info, + to_html, +) from src.utils.message_split import split_caption, split_html_text from src.utils.message_permissions import classify_message_permissions from src.utils.stats import get_summary, get_user_stats @@ -128,6 +135,10 @@ def help_command(self, message: Message, menu_callback): menu_callback(message) else: if getattr(message.chat, "type", None) == "private": + with sqlite3.connect(self.db_path) as db: + if is_user_blocked(db, message.from_user.id): + self.bot.send_message(message.chat.id, blocked_user_notice(self.cache)) + return self._save_start_tag(message) default_message = self._get_setting('default_message') if default_message is None: diff --git a/src/handlers/message_handler.py b/src/handlers/message_handler.py index b4b431c..5bfa84f 100644 --- a/src/handlers/message_handler.py +++ b/src/handlers/message_handler.py @@ -4,12 +4,19 @@ import pytz from telebot.apihelper import ApiTelegramException, create_forum_topic -from telebot.types import Message +from telebot.types import Message, ReplyParameters from src.config import logger, _ from src.utils.captcha import parse_captcha_config, pick_captcha_type from src.utils.db_helper import get_db_connection -from src.utils.helpers import build_user_info_pin_text, escape_markdown, send_and_pin_user_info, to_html +from src.utils.helpers import ( + blocked_user_notice, + build_user_info_pin_text, + escape_markdown, + is_user_blocked, + send_and_pin_user_info, + to_html, +) from src.utils.message_permissions import classify_message_permissions from src.utils.message_split import split_caption, split_html_text from src.utils.stats import record_incoming, record_outgoing @@ -77,6 +84,10 @@ def _handle_user_message(self, message: Message, msg_text: str, msg_caption: str _("Received message from {}, content: {}, type: {}").format( message.from_user.id, message.text, message.content_type)) + # Ban first: never start or complete captcha / TGuard for blocked users. + if self._reject_blocked_user(message, cursor, start_time): + return + # Captcha handler if not self._check_captcha(message, cursor, db): processing_time = (time.time() - start_time) * 1000 @@ -84,35 +95,6 @@ def _handle_user_message(self, message: Message, msg_text: str, msg_caption: str message.from_user.id, processing_time)) return - # Check if the user is blocked - is_blocked = cursor.execute("SELECT 1 FROM blocked_users WHERE user_id = ? LIMIT 1", - (message.from_user.id,)).fetchone() is not None - - if is_blocked: - # Update user info in blocked_users table - cursor.execute( - "UPDATE blocked_users SET username = ?, first_name = ?, last_name = ? WHERE user_id = ?", - (message.from_user.username, message.from_user.first_name, - message.from_user.last_name, message.from_user.id) - ) - - processing_time = (time.time() - start_time) * 1000 - logger.info(_("Message from blocked user {} rejected ({:.2f}ms)").format( - message.from_user.id, processing_time)) - - # Send auto-reply if enabled - if self.cache.get("setting_blocked_user_reply_enabled") == "enable": - reply_message = self.cache.get("setting_blocked_user_reply_message") - if reply_message: - try: - self.bot.send_message(message.chat.id, reply_message) - logger.info(_("Sent auto-reply to blocked user {}").format(message.from_user.id)) - except Exception as e: - logger.error(_("Failed to send auto-reply to blocked user {}: {}").format( - message.from_user.id, str(e))) - - return - denied_permissions = self._get_denied_permissions(message) if denied_permissions and self._handle_permission_restriction(message, denied_permissions): processing_time = (time.time() - start_time) * 1000 @@ -280,6 +262,29 @@ def _handle_permission_restriction(self, message: Message, denied_permissions: l return True + def _reject_blocked_user(self, message: Message, cursor, start_time: float) -> bool: + """Notify and stop when the sender is banned. Returns True if rejected.""" + if not is_user_blocked(cursor, message.from_user.id): + return False + + cursor.execute( + "UPDATE blocked_users SET username = ?, first_name = ?, last_name = ? WHERE user_id = ?", + (message.from_user.username, message.from_user.first_name, + message.from_user.last_name, message.from_user.id) + ) + + processing_time = (time.time() - start_time) * 1000 + logger.info(_("Message from blocked user {} rejected ({:.2f}ms)").format( + message.from_user.id, processing_time)) + + try: + self.bot.send_message(message.chat.id, blocked_user_notice(self.cache)) + logger.info(_("Sent auto-reply to blocked user {}").format(message.from_user.id)) + except Exception as e: + logger.error(_("Failed to send auto-reply to blocked user {}: {}").format( + message.from_user.id, str(e))) + return True + def _check_captcha(self, message: Message, cursor, db) -> bool: """Check and handle captcha verification.""" config = parse_captcha_config(self.cache.get("setting_captcha")) @@ -287,6 +292,9 @@ def _check_captcha(self, message: Message, cursor, db) -> bool: return True user_id = message.from_user.id + if is_user_blocked(cursor, user_id): + return False + pending = self.captcha_manager.get_pending(user_id) if pending: pending_type = pending.get("type") @@ -613,9 +621,73 @@ def _get_reply_id(self, message: Message, topic_id: int, cursor, in_group: bool) return int(result[0]) return None + @staticmethod + def _excerpt_quote(message: Message): + """Return a manual/partial quote excerpt, or None for a full-message reply. + + Telegram sets ``Message.quote`` (TextQuote) when a reply cites part of + another message. ``is_manual=False`` is an automatic preview added to + ordinary swipe-replies (typically long messages) and must keep the + existing full-reply behavior. + """ + quote = getattr(message, "quote", None) + if quote is None: + return None + if not getattr(quote, "text", None): + return None + if getattr(quote, "is_manual", None) is False: + return None + return quote + + @staticmethod + def _is_quote_error(exc: Exception) -> bool: + """Return True when Telegram rejected the quoted excerpt.""" + description = getattr(exc, "description", "") or "" + haystack = f"{exc} {description}".lower() + return "quote" in haystack + + @staticmethod + def _quote_blockquote(quote) -> str: + """Render a quoted excerpt as Telegram HTML blockquote.""" + return f"
{to_html(quote.text, getattr(quote, 'entities', None))}" + + @staticmethod + def _reply_send_kwargs(reply_id: int | None, quote=None) -> dict: + """Build send_* kwargs for a mapped reply, including a native quote excerpt.""" + if reply_id is None: + return {} + if quote is not None: + entities = getattr(quote, "entities", None) or None + return { + "reply_parameters": ReplyParameters( + message_id=reply_id, + quote=quote.text, + quote_entities=entities, + quote_position=getattr(quote, "position", None), + ) + } + return {"reply_to_message_id": reply_id} + + @staticmethod + def _embed_quote_excerpt(message: Message, msg_text: str | None, msg_caption: str | None, + quote) -> tuple[str | None, str | None, bool]: + """Prepend the quoted excerpt when a native reply quote cannot be used. + + Returns (msg_text, msg_caption, needs_standalone_prefix). + """ + block = MessageHandler._quote_blockquote(quote) + if message.content_type == "text" or msg_text: + joined = f"{block}\n{msg_text}" if msg_text else block + return joined, msg_caption, False + if message.content_type in ("photo", "video", "document", "audio", "voice", "animation"): + joined = f"{block}\n{msg_caption}" if msg_caption else block + return msg_text, joined, False + return msg_text, msg_caption, True + def _send_text_chunks(self, chat_id: int, thread_id, chunks: list[str], - reply_id: int | None, silent: bool) -> list[Message]: - """Send pre-split text chunks; only the first keeps reply_to_message_id.""" + reply_id: int | None, silent: bool, quote=None) -> list[Message]: + """Send pre-split text chunks; only the first keeps the reply/quote.""" + first_kwargs = self._reply_send_kwargs(reply_id, quote) sent_messages: list[Message] = [] for index, chunk in enumerate(chunks): try: @@ -624,9 +696,9 @@ def _send_text_chunks(self, chat_id: int, thread_id, chunks: list[str], chat_id=chat_id, text=chunk, message_thread_id=thread_id, - reply_to_message_id=reply_id if index == 0 else None, parse_mode='HTML', disable_notification=silent, + **(first_kwargs if index == 0 else {}), ) ) except ApiTelegramException as e: @@ -635,12 +707,13 @@ def _send_text_chunks(self, chat_id: int, thread_id, chunks: list[str], def _send_media_with_caption(self, send_media, chat_id: int, thread_id, msg_caption: str | None, reply_id: int | None, - silent: bool) -> list[Message]: + silent: bool, quote=None) -> list[Message]: """Send media plus caption overflow follow-ups, tracking partial progress.""" caption, extras = split_caption(msg_caption) + reply_kwargs = self._reply_send_kwargs(reply_id, quote) sent: list[Message] = [] try: - sent.append(send_media(caption=caption, reply_to_message_id=reply_id)) + sent.append(send_media(caption=caption, **reply_kwargs)) except ApiTelegramException as e: # Media itself failed: caller must fully retry (cannot resume with text-only). raise PartialSendError(e, sent, extras, needs_full_retry=True) from e @@ -662,83 +735,118 @@ def _send_media_with_caption(self, send_media, chat_id: int, thread_id, e, sent, extras[index:], needs_full_retry=True) from e return sent - def _send_message_by_type(self, message: Message, msg_text: str, msg_caption: str, - chat_id: int, thread_id: int = None, reply_id: int = None, - silent: bool = False) -> list[Message]: - """Send a message based on its type. - - Text messages longer than Telegram's limit are split into multiple sends. - Oversized captions are truncated onto the media with follow-up text chunks. - Only the first chunk keeps reply_to_message_id. - - Raises PartialSendError when some chunks succeed before an API failure so - callers can resume the remaining chunks after topic recovery. - """ + def _dispatch_send_by_type(self, message: Message, msg_text: str, msg_caption: str, + chat_id: int, thread_id: int | None, reply_id: int | None, + silent: bool, quote) -> list[Message]: + """Send one message (or its split chunks) with the given reply/quote.""" match message.content_type: case "photo": return self._send_media_with_caption( - lambda caption, reply_to_message_id: self.bot.send_photo( + lambda caption, **reply_kwargs: self.bot.send_photo( chat_id=chat_id, photo=message.photo[-1].file_id, caption=caption, message_thread_id=thread_id, - reply_to_message_id=reply_to_message_id, parse_mode='HTML', - disable_notification=silent), - chat_id, thread_id, msg_caption, reply_id, silent) + parse_mode='HTML', disable_notification=silent, **reply_kwargs), + chat_id, thread_id, msg_caption, reply_id, silent, quote) case "text": return self._send_text_chunks( - chat_id, thread_id, split_html_text(msg_text), reply_id, silent) + chat_id, thread_id, split_html_text(msg_text), reply_id, silent, quote) case "sticker": return [self.bot.send_sticker(chat_id=chat_id, sticker=message.sticker.file_id, message_thread_id=thread_id, - reply_to_message_id=reply_id, - disable_notification=silent)] + disable_notification=silent, + **self._reply_send_kwargs(reply_id, quote))] case "video": return self._send_media_with_caption( - lambda caption, reply_to_message_id: self.bot.send_video( + lambda caption, **reply_kwargs: self.bot.send_video( chat_id=chat_id, video=message.video.file_id, caption=caption, message_thread_id=thread_id, - reply_to_message_id=reply_to_message_id, parse_mode='HTML', - disable_notification=silent), - chat_id, thread_id, msg_caption, reply_id, silent) + parse_mode='HTML', disable_notification=silent, **reply_kwargs), + chat_id, thread_id, msg_caption, reply_id, silent, quote) case "document": return self._send_media_with_caption( - lambda caption, reply_to_message_id: self.bot.send_document( + lambda caption, **reply_kwargs: self.bot.send_document( chat_id=chat_id, document=message.document.file_id, caption=caption, message_thread_id=thread_id, - reply_to_message_id=reply_to_message_id, parse_mode='HTML', - disable_notification=silent), - chat_id, thread_id, msg_caption, reply_id, silent) + parse_mode='HTML', disable_notification=silent, **reply_kwargs), + chat_id, thread_id, msg_caption, reply_id, silent, quote) case "audio": return self._send_media_with_caption( - lambda caption, reply_to_message_id: self.bot.send_audio( + lambda caption, **reply_kwargs: self.bot.send_audio( chat_id=chat_id, audio=message.audio.file_id, caption=caption, message_thread_id=thread_id, - reply_to_message_id=reply_to_message_id, parse_mode='HTML', - disable_notification=silent), - chat_id, thread_id, msg_caption, reply_id, silent) + parse_mode='HTML', disable_notification=silent, **reply_kwargs), + chat_id, thread_id, msg_caption, reply_id, silent, quote) case "voice": return self._send_media_with_caption( - lambda caption, reply_to_message_id: self.bot.send_voice( + lambda caption, **reply_kwargs: self.bot.send_voice( chat_id=chat_id, voice=message.voice.file_id, caption=caption, message_thread_id=thread_id, - reply_to_message_id=reply_to_message_id, parse_mode='HTML', - disable_notification=silent), - chat_id, thread_id, msg_caption, reply_id, silent) + parse_mode='HTML', disable_notification=silent, **reply_kwargs), + chat_id, thread_id, msg_caption, reply_id, silent, quote) case "animation": return self._send_media_with_caption( - lambda caption, reply_to_message_id: self.bot.send_animation( + lambda caption, **reply_kwargs: self.bot.send_animation( chat_id=chat_id, animation=message.animation.file_id, caption=caption, message_thread_id=thread_id, - reply_to_message_id=reply_to_message_id, parse_mode='HTML', - disable_notification=silent), - chat_id, thread_id, msg_caption, reply_id, silent) + parse_mode='HTML', disable_notification=silent, **reply_kwargs), + chat_id, thread_id, msg_caption, reply_id, silent, quote) case "contact": return [self.bot.send_contact(chat_id=chat_id, phone_number=message.contact.phone_number, first_name=message.contact.first_name, last_name=message.contact.last_name, message_thread_id=thread_id, - reply_to_message_id=reply_id, - disable_notification=silent)] + disable_notification=silent, + **self._reply_send_kwargs(reply_id, quote))] case _: logger.error(_("Unsupported message type") + message.content_type) raise ValueError(_("Unsupported message type") + message.content_type) + + def _send_message_by_type(self, message: Message, msg_text: str, msg_caption: str, + chat_id: int, thread_id: int = None, reply_id: int = None, + silent: bool = False) -> list[Message]: + """Send a message based on its type. + + Text messages longer than Telegram's limit are split into multiple sends. + Oversized captions are truncated onto the media with follow-up text chunks. + Only the first chunk keeps the reply (and a partial quote excerpt when + the sender cited a portion of the source message). + + Raises PartialSendError when some chunks succeed before an API failure so + callers can resume the remaining chunks after topic recovery. + """ + quote = self._excerpt_quote(message) + prefix: list[Message] = [] + if quote is not None and reply_id is None: + msg_text, msg_caption, needs_prefix = self._embed_quote_excerpt( + message, msg_text, msg_caption, quote) + if needs_prefix: + prefix = self._send_text_chunks( + chat_id, thread_id, [self._quote_blockquote(quote)], None, silent) + quote = None + + try: + sent = self._dispatch_send_by_type( + message, msg_text, msg_caption, chat_id, thread_id, reply_id, silent, quote) + except (PartialSendError, ApiTelegramException) as e: + api_error = e.cause if isinstance(e, PartialSendError) else e + already_sent = e.sent if isinstance(e, PartialSendError) else [] + if ( + quote is None + or reply_id is None + or already_sent + or not self._is_quote_error(api_error) + ): + raise + logger.warning( + _("Quoted excerpt could not be attached, embedding it instead: {}").format( + api_error)) + msg_text, msg_caption, needs_prefix = self._embed_quote_excerpt( + message, msg_text, msg_caption, quote) + if needs_prefix: + prefix = self._send_text_chunks( + chat_id, thread_id, [self._quote_blockquote(quote)], reply_id, silent) + reply_id = None + sent = self._dispatch_send_by_type( + message, msg_text, msg_caption, chat_id, thread_id, reply_id, silent, None) + return prefix + sent diff --git a/src/utils/helpers.py b/src/utils/helpers.py index 9af8d3b..3b584fd 100644 --- a/src/utils/helpers.py +++ b/src/utils/helpers.py @@ -11,6 +11,25 @@ START_PAYLOAD_RE = re.compile(r'^[A-Za-z0-9_-]{1,64}$') +def is_user_blocked(cursor, user_id: int) -> bool: + """Return True when the user is in blocked_users.""" + return cursor.execute( + "SELECT 1 FROM blocked_users WHERE user_id = ? LIMIT 1", (user_id,) + ).fetchone() is not None + + +def blocked_user_notice(cache) -> str: + """Message shown when a banned user contacts the bot. + + A configured blocked-user auto-reply overrides the default notice. + """ + if cache.get("setting_blocked_user_reply_enabled") == "enable": + reply = cache.get("setting_blocked_user_reply_message") + if reply: + return reply + return _("You have been banned.") + + def to_html(text: str | None, entities) -> str | None: """Render message text/caption with its entities as Telegram HTML.""" if text is None: diff --git a/tests/helpers.py b/tests/helpers.py index 5448454..c136e8b 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -21,6 +21,15 @@ def make_user(user_id: int = 101, first_name: str = "Alice", username: str = "al ) +def make_quote(text: str, position: int = 0, is_manual: bool = True, entities=None): + return SimpleNamespace( + text=text, + position=position, + is_manual=is_manual, + entities=entities, + ) + + def make_message( *, message_id: int = 1, @@ -34,6 +43,7 @@ def make_message( caption=None, caption_entities=None, reply_to_message=None, + quote=None, **extra, ): user = make_user(user_id=user_id) @@ -48,6 +58,7 @@ def make_message( caption=caption, caption_entities=caption_entities, reply_to_message=reply_to_message, + quote=quote, photo=extra.get("photo"), sticker=extra.get("sticker"), video=extra.get("video"), diff --git a/tests/test_captcha.py b/tests/test_captcha.py index 5a3acf4..d0b4c4d 100644 --- a/tests/test_captcha.py +++ b/tests/test_captcha.py @@ -253,3 +253,89 @@ def test_random_selection_excludes_unconfigured_methods(env, monkeypatch): ("button", ["button"]), ("tguard", ["tguard"])]) def test_legacy_captcha_settings_remain_supported(legacy, methods): assert parse_captcha_config(legacy)["methods"] == methods + + +def _sent_texts(bot): + texts = [] + for call in bot.send_message.call_args_list: + if len(call.args) > 1: + texts.append(call.args[1]) + elif "text" in call.kwargs: + texts.append(call.kwargs["text"]) + return texts + + +def test_banned_user_does_not_start_verification(env, monkeypatch): + env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,)) + env.db.commit() + env.cache.set("setting_captcha", json.dumps({"methods": ["tguard"]})) + env.cache.set("setting_tguard_api_url", "https://example.com") + env.cache.set("setting_tguard_api_key", "test") + client = MagicMock() + factory = MagicMock() + factory.return_value.__enter__.return_value = client + monkeypatch.setattr("src.utils.captcha.httpx.Client", factory) + + generate = MagicMock(wraps=env.captcha.generate_captcha) + monkeypatch.setattr(env.captcha, "generate_captcha", generate) + + env.handler.handle_message(make_message(chat_id=USER_ID, user_id=USER_ID, text="hello")) + + client.post.assert_not_called() + generate.assert_not_called() + assert env.captcha.get_pending(USER_ID) is None + assert "You have been banned." in _sent_texts(env.bot) + assert not env.captcha.is_user_verified(USER_ID, env.db) + + +def test_banned_user_receives_custom_reply_instead_of_captcha(env): + env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,)) + env.db.commit() + env.cache.set("setting_captcha", json.dumps({"methods": ["math"]})) + env.cache.set("setting_blocked_user_reply_enabled", "enable") + env.cache.set("setting_blocked_user_reply_message", "Stay out") + + env.handler.handle_message(make_message(chat_id=USER_ID, user_id=USER_ID, text="hello")) + + assert env.captcha.get_pending(USER_ID) is None + assert "Stay out" in _sent_texts(env.bot) + assert not any("Captcha is enabled" in str(text) for text in _sent_texts(env.bot)) + + +def test_banned_user_cannot_complete_callback_verification(env): + env.captcha.generate_captcha(USER_ID, "button") + env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,)) + env.db.commit() + env.bot.reset_mock() + + click(env, "verify_button") + + assert not env.captcha.is_user_verified(USER_ID, env.db) + assert env.captcha.get_pending(USER_ID) is None + assert env.bot.answer_callback_query.call_args.kwargs["show_alert"] + assert env.bot.answer_callback_query.call_args.args[1] == "You have been banned." + env.bot.send_message.assert_not_called() + + +def test_banned_user_check_captcha_does_not_generate(env, monkeypatch): + env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,)) + env.db.commit() + generate = MagicMock() + monkeypatch.setattr(env.captcha, "generate_captcha", generate) + assert check_message(env) is False + generate.assert_not_called() + + +def test_banned_user_start_gets_notice_not_welcome(env): + env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,)) + env.db.commit() + handler = CommandHandler(env.bot, GROUP_ID, env.db_path, env.cache, None, env.captcha) + handler.help_command(make_message(chat_id=USER_ID, user_id=USER_ID, text="/start"), MagicMock()) + texts = _sent_texts(env.bot) + assert texts == ["You have been banned."] + + +def test_non_banned_user_still_starts_verification(env): + assert check_message(env) is False + assert env.captcha.get_pending(USER_ID)["type"] == "math" + assert any("Captcha is enabled" in str(text) for text in _sent_texts(env.bot)) diff --git a/tests/test_message_handler.py b/tests/test_message_handler.py index e588406..7e50641 100644 --- a/tests/test_message_handler.py +++ b/tests/test_message_handler.py @@ -13,6 +13,7 @@ make_api_error, make_cache, make_message, + make_quote, ) @@ -313,3 +314,241 @@ def test_denied_permission_blocks_forward(handler_env): with sqlite3.connect(db_path) as conn: count = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0] assert count == 0 + + +def test_excerpt_quote_detects_manual_partial_quote(): + message = make_message(quote=make_quote("only this part", position=4, is_manual=True)) + quote = MessageHandler._excerpt_quote(message) + assert quote is not None + assert quote.text == "only this part" + + auto_quote = make_message(quote=make_quote("preview", is_manual=False)) + assert MessageHandler._excerpt_quote(auto_quote) is None + assert MessageHandler._excerpt_quote(make_message()) is None + assert MessageHandler._excerpt_quote(make_message(quote=make_quote(""))) is None + + +def test_full_reply_from_user_maps_to_source_message(handler_env): + handler, bot, cache, db_path = handler_env + user_id = 101 + thread_id = 555 + admin_msg_id = 11 + user_copy_id = 22 + _seed_topic(db_path, user_id, thread_id) + cache.set(f"chat_{user_id}_threadid", thread_id) + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO messages (received_id, forwarded_id, topic_id, in_group) VALUES (?, ?, ?, ?)", + (admin_msg_id, user_copy_id, thread_id, True), + ) + conn.commit() + + forwarded = MagicMock(spec=Message) + forwarded.message_id = 9002 + bot.send_message.return_value = forwarded + + source = make_message(message_id=user_copy_id, chat_id=user_id, user_id=0, text="whole source") + message = make_message( + message_id=80, + chat_id=user_id, + user_id=user_id, + text="full reply", + reply_to_message=source, + ) + handler.handle_message(message) + + kwargs = bot.send_message.call_args.kwargs + assert kwargs["chat_id"] == GROUP_ID + assert kwargs["reply_to_message_id"] == admin_msg_id + assert "reply_parameters" not in kwargs + assert kwargs["text"] == "full reply" + + +def test_manual_quote_from_user_forwards_excerpt(handler_env): + handler, bot, cache, db_path = handler_env + user_id = 101 + thread_id = 555 + admin_msg_id = 11 + user_copy_id = 22 + _seed_topic(db_path, user_id, thread_id) + cache.set(f"chat_{user_id}_threadid", thread_id) + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO messages (received_id, forwarded_id, topic_id, in_group) VALUES (?, ?, ?, ?)", + (admin_msg_id, user_copy_id, thread_id, True), + ) + conn.commit() + + forwarded = MagicMock(spec=Message) + forwarded.message_id = 9003 + bot.send_message.return_value = forwarded + + source = make_message( + message_id=user_copy_id, + chat_id=user_id, + user_id=0, + text="Hello world, this is a long message", + ) + message = make_message( + message_id=81, + chat_id=user_id, + user_id=user_id, + text="got it", + reply_to_message=source, + quote=make_quote("this is a long", position=13, is_manual=True), + ) + handler.handle_message(message) + + kwargs = bot.send_message.call_args.kwargs + assert kwargs["chat_id"] == GROUP_ID + assert "reply_to_message_id" not in kwargs + reply = kwargs["reply_parameters"] + assert reply.message_id == admin_msg_id + assert reply.quote == "this is a long" + assert reply.quote_position == 13 + assert kwargs["text"] == "got it" + + +def test_auto_quote_keeps_full_reply_behavior(handler_env): + handler, bot, cache, db_path = handler_env + user_id = 101 + thread_id = 555 + admin_msg_id = 11 + user_copy_id = 22 + _seed_topic(db_path, user_id, thread_id) + cache.set(f"chat_{user_id}_threadid", thread_id) + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO messages (received_id, forwarded_id, topic_id, in_group) VALUES (?, ?, ?, ?)", + (admin_msg_id, user_copy_id, thread_id, True), + ) + conn.commit() + + forwarded = MagicMock(spec=Message) + forwarded.message_id = 9004 + bot.send_message.return_value = forwarded + + source = make_message(message_id=user_copy_id, chat_id=user_id, user_id=0, text="long original") + message = make_message( + message_id=82, + chat_id=user_id, + user_id=user_id, + text="swipe reply", + reply_to_message=source, + quote=make_quote("long original", position=0, is_manual=False), + ) + handler.handle_message(message) + + kwargs = bot.send_message.call_args.kwargs + assert kwargs["reply_to_message_id"] == admin_msg_id + assert "reply_parameters" not in kwargs + assert kwargs["text"] == "swipe reply" + + +def test_group_manual_quote_forwards_excerpt_to_user(handler_env): + handler, bot, cache, db_path = handler_env + user_id = 303 + thread_id = 777 + user_msg_id = 11 + group_copy_id = 22 + _seed_topic(db_path, user_id, thread_id) + + forwarded = MagicMock(spec=Message) + forwarded.message_id = 5002 + bot.send_message.return_value = forwarded + + source = make_message( + message_id=group_copy_id, + chat_id=GROUP_ID, + chat_type="supergroup", + user_id=0, + text="user said several things here", + message_thread_id=thread_id, + ) + message = make_message( + message_id=67, + chat_id=GROUP_ID, + chat_type="supergroup", + user_id=999, + text="about this part", + message_thread_id=thread_id, + reply_to_message=source, + quote=make_quote("several things", position=10, is_manual=True), + ) + handler.handle_message(message) + + kwargs = bot.send_message.call_args.kwargs + assert kwargs["chat_id"] == user_id + reply = kwargs["reply_parameters"] + assert reply.message_id == user_msg_id + assert reply.quote == "several things" + assert reply.quote_position == 10 + assert kwargs["text"] == "about this part" + + +def test_unmapped_quote_embeds_excerpt_as_blockquote(handler_env): + handler, bot, cache, db_path = handler_env + user_id = 101 + thread_id = 555 + _seed_topic(db_path, user_id, thread_id) + cache.set(f"chat_{user_id}_threadid", thread_id) + + forwarded = MagicMock(spec=Message) + forwarded.message_id = 9005 + bot.send_message.return_value = forwarded + + source = make_message(message_id=404, chat_id=user_id, user_id=0, text="not in mapping") + message = make_message( + message_id=83, + chat_id=user_id, + user_id=user_id, + text="still reply", + reply_to_message=source, + quote=make_quote("not in", position=0, is_manual=True), + ) + handler.handle_message(message) + + kwargs = bot.send_message.call_args.kwargs + assert "reply_to_message_id" not in kwargs + assert "reply_parameters" not in kwargs + assert kwargs["text"] == "
not in\nstill reply" + + +def test_invalid_quote_falls_back_to_embed_and_full_reply(handler_env): + handler, bot, cache, db_path = handler_env + user_id = 101 + thread_id = 555 + admin_msg_id = 11 + user_copy_id = 22 + _seed_topic(db_path, user_id, thread_id) + cache.set(f"chat_{user_id}_threadid", thread_id) + with sqlite3.connect(db_path) as conn: + conn.execute( + "INSERT INTO messages (received_id, forwarded_id, topic_id, in_group) VALUES (?, ?, ?, ?)", + (admin_msg_id, user_copy_id, thread_id, True), + ) + conn.commit() + + forwarded = MagicMock(spec=Message) + forwarded.message_id = 9006 + bot.send_message.side_effect = [ + make_api_error("Bad Request: QUOTE_TEXT_INVALID"), + forwarded, + ] + + source = make_message(message_id=user_copy_id, chat_id=user_id, user_id=0, text="original") + message = make_message( + message_id=84, + chat_id=user_id, + user_id=user_id, + text="comment", + reply_to_message=source, + quote=make_quote("missing slice", position=2, is_manual=True), + ) + handler.handle_message(message) + + assert bot.send_message.call_count == 2 + retry = bot.send_message.call_args.kwargs + assert retry["reply_to_message_id"] == admin_msg_id + assert "reply_parameters" not in retry + assert retry["text"] == "
missing slice\ncomment"