💡 add adapter docstring

This commit is contained in:
yanyongyu 2020-10-01 23:52:56 +08:00
parent 1aac3d562d
commit 3e4dc1a123
4 changed files with 291 additions and 9 deletions

View File

@ -5,20 +5,228 @@ sidebarDepth: 0
# NoneBot.adapters 模块 # NoneBot.adapters 模块
## 协议适配基类
各协议请继承以下基类,并使用 `driver.register_adapter` 注册适配器
## _class_ `BaseBot` ## _class_ `BaseBot`
基类:`abc.ABC` 基类:`abc.ABC`
Bot 基类。用于处理上报消息,并提供 API 调用接口。
### _abstract_ `__init__(driver, connection_type, config, self_id, *, websocket=None)`
* **参数**
* `driver: Driver`: Driver 对象
* `connection_type: str`: http 或者 websocket
* `config: Config`: Config 对象
* `self_id: str`: 机器人 ID
* `websocket: Optional[WebSocket]`: Websocket 连接对象
### `driver`
Driver 对象
### `connection_type`
连接类型
### `config`
Config 配置对象
### `self_id`
机器人 ID
### `websocket`
Websocket 连接对象
### _abstract property_ `type`
Adapter 类型
### _abstract async_ `handle_message(message)`
* **说明**
处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。
* **参数**
* `message: dict`: 收到的上报消息
### _abstract async_ `call_api(api, **data)`
* **说明**
调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用
* **参数**
* `api: str`: API 名称
* `**data`: API 数据
* **示例**
```python
await bot.call_api("send_msg", data={"message": "hello world"})
await bot.send_msg(message="hello world")
```
### _abstract async_ `send(*args, **kwargs)`
* **说明**
调用机器人基础发送消息接口
* **参数**
* `*args`
* `**kwargs`
## _class_ `BaseEvent` ## _class_ `BaseEvent`
基类:`abc.ABC` 基类:`abc.ABC`
Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。
### `_raw_event`
原始 event ### `__init__(raw_event)`
* **参数**
* `raw_event: dict`: 原始上报消息
### _property_ `raw_event`
原始上报消息
### _abstract property_ `id`
事件 ID
### _abstract property_ `name`
事件名称
### _abstract property_ `self_id`
机器人 ID
### _abstract property_ `time`
事件发生时间
### _abstract property_ `type`
事件主类型
### _abstract property_ `detail_type`
事件详细类型
### _abstract property_ `sub_type`
事件子类型
### _abstract property_ `user_id`
触发事件的主体 ID
### _abstract property_ `group_id`
触发事件的主体群 ID
### _abstract property_ `to_me`
事件是否为发送给机器人的消息
### _abstract property_ `message`
消息内容
### _abstract property_ `reply`
回复的消息
### _abstract property_ `raw_message`
原始消息
### _abstract property_ `plain_text`
纯文本消息
### _abstract property_ `sender`
消息发送者信息
## _class_ `BaseMessageSegment` ## _class_ `BaseMessageSegment`
@ -31,6 +239,11 @@ sidebarDepth: 0
基类:`list`, `abc.ABC` 基类:`list`, `abc.ABC`
### `__init__(message=None, *args, **kwargs)`
Initialize self. See help(type(self)) for accurate signature.
### `append(obj)` ### `append(obj)`
Append object to the end of the list. Append object to the end of the list.

View File

@ -9,4 +9,5 @@ NoneBot.adapters 模块
.. automodule:: nonebot.adapters .. automodule:: nonebot.adapters
:members: :members:
:private-members: :private-members:
:special-members: __init__
:show-inheritance: :show-inheritance:

View File

@ -1,5 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""
协议适配基类
===========
各协议请继承以下基类并使用 ``driver.register_adapter`` 注册适配器
"""
import abc import abc
from functools import reduce, partial from functools import reduce, partial
@ -11,6 +17,9 @@ from nonebot.typing import Any, Dict, Union, Optional, Callable, Iterable, Await
class BaseBot(abc.ABC): class BaseBot(abc.ABC):
"""
Bot 基类用于处理上报消息并提供 API 调用接口
"""
@abc.abstractmethod @abc.abstractmethod
def __init__(self, def __init__(self,
@ -19,12 +28,25 @@ class BaseBot(abc.ABC):
config: Config, config: Config,
self_id: str, self_id: str,
*, *,
websocket: WebSocket = None): websocket: Optional[WebSocket] = None):
"""
:参数:
* ``driver: Driver``: Driver 对象
* ``connection_type: str``: http 或者 websocket
* ``config: Config``: Config 对象
* ``self_id: str``: 机器人 ID
* ``websocket: Optional[WebSocket]``: Websocket 连接对象
"""
self.driver = driver self.driver = driver
"""Driver 对象"""
self.connection_type = connection_type self.connection_type = connection_type
"""连接类型"""
self.config = config self.config = config
"""Config 配置对象"""
self.self_id = self_id self.self_id = self_id
"""机器人 ID"""
self.websocket = websocket self.websocket = websocket
"""Websocket 连接对象"""
def __getattr__(self, name: str) -> Callable[..., Awaitable[Any]]: def __getattr__(self, name: str) -> Callable[..., Awaitable[Any]]:
return partial(self.call_api, name) return partial(self.call_api, name)
@ -32,60 +54,96 @@ class BaseBot(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def type(self) -> str: def type(self) -> str:
"""Adapter 类型"""
raise NotImplementedError raise NotImplementedError
@abc.abstractmethod @abc.abstractmethod
async def handle_message(self, message: dict): async def handle_message(self, message: dict):
"""
:说明:
处理上报消息的函数转换为 ``Event`` 事件后调用 ``nonebot.message.handle_event`` 进一步处理事件
:参数:
* ``message: dict``: 收到的上报消息
"""
raise NotImplementedError raise NotImplementedError
@abc.abstractmethod @abc.abstractmethod
async def call_api(self, api: str, data: dict): async def call_api(self, api: str, **data):
"""
:说明:
调用机器人 API 接口可以通过该函数或直接通过 bot 属性进行调用
:参数:
* ``api: str``: API 名称
* ``**data``: API 数据
:示例:
.. code-block:: python
await bot.call_api("send_msg", data={"message": "hello world"})
await bot.send_msg(message="hello world")
"""
raise NotImplementedError raise NotImplementedError
@abc.abstractmethod @abc.abstractmethod
async def send(self, *args, **kwargs): async def send(self, *args, **kwargs):
"""
:说明:
调用机器人基础发送消息接口
:参数:
* ``*args``
* ``**kwargs``
"""
raise NotImplementedError raise NotImplementedError
# TODO: improve event
class BaseEvent(abc.ABC): class BaseEvent(abc.ABC):
"""
Event 基类提供上报信息的关键信息其余信息可从原始上报消息获取
"""
def __init__(self, raw_event: dict): def __init__(self, raw_event: dict):
"""
:参数:
* ``raw_event: dict``: 原始上报消息
"""
self._raw_event = raw_event self._raw_event = raw_event
"""
原始 event
"""
def __repr__(self) -> str: def __repr__(self) -> str:
return f"<Event {self.self_id}: {self.name} {self.time}>" return f"<Event {self.self_id}: {self.name} {self.time}>"
@property @property
def raw_event(self) -> dict: def raw_event(self) -> dict:
"""原始上报消息"""
return self._raw_event return self._raw_event
@property @property
@abc.abstractmethod @abc.abstractmethod
def id(self) -> int: def id(self) -> int:
"""事件 ID"""
raise NotImplementedError raise NotImplementedError
@property @property
@abc.abstractmethod @abc.abstractmethod
def name(self) -> str: def name(self) -> str:
"""事件名称"""
raise NotImplementedError raise NotImplementedError
@property @property
@abc.abstractmethod @abc.abstractmethod
def self_id(self) -> str: def self_id(self) -> str:
"""机器人 ID"""
raise NotImplementedError raise NotImplementedError
@property @property
@abc.abstractmethod @abc.abstractmethod
def time(self) -> int: def time(self) -> int:
"""事件发生时间"""
raise NotImplementedError raise NotImplementedError
@property @property
@abc.abstractmethod @abc.abstractmethod
def type(self) -> str: def type(self) -> str:
"""事件主类型"""
raise NotImplementedError raise NotImplementedError
@type.setter @type.setter
@ -96,6 +154,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def detail_type(self) -> str: def detail_type(self) -> str:
"""事件详细类型"""
raise NotImplementedError raise NotImplementedError
@detail_type.setter @detail_type.setter
@ -106,6 +165,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def sub_type(self) -> Optional[str]: def sub_type(self) -> Optional[str]:
"""事件子类型"""
raise NotImplementedError raise NotImplementedError
@sub_type.setter @sub_type.setter
@ -116,6 +176,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def user_id(self) -> Optional[int]: def user_id(self) -> Optional[int]:
"""触发事件的主体 ID"""
raise NotImplementedError raise NotImplementedError
@user_id.setter @user_id.setter
@ -126,6 +187,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def group_id(self) -> Optional[int]: def group_id(self) -> Optional[int]:
"""触发事件的主体群 ID"""
raise NotImplementedError raise NotImplementedError
@group_id.setter @group_id.setter
@ -136,6 +198,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def to_me(self) -> Optional[bool]: def to_me(self) -> Optional[bool]:
"""事件是否为发送给机器人的消息"""
raise NotImplementedError raise NotImplementedError
@to_me.setter @to_me.setter
@ -146,6 +209,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def message(self) -> Optional[Message]: def message(self) -> Optional[Message]:
"""消息内容"""
raise NotImplementedError raise NotImplementedError
@message.setter @message.setter
@ -156,6 +220,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def reply(self) -> Optional[dict]: def reply(self) -> Optional[dict]:
"""回复的消息"""
raise NotImplementedError raise NotImplementedError
@reply.setter @reply.setter
@ -166,6 +231,7 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def raw_message(self) -> Optional[str]: def raw_message(self) -> Optional[str]:
"""原始消息"""
raise NotImplementedError raise NotImplementedError
@raw_message.setter @raw_message.setter
@ -176,11 +242,13 @@ class BaseEvent(abc.ABC):
@property @property
@abc.abstractmethod @abc.abstractmethod
def plain_text(self) -> Optional[str]: def plain_text(self) -> Optional[str]:
"""纯文本消息"""
raise NotImplementedError raise NotImplementedError
@property @property
@abc.abstractmethod @abc.abstractmethod
def sender(self) -> Optional[dict]: def sender(self) -> Optional[dict]:
"""消息发送者信息"""
raise NotImplementedError raise NotImplementedError
@sender.setter @sender.setter

View File

@ -265,7 +265,7 @@ class Bot(BaseBot):
config: Config, config: Config,
self_id: str, self_id: str,
*, *,
websocket: WebSocket = None): websocket: Optional[WebSocket] = None):
if connection_type not in ["http", "websocket"]: if connection_type not in ["http", "websocket"]:
raise ValueError("Unsupported connection type") raise ValueError("Unsupported connection type")