Skip to content

Commit

Permalink
✨ default FallbackStrategy.auto in matcher
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Aug 2, 2024
1 parent 9b541ed commit 7668c49
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 24 deletions.
18 changes: 9 additions & 9 deletions src/nonebot_plugin_alconna/matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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:
"""发送一条消息给当前交互用户
Expand All @@ -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:
"""发送一条消息给当前交互用户并结束当前事件响应器
Expand All @@ -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:
"""发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
Expand All @@ -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` 接收的消息不符合预期,
Expand All @@ -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` 接收的消息不符合预期,
Expand All @@ -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` 接收的消息不符合预期,
Expand All @@ -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` 接收的消息不符合预期,
Expand Down
32 changes: 25 additions & 7 deletions src/nonebot_plugin_alconna/uniseg/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,25 +30,42 @@
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} ")]
return [Text(f"@{seg.display or seg.target} ")]
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):
Expand All @@ -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:
Expand Down Expand Up @@ -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):
Expand Down
12 changes: 4 additions & 8 deletions tests/test_uniseg.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,25 +74,21 @@ 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

msg = UniMessage.at("123").at_channel("456").image(url="https://example.com/1.jpg").text("hello")
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"
)


Expand Down

0 comments on commit 7668c49

Please sign in to comment.