nonebot2/nonebot/adapters/__init__.py

446 lines
12 KiB
Python
Raw Normal View History

2020-10-01 23:52:56 +08:00
"""
协议适配基类
============
2020-10-01 23:52:56 +08:00
各协议请继承以下基类并使用 ``driver.register_adapter`` 注册适配器
"""
2020-07-05 20:39:34 +08:00
2020-07-18 18:18:43 +08:00
import abc
2020-12-09 19:57:49 +08:00
from typing_extensions import Literal
2020-08-13 15:23:04 +08:00
from functools import reduce, partial
2020-08-10 13:06:02 +08:00
from dataclasses import dataclass, field
from typing import Any, Dict, Union, TypeVar, Optional, Callable, Iterable, Awaitable, TYPE_CHECKING
2020-07-11 17:32:03 +08:00
2020-12-03 00:59:32 +08:00
from pydantic import BaseModel
2020-07-11 17:32:03 +08:00
from nonebot.config import Config
2020-12-06 02:30:19 +08:00
if TYPE_CHECKING:
2020-12-07 00:06:09 +08:00
from nonebot.drivers import Driver, WebSocket
2020-07-11 17:32:03 +08:00
2020-07-05 20:39:34 +08:00
2020-12-07 00:06:09 +08:00
class Bot(abc.ABC):
2020-10-01 23:52:56 +08:00
"""
Bot 基类用于处理上报消息并提供 API 调用接口
"""
2020-07-05 20:39:34 +08:00
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-08-01 22:03:40 +08:00
def __init__(self,
2020-12-06 02:30:19 +08:00
driver: "Driver",
2020-08-07 17:51:57 +08:00
connection_type: str,
2020-08-01 22:03:40 +08:00
config: Config,
2020-08-13 15:23:04 +08:00
self_id: str,
2020-08-01 22:03:40 +08:00
*,
2020-12-06 02:30:19 +08:00
websocket: Optional["WebSocket"] = None):
2020-10-01 23:52:56 +08:00
"""
:参数:
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
* ``driver: Driver``: Driver 对象
* ``connection_type: str``: http 或者 websocket
* ``config: Config``: Config 对象
* ``self_id: str``: 机器人 ID
* ``websocket: Optional[WebSocket]``: Websocket 连接对象
"""
2020-08-13 15:23:04 +08:00
self.driver = driver
2020-10-01 23:52:56 +08:00
"""Driver 对象"""
2020-08-07 17:51:57 +08:00
self.connection_type = connection_type
2020-10-01 23:52:56 +08:00
"""连接类型"""
2020-08-07 17:51:57 +08:00
self.config = config
2020-10-01 23:52:56 +08:00
"""Config 配置对象"""
2020-08-07 17:51:57 +08:00
self.self_id = self_id
2020-10-01 23:52:56 +08:00
"""机器人 ID"""
2020-08-07 17:51:57 +08:00
self.websocket = websocket
2020-10-01 23:52:56 +08:00
"""Websocket 连接对象"""
2020-08-07 17:51:57 +08:00
2020-08-13 15:23:04 +08:00
def __getattr__(self, name: str) -> Callable[..., Awaitable[Any]]:
return partial(self.call_api, name)
2020-08-07 17:51:57 +08:00
@property
@abc.abstractmethod
def type(self) -> str:
2020-10-01 23:52:56 +08:00
"""Adapter 类型"""
2020-07-11 17:32:03 +08:00
raise NotImplementedError
@classmethod
@abc.abstractmethod
2020-12-06 02:30:19 +08:00
async def check_permission(cls, driver: "Driver", connection_type: str,
2020-12-05 20:32:38 +08:00
headers: dict, body: Optional[dict]) -> str:
2020-11-13 01:46:26 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-11-13 01:46:26 +08:00
检查连接请求是否合法的函数如果合法则返回当前连接 ``唯一标识符``通常为机器人 ID如果不合法则抛出 ``RequestDenied`` 异常
2020-11-30 11:08:00 +08:00
2020-11-13 01:46:26 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-11-13 01:46:26 +08:00
* ``driver: Driver``: Driver 对象
* ``connection_type: str``: 连接类型
* ``headers: dict``: 请求头
* ``body: Optional[dict]``: 请求数据WebSocket 连接该部分为空
2020-11-30 11:08:00 +08:00
2020-11-13 01:46:26 +08:00
:返回:
2020-11-30 11:08:00 +08:00
2020-11-13 01:46:26 +08:00
- ``str``: 连接唯一标识符
2020-11-30 11:08:00 +08:00
2020-11-13 01:46:26 +08:00
:异常:
2020-11-30 11:08:00 +08:00
2020-11-13 01:46:26 +08:00
- ``RequestDenied``: 请求非法
"""
raise NotImplementedError
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-07-11 17:32:03 +08:00
async def handle_message(self, message: dict):
2020-10-01 23:52:56 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
处理上报消息的函数转换为 ``Event`` 事件后调用 ``nonebot.message.handle_event`` 进一步处理事件
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
* ``message: dict``: 收到的上报消息
"""
2020-07-11 17:32:03 +08:00
raise NotImplementedError
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-10-01 23:52:56 +08:00
async def call_api(self, api: str, **data):
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
调用机器人 API 接口可以通过该函数或直接通过 bot 属性进行调用
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
* ``api: str``: API 名称
* ``**data``: API 数据
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
:示例:
.. code-block:: python
2020-12-21 19:32:58 +08:00
await bot.call_api("send_msg", message="hello world")
2020-10-01 23:52:56 +08:00
await bot.send_msg(message="hello world")
"""
2020-07-11 17:32:03 +08:00
raise NotImplementedError
@abc.abstractmethod
2020-12-07 00:31:14 +08:00
async def send(self, event: "Event",
message: Union[str, "Message", "MessageSegment"], **kwargs):
2020-10-01 23:52:56 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
调用机器人基础发送消息接口
2020-11-30 11:08:00 +08:00
2020-10-01 23:52:56 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-10-06 17:03:05 +08:00
* ``event: Event``: 上报事件
* ``message: Union[str, Message, MessageSegment]``: 要发送的消息
2020-10-01 23:52:56 +08:00
* ``**kwargs``
"""
raise NotImplementedError
2020-07-11 17:32:03 +08:00
2020-12-09 14:39:25 +08:00
class Event(abc.ABC, BaseModel):
2020-12-19 15:30:34 +08:00
"""Event 基类。提供获取关键信息的方法,其余信息可直接获取。"""
2020-12-03 00:59:32 +08:00
2020-12-09 14:39:25 +08:00
class Config:
extra = "allow"
2020-12-03 00:59:32 +08:00
2020-08-10 14:50:12 +08:00
@abc.abstractmethod
2020-12-09 14:39:25 +08:00
def get_type(self) -> Literal["message", "notice", "request", "meta_event"]:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取事件类型的方法类型通常为 NoneBot 内置的四种类型
:返回:
* ``Literal["message", "notice", "request", "meta_event"]``
"""
2020-08-10 14:50:12 +08:00
raise NotImplementedError
2020-08-08 23:08:01 +08:00
2020-08-10 14:50:12 +08:00
@abc.abstractmethod
2020-12-09 14:39:25 +08:00
def get_event_name(self) -> str:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取事件名称的方法
:返回:
* ``str``
"""
2020-08-10 14:50:12 +08:00
raise NotImplementedError
2020-08-08 23:08:01 +08:00
2020-08-14 17:41:24 +08:00
@abc.abstractmethod
2020-12-09 14:39:25 +08:00
def get_event_description(self) -> str:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取事件描述的方法通常为事件具体内容
:返回:
* ``str``
"""
2020-08-14 17:41:24 +08:00
raise NotImplementedError
2020-12-19 00:26:24 +08:00
def __str__(self) -> str:
2020-12-09 14:39:25 +08:00
return f"[{self.get_event_name()}]: {self.get_event_description()}"
2020-12-19 14:16:47 +08:00
def get_log_string(self) -> str:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取事件日志信息的方法通常你不需要修改这个方法只有当希望 NoneBot 隐藏该事件日志时可以抛出 ``NoLogException`` 异常
:返回:
* ``str``
:异常:
- ``NoLogException``
"""
2020-12-19 14:16:47 +08:00
return f"[{self.get_event_name()}]: {self.get_event_description()}"
2020-08-14 17:41:24 +08:00
2020-12-10 02:13:25 +08:00
@abc.abstractmethod
def get_user_id(self) -> str:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取事件主体 id 的方法通常是用户 id
:返回:
* ``str``
"""
2020-12-10 02:13:25 +08:00
raise NotImplementedError
2020-08-14 17:41:24 +08:00
@abc.abstractmethod
2020-12-09 14:39:25 +08:00
def get_session_id(self) -> str:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取会话 id 的方法用于判断当前事件属于哪一个会话通常是用户 id群组 id 组合
:返回:
* ``str``
"""
2020-08-14 17:41:24 +08:00
raise NotImplementedError
2020-12-09 19:57:49 +08:00
@abc.abstractmethod
def get_message(self) -> "Message":
2020-12-19 15:30:34 +08:00
"""
:说明:
获取事件消息内容的方法
:返回:
* ``Message``
"""
2020-12-09 19:57:49 +08:00
raise NotImplementedError
def get_plaintext(self) -> str:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取消息纯文本的方法通常不需要修改默认通过 ``get_message().extract_plain_text`` 获取
:返回:
* ``str``
"""
return self.get_message().extract_plain_text()
2020-12-09 19:57:49 +08:00
2020-12-10 02:13:25 +08:00
@abc.abstractmethod
def is_tome(self) -> bool:
2020-12-19 15:30:34 +08:00
"""
:说明:
获取事件是否与机器人有关的方法
:返回:
* ``bool``
"""
2020-12-10 02:13:25 +08:00
raise NotImplementedError
2020-08-17 16:09:41 +08:00
T_Message = TypeVar("T_Message", bound="Message")
T_MessageSegment = TypeVar("T_MessageSegment", bound="MessageSegment")
2020-08-10 14:50:12 +08:00
@dataclass
2020-12-07 00:06:09 +08:00
class MessageSegment(abc.ABC):
2020-10-03 18:18:43 +08:00
"""消息段基类"""
2020-08-10 14:50:12 +08:00
type: str
2020-10-03 18:18:43 +08:00
"""
- 类型: ``str``
- 说明: 消息段类型
"""
data: Dict[str, Any] = field(default_factory=lambda: {})
2020-10-03 18:18:43 +08:00
"""
- 类型: ``Dict[str, Union[str, list]]``
- 说明: 消息段数据
"""
2020-08-10 14:50:12 +08:00
@abc.abstractmethod
def __str__(self: T_MessageSegment) -> str:
"""该消息段所代表的 str在命令匹配部分使用"""
2020-08-10 14:50:12 +08:00
raise NotImplementedError
2020-07-11 17:32:03 +08:00
2020-08-10 14:50:12 +08:00
@abc.abstractmethod
def __add__(self: T_MessageSegment, other: Union[str, T_MessageSegment,
T_Message]) -> "T_Message":
"""你需要在这里实现不同消息段的合并:
比如
if isinstance(other, str):
...
elif isinstance(other, MessageSegment):
...
注意需要返回一个新生成的对象
"""
raise NotImplementedError
@abc.abstractmethod
def __radd__(
self: T_MessageSegment, other: Union[str, dict, list, T_MessageSegment,
T_Message]) -> "T_Message":
"""你需要在这里实现不同消息段的合并:
比如
if isinstance(other, str):
...
elif isinstance(other, MessageSegment):
...
注意需要返回一个新生成的对象
"""
2020-08-10 14:50:12 +08:00
raise NotImplementedError
2020-08-08 23:08:01 +08:00
2020-10-09 00:10:50 +08:00
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, value):
return setattr(self, key, value)
2020-11-01 19:20:18 +08:00
def get(self, key, default=None):
return getattr(self, key, default)
@abc.abstractmethod
2020-12-10 02:13:25 +08:00
def is_text(self) -> bool:
raise NotImplementedError
2020-08-08 23:08:01 +08:00
2020-12-07 00:06:09 +08:00
class Message(list, abc.ABC):
2020-10-03 18:18:43 +08:00
"""消息数组"""
2020-07-11 17:32:03 +08:00
2020-07-18 18:18:43 +08:00
def __init__(self,
message: Union[str, list, dict, T_MessageSegment, T_Message, Any] = None,
2020-07-18 18:18:43 +08:00
*args,
**kwargs):
2020-10-03 18:18:43 +08:00
"""
:参数:
2020-11-30 11:08:00 +08:00
* ``message: Union[MessageSegment, Message, Any]``: 消息内容
2020-10-03 18:18:43 +08:00
"""
2020-07-18 18:18:43 +08:00
super().__init__(*args, **kwargs)
if isinstance(message, Message):
2020-07-18 18:18:43 +08:00
self.extend(message)
2020-12-07 00:31:14 +08:00
elif isinstance(message, MessageSegment):
2020-07-18 18:18:43 +08:00
self.append(message)
else:
self.extend(self._construct(message))
2020-07-11 17:32:03 +08:00
def __str__(self):
return ''.join((str(seg) for seg in self))
2020-07-18 18:18:43 +08:00
2020-12-10 02:13:25 +08:00
@classmethod
2020-12-10 21:33:51 +08:00
def __get_validators__(cls):
2020-12-10 02:13:25 +08:00
yield cls._validate
@classmethod
def _validate(cls, value):
return cls(value)
2020-07-18 18:18:43 +08:00
@staticmethod
2020-08-08 23:08:01 +08:00
@abc.abstractmethod
def _construct(msg: Union[Any]) -> Iterable[T_MessageSegment]:
2020-07-18 18:18:43 +08:00
raise NotImplementedError
def __add__(self: T_Message, other: Union[str, T_MessageSegment,
T_Message]) -> T_Message:
2020-07-18 18:18:43 +08:00
result = self.__class__(self)
if isinstance(other, str):
result.extend(self._construct(other))
2020-12-07 00:31:14 +08:00
elif isinstance(other, MessageSegment):
2020-07-18 18:18:43 +08:00
result.append(other)
2020-12-07 00:31:14 +08:00
elif isinstance(other, Message):
2020-07-18 18:18:43 +08:00
result.extend(other)
return result
def __radd__(self: T_Message, other: Union[str, T_MessageSegment,
T_Message]):
2020-07-18 18:18:43 +08:00
result = self.__class__(other)
return result.__add__(self)
def append(self: T_Message, obj: Union[str, T_MessageSegment]) -> T_Message:
2020-10-03 18:18:43 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-03 18:18:43 +08:00
添加一个消息段到消息数组末尾
2020-11-30 11:08:00 +08:00
2020-10-03 18:18:43 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-10-03 18:18:43 +08:00
* ``obj: Union[str, MessageSegment]``: 要添加的消息段
"""
2020-12-07 00:31:14 +08:00
if isinstance(obj, MessageSegment):
super().append(obj)
2020-07-18 18:18:43 +08:00
elif isinstance(obj, str):
self.extend(self._construct(obj))
else:
raise ValueError(f"Unexpected type: {type(obj)} {obj}")
return self
def extend(self: T_Message,
obj: Union[T_Message, Iterable[T_MessageSegment]]) -> T_Message:
2020-10-03 18:18:43 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-03 18:18:43 +08:00
拼接一个消息数组或多个消息段到消息数组末尾
2020-11-30 11:08:00 +08:00
2020-10-03 18:18:43 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-10-03 18:18:43 +08:00
* ``obj: Union[Message, Iterable[MessageSegment]]``: 要添加的消息数组
"""
2020-07-18 18:18:43 +08:00
for segment in obj:
self.append(segment)
return self
def reduce(self: T_Message) -> None:
2020-10-03 18:18:43 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
缩减消息数组即按 MessageSegment 的实现拼接相邻消息段
2020-10-03 18:18:43 +08:00
"""
2020-07-18 18:18:43 +08:00
index = 0
while index < len(self):
2020-12-10 02:13:25 +08:00
if index > 0 and self[index -
1].is_text() and self[index].is_text():
self[index - 1] += self[index]
2020-07-18 18:18:43 +08:00
del self[index]
else:
index += 1
def extract_plain_text(self: T_Message) -> str:
2020-10-03 18:18:43 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-03 18:18:43 +08:00
提取消息内纯文本消息
"""
2020-07-18 18:18:43 +08:00
def _concat(x: str, y: T_MessageSegment) -> str:
2020-12-10 02:13:25 +08:00
return f"{x} {y}" if y.is_text() else x
2020-07-18 18:18:43 +08:00
plain_text = reduce(_concat, self, "")
2020-12-03 19:12:46 +08:00
return plain_text[1:] if plain_text else plain_text