mirror of
				https://github.com/nonebot/nonebot2.git
				synced 2025-10-30 22:46:40 +00:00 
			
		
		
		
	🐛 fix type checking for bot
This commit is contained in:
		| @@ -121,9 +121,8 @@ class Bot(abc.ABC): | |||||||
|         raise NotImplementedError |         raise NotImplementedError | ||||||
|  |  | ||||||
|     @abc.abstractmethod |     @abc.abstractmethod | ||||||
|     async def send(self, event: "BaseEvent", |     async def send(self, event: "Event", | ||||||
|                    message: Union[str, "BaseMessage", |                    message: Union[str, "Message", "MessageSegment"], **kwargs): | ||||||
|                                   "BaseMessageSegment"], **kwargs): |  | ||||||
|         """ |         """ | ||||||
|         :说明: |         :说明: | ||||||
|  |  | ||||||
| @@ -254,7 +253,7 @@ class Event(abc.ABC, Generic[T]): | |||||||
|  |  | ||||||
|     @property |     @property | ||||||
|     @abc.abstractmethod |     @abc.abstractmethod | ||||||
|     def message(self) -> Optional["BaseMessage"]: |     def message(self) -> Optional["Message"]: | ||||||
|         """消息内容""" |         """消息内容""" | ||||||
|         raise NotImplementedError |         raise NotImplementedError | ||||||
|  |  | ||||||
| @@ -345,7 +344,7 @@ class MessageSegment(abc.ABC): | |||||||
|  |  | ||||||
|     @classmethod |     @classmethod | ||||||
|     @abc.abstractmethod |     @abc.abstractmethod | ||||||
|     def text(cls, text: str) -> "BaseMessageSegment": |     def text(cls, text: str) -> "MessageSegment": | ||||||
|         return cls("text", {"text": text}) |         return cls("text", {"text": text}) | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -353,8 +352,8 @@ class Message(list, abc.ABC): | |||||||
|     """消息数组""" |     """消息数组""" | ||||||
|  |  | ||||||
|     def __init__(self, |     def __init__(self, | ||||||
|                  message: Union[str, dict, list, BaseModel, BaseMessageSegment, |                  message: Union[str, dict, list, BaseModel, MessageSegment, | ||||||
|                                 "BaseMessage"] = None, |                                 "Message"] = None, | ||||||
|                  *args, |                  *args, | ||||||
|                  **kwargs): |                  **kwargs): | ||||||
|         """ |         """ | ||||||
| @@ -365,9 +364,9 @@ class Message(list, abc.ABC): | |||||||
|         super().__init__(*args, **kwargs) |         super().__init__(*args, **kwargs) | ||||||
|         if isinstance(message, (str, dict, list, BaseModel)): |         if isinstance(message, (str, dict, list, BaseModel)): | ||||||
|             self.extend(self._construct(message)) |             self.extend(self._construct(message)) | ||||||
|         elif isinstance(message, BaseMessage): |         elif isinstance(message, Message): | ||||||
|             self.extend(message) |             self.extend(message) | ||||||
|         elif isinstance(message, BaseMessageSegment): |         elif isinstance(message, MessageSegment): | ||||||
|             self.append(message) |             self.append(message) | ||||||
|  |  | ||||||
|     def __str__(self): |     def __str__(self): | ||||||
| @@ -376,27 +375,25 @@ class Message(list, abc.ABC): | |||||||
|     @staticmethod |     @staticmethod | ||||||
|     @abc.abstractmethod |     @abc.abstractmethod | ||||||
|     def _construct( |     def _construct( | ||||||
|             msg: Union[str, dict, list, |             msg: Union[str, dict, list, BaseModel]) -> Iterable[MessageSegment]: | ||||||
|                        BaseModel]) -> Iterable[BaseMessageSegment]: |  | ||||||
|         raise NotImplementedError |         raise NotImplementedError | ||||||
|  |  | ||||||
|     def __add__( |     def __add__(self, other: Union[str, MessageSegment, | ||||||
|             self, other: Union[str, BaseMessageSegment, |                                    "Message"]) -> "Message": | ||||||
|                                "BaseMessage"]) -> "BaseMessage": |  | ||||||
|         result = self.__class__(self) |         result = self.__class__(self) | ||||||
|         if isinstance(other, str): |         if isinstance(other, str): | ||||||
|             result.extend(self._construct(other)) |             result.extend(self._construct(other)) | ||||||
|         elif isinstance(other, BaseMessageSegment): |         elif isinstance(other, MessageSegment): | ||||||
|             result.append(other) |             result.append(other) | ||||||
|         elif isinstance(other, BaseMessage): |         elif isinstance(other, Message): | ||||||
|             result.extend(other) |             result.extend(other) | ||||||
|         return result |         return result | ||||||
|  |  | ||||||
|     def __radd__(self, other: Union[str, BaseMessageSegment, "BaseMessage"]): |     def __radd__(self, other: Union[str, MessageSegment, "Message"]): | ||||||
|         result = self.__class__(other) |         result = self.__class__(other) | ||||||
|         return result.__add__(self) |         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]``: 要添加的消息段 |           * ``obj: Union[str, MessageSegment]``: 要添加的消息段 | ||||||
|         """ |         """ | ||||||
|         if isinstance(obj, BaseMessageSegment): |         if isinstance(obj, MessageSegment): | ||||||
|             super().append(obj) |             super().append(obj) | ||||||
|         elif isinstance(obj, str): |         elif isinstance(obj, str): | ||||||
|             self.extend(self._construct(obj)) |             self.extend(self._construct(obj)) | ||||||
| @@ -414,9 +411,8 @@ class Message(list, abc.ABC): | |||||||
|             raise ValueError(f"Unexpected type: {type(obj)} {obj}") |             raise ValueError(f"Unexpected type: {type(obj)} {obj}") | ||||||
|         return self |         return self | ||||||
|  |  | ||||||
|     def extend( |     def extend(self, obj: Union["Message", | ||||||
|         self, obj: Union["BaseMessage", |                                 Iterable[MessageSegment]]) -> "Message": | ||||||
|                          Iterable[BaseMessageSegment]]) -> "BaseMessage": |  | ||||||
|         """ |         """ | ||||||
|         :说明: |         :说明: | ||||||
|  |  | ||||||
| @@ -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 |             return f"{x} {y}" if y.type == "text" else x | ||||||
|  |  | ||||||
|         plain_text = reduce(_concat, self, "") |         plain_text = reduce(_concat, self, "") | ||||||
|   | |||||||
| @@ -416,10 +416,12 @@ class Matcher(metaclass=MatcherMeta): | |||||||
|  |  | ||||||
|             for _ in range(len(self.handlers)): |             for _ in range(len(self.handlers)): | ||||||
|                 handler = self.handlers.pop(0) |                 handler = self.handlers.pop(0) | ||||||
|                 annotation = typing.get_type_hints(handler) |                 # annotation = typing.get_type_hints(handler) | ||||||
|                 BotType = annotation.get("bot") |                 # BotType = annotation.get("bot") | ||||||
|                 if BotType and inspect.isclass(BotType) and not isinstance( |                 signature = inspect.signature(handler) | ||||||
|                         bot, BotType): |                 BotType = signature.parameters.get("bot").annotation | ||||||
|  |                 if BotType is not inspect.Parameter.empty and inspect.isclass( | ||||||
|  |                         BotType) and not isinstance(bot, BotType): | ||||||
|                     continue |                     continue | ||||||
|                 await handler(bot, event, self.state) |                 await handler(bot, event, self.state) | ||||||
|  |  | ||||||
|   | |||||||
| @@ -18,10 +18,11 @@ | |||||||
|     https://docs.python.org/3/library/typing.html |     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: | if TYPE_CHECKING: | ||||||
|     from nonebot.rule import Rule |     from nonebot.adapters import Bot, Event | ||||||
|  |     from nonebot.matcher import Matcher | ||||||
|  |  | ||||||
|  |  | ||||||
| def overrides(InterfaceClass: object): | def overrides(InterfaceClass: object): | ||||||
| @@ -42,7 +43,7 @@ State = Dict[Any, Any] | |||||||
|  |  | ||||||
|   事件处理状态 State 类型 |   事件处理状态 State 类型 | ||||||
| """ | """ | ||||||
| EventPreProcessor = Callable[[Bot, Event, State], Awaitable[None]] | EventPreProcessor = Callable[["Bot", "Event", State], Awaitable[None]] | ||||||
| """ | """ | ||||||
| :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` | :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` | ||||||
|  |  | ||||||
| @@ -50,7 +51,7 @@ EventPreProcessor = Callable[[Bot, Event, State], Awaitable[None]] | |||||||
|  |  | ||||||
|   事件预处理函数 EventPreProcessor 类型 |   事件预处理函数 EventPreProcessor 类型 | ||||||
| """ | """ | ||||||
| EventPostProcessor = Callable[[Bot, Event, State], Awaitable[None]] | EventPostProcessor = Callable[["Bot", "Event", State], Awaitable[None]] | ||||||
| """ | """ | ||||||
| :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` | :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` | ||||||
|  |  | ||||||
| @@ -58,7 +59,7 @@ EventPostProcessor = Callable[[Bot, Event, State], Awaitable[None]] | |||||||
|  |  | ||||||
|   事件预处理函数 EventPostProcessor 类型 |   事件预处理函数 EventPostProcessor 类型 | ||||||
| """ | """ | ||||||
| RunPreProcessor = Callable[["Matcher", Bot, Event, State], Awaitable[None]] | RunPreProcessor = Callable[["Matcher", "Bot", "Event", State], Awaitable[None]] | ||||||
| """ | """ | ||||||
| :类型: ``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 类型 |   事件响应器运行前预处理函数 RunPreProcessor 类型 | ||||||
| """ | """ | ||||||
| RunPostProcessor = Callable[["Matcher", Optional[Exception], Bot, Event, State], | RunPostProcessor = Callable[ | ||||||
|                             Awaitable[None]] |     ["Matcher", Optional[Exception], "Bot", "Event", State], Awaitable[None]] | ||||||
| """ | """ | ||||||
| :类型: ``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 类型,第二个参数为运行时产生的错误(如果存在) |   事件响应器运行前预处理函数 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]]]`` | :类型: ``Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]]`` | ||||||
|  |  | ||||||
| @@ -84,7 +85,7 @@ RuleChecker = Callable[[Bot, Event, State], Union[bool, Awaitable[bool]]] | |||||||
|  |  | ||||||
|   RuleChecker 即判断是否响应事件的处理函数。 |   RuleChecker 即判断是否响应事件的处理函数。 | ||||||
| """ | """ | ||||||
| PermissionChecker = Callable[[Bot, Event], Union[bool, Awaitable[bool]]] | PermissionChecker = Callable[["Bot", "Event"], Union[bool, Awaitable[bool]]] | ||||||
| """ | """ | ||||||
| :类型: ``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 即判断是否响应消息的处理函数。 |   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 即事件的处理函数。 |   Handler 即事件的处理函数。 | ||||||
| """ | """ | ||||||
| ArgsParser = Callable[[Bot, Event, State], Awaitable[None]] | ArgsParser = Callable[["Bot", "Event", State], Awaitable[None]] | ||||||
| """ | """ | ||||||
| :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` | :类型: ``Callable[[Bot, Event, State], Awaitable[None]]`` | ||||||
|  |  | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user