add send pause reject finish template

This commit is contained in:
yanyongyu 2021-09-17 23:28:08 +08:00
parent 55a402203e
commit a273d75b07
4 changed files with 63 additions and 26 deletions

View File

@ -10,18 +10,18 @@ from types import ModuleType
from datetime import datetime from datetime import datetime
from contextvars import ContextVar from contextvars import ContextVar
from collections import defaultdict from collections import defaultdict
from typing import (Any, Type, List, Dict, Union, Mapping, Iterable, Callable, from typing import (TYPE_CHECKING, Any, Dict, List, Type, Union, Mapping,
Optional, NoReturn, TYPE_CHECKING) Callable, Iterable, NoReturn, Optional)
from nonebot.rule import Rule from nonebot.rule import Rule
from nonebot.log import logger from nonebot.log import logger
from nonebot.handler import Handler from nonebot.handler import Handler
from nonebot.adapters import MessageTemplate from nonebot.adapters import MessageTemplate
from nonebot.permission import Permission, USER from nonebot.permission import USER, Permission
from nonebot.typing import (T_State, T_StateFactory, T_Handler, T_ArgsParser, from nonebot.exception import (PausedException, StopPropagation,
T_TypeUpdater, T_PermissionUpdater) FinishedException, RejectedException)
from nonebot.exception import (PausedException, RejectedException, from nonebot.typing import (T_State, T_Handler, T_ArgsParser, T_TypeUpdater,
FinishedException, StopPropagation) T_StateFactory, T_PermissionUpdater)
if TYPE_CHECKING: if TYPE_CHECKING:
from nonebot.adapters import Bot, Event, Message, MessageSegment from nonebot.adapters import Bot, Event, Message, MessageSegment
@ -31,8 +31,9 @@ matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list)
:类型: ``Dict[int, List[Type[Matcher]]]`` :类型: ``Dict[int, List[Type[Matcher]]]``
:说明: 用于存储当前所有的事件响应器 :说明: 用于存储当前所有的事件响应器
""" """
current_bot: ContextVar = ContextVar("current_bot") current_bot: ContextVar["Bot"] = ContextVar("current_bot")
current_event: ContextVar = ContextVar("current_event") current_event: ContextVar["Event"] = ContextVar("current_event")
current_state: ContextVar[T_State] = ContextVar("current_state")
class MatcherMeta(type): class MatcherMeta(type):
@ -421,7 +422,7 @@ class Matcher(metaclass=MatcherMeta):
async def _key_getter(bot: "Bot", event: "Event", state: T_State): async def _key_getter(bot: "Bot", event: "Event", state: T_State):
state["_current_key"] = key state["_current_key"] = key
if key not in state: if key not in state:
if prompt: if prompt is not None:
if isinstance(prompt, MessageTemplate): if isinstance(prompt, MessageTemplate):
_prompt = prompt.format(**state) _prompt = prompt.format(**state)
else: else:
@ -472,8 +473,8 @@ class Matcher(metaclass=MatcherMeta):
return _decorator return _decorator
@classmethod @classmethod
async def send(cls, message: Union[str, "Message", "MessageSegment"], async def send(cls, message: Union[str, "Message", "MessageSegment",
**kwargs) -> Any: MessageTemplate], **kwargs) -> Any:
""" """
:说明: :说明:
@ -484,14 +485,19 @@ class Matcher(metaclass=MatcherMeta):
* ``message: Union[str, Message, MessageSegment]``: 消息内容 * ``message: Union[str, Message, MessageSegment]``: 消息内容
* ``**kwargs``: 其他传递给 ``bot.send`` 的参数请参考对应 adapter bot 对象 api * ``**kwargs``: 其他传递给 ``bot.send`` 的参数请参考对应 adapter bot 对象 api
""" """
bot: "Bot" = current_bot.get() bot = current_bot.get()
event = current_event.get() event = current_event.get()
return await bot.send(event=event, message=message, **kwargs) state = current_state.get()
if isinstance(message, MessageTemplate):
_message = message.format(**state)
else:
_message = message
return await bot.send(event=event, message=_message, **kwargs)
@classmethod @classmethod
async def finish(cls, async def finish(cls,
message: Optional[Union[str, "Message", message: Optional[Union[str, "Message", "MessageSegment",
"MessageSegment"]] = None, MessageTemplate]] = None,
**kwargs) -> NoReturn: **kwargs) -> NoReturn:
""" """
:说明: :说明:
@ -505,14 +511,19 @@ class Matcher(metaclass=MatcherMeta):
""" """
bot = current_bot.get() bot = current_bot.get()
event = current_event.get() event = current_event.get()
if message is not None: state = current_state.get()
await bot.send(event=event, message=message, **kwargs) if isinstance(message, MessageTemplate):
_message = message.format(**state)
else:
_message = message
if _message is not None:
await bot.send(event=event, message=_message, **kwargs)
raise FinishedException raise FinishedException
@classmethod @classmethod
async def pause(cls, async def pause(cls,
prompt: Optional[Union[str, "Message", prompt: Optional[Union[str, "Message", "MessageSegment",
"MessageSegment"]] = None, MessageTemplate]] = None,
**kwargs) -> NoReturn: **kwargs) -> NoReturn:
""" """
:说明: :说明:
@ -526,8 +537,13 @@ class Matcher(metaclass=MatcherMeta):
""" """
bot = current_bot.get() bot = current_bot.get()
event = current_event.get() event = current_event.get()
if prompt: state = current_state.get()
await bot.send(event=event, message=prompt, **kwargs) if isinstance(prompt, MessageTemplate):
_prompt = prompt.format(**state)
else:
_prompt = prompt
if _prompt is not None:
await bot.send(event=event, message=_prompt, **kwargs)
raise PausedException raise PausedException
@classmethod @classmethod
@ -547,8 +563,13 @@ class Matcher(metaclass=MatcherMeta):
""" """
bot = current_bot.get() bot = current_bot.get()
event = current_event.get() event = current_event.get()
if prompt: state = current_state.get()
await bot.send(event=event, message=prompt, **kwargs) if isinstance(prompt, MessageTemplate):
_prompt = prompt.format(**state)
else:
_prompt = prompt
if _prompt is not None:
await bot.send(event=event, message=_prompt, **kwargs)
raise RejectedException raise RejectedException
def stop_propagation(self): def stop_propagation(self):
@ -563,6 +584,7 @@ class Matcher(metaclass=MatcherMeta):
async def run(self, bot: "Bot", event: "Event", state: T_State): async def run(self, bot: "Bot", event: "Event", state: T_State):
b_t = current_bot.set(bot) b_t = current_bot.set(bot)
e_t = current_event.set(event) e_t = current_event.set(event)
s_t = current_state.set(self.state)
try: try:
# Refresh preprocess state # Refresh preprocess state
self.state = await self._default_state_factory( self.state = await self._default_state_factory(
@ -655,3 +677,4 @@ class Matcher(metaclass=MatcherMeta):
logger.info(f"Matcher {self} running complete") logger.info(f"Matcher {self} running complete")
current_bot.reset(b_t) current_bot.reset(b_t)
current_event.reset(e_t) current_event.reset(e_t)
current_state.reset(s_t)

View File

@ -7,7 +7,7 @@ sidebar: auto
## v2.0.0a16 ## v2.0.0a16
- 新增 `MessageFormatter` 可用于 `Message` 的模板生成 - 新增 `MessageFormatter` 可用于 `Message` 的模板生成
- 新增 `matcher.got` 支持 `MessageFormatter` - 新增 `matcher.got` `matcher.send` `matcher.pause` `matcher.reject` `matcher.finish` 支持 `MessageFormatter`
- 移除 `matcher.got` 原本的 `state format` 支持,由 `MessageFormatter` template 替代 - 移除 `matcher.got` 原本的 `state format` 支持,由 `MessageFormatter` template 替代
- `adapter` 基类拆分为单独文件 - `adapter` 基类拆分为单独文件
- 修复 `fastapi` Driver Websocket 未能正确提供请求头部 - 修复 `fastapi` Driver Websocket 未能正确提供请求头部

View File

@ -13,7 +13,7 @@ COMMAND_SEP=["/", "."]
CUSTOM_CONFIG1=config in env CUSTOM_CONFIG1=config in env
CUSTOM_CONFIG3= CUSTOM_CONFIG3=
CQHTTP_WS_URLS={"123123123": "ws://127.0.0.1:6700/"} # CQHTTP_WS_URLS={"123123123": "ws://127.0.0.1:6700/"}
MIRAI_AUTH_KEY=12345678 MIRAI_AUTH_KEY=12345678
MIRAI_HOST=127.0.0.1 MIRAI_HOST=127.0.0.1

View File

@ -0,0 +1,14 @@
from nonebot import on_command
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, MessageSegment, GroupMessageEvent
template = on_command("template")
@template.handle()
async def _(bot: Bot, event: GroupMessageEvent, state: T_State):
state["at"] = MessageSegment.at(event.get_user_id())
state["test"] = "test"
# message: /template {at} hello {test}!
ft = event.message.template(event.get_plaintext())
await template.send(ft)