🔀 Merge pull request #310

Pre Release 2.0.0a13
This commit is contained in:
Ju4tCode 2021-04-01 07:44:52 -05:00 committed by GitHub
commit b09a7518f5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
55 changed files with 189 additions and 21 deletions

View File

@ -19,7 +19,7 @@ from nonebot import get_driver
driver=get_driver()
```
共分为种函数:
共分为种函数:
### 启动准备
@ -73,6 +73,18 @@ async def handle_api_call(bot: Bot, api: str, data: Dict[str, Any]):
pass
```
### bot api 调用后钩子
这个钩子函数会在 `Bot` 调用 API 后运行。
```python
from nonebot.adapters import Bot
@Bot.on_called_api
async def handle_api_result(bot: Bot, exception: Optional[Exception], api: str, data: Dict[str, Any], result: Any):
pass
```
## 事件处理钩子
这些钩子函数指的是影响 `nonebot2` 进行 `事件处理` 的函数。

View File

@ -27,7 +27,7 @@ Driver 对象
Config 配置对象
### `_call_api_hook`
### `_calling_api_hook`
* **类型**
@ -42,6 +42,21 @@ Config 配置对象
### `_called_api_hook`
* **类型**
`Set[T_CalledAPIHook]`
* **说明**
call_api 后执行的函数
### _abstract_ `__init__(connection_type, self_id, *, websocket=None)`

View File

@ -78,6 +78,38 @@ sidebarDepth: 0
## `T_CallingAPIHook`
* **类型**
`Callable[[Bot, str, Dict[str, Any]], Awaitable[None]]`
* **说明**
`bot.call_api` 时执行的函数
## `T_CalledAPIHook`
* **类型**
`Callable[[Bot, Optional[Exception], str, Dict[str, Any], Any], Awaitable[None]]`
* **说明**
`bot.call_api` 后执行的函数,参数分别为 bot, exception, api, data, result
## `T_EventPreProcessor`

View File

Before

Width:  |  Height:  |  Size: 124 KiB

After

Width:  |  Height:  |  Size: 124 KiB

View File

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 100 KiB

View File

Before

Width:  |  Height:  |  Size: 75 KiB

After

Width:  |  Height:  |  Size: 75 KiB

View File

Before

Width:  |  Height:  |  Size: 100 KiB

After

Width:  |  Height:  |  Size: 100 KiB

View File

@ -1,5 +1,5 @@
[
"2.0.0a12",
"2.0.0a13",
"2.0.0a10",
"2.0.0a8.post2",
"2.0.0a7"

View File

@ -19,7 +19,7 @@ from nonebot import get_driver
driver=get_driver()
```
共分为种函数:
共分为种函数:
### 启动准备
@ -73,6 +73,18 @@ async def handle_api_call(bot: Bot, api: str, data: Dict[str, Any]):
pass
```
### bot api 调用后钩子
这个钩子函数会在 `Bot` 调用 API 后运行。
```python
from nonebot.adapters import Bot
@Bot.on_called_api
async def handle_api_result(bot: Bot, exception: Optional[Exception], api: str, data: Dict[str, Any], result: Any):
pass
```
## 事件处理钩子
这些钩子函数指的是影响 `nonebot2` 进行 `事件处理` 的函数。

View File

@ -27,7 +27,7 @@ Driver 对象
Config 配置对象
### `_call_api_hook`
### `_calling_api_hook`
* **类型**
@ -42,6 +42,21 @@ Config 配置对象
### `_called_api_hook`
* **类型**
`Set[T_CalledAPIHook]`
* **说明**
call_api 后执行的函数
### _abstract_ `__init__(connection_type, self_id, *, websocket=None)`

View File

@ -78,6 +78,38 @@ sidebarDepth: 0
## `T_CallingAPIHook`
* **类型**
`Callable[[Bot, str, Dict[str, Any]], Awaitable[None]]`
* **说明**
`bot.call_api` 时执行的函数
## `T_CalledAPIHook`
* **类型**
`Callable[[Bot, Optional[Exception], str, Dict[str, Any], Any], Awaitable[None]]`
* **说明**
`bot.call_api` 后执行的函数,参数分别为 bot, exception, api, data, result
## `T_EventPreProcessor`

View File

@ -17,7 +17,7 @@ from pydantic import BaseModel
from nonebot.log import logger
from nonebot.utils import DataclassEncoder
from nonebot.typing import T_CallingAPIHook
from nonebot.typing import T_CallingAPIHook, T_CalledAPIHook
if TYPE_CHECKING:
from nonebot.config import Config
@ -39,11 +39,16 @@ class Bot(abc.ABC):
"""Driver 对象"""
config: "Config"
"""Config 配置对象"""
_call_api_hook: Set[T_CallingAPIHook] = set()
_calling_api_hook: Set[T_CallingAPIHook] = set()
"""
:类型: ``Set[T_CallingAPIHook]``
:说明: call_api 时执行的函数
"""
_called_api_hook: Set[T_CalledAPIHook] = set()
"""
:类型: ``Set[T_CalledAPIHook]``
:说明: call_api 后执行的函数
"""
@abc.abstractmethod
def __init__(self,
@ -156,7 +161,7 @@ class Bot(abc.ABC):
await bot.call_api("send_msg", message="hello world")
await bot.send_msg(message="hello world")
"""
coros = list(map(lambda x: x(self, api, data), self._call_api_hook))
coros = list(map(lambda x: x(self, api, data), self._calling_api_hook))
if coros:
try:
logger.debug("Running CallingAPI hooks...")
@ -166,13 +171,33 @@ class Bot(abc.ABC):
"<r><bg #f8bbd0>Error when running CallingAPI hook. "
"Running cancelled!</bg #f8bbd0></r>")
if "self_id" in data:
self_id = data.pop("self_id")
if self_id:
bot = self.driver.bots[str(self_id)]
return await bot._call_api(api, **data)
exception = None
result = None
return await self._call_api(api, **data)
try:
if "self_id" in data and data["self_id"]:
bot = self.driver.bots[str(data["self_id"])]
result = await bot._call_api(api, **data)
else:
result = await self._call_api(api, **data)
except Exception as e:
exception = e
coros = list(
map(lambda x: x(self, exception, api, data, result),
self._called_api_hook))
if coros:
try:
logger.debug("Running CalledAPI hooks...")
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running CalledAPI hook. "
"Running cancelled!</bg #f8bbd0></r>")
if exception:
raise exception
return result
@abc.abstractmethod
async def send(self, event: "Event", message: Union[str, "Message",
@ -193,7 +218,12 @@ class Bot(abc.ABC):
@classmethod
def on_calling_api(cls, func: T_CallingAPIHook) -> T_CallingAPIHook:
cls._call_api_hook.add(func)
cls._calling_api_hook.add(func)
return func
@classmethod
def on_called_api(cls, func: T_CalledAPIHook) -> T_CalledAPIHook:
cls._called_api_hook.add(func)
return func

View File

@ -418,6 +418,7 @@ class Matcher(metaclass=MatcherMeta):
def _decorator(func: T_Handler) -> T_Handler:
if not hasattr(cls.handlers[-1], "__wrapped__"):
parser = cls.handlers.pop()
func_handler = Handler(func)
@wraps(func)
async def wrapper(bot: "Bot", event: "Event", state: T_State,
@ -427,12 +428,14 @@ class Matcher(metaclass=MatcherMeta):
if "_current_key" in state:
del state["_current_key"]
func_handler = cls.append_handler(wrapper)
wrapper_handler = cls.append_handler(wrapper)
getter_handler.update_signature(bot=func_handler.bot_type,
event=func_handler.event_type)
parser_handler.update_signature(bot=func_handler.bot_type,
event=func_handler.event_type)
getter_handler.update_signature(
bot=wrapper_handler.bot_type,
event=wrapper_handler.event_type)
parser_handler.update_signature(
bot=wrapper_handler.bot_type,
event=wrapper_handler.event_type)
return func

View File

@ -72,6 +72,22 @@ T_WebSocketDisconnectionHook = Callable[["Bot"], Awaitable[None]]
WebSocket 连接断开时执行的函数
"""
T_CallingAPIHook = Callable[["Bot", str, Dict[str, Any]], Awaitable[None]]
"""
:类型: ``Callable[[Bot, str, Dict[str, Any]], Awaitable[None]]``
:说明:
``bot.call_api`` 时执行的函数
"""
T_CalledAPIHook = Callable[
["Bot", Optional[Exception], str, Dict[str, Any], Any], Awaitable[None]]
"""
:类型: ``Callable[[Bot, Optional[Exception], str, Dict[str, Any], Any], Awaitable[None]]``
:说明:
``bot.call_api`` 后执行的函数参数分别为 bot, exception, api, data, result
"""
T_EventPreProcessor = Callable[["Bot", "Event", T_State], Awaitable[None]]
"""

View File

@ -58,6 +58,7 @@ async def _check_reply(bot: "Bot", event: "Event"):
))
except Exception as e:
log("WARNING", f"Error when getting message reply info: {repr(e)}", e)
return
# ensure string comparation
if str(event.reply.sender.user_id) == str(event.self_id):
event.to_me = True

View File

@ -1,6 +1,6 @@
[tool.poetry]
name = "nonebot2"
version = "2.0.0-alpha.12"
version = "2.0.0-alpha.13"
description = "An asynchronous python bot framework."
authors = ["yanyongyu <yyy@nonebot.dev>"]
license = "MIT"