From 7668c49d4ed537694b85cbee54258053c66e63bc Mon Sep 17 00:00:00 2001 From: rf_tar_railt <3165388245@qq.com> Date: Sat, 3 Aug 2024 01:13:02 +0800 Subject: [PATCH] :sparkles: default FallbackStrategy.auto in matcher --- src/nonebot_plugin_alconna/matcher.py | 18 +++++------ src/nonebot_plugin_alconna/uniseg/exporter.py | 32 +++++++++++++++---- tests/test_uniseg.py | 12 +++---- 3 files changed, 38 insertions(+), 24 deletions(-) diff --git a/src/nonebot_plugin_alconna/matcher.py b/src/nonebot_plugin_alconna/matcher.py index 7f670b0..005391d 100644 --- a/src/nonebot_plugin_alconna/matcher.py +++ b/src/nonebot_plugin_alconna/matcher.py @@ -421,7 +421,7 @@ def got( key: str, prompt: _M | None = None, parameterless: Iterable[Any] | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, override: tuple[Literal["insert", "replace"], int] | None = None, ) -> Callable[[T_Handler], T_Handler]: """装饰一个函数来指示 NoneBot 获取一个参数 `key` @@ -488,7 +488,7 @@ def got_path( prompt: _M | None = None, middleware: MIDDLEWARE | None = None, parameterless: Iterable[Any] | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, override: tuple[Literal["insert", "replace"], int] | None = None, ) -> Callable[[T_Handler], T_Handler]: """装饰一个函数来指示 NoneBot 获取一个路径下的参数 `path` @@ -622,7 +622,7 @@ def i18n( async def send( cls, message: _M, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, **kwargs: Any, ) -> Any: """发送一条消息给当前交互用户 @@ -648,7 +648,7 @@ async def send( async def finish( cls, message: _M | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, **kwargs, ) -> NoReturn: """发送一条消息给当前交互用户并结束当前事件响应器 @@ -667,7 +667,7 @@ async def finish( async def pause( cls, prompt: _M | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, **kwargs, ) -> NoReturn: """发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数 @@ -686,7 +686,7 @@ async def pause( async def reject( cls, prompt: _M | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, **kwargs, ) -> NoReturn: """最近使用 `got` / `receive` 接收的消息不符合预期, @@ -707,7 +707,7 @@ async def reject_path( cls, path: str, prompt: _M | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, **kwargs, ) -> NoReturn: """最近使用 `got_path` 接收的消息不符合预期, @@ -731,7 +731,7 @@ async def reject_arg( cls, key: str, prompt: _M | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, **kwargs, ) -> NoReturn: """最近使用 `got` 接收的消息不符合预期, @@ -755,7 +755,7 @@ async def reject_receive( cls, id: str = "", prompt: _M | None = None, - fallback: bool | FallbackStrategy = FallbackStrategy.ignore, + fallback: bool | FallbackStrategy = FallbackStrategy.auto, **kwargs, ) -> NoReturn: """最近使用 `receive` 接收的消息不符合预期, diff --git a/src/nonebot_plugin_alconna/uniseg/exporter.py b/src/nonebot_plugin_alconna/uniseg/exporter.py index 7eb8b09..709c65b 100644 --- a/src/nonebot_plugin_alconna/uniseg/exporter.py +++ b/src/nonebot_plugin_alconna/uniseg/exporter.py @@ -30,17 +30,34 @@ TM = TypeVar("TM", bound=Message) +def merge_text(msg: Message) -> Message: + if not msg: + return msg + result = [] + last = list.__getitem__(msg, 0) + for seg in list.__getitem__(msg, slice(1, None)): + if seg.is_text() and last.is_text(): + last.data["text"] += seg.data["text"] + else: + result.append(last) + last = seg + result.append(last) + msg.clear() + msg.extend(result) + return msg + + async def _auto_fallback(seg: Segment, bot: Union[Bot, None]): if isinstance(seg, Media): if seg.url: - return [Text(f"[{seg.type}]{seg.url}")] + return [Text(f"[{seg.type}]{seg.url} ")] if seg.__class__.to_url and seg.raw: url = await seg.__class__.to_url(seg.raw, bot, None if seg.name == seg.__default_name__ else seg.name) - return [Text(f"[{seg.type}]{url}")] + return [Text(f"[{seg.type}]{url} ")] if seg.__class__.to_url and seg.path: url = await seg.__class__.to_url(seg.path, bot, None if seg.name == seg.__default_name__ else seg.name) - return [Text(f"[{seg.type}]{url}")] - return [Text(f"[{seg.type}]{'' if seg.name == seg.__default_name__ else seg.name}")] + return [Text(f"[{seg.type}]{url} ")] + return [Text(f"[{seg.type}]{'' if seg.name == seg.__default_name__ else seg.name} ")] if isinstance(seg, At): if seg.flag == "channel": return [Text(f"#{seg.display or seg.target} ")] @@ -48,7 +65,7 @@ async def _auto_fallback(seg: Segment, bot: Union[Bot, None]): if isinstance(seg, AtAll): return [Text("@全体成员 ")] if isinstance(seg, Emoji): - return [Text(f"emoji({seg.name or seg.id})")] + return [Text(f"[{seg.name}]")] if seg.name else [Text(f"[表情:{seg.id}]")] if isinstance(seg, Hyper): return [Text(f"[{seg.format}]")] if isinstance(seg, Reply): @@ -57,7 +74,7 @@ async def _auto_fallback(seg: Segment, bot: Union[Bot, None]): if seg.flag == "link": return [Text(f"[{seg.label}]({seg.url})")] elif seg.flag != "action": - return [Text(f"[{seg.label}]{seg.text}")] + return [Text(f"[{seg.label}]{seg.text} ")] return [Text(f"[{seg.label}]")] if isinstance(seg, Keyboard): if seg.children: @@ -212,7 +229,8 @@ async def export(self, source: Sequence[Segment], bot: Union[Bot, None], fallbac target=seg, adapter=bot.adapter.get_name() if bot else "Unknown" ) ) - return message + + return merge_text(message) @abstractmethod async def send_to(self, target: Union[Target, Event], bot: Bot, message: Message, **kwargs): diff --git a/tests/test_uniseg.py b/tests/test_uniseg.py index 94a8ba7..ff5c6dd 100644 --- a/tests/test_uniseg.py +++ b/tests/test_uniseg.py @@ -74,7 +74,7 @@ def test_unimsg(): @pytest.mark.asyncio() async def test_fallback(app: App): - from nonebot.adapters.console import Message, MessageSegment + from nonebot.adapters.console import Message from nonebot_plugin_alconna.uniseg import Button, UniMessage, SerializeFailed, fallback @@ -82,17 +82,13 @@ async def test_fallback(app: App): with pytest.raises(SerializeFailed): await msg.export(adapter="OneBot V11", fallback=fallback.FORBID) assert (await msg.export(adapter="Console", fallback=fallback.IGNORE)) == Message("hello") - assert (await msg.export(adapter="Console", fallback=fallback.TO_TEXT)) == MessageSegment.text( - "[at]" - ) + MessageSegment.text("[at]") + MessageSegment.text("[image]") + MessageSegment.text("hello") + assert (await msg.export(adapter="Console", fallback=fallback.TO_TEXT)) == Message("[at][at][image]hello") msg1 = UniMessage.keyboard(Button("input", "foo", text="/bar")) assert (await msg1.export(adapter="Console", fallback=fallback.ROLLBACK)) == Message("foo[/bar]") - assert (await msg.export(adapter="Console", fallback=fallback.AUTO)) == MessageSegment.text( - "@123 " - ) + MessageSegment.text("#456 ") + MessageSegment.text("[image]https://example.com/1.jpg") + MessageSegment.text( - "hello" + assert (await msg.export(adapter="Console", fallback=fallback.AUTO)) == Message( + "@123 #456 [image]https://example.com/1.jpg hello" )