From 207023c2172b7b31bde287b40c9cf16ca4ae80b6 Mon Sep 17 00:00:00 2001 From: pplulee Date: Thu, 5 Nov 2026 11:37:00 +0900 Subject: [PATCH 1/2] =?UTF-8?q?fix:=20=E8=BD=AC=E5=8F=91=E6=97=B6=E4=BF=9D?= =?UTF-8?q?=E7=95=99=20Telegram=20=E9=83=A8=E5=88=86=E5=BC=95=E7=94=A8?= =?UTF-8?q?=E6=91=98=E5=BD=95=20(#88)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Manual partial quotes now forward via ReplyParameters so the cited text is shown instead of a full-message reply. Ordinary swipe-replies keep the existing mapped reply_to_message_id behavior. Co-authored-by: Cursor Agent --- src/handlers/message_handler.py | 194 +++++++++++++++++++------- tests/helpers.py | 11 ++ tests/test_message_handler.py | 239 ++++++++++++++++++++++++++++++++ 3 files changed, 397 insertions(+), 47 deletions(-) diff --git a/src/handlers/message_handler.py b/src/handlers/message_handler.py index b4b431c..10803c3 100644 --- a/src/handlers/message_handler.py +++ b/src/handlers/message_handler.py @@ -4,7 +4,7 @@ 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 @@ -613,9 +613,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 +688,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 +699,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 +727,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/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_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" From 97027c3047a98790fb965d50ff797cfafb751692 Mon Sep 17 00:00:00 2001 From: pplulee Date: Thu, 5 Nov 2026 22:10:39 +0900 Subject: [PATCH 2/2] =?UTF-8?q?fix:=20=E5=B0=81=E7=A6=81=E7=94=A8=E6=88=B7?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E8=A7=A6=E5=8F=91=E9=AA=8C=E8=AF=81=20(#90)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Banned users were hitting captcha before the blocked_users check, so /ban still started TGuard/hCaptcha and accepted later messages without forwarding them. Check the ban first, reply with a banned notice, and refuse verification callbacks. Co-authored-by: Cursor Agent --- locale/ja_JP/LC_MESSAGES/BetterForward.mo | Bin 36999 -> 37077 bytes locale/ja_JP/LC_MESSAGES/BetterForward.po | 4 + locale/zh_CN/LC_MESSAGES/BetterForward.mo | Bin 30957 -> 31014 bytes locale/zh_CN/LC_MESSAGES/BetterForward.po | 4 + src/handlers/callback_handler.py | 15 ++++ src/handlers/command_handler.py | 13 +++- src/handlers/message_handler.py | 68 +++++++++-------- src/utils/helpers.py | 19 +++++ tests/test_captcha.py | 86 ++++++++++++++++++++++ 9 files changed, 178 insertions(+), 31 deletions(-) diff --git a/locale/ja_JP/LC_MESSAGES/BetterForward.mo b/locale/ja_JP/LC_MESSAGES/BetterForward.mo index 4959cea65cb4676d4744b43aa630ad77e6f5930d..3cd3c044b892a4c337e4a296fa4c82ea68d95cec 100644 GIT binary patch delta 6313 zcmYM%30PKD9>?)xAPV9FZh#9fi-`y#?uZJE3n7N$uA?RhuBa_4ZgqXtG!->8cg=JP zCL^auL^IRJF&neYGIMgA8A{*ErY!BrCCZxl{y6t}rpNr8bMC!o`Tzg-f~)sEba~%H zPIajN7Q=tuI>xld*kJXHNeKJD4QM9Pmnp6Tu_gUnY=|?k1r}o?+<>}&4{FL+U5{V{ z{dbW29aBxC9s_rgKjt_7(t|C+jhTnhn1tIf2+v{@{KVCVq4e)yGpxt#{@5CIe-wsb z0%{}uP|s)AUU!U{K*PhpG}Hvop(fl@dxJ4=U@ZOP7=vG68v3^~=3yLwZE+TI$*e^k zg0=12U>{)$LzpVtVBip7COq^eHz+nU5*ijA*ft-MV)vsYT`Mllq^Txe;>7w zU!;v#Bg~{9h1%c@Y>dm1!ZH?1Bna8ft<} zOvKel&`cF-flH_btFa6IjNP##$K^~W58I&^6`69>+jGjHq0n4GO?U@YR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@(IF23Zcn%e5rCD~b8(>N5 zshEzvunc~Pns6s-L4{ZqFJUWufSR~ouHAw-jMgzqrO=EAS 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 10803c3..5bfa84f 100644 --- a/src/handlers/message_handler.py +++ b/src/handlers/message_handler.py @@ -9,7 +9,14 @@ 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") 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/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))