From f5efdd665b657ab645c029b1d08e1cb8f710a30d Mon Sep 17 00:00:00 2001 From: ChanningHe Date: Fri, 18 Jul 2025 21:59:04 +0900 Subject: [PATCH] =?UTF-8?q?fix:=20=E6=B8=85=E7=90=86Telegram=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E4=B8=AD=E7=9A=84@bot=E9=83=A8=E5=88=86=E4=BB=A5?= =?UTF-8?q?=E7=A1=AE=E4=BF=9D=E4=B8=80=E8=87=B4=E6=80=A7=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/modules/telegram/__init__.py | 35 ++++++++++++++++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/app/modules/telegram/__init__.py b/app/modules/telegram/__init__.py index e43900c7..eedab3a5 100644 --- a/app/modules/telegram/__init__.py +++ b/app/modules/telegram/__init__.py @@ -1,5 +1,6 @@ import copy import json +import re from typing import Dict from typing import Optional, Union, List, Tuple, Any @@ -202,12 +203,15 @@ class TelegramModule(_ModuleBase, _MessageBase[Telegram]): logger.info(f"收到来自 {client_config.name} 的Telegram消息:" f"userid={user_id}, username={user_name}, chat_id={chat_id}, text={text}") + # Clean bot mentions from text to ensure consistent processing + cleaned_text = TelegramModule._clean_bot_mention(text, client._bot_username if client else None) + # 检查权限 admin_users = client_config.config.get("TELEGRAM_ADMINS") user_list = client_config.config.get("TELEGRAM_USERS") config_chat_id = client_config.config.get("TELEGRAM_CHAT_ID") - if text.startswith("/"): + if cleaned_text.startswith("/"): if admin_users \ and str(user_id) not in admin_users.split(',') \ and str(user_id) != config_chat_id: @@ -225,11 +229,38 @@ class TelegramModule(_ModuleBase, _MessageBase[Telegram]): source=client_config.name, userid=user_id, username=user_name, - text=text, + text=cleaned_text, # Use cleaned text chat_id=str(chat_id) if chat_id else None ) return None + @staticmethod + def _clean_bot_mention(text: str, bot_username: Optional[str]) -> str: + """ + 清理消息中的@bot部分,确保文本处理一致性 + :param text: 原始消息文本 + :param bot_username: bot用户名 + :return: 清理后的文本 + """ + if not text or not bot_username: + return text + + # Remove @bot_username from the beginning and any position in text + cleaned = text + mention_pattern = f"@{bot_username}" + + # Remove mention at the beginning with optional following space + if cleaned.startswith(mention_pattern): + cleaned = cleaned[len(mention_pattern):].lstrip() + + # Remove mention at any other position + cleaned = cleaned.replace(mention_pattern, "").strip() + + # Clean up multiple spaces + cleaned = re.sub(r'\s+', ' ', cleaned).strip() + + return cleaned + def post_message(self, message: Notification) -> None: """ 发送消息