nonebot2/nonebot/drivers/__init__.py

270 lines
7.3 KiB
Python
Raw Normal View History

2020-10-10 23:40:01 +08:00
"""
后端驱动适配基类
2020-11-13 01:46:26 +08:00
=================
2020-10-10 23:40:01 +08:00
各驱动请继承以下基类
"""
2020-07-04 22:51:10 +08:00
2020-07-18 18:18:43 +08:00
import abc
2020-12-28 13:36:00 +08:00
import asyncio
from typing import Set, Dict, Type, Optional, Callable, TYPE_CHECKING
2020-07-04 22:51:10 +08:00
2020-08-14 17:41:24 +08:00
from nonebot.log import logger
2020-08-10 13:06:02 +08:00
from nonebot.config import Env, Config
2020-12-28 13:36:00 +08:00
from nonebot.typing import T_WebSocketConnectionHook, T_WebSocketDisconnectionHook
2020-12-06 02:30:19 +08:00
if TYPE_CHECKING:
2020-12-07 00:06:09 +08:00
from nonebot.adapters import Bot
2020-07-11 17:32:03 +08:00
2020-07-04 22:51:10 +08:00
2020-12-07 00:06:09 +08:00
class Driver(abc.ABC):
2020-10-10 23:40:01 +08:00
"""
Driver 基类将后端框架封装以满足适配器使用
"""
2020-12-06 02:30:19 +08:00
_adapters: Dict[str, Type["Bot"]] = {}
2020-10-10 23:40:01 +08:00
"""
:类型: ``Dict[str, Type[Bot]]``
:说明: 已注册的适配器列表
"""
2020-12-28 13:36:00 +08:00
_ws_connection_hook: Set[T_WebSocketConnectionHook] = set()
"""
:类型: ``Set[T_WebSocketConnectionHook]``
:说明: WebSocket 连接建立时执行的函数
"""
_ws_disconnection_hook: Set[T_WebSocketDisconnectionHook] = set()
"""
:类型: ``Set[T_WebSocketDisconnectionHook]``
:说明: WebSocket 连接断开时执行的函数
"""
2020-07-04 22:51:10 +08:00
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-08-10 13:06:02 +08:00
def __init__(self, env: Env, config: Config):
2020-10-16 01:10:46 +08:00
"""
:参数:
2020-11-13 01:46:26 +08:00
2020-10-16 01:10:46 +08:00
* ``env: Env``: 包含环境信息的 Env 对象
* ``config: Config``: 包含配置信息的 Config 对象
"""
2020-08-10 13:06:02 +08:00
self.env = env.environment
2020-10-16 01:10:46 +08:00
"""
:类型: ``str``
:说明: 环境名称
"""
2020-08-07 17:51:57 +08:00
self.config = config
2020-10-16 01:10:46 +08:00
"""
:类型: ``Config``
:说明: 配置对象
"""
2020-12-06 02:30:19 +08:00
self._clients: Dict[str, "Bot"] = {}
2020-10-16 01:10:46 +08:00
"""
:类型: ``Dict[str, Bot]``
:说明: 已连接的 Bot
"""
2020-08-13 15:23:04 +08:00
2021-02-05 13:31:33 +08:00
def register_adapter(self, name: str, adapter: Type["Bot"], **kwargs):
2020-10-16 01:10:46 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-16 01:10:46 +08:00
注册一个协议适配器
2020-11-30 11:08:00 +08:00
2020-10-16 01:10:46 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-10-16 01:10:46 +08:00
* ``name: str``: 适配器名称用于在连接时进行识别
* ``adapter: Type[Bot]``: 适配器 Class
"""
if name in self._adapters:
logger.opt(
colors=True).debug(f'Adapter "<y>{name}</y>" already exists')
return
2021-01-17 13:46:29 +08:00
self._adapters[name] = adapter
2021-02-05 13:31:33 +08:00
adapter.register(self, self.config, **kwargs)
2020-08-27 13:27:42 +08:00
logger.opt(
colors=True).debug(f'Succeeded to load adapter "<y>{name}</y>"')
2020-07-05 20:39:34 +08:00
2020-08-13 15:56:09 +08:00
@property
@abc.abstractmethod
def type(self):
2020-10-16 01:10:46 +08:00
"""驱动类型名称"""
2020-08-13 15:56:09 +08:00
raise NotImplementedError
2020-07-04 22:51:10 +08:00
@property
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-07-04 22:51:10 +08:00
def server_app(self):
2020-10-16 01:10:46 +08:00
"""驱动 APP 对象"""
2020-07-04 22:51:10 +08:00
raise NotImplementedError
@property
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-07-04 22:51:10 +08:00
def asgi(self):
2020-10-16 01:10:46 +08:00
"""驱动 ASGI 对象"""
2020-07-04 22:51:10 +08:00
raise NotImplementedError
@property
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-07-04 22:51:10 +08:00
def logger(self):
2020-10-16 01:10:46 +08:00
"""驱动专属 logger 日志记录器"""
2020-07-04 22:51:10 +08:00
raise NotImplementedError
2020-08-07 17:51:57 +08:00
@property
2020-12-06 02:30:19 +08:00
def bots(self) -> Dict[str, "Bot"]:
2020-10-16 01:10:46 +08:00
"""
2020-12-28 13:36:00 +08:00
:类型:
``Dict[str, Bot]``
:说明:
获取当前所有已连接的 Bot
2020-10-16 01:10:46 +08:00
"""
2020-08-07 17:51:57 +08:00
return self._clients
2020-08-11 10:44:05 +08:00
@abc.abstractmethod
def on_startup(self, func: Callable) -> Callable:
2020-10-16 01:10:46 +08:00
"""注册一个在驱动启动时运行的函数"""
2020-08-11 10:44:05 +08:00
raise NotImplementedError
@abc.abstractmethod
def on_shutdown(self, func: Callable) -> Callable:
2020-10-16 01:10:46 +08:00
"""注册一个在驱动停止时运行的函数"""
2020-08-11 10:44:05 +08:00
raise NotImplementedError
2020-12-28 13:36:00 +08:00
def on_bot_connect(
self, func: T_WebSocketConnectionHook) -> T_WebSocketConnectionHook:
"""
:说明:
装饰一个函数使他在 bot 通过 WebSocket 连接成功时执行
:函数参数:
* ``bot: Bot``: 当前连接上的 Bot 对象
"""
self._ws_connection_hook.add(func)
return func
def on_bot_disconnect(
self,
func: T_WebSocketDisconnectionHook) -> T_WebSocketDisconnectionHook:
2020-12-28 13:36:00 +08:00
"""
:说明:
装饰一个函数使他在 bot 通过 WebSocket 连接断开时执行
:函数参数:
* ``bot: Bot``: 当前连接上的 Bot 对象
"""
self._ws_disconnection_hook.add(func)
return func
2020-12-28 13:59:54 +08:00
def _bot_connect(self, bot: "Bot") -> None:
2020-12-28 13:36:00 +08:00
"""在 WebSocket 连接成功后,调用该函数来注册 bot 对象"""
self._clients[bot.self_id] = bot
async def _run_hook(bot: "Bot") -> None:
coros = list(map(lambda x: x(bot), self._ws_connection_hook))
if coros:
try:
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running WebSocketConnection hook. "
"Running cancelled!</bg #f8bbd0></r>")
asyncio.create_task(_run_hook(bot))
2020-12-28 13:59:54 +08:00
def _bot_disconnect(self, bot: "Bot") -> None:
2020-12-28 13:36:00 +08:00
"""在 WebSocket 连接断开后,调用该函数来注销 bot 对象"""
if bot.self_id in self._clients:
del self._clients[bot.self_id]
async def _run_hook(bot: "Bot") -> None:
coros = list(map(lambda x: x(bot), self._ws_disconnection_hook))
if coros:
try:
await asyncio.gather(*coros)
except Exception as e:
logger.opt(colors=True, exception=e).error(
"<r><bg #f8bbd0>Error when running WebSocketDisConnection hook. "
"Running cancelled!</bg #f8bbd0></r>")
asyncio.create_task(_run_hook(bot))
2020-12-28 13:36:00 +08:00
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-07-04 22:51:10 +08:00
def run(self,
2020-08-18 17:24:49 +08:00
host: Optional[str] = None,
2020-07-04 22:51:10 +08:00
port: Optional[int] = None,
*args,
**kwargs):
2020-10-16 01:10:46 +08:00
"""
:说明:
2020-11-30 11:08:00 +08:00
2020-10-16 01:10:46 +08:00
启动驱动框架
2020-11-30 11:08:00 +08:00
2020-10-16 01:10:46 +08:00
:参数:
2020-11-30 11:08:00 +08:00
2020-10-16 01:10:46 +08:00
* ``host: Optional[str]``: 驱动绑定 IP
* ``post: Optional[int]``: 驱动绑定端口
* ``*args``
* ``**kwargs``
"""
2020-12-02 13:25:57 +08:00
logger.opt(colors=True).debug(
f"<g>Loaded adapters: {', '.join(self._adapters)}</g>")
2020-07-05 20:39:34 +08:00
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-07-05 20:39:34 +08:00
async def _handle_http(self):
2020-10-16 01:10:46 +08:00
"""用于处理 HTTP 类型请求的函数"""
2020-07-05 20:39:34 +08:00
raise NotImplementedError
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-07-05 20:39:34 +08:00
async def _handle_ws_reverse(self):
2020-10-16 01:10:46 +08:00
"""用于处理 WebSocket 类型请求的函数"""
2020-07-05 20:39:34 +08:00
raise NotImplementedError
2020-07-11 17:32:03 +08:00
2020-12-07 00:06:09 +08:00
class WebSocket(object):
2020-10-16 01:10:46 +08:00
"""WebSocket 连接封装,统一接口方便外部调用。"""
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
def __init__(self, websocket):
2020-10-16 01:10:46 +08:00
"""
:参数:
2020-11-13 01:46:26 +08:00
2020-10-16 01:10:46 +08:00
* ``websocket: Any``: WebSocket 连接对象
"""
self._websocket = websocket
@property
def websocket(self):
2020-10-16 01:10:46 +08:00
"""WebSocket 连接对象"""
return self._websocket
@property
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
def closed(self):
2020-10-16 01:10:46 +08:00
"""
:类型: ``bool``
:说明: 连接是否已经关闭
"""
raise NotImplementedError
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
async def accept(self):
2020-10-16 01:10:46 +08:00
"""接受 WebSocket 连接请求"""
raise NotImplementedError
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
2020-08-01 22:03:40 +08:00
async def close(self, code: int):
2020-10-16 01:10:46 +08:00
"""关闭 WebSocket 连接请求"""
raise NotImplementedError
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
async def receive(self) -> dict:
2020-10-16 01:10:46 +08:00
"""接收一条 WebSocket 信息"""
raise NotImplementedError
2020-07-18 18:18:43 +08:00
@abc.abstractmethod
async def send(self, data: dict):
2020-10-16 01:10:46 +08:00
"""发送一条 WebSocket 信息"""
raise NotImplementedError