nonebot2/nonebot/adapters/_adapter.py

74 lines
2.2 KiB
Python
Raw Normal View History

2021-12-06 22:19:05 +08:00
import abc
from contextlib import asynccontextmanager
from typing import Any, Dict, AsyncGenerator
2021-12-06 22:19:05 +08:00
from nonebot.config import Config
from nonebot.drivers import (
Driver,
2021-12-20 00:28:02 +08:00
Request,
Response,
WebSocket,
2021-12-06 22:19:05 +08:00
ForwardDriver,
ReverseDriver,
HTTPServerSetup,
WebSocketServerSetup,
)
2022-01-15 21:27:43 +08:00
from ._bot import Bot
2021-12-06 22:19:05 +08:00
class Adapter(abc.ABC):
def __init__(self, driver: Driver, **kwargs: Any):
2021-12-07 02:16:18 +08:00
self.driver: Driver = driver
2021-12-06 22:19:05 +08:00
self.bots: Dict[str, Bot] = {}
@classmethod
@abc.abstractmethod
def get_name(cls) -> str:
raise NotImplementedError
@property
def config(self) -> Config:
return self.driver.config
2021-12-21 18:22:14 +08:00
def bot_connect(self, bot: Bot) -> None:
2021-12-06 22:19:05 +08:00
self.driver._bot_connect(bot)
self.bots[bot.self_id] = bot
2021-12-21 18:22:14 +08:00
def bot_disconnect(self, bot: Bot) -> None:
2021-12-06 22:19:05 +08:00
self.driver._bot_disconnect(bot)
self.bots.pop(bot.self_id, None)
def setup_http_server(self, setup: HTTPServerSetup):
if not isinstance(self.driver, ReverseDriver):
raise TypeError("Current driver does not support http server")
self.driver.setup_http_server(setup)
def setup_websocket_server(self, setup: WebSocketServerSetup):
if not isinstance(self.driver, ReverseDriver):
raise TypeError("Current driver does not support websocket server")
self.driver.setup_websocket_server(setup)
2021-12-20 00:28:02 +08:00
async def request(self, setup: Request) -> Response:
if not isinstance(self.driver, ForwardDriver):
raise TypeError("Current driver does not support http client")
return await self.driver.request(setup)
@asynccontextmanager
async def websocket(self, setup: Request) -> AsyncGenerator[WebSocket, None]:
2021-12-20 00:28:02 +08:00
if not isinstance(self.driver, ForwardDriver):
raise TypeError("Current driver does not support websocket client")
async with self.driver.websocket(setup) as ws:
yield ws
2021-12-20 00:28:02 +08:00
2021-12-06 22:19:05 +08:00
@abc.abstractmethod
2021-12-21 18:22:14 +08:00
async def _call_api(self, bot: Bot, api: str, **data) -> Any:
2021-12-06 22:19:05 +08:00
"""
2022-01-12 18:19:21 +08:00
`adapter` 实际调用 api 的逻辑实现函数实现该方法以调用 api
2021-12-06 22:19:05 +08:00
2022-01-12 18:31:12 +08:00
参数:
2022-01-12 19:10:29 +08:00
api: API 名称
**data: API 数据
2021-12-06 22:19:05 +08:00
"""
raise NotImplementedError