nonebot2/nonebot/matcher.py

182 lines
5.5 KiB
Python
Raw Normal View History

2020-06-30 10:13:58 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
2020-08-13 15:23:04 +08:00
import typing
2020-05-02 20:03:36 +08:00
from functools import wraps
2020-08-06 17:54:55 +08:00
from datetime import datetime
2020-06-30 10:13:58 +08:00
from collections import defaultdict
2020-05-02 20:03:36 +08:00
2020-07-05 20:39:34 +08:00
from nonebot.rule import Rule, user
2020-08-10 13:06:02 +08:00
from nonebot.typing import Bot, Event, Handler
from nonebot.typing import Type, List, Dict, Optional, NoReturn
2020-07-05 20:39:34 +08:00
from nonebot.exception import PausedException, RejectedException, FinishedException
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list)
2020-05-02 20:03:36 +08:00
class Matcher:
2020-07-04 22:51:10 +08:00
"""`Matcher`类
"""
2020-05-02 20:03:36 +08:00
2020-05-05 16:11:05 +08:00
rule: Rule = Rule()
2020-06-30 10:13:58 +08:00
handlers: List[Handler] = []
2020-05-05 16:11:05 +08:00
temp: bool = False
2020-08-06 17:54:55 +08:00
expire_time: Optional[datetime] = None
2020-06-30 10:13:58 +08:00
priority: int = 1
2020-05-05 16:11:05 +08:00
_default_state: dict = {}
2020-06-30 10:13:58 +08:00
# _default_parser: Optional[Callable[[Event, dict], None]] = None
# _args_parser: Optional[Callable[[Event, dict], None]] = None
2020-05-05 16:11:05 +08:00
def __init__(self):
2020-07-04 22:51:10 +08:00
"""实例化 Matcher 以便运行
"""
2020-05-05 16:11:05 +08:00
self.handlers = self.handlers.copy()
self.state = self._default_state.copy()
2020-06-30 10:13:58 +08:00
# self.parser = self._args_parser or self._default_parser
2020-05-05 16:11:05 +08:00
@classmethod
2020-06-30 10:13:58 +08:00
def new(cls,
rule: Rule = Rule(),
handlers: list = [],
temp: bool = False,
priority: int = 1,
*,
2020-08-06 17:54:55 +08:00
default_state: dict = {},
expire_time: Optional[datetime] = None) -> Type["Matcher"]:
2020-07-04 22:51:10 +08:00
"""创建新的 Matcher
Returns:
Type["Matcher"]: 新的 Matcher
"""
2020-05-05 16:11:05 +08:00
NewMatcher = type(
2020-06-24 21:56:49 +08:00
"Matcher", (Matcher,), {
2020-05-05 16:11:05 +08:00
"rule": rule,
"handlers": handlers,
"temp": temp,
2020-08-06 17:54:55 +08:00
"expire_time": expire_time,
2020-06-30 10:13:58 +08:00
"priority": priority,
"_default_state": default_state
2020-05-05 16:11:05 +08:00
})
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
2020-08-10 13:06:02 +08:00
def check_rule(cls, bot: Bot, event: Event) -> bool:
2020-07-04 22:51:10 +08:00
"""检查 Matcher 的 Rule 是否成立
Args:
event (Event): 消息事件
Returns:
bool: 条件成立与否
"""
2020-07-25 12:28:30 +08:00
return cls.rule(bot, event)
2020-07-04 22:51:10 +08:00
2020-06-30 10:13:58 +08:00
# @classmethod
# def args_parser(cls, func: Callable[[Event, dict], None]):
# cls._default_parser = func
# return func
2020-05-05 16:11:05 +08:00
@classmethod
2020-06-30 10:13:58 +08:00
def handle(cls):
2020-07-04 22:51:10 +08:00
"""直接处理消息事件"""
2020-06-30 10:13:58 +08:00
def _decorator(func: Handler) -> Handler:
cls.handlers.append(func)
return func
return _decorator
2020-05-02 20:03:36 +08:00
2020-05-05 16:11:05 +08:00
@classmethod
def receive(cls):
2020-07-04 22:51:10 +08:00
"""接收一条新消息并处理"""
2020-05-02 20:03:36 +08:00
def _decorator(func: Handler) -> Handler:
2020-08-10 13:06:02 +08:00
async def _handler(bot: Bot, event: Event, state: dict) -> NoReturn:
2020-05-05 16:11:05 +08:00
raise PausedException
cls.handlers.append(_handler)
2020-06-30 10:13:58 +08:00
cls.handlers.append(func)
2020-05-02 20:03:36 +08:00
return func
return _decorator
2020-06-30 10:13:58 +08:00
# @classmethod
# def got(cls,
# key: str,
# prompt: Optional[str] = None,
# args_parser: Optional[Callable[[Event, dict], None]] = None):
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
# def _decorator(func: Handler) -> Handler:
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
# @wraps(func)
# def _handler(event: Event, state: dict):
# if key not in state:
# if state.get("__current_arg__", None) == key:
# state[key] = event.message
# del state["__current_arg__"]
# return func(event, state)
# state["__current_arg__"] = key
# cls._args_parser = args_parser
# raise RejectedException
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
# return func(event, state)
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
# cls.handlers.append(_handler)
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
# return func
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
# return _decorator
2020-05-02 20:03:36 +08:00
2020-06-30 10:13:58 +08:00
# @classmethod
# def finish(cls, prompt: Optional[str] = None):
# raise FinishedException
# @classmethod
# def reject(cls, prompt: Optional[str] = None):
# raise RejectedException
2020-05-02 20:03:36 +08:00
2020-07-04 22:51:10 +08:00
# 运行handlers
2020-08-10 13:06:02 +08:00
async def run(self, bot: Bot, event: Event):
2020-05-05 16:11:05 +08:00
try:
2020-06-30 10:13:58 +08:00
# if self.parser:
# await self.parser(event, state) # type: ignore
2020-05-05 16:11:05 +08:00
for _ in range(len(self.handlers)):
handler = self.handlers.pop(0)
2020-08-13 15:23:04 +08:00
annotation = typing.get_type_hints(handler)
BotType = annotation.get("bot")
if BotType and not isinstance(bot, BotType):
continue
2020-06-30 10:13:58 +08:00
await handler(bot, event, self.state)
2020-05-05 16:11:05 +08:00
except RejectedException:
2020-06-30 10:13:58 +08:00
self.handlers.insert(0, handler) # type: ignore
matcher = Matcher.new(user(event.user_id) & self.rule,
2020-05-05 16:11:05 +08:00
self.handlers,
temp=True,
2020-06-30 10:13:58 +08:00
priority=0,
2020-08-06 17:54:55 +08:00
default_state=self.state,
expire_time=datetime.now() +
bot.config.session_expire_timeout)
2020-06-30 10:13:58 +08:00
matchers[0].append(matcher)
2020-05-05 16:11:05 +08:00
return
except PausedException:
2020-06-30 10:13:58 +08:00
matcher = Matcher.new(user(event.user_id) & self.rule,
2020-05-05 16:11:05 +08:00
self.handlers,
temp=True,
2020-06-30 10:13:58 +08:00
priority=0,
2020-08-06 17:54:55 +08:00
default_state=self.state,
expire_time=datetime.now() +
bot.config.session_expire_timeout)
2020-06-30 10:13:58 +08:00
matchers[0].append(matcher)
2020-05-05 16:11:05 +08:00
return
except FinishedException:
return