Skip to content

Commit 9a648eb

Browse files
authored
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 方法的测试用例 - 测试用例涵盖了流式和非流式场景下的文本提取行为
1 parent 24f568b commit 9a648eb

1 file changed

Lines changed: 19 additions & 4 deletions

File tree

astrbot/core/platform/sources/wecom_ai_bot/wecomai_event.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,17 @@ async def _send(
125125
return data
126126

127127
@staticmethod
128-
def _extract_plain_text_from_chain(message_chain: MessageChain | None) -> str:
128+
def _extract_plain_text_from_chain(
129+
message_chain: MessageChain | None,
130+
strip_result: bool = True,
131+
) -> str:
132+
"""从消息链中提取纯文本
133+
134+
Args:
135+
message_chain: 消息链
136+
strip_result: 是否去除首尾空白。流式输出时应设为 False,
137+
以保留换行等格式字符;非流式发送时可保留默认 True
138+
"""
129139
if not message_chain:
130140
return ""
131141
plain_parts: list[str] = []
@@ -134,7 +144,8 @@ def _extract_plain_text_from_chain(message_chain: MessageChain | None) -> str:
134144
plain_parts.append(f"@{comp.name} ")
135145
elif isinstance(comp, Plain):
136146
plain_parts.append(comp.text)
137-
return "".join(plain_parts).strip()
147+
result = "".join(plain_parts)
148+
return result.strip() if strip_result else result
138149

139150
async def send(self, message: MessageChain | None) -> None:
140151
"""发送消息"""
@@ -254,7 +265,10 @@ async def send_streaming(self, generator, use_fallback=False) -> None:
254265
)
255266

256267
chain.squash_plain()
257-
chunk_text = self._extract_plain_text_from_chain(chain)
268+
# 流式输出不 strip,保留换行等格式字符
269+
chunk_text = self._extract_plain_text_from_chain(
270+
chain, strip_result=False
271+
)
258272
if chunk_text:
259273
increment_plain += chunk_text
260274
now = asyncio.get_running_loop().time()
@@ -334,7 +348,8 @@ async def enqueue_stream_plain(text: str) -> None:
334348
increment_plain = ""
335349
continue
336350

337-
chunk_text = self._extract_plain_text_from_chain(chain)
351+
# 流式输出不 strip,保留换行等格式字符
352+
chunk_text = self._extract_plain_text_from_chain(chain, strip_result=False)
338353
if chunk_text:
339354
increment_plain += chunk_text
340355
final_data += chunk_text

0 commit comments

Comments
 (0)