fix(wecomai_event): Fix whitespace handling when extracting plain text from message chains (#8563)

* 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 方法的测试用例
- 测试用例涵盖了流式和非流式场景下的文本提取行为
This commit is contained in:
NayukiChiba
2026-06-04 08:59:59 +08:00
committed by GitHub
parent 24f568b149
commit 9a648eb426

View File

@@ -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