From 9a648eb4267eb05488647b244c6ca489f5ca5807 Mon Sep 17 00:00:00 2001 From: NayukiChiba Date: Thu, 4 Jun 2026 08:59:59 +0800 Subject: [PATCH] fix(wecomai_event): Fix whitespace handling when extracting plain text from message chains (#8563) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(wecomai_event): 修复消息链提取纯文本时的空白处理 - 增加了strip_result参数以控制是否去除首尾空白 - 流式输出时保留换行等格式字符 - 更新相关调用以适应新参数 * test(wecomai_event): 添加企业微信智能机器人消息事件处理的单元测试 - 测试 _extract_plain_text_from_chain 方法在流式和非流式场景下的行为 - 确保流式输出时换行符等格式字符能够正确保留 - 覆盖了不同输入场景的测试用例 * fix(wecomai_event): 删除企业微信智能机器人消息事件处理的单元测试 - 移除测试文件 test_wecomai_event.py,包含多个针对 _extract_plain_text_from_chain 方法的测试用例 - 测试用例涵盖了流式和非流式场景下的文本提取行为 --- .../sources/wecom_ai_bot/wecomai_event.py | 23 +++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/astrbot/core/platform/sources/wecom_ai_bot/wecomai_event.py b/astrbot/core/platform/sources/wecom_ai_bot/wecomai_event.py index f27d4671e..74d120f5f 100644 --- a/astrbot/core/platform/sources/wecom_ai_bot/wecomai_event.py +++ b/astrbot/core/platform/sources/wecom_ai_bot/wecomai_event.py @@ -125,7 +125,17 @@ class WecomAIBotMessageEvent(AstrMessageEvent): return data @staticmethod - def _extract_plain_text_from_chain(message_chain: MessageChain | None) -> str: + def _extract_plain_text_from_chain( + message_chain: MessageChain | None, + strip_result: bool = True, + ) -> str: + """从消息链中提取纯文本 + + Args: + message_chain: 消息链 + strip_result: 是否去除首尾空白。流式输出时应设为 False, + 以保留换行等格式字符;非流式发送时可保留默认 True + """ if not message_chain: return "" plain_parts: list[str] = [] @@ -134,7 +144,8 @@ class WecomAIBotMessageEvent(AstrMessageEvent): plain_parts.append(f"@{comp.name} ") elif isinstance(comp, Plain): plain_parts.append(comp.text) - return "".join(plain_parts).strip() + result = "".join(plain_parts) + return result.strip() if strip_result else result async def send(self, message: MessageChain | None) -> None: """发送消息""" @@ -254,7 +265,10 @@ class WecomAIBotMessageEvent(AstrMessageEvent): ) chain.squash_plain() - chunk_text = self._extract_plain_text_from_chain(chain) + # 流式输出不 strip,保留换行等格式字符 + chunk_text = self._extract_plain_text_from_chain( + chain, strip_result=False + ) if chunk_text: increment_plain += chunk_text now = asyncio.get_running_loop().time() @@ -334,7 +348,8 @@ class WecomAIBotMessageEvent(AstrMessageEvent): increment_plain = "" continue - chunk_text = self._extract_plain_text_from_chain(chain) + # 流式输出不 strip,保留换行等格式字符 + chunk_text = self._extract_plain_text_from_chain(chain, strip_result=False) if chunk_text: increment_plain += chunk_text final_data += chunk_text