nonebot2/nonebot/matcher.py

717 lines
22 KiB
Python
Raw Normal View History

"""
2022-01-12 19:24:01 +08:00
## 事件响应器
2021-03-18 19:16:18 +08:00
该模块实现事件响应器的创建与运行并提供一些快捷方法来帮助用户更好的与机器人进行对话
"""
2020-06-30 10:13:58 +08:00
from types import ModuleType
2020-08-06 17:54:55 +08:00
from datetime import datetime
from contextvars import ContextVar
2020-06-30 10:13:58 +08:00
from collections import defaultdict
from contextlib import AsyncExitStack
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Type,
Union,
TypeVar,
Callable,
NoReturn,
Optional,
)
2020-05-02 20:03:36 +08:00
from nonebot import params
2020-08-17 16:09:41 +08:00
from nonebot.rule import Rule
2020-12-06 02:30:19 +08:00
from nonebot.log import logger
from nonebot.dependencies import Dependent
from nonebot.permission import USER, Permission
from nonebot.adapters import (
Bot,
Event,
Message,
MessageSegment,
MessageTemplate,
)
2021-12-24 14:09:43 +08:00
from nonebot.consts import (
ARG_KEY,
RECEIVE_KEY,
REJECT_TARGET,
LAST_RECEIVE_KEY,
REJECT_CACHE_TARGET,
)
from nonebot.typing import (
Any,
T_State,
T_Handler,
T_TypeUpdater,
2021-12-16 23:22:25 +08:00
T_DependencyCache,
T_PermissionUpdater,
)
2021-12-29 21:52:46 +08:00
from nonebot.exception import (
TypeMisMatch,
PausedException,
StopPropagation,
SkippedException,
FinishedException,
RejectedException,
)
2020-05-02 20:03:36 +08:00
2020-12-06 02:30:19 +08:00
if TYPE_CHECKING:
2021-11-08 01:02:35 +08:00
from nonebot.plugin import Plugin
2020-12-06 02:30:19 +08:00
T = TypeVar("T")
2020-06-30 10:13:58 +08:00
matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list)
2020-10-05 23:10:20 +08:00
"""
2022-01-12 18:16:05 +08:00
用于存储当前所有的事件响应器
2020-10-05 23:10:20 +08:00
"""
2021-11-14 18:51:23 +08:00
current_bot: ContextVar[Bot] = ContextVar("current_bot")
current_event: ContextVar[Event] = ContextVar("current_event")
2021-12-21 10:57:47 +08:00
current_matcher: ContextVar["Matcher"] = ContextVar("current_matcher")
current_handler: ContextVar[Dependent] = ContextVar("current_handler")
2020-06-30 10:13:58 +08:00
2020-05-02 20:03:36 +08:00
2020-08-27 16:43:58 +08:00
class MatcherMeta(type):
2021-03-18 19:16:18 +08:00
if TYPE_CHECKING:
module: Optional[str]
plugin_name: Optional[str]
module_name: Optional[str]
module_prefix: Optional[str]
2021-03-18 19:16:18 +08:00
type: str
rule: Rule
permission: Permission
handlers: List[T_Handler]
priority: int
block: bool
temp: bool
expire_time: Optional[datetime]
2020-08-27 16:43:58 +08:00
def __repr__(self) -> str:
return (
f"<Matcher from {self.module_name or 'unknown'}, "
f"type={self.type}, priority={self.priority}, "
f"temp={self.temp}>"
)
2020-08-27 16:43:58 +08:00
def __str__(self) -> str:
2021-03-25 18:22:56 +08:00
return repr(self)
2020-08-27 16:43:58 +08:00
class Matcher(metaclass=MatcherMeta):
"""事件响应器类"""
2021-11-08 01:02:35 +08:00
plugin: Optional["Plugin"] = None
"""
2022-01-12 18:16:05 +08:00
事件响应器所在插件
2021-11-08 01:02:35 +08:00
"""
module: Optional[ModuleType] = None
"""
2022-01-12 18:16:05 +08:00
事件响应器所在插件模块
"""
2021-11-08 01:02:35 +08:00
plugin_name: Optional[str] = None
2021-05-10 18:42:32 +08:00
"""
2022-01-12 18:16:05 +08:00
事件响应器所在插件名
2021-05-10 18:42:32 +08:00
"""
2021-11-08 01:02:35 +08:00
module_name: Optional[str] = None
2021-05-10 18:42:32 +08:00
"""
2022-01-12 18:16:05 +08:00
事件响应器所在点分割插件模块路径
2021-05-10 18:42:32 +08:00
"""
2020-05-02 20:03:36 +08:00
2020-08-20 17:15:05 +08:00
type: str = ""
"""
2022-01-12 18:16:05 +08:00
事件响应器类型
"""
2020-08-17 16:09:41 +08:00
rule: Rule = Rule()
"""
2022-01-12 18:16:05 +08:00
事件响应器匹配规则
"""
2020-08-17 16:09:41 +08:00
permission: Permission = Permission()
"""
2022-01-12 18:16:05 +08:00
事件响应器触发权限
"""
handlers: List[Dependent[Any]] = []
"""
2022-01-12 18:16:05 +08:00
事件响应器拥有的事件处理函数列表
"""
2020-06-30 10:13:58 +08:00
priority: int = 1
"""
2022-01-12 18:16:05 +08:00
事件响应器优先级
"""
block: bool = False
"""
2022-01-12 18:16:05 +08:00
事件响应器是否阻止事件传播
"""
temp: bool = False
"""
2022-01-12 18:16:05 +08:00
事件响应器是否为临时
"""
expire_time: Optional[datetime] = None
"""
2022-01-12 18:16:05 +08:00
事件响应器过期时间点
"""
2020-05-05 16:11:05 +08:00
2020-12-17 21:09:30 +08:00
_default_state: T_State = {}
"""
2022-01-12 18:16:05 +08:00
事件响应器默认状态
"""
2020-06-30 10:13:58 +08:00
_default_type_updater: Optional[Dependent[str]] = None
"""
2022-01-12 18:16:05 +08:00
事件响应器类型更新函数
"""
_default_permission_updater: Optional[Dependent[Permission]] = None
"""
2022-01-12 18:16:05 +08:00
事件响应器权限更新函数
"""
2020-05-05 16:11:05 +08:00
2021-11-15 21:44:24 +08:00
HANDLER_PARAM_TYPES = [
params.DependParam,
params.BotParam,
params.EventParam,
params.StateParam,
2021-12-20 00:28:02 +08:00
params.ArgParam,
params.MatcherParam,
params.DefaultParam,
2021-11-15 21:44:24 +08:00
]
2020-05-05 16:11:05 +08:00
def __init__(self):
2020-11-30 11:08:00 +08:00
"""实例化 Matcher 以便运行"""
2020-05-05 16:11:05 +08:00
self.handlers = self.handlers.copy()
self.state = self._default_state.copy()
2020-08-24 17:59:36 +08:00
def __repr__(self) -> str:
return (
f"<Matcher from {self.module_name or 'unknown'}, type={self.type}, "
f"priority={self.priority}, temp={self.temp}>"
)
2020-08-24 17:59:36 +08:00
def __str__(self) -> str:
2021-03-25 18:22:56 +08:00
return repr(self)
2020-08-24 17:59:36 +08:00
2020-05-05 16:11:05 +08:00
@classmethod
def new(
cls,
type_: str = "",
rule: Optional[Rule] = None,
permission: Optional[Permission] = None,
handlers: Optional[List[Union[T_Handler, Dependent[Any]]]] = None,
temp: bool = False,
priority: int = 1,
block: bool = False,
*,
2021-11-08 01:02:35 +08:00
plugin: Optional["Plugin"] = None,
2021-11-09 00:57:59 +08:00
module: Optional[ModuleType] = None,
expire_time: Optional[datetime] = None,
default_state: Optional[T_State] = None,
default_type_updater: Optional[T_TypeUpdater] = None,
default_permission_updater: Optional[T_PermissionUpdater] = None,
) -> Type["Matcher"]:
"""
2022-01-12 18:16:05 +08:00
创建一个新的事件响应器并存储至 `matchers <#matchers>`_
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
type_: 事件响应器类型 `event.get_type()` 一致时触发空字符串表示任意
rule: 匹配规则
permission: 权限
handlers: 事件处理函数列表
temp: 是否为临时事件响应器即触发一次后删除
priority: 响应优先级
block: 是否阻止事件向更低优先级的响应器传播
plugin: 事件响应器所在插件
module: 事件响应器所在模块
default_state: 默认状态 `state`
expire_time: 事件响应器最终有效时间点过时即被删除
2020-11-30 11:08:00 +08:00
2022-01-12 18:43:07 +08:00
返回:
2022-01-12 19:10:29 +08:00
Type[Matcher]: 新的事件响应器类
2020-07-04 22:51:10 +08:00
"""
2020-05-05 16:11:05 +08:00
NewMatcher = type(
"Matcher",
(Matcher,),
{
"plugin": plugin,
"module": module,
"plugin_name": plugin and plugin.name,
"module_name": module and module.__name__,
"type": type_,
"rule": rule or Rule(),
"permission": permission or Permission(),
2021-02-02 12:48:16 +08:00
"handlers": [
handler
if isinstance(handler, Dependent)
else Dependent[Any].parse(
call=handler, allow_types=cls.HANDLER_PARAM_TYPES
)
2021-03-18 19:16:18 +08:00
for handler in handlers
]
if handlers
else [],
"temp": temp,
"expire_time": expire_time,
"priority": priority,
"block": block,
"_default_state": default_state or {},
"_default_type_updater": default_type_updater,
"_default_permission_updater": default_permission_updater,
},
)
2020-05-05 16:11:05 +08:00
2021-12-24 15:04:18 +08:00
logger.trace(f"Define new matcher {NewMatcher}")
2020-06-30 10:13:58 +08:00
matchers[priority].append(NewMatcher)
2020-05-05 16:11:05 +08:00
return NewMatcher
2020-07-04 22:51:10 +08:00
@classmethod
async def check_perm(
cls,
bot: Bot,
event: Event,
stack: Optional[AsyncExitStack] = None,
2021-12-16 23:22:25 +08:00
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""
2022-01-12 18:16:05 +08:00
检查是否满足触发权限
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
bot: Bot 对象
event: 上报事件
2020-11-30 11:08:00 +08:00
2022-01-12 18:43:07 +08:00
返回:
2022-01-12 19:10:29 +08:00
bool: 是否满足权限
"""
2021-02-02 12:48:16 +08:00
event_type = event.get_type()
return event_type == (cls.type or event_type) and await cls.permission(
bot, event, stack, dependency_cache
)
2020-08-17 16:09:41 +08:00
@classmethod
async def check_rule(
cls,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
2021-12-16 23:22:25 +08:00
dependency_cache: Optional[T_DependencyCache] = None,
) -> bool:
"""
2022-01-12 18:16:05 +08:00
检查是否满足匹配规则
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
bot: Bot 对象
event: 上报事件
state: 当前状态
2020-11-30 11:08:00 +08:00
2022-01-12 18:43:07 +08:00
返回:
2022-01-12 19:10:29 +08:00
bool: 是否满足匹配规则
2020-07-04 22:51:10 +08:00
"""
2020-12-09 19:57:49 +08:00
event_type = event.get_type()
return event_type == (cls.type or event_type) and await cls.rule(
bot, event, state, stack, dependency_cache
)
2020-07-04 22:51:10 +08:00
@classmethod
def type_updater(cls, func: T_TypeUpdater) -> T_TypeUpdater:
"""
2022-01-12 18:16:05 +08:00
装饰一个函数来更改当前事件响应器的默认响应事件类型更新函数
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
func: 响应事件类型更新函数
"""
cls._default_type_updater = Dependent[str].parse(
call=func, allow_types=cls.HANDLER_PARAM_TYPES
)
return func
@classmethod
def permission_updater(cls, func: T_PermissionUpdater) -> T_PermissionUpdater:
"""
2022-01-12 18:16:05 +08:00
装饰一个函数来更改当前事件响应器的默认会话权限更新函数
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
func: 会话权限更新函数
"""
cls._default_permission_updater = Dependent[Permission].parse(
call=func, allow_types=cls.HANDLER_PARAM_TYPES
)
return func
2020-12-16 23:13:00 +08:00
@classmethod
def append_handler(
cls, handler: T_Handler, parameterless: Optional[List[Any]] = None
) -> Dependent[Any]:
handler_ = Dependent[Any].parse(
call=handler,
parameterless=parameterless,
allow_types=cls.HANDLER_PARAM_TYPES,
)
2021-03-18 19:16:18 +08:00
cls.handlers.append(handler_)
return handler_
2020-12-16 23:13:00 +08:00
2020-05-05 16:11:05 +08:00
@classmethod
2021-12-03 23:30:15 +08:00
def handle(
cls, parameterless: Optional[List[Any]] = None
2021-12-03 23:30:15 +08:00
) -> Callable[[T_Handler], T_Handler]:
2020-10-06 17:03:05 +08:00
"""
2022-01-12 18:16:05 +08:00
装饰一个函数来向事件响应器直接添加一个处理函数
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
parameterless: 非参数类型依赖列表
2020-10-06 17:03:05 +08:00
"""
2020-06-30 10:13:58 +08:00
2020-12-17 21:09:30 +08:00
def _decorator(func: T_Handler) -> T_Handler:
cls.append_handler(func, parameterless=parameterless)
2020-06-30 10:13:58 +08:00
return func
return _decorator
2020-05-02 20:03:36 +08:00
2020-05-05 16:11:05 +08:00
@classmethod
2021-12-03 23:30:15 +08:00
def receive(
2021-12-21 10:57:47 +08:00
cls, id: str = "", parameterless: Optional[List[Any]] = None
2021-12-03 23:30:15 +08:00
) -> Callable[[T_Handler], T_Handler]:
2020-10-06 17:03:05 +08:00
"""
2022-01-12 18:16:05 +08:00
装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
id: 消息 ID
parameterless: 非参数类型依赖列表
2020-10-06 17:03:05 +08:00
"""
2020-05-02 20:03:36 +08:00
async def _receive(event: Event, matcher: "Matcher") -> Union[None, NoReturn]:
2021-12-24 14:09:43 +08:00
matcher.set_target(RECEIVE_KEY.format(id=id))
2021-12-21 10:57:47 +08:00
if matcher.get_target() == RECEIVE_KEY.format(id=id):
matcher.set_receive(id, event)
2021-11-14 18:51:23 +08:00
return
if matcher.get_receive(id, ...) is not ...:
return
2022-01-05 18:29:11 +08:00
await matcher.reject()
2020-05-02 20:03:36 +08:00
_parameterless = [params.Depends(_receive), *(parameterless or [])]
2020-05-05 16:11:05 +08:00
2021-12-03 23:30:15 +08:00
def _decorator(func: T_Handler) -> T_Handler:
2021-11-14 18:51:23 +08:00
if cls.handlers and cls.handlers[-1].call is func:
2021-11-13 19:38:01 +08:00
func_handler = cls.handlers[-1]
for depend in reversed(_parameterless):
func_handler.prepend_parameterless(depend)
2021-11-13 19:38:01 +08:00
else:
cls.append_handler(func, parameterless=_parameterless)
2020-05-02 20:03:36 +08:00
return func
return _decorator
@classmethod
def got(
cls,
key: str,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
parameterless: Optional[List[Any]] = None,
2020-12-17 21:09:30 +08:00
) -> Callable[[T_Handler], T_Handler]:
2020-10-06 17:03:05 +08:00
"""
2022-01-12 19:10:29 +08:00
装饰一个函数来指示 NoneBot 当要获取的 `key` 不存在时接收用户新的一条消息再运行该函数如果 `key` 已存在则直接继续运行
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
key: 参数名
prompt: 在参数不存在时向用户发送的消息
parameterless: 非参数类型依赖列表
2020-10-06 17:03:05 +08:00
"""
2020-05-02 20:03:36 +08:00
async def _key_getter(event: Event, matcher: "Matcher"):
2021-12-24 14:09:43 +08:00
matcher.set_target(ARG_KEY.format(key=key))
if matcher.get_target() == ARG_KEY.format(key=key):
2021-12-23 22:16:55 +08:00
matcher.set_arg(key, event.get_message())
2021-11-14 18:51:23 +08:00
return
if matcher.get_arg(key, ...) is not ...:
2021-12-21 10:57:47 +08:00
return
2022-01-05 18:29:11 +08:00
await matcher.reject(prompt)
2021-11-14 18:51:23 +08:00
_parameterless = [
params.Depends(_key_getter),
*(parameterless or []),
2021-12-03 23:30:15 +08:00
]
2021-11-13 19:38:01 +08:00
2021-12-03 23:30:15 +08:00
def _decorator(func: T_Handler) -> T_Handler:
2021-11-13 19:38:01 +08:00
if cls.handlers and cls.handlers[-1].call is func:
2021-11-13 19:38:01 +08:00
func_handler = cls.handlers[-1]
for depend in reversed(_parameterless):
func_handler.prepend_parameterless(depend)
2021-11-13 19:38:01 +08:00
else:
cls.append_handler(func, parameterless=_parameterless)
return func
2020-05-02 20:03:36 +08:00
return _decorator
2020-05-02 20:03:36 +08:00
2020-10-06 16:24:04 +08:00
@classmethod
async def send(
2021-12-20 00:28:02 +08:00
cls,
message: Union[str, Message, MessageSegment, MessageTemplate],
**kwargs: Any,
) -> Any:
2020-10-06 17:03:05 +08:00
"""
2022-01-12 18:16:05 +08:00
发送一条消息给当前交互用户
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
message: 消息内容
**kwargs: `bot.send` 的参数请参考对应 adapter bot 对象 api
2020-10-06 17:03:05 +08:00
"""
bot = current_bot.get()
2020-10-06 16:24:04 +08:00
event = current_event.get()
2021-12-21 10:57:47 +08:00
state = current_matcher.get().state
if isinstance(message, MessageTemplate):
_message = message.format(**state)
else:
_message = message
return await bot.send(event=event, message=_message, **kwargs)
2020-10-06 16:24:04 +08:00
@classmethod
async def finish(
cls,
message: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
2020-10-06 17:03:05 +08:00
"""
2022-01-12 18:16:05 +08:00
发送一条消息给当前交互用户并结束当前事件响应器
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
message: 消息内容
**kwargs: `bot.send` 的参数请参考对应 adapter bot 对象 api
2020-10-06 17:03:05 +08:00
"""
if message is not None:
await cls.send(message, **kwargs)
raise FinishedException
2020-05-02 20:03:36 +08:00
@classmethod
async def pause(
cls,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
2020-10-06 17:03:05 +08:00
"""
2022-01-12 18:16:05 +08:00
发送一条消息给当前交互用户并暂停事件响应器在接收用户新的一条消息后继续下一个处理函数
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
prompt: 消息内容
**kwargs`: bot.send` 的参数请参考对应 adapter bot 对象 api
2020-10-06 17:03:05 +08:00
"""
if prompt is not None:
await cls.send(prompt, **kwargs)
raise PausedException
2020-06-30 10:13:58 +08:00
@classmethod
async def reject(
2022-01-05 18:29:11 +08:00
cls,
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
**kwargs,
) -> NoReturn:
2020-10-06 17:03:05 +08:00
"""
2022-01-12 18:19:21 +08:00
最近使用 `got` / `receive` 接收的消息不符合预期发送一条消息给当前交互用户并暂停事件响应器在接收用户新的一条消息后继续当前处理函数
2021-12-21 10:57:47 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
prompt: 消息内容
**kwargs: `bot.send` 的参数请参考对应 adapter bot 对象 api
2021-12-21 10:57:47 +08:00
"""
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
async def reject_arg(
cls,
key: str,
2022-01-05 18:29:11 +08:00
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
2021-12-21 10:57:47 +08:00
**kwargs,
) -> NoReturn:
"""
2022-01-12 18:19:21 +08:00
最近使用 `got` 接收的消息不符合预期发送一条消息给当前交互用户并暂停事件响应器在接收用户新的一条消息后继续当前处理函数
2021-12-21 10:57:47 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
key: 参数名
prompt: 消息内容
**kwargs: `bot.send` 的参数请参考对应 adapter bot 对象 api
2021-12-21 10:57:47 +08:00
"""
matcher = current_matcher.get()
matcher.set_target(ARG_KEY.format(key=key))
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
@classmethod
async def reject_receive(
cls,
id: str = "",
2022-01-05 18:29:11 +08:00
prompt: Optional[Union[str, Message, MessageSegment, MessageTemplate]] = None,
2021-12-21 10:57:47 +08:00
**kwargs,
) -> NoReturn:
"""
2022-01-12 18:19:21 +08:00
最近使用 `got` 接收的消息不符合预期发送一条消息给当前交互用户并暂停事件响应器在接收用户新的一条消息后继续当前处理函数
2020-11-30 11:08:00 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
id: 消息 id
prompt: 消息内容
**kwargs: `bot.send` 的参数请参考对应 adapter bot 对象 api
2020-10-06 17:03:05 +08:00
"""
2021-12-21 10:57:47 +08:00
matcher = current_matcher.get()
matcher.set_target(RECEIVE_KEY.format(id=id))
if prompt is not None:
await cls.send(prompt, **kwargs)
raise RejectedException
2020-05-02 20:03:36 +08:00
2021-12-29 21:52:46 +08:00
@classmethod
def skip(cls) -> NoReturn:
raise SkippedException
def get_receive(self, id: str, default: T = None) -> Union[Event, T]:
return self.state.get(RECEIVE_KEY.format(id=id), default)
def set_receive(self, id: str, event: Event) -> None:
self.state[RECEIVE_KEY.format(id=id)] = event
self.state[LAST_RECEIVE_KEY] = event
def get_last_receive(self, default: T = None) -> Union[Event, T]:
return self.state.get(LAST_RECEIVE_KEY, default)
2021-12-23 22:16:55 +08:00
def get_arg(self, key: str, default: T = None) -> Union[Message, T]:
return self.state.get(ARG_KEY.format(key=key), default)
2021-12-23 22:16:55 +08:00
def set_arg(self, key: str, message: Message) -> None:
self.state[ARG_KEY.format(key=key)] = message
2021-12-24 14:09:43 +08:00
def set_target(self, target: str, cache: bool = True) -> None:
if cache:
self.state[REJECT_CACHE_TARGET] = target
else:
self.state[REJECT_TARGET] = target
def get_target(self, default: T = None) -> Union[str, T]:
return self.state.get(REJECT_TARGET, default)
2020-12-24 22:19:08 +08:00
def stop_propagation(self):
"""
2022-01-12 18:16:05 +08:00
阻止事件传播
"""
2020-12-24 22:19:08 +08:00
self.block = True
2021-12-10 15:46:06 +08:00
async def update_type(self, bot: Bot, event: Event) -> str:
updater = self.__class__._default_type_updater
if not updater:
return "message"
return await updater(bot=bot, event=event, state=self.state, matcher=self)
2021-12-10 15:46:06 +08:00
async def update_permission(self, bot: Bot, event: Event) -> Permission:
updater = self.__class__._default_permission_updater
if not updater:
return USER(event.get_session_id(), perm=self.permission)
return await updater(bot=bot, event=event, state=self.state, matcher=self)
2021-12-10 15:46:06 +08:00
2021-12-24 14:09:43 +08:00
async def resolve_reject(self):
handler = current_handler.get()
self.handlers.insert(0, handler)
2021-12-28 11:51:14 +08:00
if REJECT_CACHE_TARGET in self.state:
self.state[REJECT_TARGET] = self.state[REJECT_CACHE_TARGET]
2021-12-24 14:09:43 +08:00
2021-12-10 15:46:06 +08:00
async def simple_run(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
2021-12-16 23:22:25 +08:00
dependency_cache: Optional[T_DependencyCache] = None,
):
2021-12-24 15:04:18 +08:00
logger.trace(
f"Matcher {self} run with incoming args: "
f"bot={bot}, event={event}, state={state}"
)
b_t = current_bot.set(bot)
e_t = current_event.set(event)
2021-12-21 10:57:47 +08:00
m_t = current_matcher.set(self)
2020-05-05 16:11:05 +08:00
try:
2020-08-17 16:09:41 +08:00
# Refresh preprocess state
self.state.update(state)
2020-08-17 16:09:41 +08:00
while self.handlers:
2020-05-05 16:11:05 +08:00
handler = self.handlers.pop(0)
2021-12-10 15:46:06 +08:00
current_handler.set(handler)
logger.debug(f"Running handler {handler}")
2021-11-19 18:18:53 +08:00
try:
await handler(
matcher=self,
bot=bot,
event=event,
state=self.state,
stack=stack,
dependency_cache=dependency_cache,
)
2021-12-29 21:52:46 +08:00
except TypeMisMatch as e:
2021-12-06 00:17:52 +08:00
logger.debug(
f"Handler {handler} param {e.param.name} value {e.value} "
f"mismatch type {e.param._type_display()}, skipped"
)
2021-12-29 21:52:46 +08:00
except SkippedException as e:
logger.debug(f"Handler {handler} skipped")
2021-12-10 15:46:06 +08:00
except StopPropagation:
self.block = True
finally:
logger.info(f"Matcher {self} running complete")
current_bot.reset(b_t)
current_event.reset(e_t)
2021-12-21 10:57:47 +08:00
current_matcher.reset(m_t)
2021-12-10 15:46:06 +08:00
# 运行handlers
async def run(
self,
bot: Bot,
event: Event,
state: T_State,
stack: Optional[AsyncExitStack] = None,
2021-12-16 23:22:25 +08:00
dependency_cache: Optional[T_DependencyCache] = None,
2021-12-10 15:46:06 +08:00
):
try:
await self.simple_run(bot, event, state, stack, dependency_cache)
2020-05-05 16:11:05 +08:00
except RejectedException:
2021-12-24 14:09:43 +08:00
await self.resolve_reject()
2021-12-10 15:46:06 +08:00
type_ = await self.update_type(bot, event)
permission = await self.update_permission(bot, event)
2021-03-12 16:28:56 +08:00
Matcher.new(
type_,
Rule(),
permission,
self.handlers,
temp=True,
priority=0,
block=True,
2021-11-08 01:02:35 +08:00
plugin=self.plugin,
2021-11-11 18:10:39 +08:00
module=self.module,
expire_time=datetime.now() + bot.config.session_expire_timeout,
default_state=self.state,
default_type_updater=self.__class__._default_type_updater,
default_permission_updater=self.__class__._default_permission_updater,
)
2020-05-05 16:11:05 +08:00
except PausedException:
2021-12-10 15:46:06 +08:00
type_ = await self.update_type(bot, event)
permission = await self.update_permission(bot, event)
2021-03-12 16:28:56 +08:00
Matcher.new(
type_,
Rule(),
permission,
self.handlers,
temp=True,
priority=0,
block=True,
2021-11-08 01:02:35 +08:00
plugin=self.plugin,
2021-11-11 18:10:39 +08:00
module=self.module,
expire_time=datetime.now() + bot.config.session_expire_timeout,
default_state=self.state,
default_type_updater=self.__class__._default_type_updater,
default_permission_updater=self.__class__._default_permission_updater,
)
2020-05-05 16:11:05 +08:00
except FinishedException:
pass