From e7993a448590400599d17cded0004597854d4fe2 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Fri, 8 Jan 2021 18:14:18 +0800 Subject: [PATCH] :bug: fix plain text escaped --- nonebot/adapters/cqhttp/message.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/nonebot/adapters/cqhttp/message.py b/nonebot/adapters/cqhttp/message.py index e5981ad6..ce1190c8 100644 --- a/nonebot/adapters/cqhttp/message.py +++ b/nonebot/adapters/cqhttp/message.py @@ -1,4 +1,5 @@ import re +from functools import reduce from typing import Any, Dict, Union, Tuple, Mapping, Iterable, Optional from nonebot.typing import overrides @@ -223,6 +224,7 @@ class Message(BaseMessage): yield MessageSegment(seg["type"], seg.get("data") or {}) return elif isinstance(msg, str): + def _iter_message(msg: str) -> Iterable[Tuple[str, str]]: text_begin = 0 for cqcode in re.finditer( @@ -232,7 +234,8 @@ class Message(BaseMessage): r"),?\]", msg): yield "text", msg[text_begin:cqcode.pos + cqcode.start()] text_begin = cqcode.pos + cqcode.end() - yield cqcode.group("type"), cqcode.group("params").lstrip(",") + yield cqcode.group("type"), cqcode.group("params").lstrip( + ",") yield "text", msg[text_begin:] for type_, data in _iter_message(msg): @@ -248,3 +251,11 @@ class Message(BaseMessage): x.lstrip() for x in data.split(",")))) } yield MessageSegment(type_, data) + + def extract_plain_text(self) -> str: + + def _concat(x: str, y: MessageSegment) -> str: + return f"{x} {y.data['text']}" if y.is_text() else x + + plain_text = reduce(_concat, self, "") + return plain_text[1:] if plain_text else plain_text