From a420af75fc22a5cddb645e359ed4fedcdb1a3652 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 7 Dec 2020 00:31:14 +0800 Subject: [PATCH] :bug: fix type checking for bot --- nonebot/adapters/__init__.py | 42 ++++++++++++++++-------------------- nonebot/matcher.py | 10 +++++---- nonebot/typing.py | 26 +++++++++++----------- 3 files changed, 39 insertions(+), 39 deletions(-) diff --git a/nonebot/adapters/__init__.py b/nonebot/adapters/__init__.py index 317b6919..ea6254d0 100644 --- a/nonebot/adapters/__init__.py +++ b/nonebot/adapters/__init__.py @@ -121,9 +121,8 @@ class Bot(abc.ABC): raise NotImplementedError @abc.abstractmethod - async def send(self, event: "BaseEvent", - message: Union[str, "BaseMessage", - "BaseMessageSegment"], **kwargs): + async def send(self, event: "Event", + message: Union[str, "Message", "MessageSegment"], **kwargs): """ :说明: @@ -254,7 +253,7 @@ class Event(abc.ABC, Generic[T]): @property @abc.abstractmethod - def message(self) -> Optional["BaseMessage"]: + def message(self) -> Optional["Message"]: """消息内容""" raise NotImplementedError @@ -345,7 +344,7 @@ class MessageSegment(abc.ABC): @classmethod @abc.abstractmethod - def text(cls, text: str) -> "BaseMessageSegment": + def text(cls, text: str) -> "MessageSegment": return cls("text", {"text": text}) @@ -353,8 +352,8 @@ class Message(list, abc.ABC): """消息数组""" def __init__(self, - message: Union[str, dict, list, BaseModel, BaseMessageSegment, - "BaseMessage"] = None, + message: Union[str, dict, list, BaseModel, MessageSegment, + "Message"] = None, *args, **kwargs): """ @@ -365,9 +364,9 @@ class Message(list, abc.ABC): super().__init__(*args, **kwargs) if isinstance(message, (str, dict, list, BaseModel)): self.extend(self._construct(message)) - elif isinstance(message, BaseMessage): + elif isinstance(message, Message): self.extend(message) - elif isinstance(message, BaseMessageSegment): + elif isinstance(message, MessageSegment): self.append(message) def __str__(self): @@ -376,27 +375,25 @@ class Message(list, abc.ABC): @staticmethod @abc.abstractmethod def _construct( - msg: Union[str, dict, list, - BaseModel]) -> Iterable[BaseMessageSegment]: + msg: Union[str, dict, list, BaseModel]) -> Iterable[MessageSegment]: raise NotImplementedError - def __add__( - self, other: Union[str, BaseMessageSegment, - "BaseMessage"]) -> "BaseMessage": + def __add__(self, other: Union[str, MessageSegment, + "Message"]) -> "Message": result = self.__class__(self) if isinstance(other, str): result.extend(self._construct(other)) - elif isinstance(other, BaseMessageSegment): + elif isinstance(other, MessageSegment): result.append(other) - elif isinstance(other, BaseMessage): + elif isinstance(other, Message): result.extend(other) return result - def __radd__(self, other: Union[str, BaseMessageSegment, "BaseMessage"]): + def __radd__(self, other: Union[str, MessageSegment, "Message"]): result = self.__class__(other) return result.__add__(self) - def append(self, obj: Union[str, BaseMessageSegment]) -> "BaseMessage": + def append(self, obj: Union[str, MessageSegment]) -> "Message": """ :说明: @@ -406,7 +403,7 @@ class Message(list, abc.ABC): * ``obj: Union[str, MessageSegment]``: 要添加的消息段 """ - if isinstance(obj, BaseMessageSegment): + if isinstance(obj, MessageSegment): super().append(obj) elif isinstance(obj, str): self.extend(self._construct(obj)) @@ -414,9 +411,8 @@ class Message(list, abc.ABC): raise ValueError(f"Unexpected type: {type(obj)} {obj}") return self - def extend( - self, obj: Union["BaseMessage", - Iterable[BaseMessageSegment]]) -> "BaseMessage": + def extend(self, obj: Union["Message", + Iterable[MessageSegment]]) -> "Message": """ :说明: @@ -452,7 +448,7 @@ class Message(list, abc.ABC): 提取消息内纯文本消息 """ - def _concat(x: str, y: BaseMessageSegment) -> str: + def _concat(x: str, y: MessageSegment) -> str: return f"{x} {y}" if y.type == "text" else x plain_text = reduce(_concat, self, "") diff --git a/nonebot/matcher.py b/nonebot/matcher.py index fc953f28..4e76701b 100644 --- a/nonebot/matcher.py +++ b/nonebot/matcher.py @@ -416,10 +416,12 @@ class Matcher(metaclass=MatcherMeta): for _ in range(len(self.handlers)): handler = self.handlers.pop(0) - annotation = typing.get_type_hints(handler) - BotType = annotation.get("bot") - if BotType and inspect.isclass(BotType) and not isinstance( - bot, BotType): + # annotation = typing.get_type_hints(handler) + # BotType = annotation.get("bot") + signature = inspect.signature(handler) + BotType = signature.parameters.get("bot").annotation + if BotType is not inspect.Parameter.empty and inspect.isclass( + BotType) and not isinstance(bot, BotType): continue await handler(bot, event, self.state) diff --git a/nonebot/typing.py b/nonebot/typing.py index a23d527f..be11e1f4 100644 --- a/nonebot/typing.py +++ b/nonebot/typing.py @@ -18,10 +18,11 @@ https://docs.python.org/3/library/typing.html """ -from typing import Any, Dict, Union, Optional, Callable, Awaitable, TYPE_CHECKING +from typing import Any, Dict, Union, Optional, Callable, NoReturn, Awaitable, TYPE_CHECKING if TYPE_CHECKING: - from nonebot.rule import Rule + from nonebot.adapters import Bot, Event + from nonebot.matcher import Matcher def overrides(InterfaceClass: object): @@ -42,7 +43,7 @@ State = Dict[Any, Any] 事件处理状态 State 类型 """ -EventPreProcessor = Callable[[Bot, Event, State], Awaitable[None]] +EventPreProcessor = Callable[["Bot", "Event", State], Awaitable[None]] """ :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` @@ -50,7 +51,7 @@ EventPreProcessor = Callable[[Bot, Event, State], Awaitable[None]] 事件预处理函数 EventPreProcessor 类型 """ -EventPostProcessor = Callable[[Bot, Event, State], Awaitable[None]] +EventPostProcessor = Callable[["Bot", "Event", State], Awaitable[None]] """ :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` @@ -58,7 +59,7 @@ EventPostProcessor = Callable[[Bot, Event, State], Awaitable[None]] 事件预处理函数 EventPostProcessor 类型 """ -RunPreProcessor = Callable[["Matcher", Bot, Event, State], Awaitable[None]] +RunPreProcessor = Callable[["Matcher", "Bot", "Event", State], Awaitable[None]] """ :类型: ``Callable[[Matcher, Bot, Event, State], Awaitable[None]]`` @@ -66,8 +67,8 @@ RunPreProcessor = Callable[["Matcher", Bot, Event, State], Awaitable[None]] 事件响应器运行前预处理函数 RunPreProcessor 类型 """ -RunPostProcessor = Callable[["Matcher", Optional[Exception], Bot, Event, State], - Awaitable[None]] +RunPostProcessor = Callable[ + ["Matcher", Optional[Exception], "Bot", "Event", State], Awaitable[None]] """ :类型: ``Callable[[Matcher, Optional[Exception], Bot, Event, State], Awaitable[None]]`` @@ -76,7 +77,7 @@ RunPostProcessor = Callable[["Matcher", Optional[Exception], Bot, Event, State], 事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在) """ -RuleChecker = Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]] +RuleChecker = Callable[["Bot", "Event", State], Union[bool, Awaitable[bool]]] """ :类型: ``Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]]`` @@ -84,7 +85,7 @@ RuleChecker = Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]] RuleChecker 即判断是否响应事件的处理函数。 """ -PermissionChecker = Callable[[Bot, Event], Union[bool, Awaitable[bool]]] +PermissionChecker = Callable[["Bot", "Event"], Union[bool, Awaitable[bool]]] """ :类型: ``Callable[[Bot, Event], Union[bool, Awaitable[bool]]]`` @@ -92,15 +93,16 @@ PermissionChecker = Callable[[Bot, Event], Union[bool, Awaitable[bool]]] RuleChecker 即判断是否响应消息的处理函数。 """ -Handler = Callable[[Bot, Event, State], Awaitable[None]] +Handler = Callable[["Bot", "Event", State], Union[Awaitable[None], + Awaitable[NoReturn]]] """ -:类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` +:类型: ``Callable[[Bot, Event, State], Union[Awaitable[None], Awaitable[NoReturn]]]`` :说明: Handler 即事件的处理函数。 """ -ArgsParser = Callable[[Bot, Event, State], Awaitable[None]] +ArgsParser = Callable[["Bot", "Event", State], Awaitable[None]] """ :类型: ``Callable[[Bot, Event, State], Awaitable[None]]``