From bc5391d7116465f5131884f3c61b3b45c5e988c8 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 4 Jan 2021 13:27:49 +0800 Subject: [PATCH 01/86] :bug: ensure message is not empty --- nonebot/adapters/cqhttp/bot.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py index 1aff6d5d..d62ff829 100644 --- a/nonebot/adapters/cqhttp/bot.py +++ b/nonebot/adapters/cqhttp/bot.py @@ -82,6 +82,10 @@ def _check_at_me(bot: "Bot", event: "Event"): if not isinstance(event, MessageEvent): return + # ensure message not empty + if not event.message: + event.message.append(MessageSegment.text("")) + if event.message_type == "private": event.to_me = True else: From 2218fa2b3380d8977fcee813e2955d025da95e57 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 4 Jan 2021 18:09:42 +0800 Subject: [PATCH 02/86] :bug: fix missing return after close ws --- nonebot/drivers/fastapi.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nonebot/drivers/fastapi.py b/nonebot/drivers/fastapi.py index 42e21490..8a19a5c7 100644 --- a/nonebot/drivers/fastapi.py +++ b/nonebot/drivers/fastapi.py @@ -184,6 +184,7 @@ class Driver(BaseDriver): logger.warning("There's already a reverse websocket connection, " f"{adapter.upper()} Bot {x_self_id} ignored.") await ws.close(code=status.WS_1008_POLICY_VIOLATION) + return bot = BotClass(self, "websocket", self.config, x_self_id, websocket=ws) From 877fa1a75adaf7412b8f33505ea83ad0995dcde4 Mon Sep 17 00:00:00 2001 From: Artin Date: Mon, 4 Jan 2021 22:24:43 +0800 Subject: [PATCH 03/86] :bug: Fix cqhttp `Message` null parameter --- nonebot/adapters/cqhttp/message.py | 50 +++++++++++++++--------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/nonebot/adapters/cqhttp/message.py b/nonebot/adapters/cqhttp/message.py index 1a7bd538..e5981ad6 100644 --- a/nonebot/adapters/cqhttp/message.py +++ b/nonebot/adapters/cqhttp/message.py @@ -222,29 +222,29 @@ class Message(BaseMessage): for seg in msg: yield MessageSegment(seg["type"], seg.get("data") or {}) return + elif isinstance(msg, str): + def _iter_message(msg: str) -> Iterable[Tuple[str, str]]: + text_begin = 0 + for cqcode in re.finditer( + r"\[CQ:(?P[a-zA-Z0-9-_.]+)" + r"(?P" + r"(?:,[a-zA-Z0-9-_.]+=[^,\]]+)*" + r"),?\]", msg): + yield "text", msg[text_begin:cqcode.pos + cqcode.start()] + text_begin = cqcode.pos + cqcode.end() + yield cqcode.group("type"), cqcode.group("params").lstrip(",") + yield "text", msg[text_begin:] - def _iter_message(msg: str) -> Iterable[Tuple[str, str]]: - text_begin = 0 - for cqcode in re.finditer( - r"\[CQ:(?P[a-zA-Z0-9-_.]+)" - r"(?P" - r"(?:,[a-zA-Z0-9-_.]+=[^,\]]+)*" - r"),?\]", msg): - yield "text", msg[text_begin:cqcode.pos + cqcode.start()] - text_begin = cqcode.pos + cqcode.end() - yield cqcode.group("type"), cqcode.group("params").lstrip(",") - yield "text", msg[text_begin:] - - for type_, data in _iter_message(msg): - if type_ == "text": - if data: - # only yield non-empty text segment - yield MessageSegment(type_, {"text": unescape(data)}) - else: - data = { - k: unescape(v) for k, v in map( - lambda x: x.split("=", maxsplit=1), - filter(lambda x: x, ( - x.lstrip() for x in data.split(",")))) - } - yield MessageSegment(type_, data) + for type_, data in _iter_message(msg): + if type_ == "text": + if data: + # only yield non-empty text segment + yield MessageSegment(type_, {"text": unescape(data)}) + else: + data = { + k: unescape(v) for k, v in map( + lambda x: x.split("=", maxsplit=1), + filter(lambda x: x, ( + x.lstrip() for x in data.split(",")))) + } + yield MessageSegment(type_, data) From 60fd09241094650f0848dd1bdaf7a3305cf8dd8d Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 5 Jan 2021 12:12:41 +0800 Subject: [PATCH 04/86] :bug: fix none message --- nonebot/adapters/__init__.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/nonebot/adapters/__init__.py b/nonebot/adapters/__init__.py index 18c2e755..623d23e9 100644 --- a/nonebot/adapters/__init__.py +++ b/nonebot/adapters/__init__.py @@ -211,7 +211,7 @@ class Message(list, abc.ABC): """消息数组""" def __init__(self, - message: Union[str, Mapping, Iterable[Mapping], + message: Union[str, None, Mapping, Iterable[Mapping], T_MessageSegment, T_Message, Any] = None, *args, **kwargs): @@ -221,7 +221,9 @@ class Message(list, abc.ABC): * ``message: Union[str, list, dict, MessageSegment, Message, Any]``: 消息内容 """ super().__init__(*args, **kwargs) - if isinstance(message, Message): + if message is None: + return + elif isinstance(message, Message): self.extend(message) elif isinstance(message, MessageSegment): self.append(message) From 5abac3664713e623e58700f2108ba4cf2ffe9268 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E4=BA=91=E7=94=9F?= Date: Tue, 5 Jan 2021 22:48:59 +0800 Subject: [PATCH 05/86] Fix typo --- docs/api/config.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/config.md b/docs/api/config.md index 2e7c6a4d..a9c8ab2b 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -211,7 +211,7 @@ X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 ```default -SUPER_USERS=["12345789"] +SUPERUSERS=["12345789"] ``` From 9d31fcce2e6bcf5d19cef228128ad512aea7a36c Mon Sep 17 00:00:00 2001 From: theprimone Date: Tue, 5 Jan 2021 14:51:38 +0000 Subject: [PATCH 06/86] :memo: update api docs --- docs/api/config.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/config.md b/docs/api/config.md index a9c8ab2b..2e7c6a4d 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -211,7 +211,7 @@ X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 ```default -SUPERUSERS=["12345789"] +SUPER_USERS=["12345789"] ``` From 0c517acee24c299ee56bd3a72104d38fcc1b91a2 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 5 Jan 2021 23:06:36 +0800 Subject: [PATCH 07/86] :pencil2: fix config typo --- nonebot/config.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nonebot/config.py b/nonebot/config.py index 43ed4fbc..af5f67c1 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -229,7 +229,7 @@ class Config(BaseConfig): .. code-block:: default - SUPER_USERS=["12345789"] + SUPERUSERS=["12345789"] """ nickname: Set[str] = set() """ From fe3122adbd948eceeb26ebfca29422de64aa0748 Mon Sep 17 00:00:00 2001 From: theprimone Date: Tue, 5 Jan 2021 15:08:58 +0000 Subject: [PATCH 08/86] :memo: update api docs --- docs/api/config.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/config.md b/docs/api/config.md index 2e7c6a4d..a9c8ab2b 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -211,7 +211,7 @@ X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 ```default -SUPER_USERS=["12345789"] +SUPERUSERS=["12345789"] ``` From b6bf4775516ecc4e58d6e0595ee7bd8691bb502f Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Wed, 6 Jan 2021 18:29:24 +0800 Subject: [PATCH 09/86] :alembic: add got receive overload #142 --- nonebot/matcher.py | 32 +++++++++++++++++++++++++++-- tests/test_plugins/test_overload.py | 19 +++++++++++++++++ 2 files changed, 49 insertions(+), 2 deletions(-) create mode 100644 tests/test_plugins/test_overload.py diff --git a/nonebot/matcher.py b/nonebot/matcher.py index 4ab2c28f..a3531932 100644 --- a/nonebot/matcher.py +++ b/nonebot/matcher.py @@ -294,18 +294,27 @@ class Matcher(metaclass=MatcherMeta): * 无 """ - async def _receive(bot: "Bot", event: "Event", - state: T_State) -> NoReturn: + async def _receive(bot: "Bot", event: "Event") -> NoReturn: raise PausedException + cls.process_handler(_receive) + if cls.handlers: # 已有前置handlers则接受一条新的消息,否则视为接收初始消息 cls.append_handler(_receive) def _decorator(func: T_Handler) -> T_Handler: + cls.process_handler(func) if not cls.handlers or cls.handlers[-1] is not func: cls.append_handler(func) + _receive.__params__.update({ + "bot": + func.__params__["bot"], + "event": + func.__params__["event"] or _receive.__params__["event"] + }) + return func return _decorator @@ -368,6 +377,25 @@ class Matcher(metaclass=MatcherMeta): cls.append_handler(wrapper) + wrapper.__params__.update({ + "bot": + func.__params__["bot"], + "event": + func.__params__["event"] or wrapper.__params__["event"] + }) + _key_getter.__params__.update({ + "bot": + func.__params__["bot"], + "event": + func.__params__["event"] or wrapper.__params__["event"] + }) + _key_parser.__params__.update({ + "bot": + func.__params__["bot"], + "event": + func.__params__["event"] or wrapper.__params__["event"] + }) + return func return _decorator diff --git a/tests/test_plugins/test_overload.py b/tests/test_plugins/test_overload.py new file mode 100644 index 00000000..06712779 --- /dev/null +++ b/tests/test_plugins/test_overload.py @@ -0,0 +1,19 @@ +from nonebot import on_command +from nonebot.adapters.cqhttp import Bot, PrivateMessageEvent, GroupMessageEvent + +overload = on_command("overload") + + +@overload.handle() +async def handle_first_receive(bot: Bot): + return + + +@overload.got("message", prompt="群?") +async def handle_group(bot: Bot, event: GroupMessageEvent): + return + + +@overload.got("message", prompt="私?") +async def handle_private(bot: Bot, event: PrivateMessageEvent): + return From e7993a448590400599d17cded0004597854d4fe2 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Fri, 8 Jan 2021 18:14:18 +0800 Subject: [PATCH 10/86] :bug: fix plain text escaped --- nonebot/adapters/cqhttp/message.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/nonebot/adapters/cqhttp/message.py b/nonebot/adapters/cqhttp/message.py index e5981ad6..ce1190c8 100644 --- a/nonebot/adapters/cqhttp/message.py +++ b/nonebot/adapters/cqhttp/message.py @@ -1,4 +1,5 @@ import re +from functools import reduce from typing import Any, Dict, Union, Tuple, Mapping, Iterable, Optional from nonebot.typing import overrides @@ -223,6 +224,7 @@ class Message(BaseMessage): yield MessageSegment(seg["type"], seg.get("data") or {}) return elif isinstance(msg, str): + def _iter_message(msg: str) -> Iterable[Tuple[str, str]]: text_begin = 0 for cqcode in re.finditer( @@ -232,7 +234,8 @@ class Message(BaseMessage): r"),?\]", msg): yield "text", msg[text_begin:cqcode.pos + cqcode.start()] text_begin = cqcode.pos + cqcode.end() - yield cqcode.group("type"), cqcode.group("params").lstrip(",") + yield cqcode.group("type"), cqcode.group("params").lstrip( + ",") yield "text", msg[text_begin:] for type_, data in _iter_message(msg): @@ -248,3 +251,11 @@ class Message(BaseMessage): x.lstrip() for x in data.split(",")))) } yield MessageSegment(type_, data) + + def extract_plain_text(self) -> str: + + def _concat(x: str, y: MessageSegment) -> str: + return f"{x} {y.data['text']}" if y.is_text() else x + + plain_text = reduce(_concat, self, "") + return plain_text[1:] if plain_text else plain_text From 01fa2ece6e187dda47fb00b915cb3417f8fa5663 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 12 Jan 2021 15:48:31 +0800 Subject: [PATCH 11/86] :bug: fix wrong space strip --- nonebot/plugin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nonebot/plugin.py b/nonebot/plugin.py index de4073c9..560d8009 100644 --- a/nonebot/plugin.py +++ b/nonebot/plugin.py @@ -425,7 +425,7 @@ def on_command(cmd: Union[str, Tuple[str, ...]], segment = message.pop(0) new_message = message.__class__( str(segment) - [len(state["_prefix"]["raw_command"]):].strip()) # type: ignore + [len(state["_prefix"]["raw_command"]):].lstrip()) # type: ignore for new_segment in reversed(new_message): message.insert(0, new_segment) From 719858168e4e003d76c0e5608f0b70311d4630db Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 12 Jan 2021 17:27:23 +0800 Subject: [PATCH 12/86] :memo: update change log --- pages/changelog.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/pages/changelog.md b/pages/changelog.md index 68a29608..722cff25 100644 --- a/pages/changelog.md +++ b/pages/changelog.md @@ -4,6 +4,12 @@ sidebar: auto # 更新日志 +## v2.0.0a9 + +- 修复 `Message` 消息为 `None` 时的处理错误 +- 修复 `Message.extract_plain_text` 返回为转义字符串的问题 +- 修复命令处理错误地删除了后续空格 + ## v2.0.0a8 - 修改 typing 类型注释 From 9d047daef5b90c902f1398b57780a7c1a80d95ed Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 12 Jan 2021 17:55:27 +0800 Subject: [PATCH 13/86] :construction: move cqhttp config into adapter --- nonebot/adapters/cqhttp/bot.py | 13 +++++++++---- nonebot/adapters/cqhttp/config.py | 12 ++++++++++++ nonebot/config.py | 3 +++ 3 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 nonebot/adapters/cqhttp/config.py diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py index d62ff829..efc9a2d8 100644 --- a/nonebot/adapters/cqhttp/bot.py +++ b/nonebot/adapters/cqhttp/bot.py @@ -14,6 +14,7 @@ from nonebot.adapters import Bot as BaseBot from nonebot.exception import RequestDenied from .utils import log, escape +from .config import Config as CQHTTPConfig from .message import Message, MessageSegment from .event import Reply, Event, MessageEvent, get_event_model from .exception import NetworkError, ApiNotAvailable, ActionFailed @@ -226,6 +227,8 @@ class Bot(BaseBot): *, websocket: Optional["WebSocket"] = None): + self.cqhttp_config = CQHTTPConfig(**config.dict()) + super().__init__(driver, connection_type, config, @@ -252,6 +255,7 @@ class Bot(BaseBot): x_self_id = headers.get("x-self-id") x_signature = headers.get("x-signature") token = get_auth_bearer(headers.get("authorization")) + cqhttp_config = CQHTTPConfig(**driver.config.dict()) # 检查连接方式 if connection_type not in ["http", "websocket"]: @@ -264,7 +268,7 @@ class Bot(BaseBot): raise RequestDenied(400, "Missing X-Self-ID Header") # 检查签名 - secret = driver.config.secret + secret = cqhttp_config.cqhttp_secret if secret and connection_type == "http": if not x_signature: log("WARNING", "Missing Signature Header") @@ -275,7 +279,7 @@ class Bot(BaseBot): log("WARNING", "Signature Header is invalid") raise RequestDenied(403, "Signature is invalid") - access_token = driver.config.access_token + access_token = cqhttp_config.cqhttp_access_token if access_token and access_token != token: log( "WARNING", "Authorization Header is invalid" @@ -374,8 +378,9 @@ class Bot(BaseBot): api_root += "/" headers = {} - if self.config.access_token is not None: - headers["Authorization"] = "Bearer " + self.config.access_token + if self.cqhttp_config.cqhttp_access_token is not None: + headers[ + "Authorization"] = "Bearer " + self.cqhttp_config.cqhttp_access_token try: async with httpx.AsyncClient(headers=headers) as client: diff --git a/nonebot/adapters/cqhttp/config.py b/nonebot/adapters/cqhttp/config.py new file mode 100644 index 00000000..ff30f172 --- /dev/null +++ b/nonebot/adapters/cqhttp/config.py @@ -0,0 +1,12 @@ +from typing import Optional + +from pydantic import Field, BaseSettings + + +class Config(BaseSettings): + cqhttp_access_token: Optional[str] = Field(default=None, + alias="access_token") + cqhttp_secret: Optional[str] = Field(default=None, alias="secret") + + class Config: + extra = "ignore" diff --git a/nonebot/config.py b/nonebot/config.py index af5f67c1..ae5b6c4b 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -276,6 +276,9 @@ class Config(BaseConfig): SESSION_EXPIRE_TIMEOUT=P[DD]DT[HH]H[MM]M[SS]S # ISO 8601 """ + # adapter configs + # adapter configs are defined in adapter/config.py + # custom configs # custom configs can be assigned during nonebot.init # or from env file using json loads From a1d801ba14ea334cdef5f156aceb007bc588dfd4 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 12 Jan 2021 18:02:05 +0800 Subject: [PATCH 14/86] :alembic: new fastapi config settings --- nonebot/drivers/fastapi.py | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/nonebot/drivers/fastapi.py b/nonebot/drivers/fastapi.py index 8a19a5c7..24a430cc 100644 --- a/nonebot/drivers/fastapi.py +++ b/nonebot/drivers/fastapi.py @@ -14,18 +14,28 @@ import logging from typing import Optional, Callable import uvicorn +from pydantic import BaseSettings from fastapi.responses import Response from fastapi import Body, status, Request, FastAPI, HTTPException from starlette.websockets import WebSocketDisconnect, WebSocket as FastAPIWebSocket from nonebot.log import logger from nonebot.typing import overrides -from nonebot.config import Env, Config from nonebot.utils import DataclassEncoder from nonebot.exception import RequestDenied +from nonebot.config import Env, Config as NoneBotConfig from nonebot.drivers import Driver as BaseDriver, WebSocket as BaseWebSocket +class Config(BaseSettings): + fastapi_openapi_url: Optional[str] = None + fastapi_docs_url: Optional[str] = None + fastapi_redoc_url: Optional[str] = None + + class Config: + extra = "ignore" + + class Driver(BaseDriver): """ FastAPI 驱动框架 @@ -38,14 +48,16 @@ class Driver(BaseDriver): * ``/{adapter name}/ws/``: WebSocket 上报 """ - def __init__(self, env: Env, config: Config): + def __init__(self, env: Env, config: NoneBotConfig): super().__init__(env, config) + self.fastapi_config = Config(**config.dict()) + self._server_app = FastAPI( debug=config.debug, - openapi_url=None, - docs_url=None, - redoc_url=None, + openapi_url=self.fastapi_config.fastapi_openapi_url, + docs_url=self.fastapi_config.fastapi_docs_url, + redoc_url=self.fastapi_config.fastapi_redoc_url, ) self._server_app.post("/{adapter}/")(self._handle_http) From fcac6f8a0f20c531feafa1198424030777178e3c Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sat, 16 Jan 2021 11:10:54 +0800 Subject: [PATCH 15/86] :wheelchair: improve session id support --- nonebot/adapters/cqhttp/event.py | 104 +++++++++++++++++++++++++++++-- 1 file changed, 100 insertions(+), 4 deletions(-) diff --git a/nonebot/adapters/cqhttp/event.py b/nonebot/adapters/cqhttp/event.py index 678ce504..083d4d0c 100644 --- a/nonebot/adapters/cqhttp/event.py +++ b/nonebot/adapters/cqhttp/event.py @@ -219,6 +219,14 @@ class GroupUploadNoticeEvent(NoticeEvent): group_id: int file: File + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class GroupAdminNoticeEvent(NoticeEvent): """群管理员变动""" @@ -228,10 +236,18 @@ class GroupAdminNoticeEvent(NoticeEvent): user_id: int group_id: int - @overrides(Event) + @overrides(NoticeEvent) def is_tome(self) -> bool: return self.user_id == self.self_id + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class GroupDecreaseNoticeEvent(NoticeEvent): """群成员减少事件""" @@ -242,10 +258,18 @@ class GroupDecreaseNoticeEvent(NoticeEvent): group_id: int operator_id: int - @overrides(Event) + @overrides(NoticeEvent) def is_tome(self) -> bool: return self.user_id == self.self_id + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class GroupIncreaseNoticeEvent(NoticeEvent): """群成员增加事件""" @@ -256,10 +280,18 @@ class GroupIncreaseNoticeEvent(NoticeEvent): group_id: int operator_id: int - @overrides(Event) + @overrides(NoticeEvent) def is_tome(self) -> bool: return self.user_id == self.self_id + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class GroupBanNoticeEvent(NoticeEvent): """群禁言事件""" @@ -271,10 +303,18 @@ class GroupBanNoticeEvent(NoticeEvent): operator_id: int duration: int - @overrides(Event) + @overrides(NoticeEvent) def is_tome(self) -> bool: return self.user_id == self.self_id + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class FriendAddNoticeEvent(NoticeEvent): """好友添加事件""" @@ -282,6 +322,14 @@ class FriendAddNoticeEvent(NoticeEvent): notice_type: Literal["friend_add"] user_id: int + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class GroupRecallNoticeEvent(NoticeEvent): """群消息撤回事件""" @@ -296,6 +344,14 @@ class GroupRecallNoticeEvent(NoticeEvent): def is_tome(self) -> bool: return self.user_id == self.self_id + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class FriendRecallNoticeEvent(NoticeEvent): """好友消息撤回事件""" @@ -304,6 +360,14 @@ class FriendRecallNoticeEvent(NoticeEvent): user_id: int message_id: int + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class NotifyEvent(NoticeEvent): """提醒事件""" @@ -313,6 +377,14 @@ class NotifyEvent(NoticeEvent): user_id: int group_id: int + @overrides(NoticeEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(NoticeEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class PokeNotifyEvent(NotifyEvent): """戳一戳提醒事件""" @@ -336,6 +408,14 @@ class LuckyKingNotifyEvent(NotifyEvent): def is_tome(self) -> bool: return self.target_id == self.self_id + @overrides(NotifyEvent) + def get_user_id(self) -> str: + return str(self.target_id) + + @overrides(NotifyEvent) + def get_session_id(self) -> str: + return str(self.target_id) + class HonorNotifyEvent(NotifyEvent): """群荣誉变更提醒事件""" @@ -370,6 +450,14 @@ class FriendRequestEvent(RequestEvent): comment: str flag: str + @overrides(RequestEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(RequestEvent) + def get_session_id(self) -> str: + return str(self.user_id) + class GroupRequestEvent(RequestEvent): """加群请求/邀请事件""" @@ -381,6 +469,14 @@ class GroupRequestEvent(RequestEvent): comment: str flag: str + @overrides(RequestEvent) + def get_user_id(self) -> str: + return str(self.user_id) + + @overrides(RequestEvent) + def get_session_id(self) -> str: + return str(self.user_id) + # Meta Events class MetaEvent(Event): From 7c3b2b514a0b806ed9ebd8c9b959a9b3d8e02c54 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sat, 16 Jan 2021 11:47:48 +0800 Subject: [PATCH 16/86] :wheelchair: add request event approve reject --- nonebot/adapters/cqhttp/event.py | 24 +++++++++++++++++++++++- pages/changelog.md | 1 + 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/nonebot/adapters/cqhttp/event.py b/nonebot/adapters/cqhttp/event.py index 083d4d0c..2037577b 100644 --- a/nonebot/adapters/cqhttp/event.py +++ b/nonebot/adapters/cqhttp/event.py @@ -1,6 +1,6 @@ import inspect from typing_extensions import Literal -from typing import Type, List, Optional +from typing import Type, List, Optional, TYPE_CHECKING from pydantic import BaseModel from pygtrie import StringTrie @@ -11,6 +11,9 @@ from nonebot.adapters import Event as BaseEvent from .message import Message +if TYPE_CHECKING: + from .bot import Bot + class Event(BaseEvent): """ @@ -458,6 +461,14 @@ class FriendRequestEvent(RequestEvent): def get_session_id(self) -> str: return str(self.user_id) + async def approve(self, bot: "Bot", remark: str = ""): + return await bot.set_friend_add_request(flag=self.flag, + approve=True, + remark=remark) + + async def reject(self, bot: "Bot"): + return await bot.set_friend_add_request(flag=self.flag, approve=False) + class GroupRequestEvent(RequestEvent): """加群请求/邀请事件""" @@ -477,6 +488,17 @@ class GroupRequestEvent(RequestEvent): def get_session_id(self) -> str: return str(self.user_id) + async def approve(self, bot: "Bot"): + return await bot.set_group_add_request(flag=self.flag, + sub_type=self.sub_type, + approve=True) + + async def reject(self, bot: "Bot", reason: str = ""): + return await bot.set_group_add_request(flag=self.flag, + sub_type=self.sub_type, + approve=False, + reason=reason) + # Meta Events class MetaEvent(Event): diff --git a/pages/changelog.md b/pages/changelog.md index 722cff25..3c237913 100644 --- a/pages/changelog.md +++ b/pages/changelog.md @@ -9,6 +9,7 @@ sidebar: auto - 修复 `Message` 消息为 `None` 时的处理错误 - 修复 `Message.extract_plain_text` 返回为转义字符串的问题 - 修复命令处理错误地删除了后续空格 +- 增加好友添加和加群请求事件 `approve`, `reject` 方法 ## v2.0.0a8 From 9685a4b1bf70dbd39962ff0e879719d2e3e221ec Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sun, 17 Jan 2021 13:46:29 +0800 Subject: [PATCH 17/86] :alembic: seperate configs --- nonebot/adapters/__init__.py | 25 ++++++++++++++++--------- nonebot/adapters/cqhttp/bot.py | 26 ++++++++++++-------------- nonebot/adapters/cqhttp/config.py | 11 ++++++----- nonebot/adapters/ding/bot.py | 20 +++++++++++++------- nonebot/adapters/ding/config.py | 11 +++++++++++ nonebot/drivers/__init__.py | 6 +++--- 6 files changed, 61 insertions(+), 38 deletions(-) create mode 100644 nonebot/adapters/ding/config.py diff --git a/nonebot/adapters/__init__.py b/nonebot/adapters/__init__.py index 623d23e9..25928d87 100644 --- a/nonebot/adapters/__init__.py +++ b/nonebot/adapters/__init__.py @@ -14,10 +14,10 @@ from typing import Any, Dict, Union, TypeVar, Mapping, Optional, Callable, Itera from pydantic import BaseModel -from nonebot.config import Config from nonebot.utils import DataclassEncoder if TYPE_CHECKING: + from nonebot.config import Config from nonebot.drivers import Driver, WebSocket @@ -26,29 +26,26 @@ class Bot(abc.ABC): Bot 基类。用于处理上报消息,并提供 API 调用接口。 """ + driver: "Driver" + """Driver 对象""" + config: "Config" + """Config 配置对象""" + @abc.abstractmethod def __init__(self, - driver: "Driver", connection_type: str, - config: Config, self_id: str, *, 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 - """Driver 对象""" self.connection_type = connection_type """连接类型""" - self.config = config - """Config 配置对象""" self.self_id = self_id """机器人 ID""" self.websocket = websocket @@ -63,6 +60,16 @@ class Bot(abc.ABC): """Adapter 类型""" raise NotImplementedError + @classmethod + def register(cls, driver: "Driver", config: "Config"): + """ + :说明: + + `register` 方法会在 `driver.register_adapter` 时被调用,用于初始化相关配置 + """ + cls.driver = driver + cls.config = config + @classmethod @abc.abstractmethod async def check_permission(cls, driver: "Driver", connection_type: str, diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py index efc9a2d8..62fb4aad 100644 --- a/nonebot/adapters/cqhttp/bot.py +++ b/nonebot/adapters/cqhttp/bot.py @@ -7,7 +7,6 @@ from typing import Any, Dict, Union, Optional, TYPE_CHECKING import httpx from nonebot.log import logger -from nonebot.config import Config from nonebot.typing import overrides from nonebot.message import handle_event from nonebot.adapters import Bot as BaseBot @@ -20,6 +19,7 @@ from .event import Reply, Event, MessageEvent, get_event_model from .exception import NetworkError, ApiNotAvailable, ActionFailed if TYPE_CHECKING: + from nonebot.config import Config from nonebot.drivers import Driver, WebSocket @@ -218,22 +218,15 @@ class Bot(BaseBot): """ CQHTTP 协议 Bot 适配。继承属性参考 `BaseBot <./#class-basebot>`_ 。 """ + cqhttp_config: CQHTTPConfig def __init__(self, - driver: "Driver", connection_type: str, - config: Config, self_id: str, *, websocket: Optional["WebSocket"] = None): - self.cqhttp_config = CQHTTPConfig(**config.dict()) - - super().__init__(driver, - connection_type, - config, - self_id, - websocket=websocket) + super().__init__(connection_type, self_id, websocket=websocket) @property @overrides(BaseBot) @@ -243,6 +236,11 @@ class Bot(BaseBot): """ return "cqhttp" + @classmethod + def register(cls, driver: "Driver", config: "Config"): + super().register(driver, config) + cls.cqhttp_config = CQHTTPConfig(**config.dict()) + @classmethod @overrides(BaseBot) async def check_permission(cls, driver: "Driver", connection_type: str, @@ -268,7 +266,7 @@ class Bot(BaseBot): raise RequestDenied(400, "Missing X-Self-ID Header") # 检查签名 - secret = cqhttp_config.cqhttp_secret + secret = cqhttp_config.secret if secret and connection_type == "http": if not x_signature: log("WARNING", "Missing Signature Header") @@ -279,7 +277,7 @@ class Bot(BaseBot): log("WARNING", "Signature Header is invalid") raise RequestDenied(403, "Signature is invalid") - access_token = cqhttp_config.cqhttp_access_token + access_token = cqhttp_config.access_token if access_token and access_token != token: log( "WARNING", "Authorization Header is invalid" @@ -378,9 +376,9 @@ class Bot(BaseBot): api_root += "/" headers = {} - if self.cqhttp_config.cqhttp_access_token is not None: + if self.cqhttp_config.access_token is not None: headers[ - "Authorization"] = "Bearer " + self.cqhttp_config.cqhttp_access_token + "Authorization"] = "Bearer " + self.cqhttp_config.access_token try: async with httpx.AsyncClient(headers=headers) as client: diff --git a/nonebot/adapters/cqhttp/config.py b/nonebot/adapters/cqhttp/config.py index ff30f172..c537170a 100644 --- a/nonebot/adapters/cqhttp/config.py +++ b/nonebot/adapters/cqhttp/config.py @@ -1,12 +1,13 @@ from typing import Optional -from pydantic import Field, BaseSettings +from pydantic import Field, BaseModel -class Config(BaseSettings): - cqhttp_access_token: Optional[str] = Field(default=None, - alias="access_token") - cqhttp_secret: Optional[str] = Field(default=None, alias="secret") +# priority: alias > origin +class Config(BaseModel): + access_token: Optional[str] = Field(default=None, + alias="cqhttp_access_token") + secret: Optional[str] = Field(default=None, alias="cqhttp_secret") class Config: extra = "ignore" diff --git a/nonebot/adapters/ding/bot.py b/nonebot/adapters/ding/bot.py index e46febc5..0b87f44c 100644 --- a/nonebot/adapters/ding/bot.py +++ b/nonebot/adapters/ding/bot.py @@ -5,18 +5,19 @@ from typing import Any, Union, Optional, TYPE_CHECKING import httpx from nonebot.log import logger -from nonebot.config import Config from nonebot.typing import overrides from nonebot.message import handle_event from nonebot.adapters import Bot as BaseBot from nonebot.exception import RequestDenied from .utils import log +from .config import Config as DingConfig from .message import Message, MessageSegment from .exception import NetworkError, ApiNotAvailable, ActionFailed, SessionExpired -from .event import Event, MessageEvent, PrivateMessageEvent, GroupMessageEvent, ConversationType +from .event import MessageEvent, PrivateMessageEvent, GroupMessageEvent, ConversationType if TYPE_CHECKING: + from nonebot.config import Config from nonebot.drivers import Driver SEND_BY_SESSION_WEBHOOK = "send_by_sessionWebhook" @@ -26,11 +27,11 @@ class Bot(BaseBot): """ 钉钉 协议 Bot 适配。继承属性参考 `BaseBot <./#class-basebot>`_ 。 """ + ding_config: DingConfig - def __init__(self, driver: "Driver", connection_type: str, config: Config, - self_id: str, **kwargs): + def __init__(self, connection_type: str, self_id: str, **kwargs): - super().__init__(driver, connection_type, config, self_id, **kwargs) + super().__init__(connection_type, self_id, **kwargs) @property def type(self) -> str: @@ -39,6 +40,11 @@ class Bot(BaseBot): """ return "ding" + @classmethod + def register(cls, driver: "Driver", config: "Config"): + super().register(driver, config) + cls.ding_config = DingConfig(**config.dict()) + @classmethod @overrides(BaseBot) async def check_permission(cls, driver: "Driver", connection_type: str, @@ -61,7 +67,7 @@ class Bot(BaseBot): raise RequestDenied(400, "Missing `timestamp` Header") # 检查 sign - secret = driver.config.secret + secret = cls.ding_config.secret if secret: if not sign: log("WARNING", "Missing Signature Header") @@ -156,7 +162,7 @@ class Bot(BaseBot): async with httpx.AsyncClient(headers=headers) as client: response = await client.post( target, - params={"access_token": self.config.access_token}, + params={"access_token": self.ding_config.access_token}, json=message._produce(), timeout=self.config.api_timeout) diff --git a/nonebot/adapters/ding/config.py b/nonebot/adapters/ding/config.py new file mode 100644 index 00000000..5b334a94 --- /dev/null +++ b/nonebot/adapters/ding/config.py @@ -0,0 +1,11 @@ +from typing import Optional + +from pydantic import Field, BaseModel + + +class Config(BaseModel): + secret: Optional[str] = Field(default=None, alias="ding_secret") + access_token: Optional[str] = Field(default=None, alias="ding_access_token") + + class Config: + extra = "ignore" diff --git a/nonebot/drivers/__init__.py b/nonebot/drivers/__init__.py index 7e95ee91..986d59a3 100644 --- a/nonebot/drivers/__init__.py +++ b/nonebot/drivers/__init__.py @@ -62,8 +62,7 @@ class Driver(abc.ABC): :说明: 已连接的 Bot """ - @classmethod - def register_adapter(cls, name: str, adapter: Type["Bot"]): + def register_adapter(self, name: str, adapter: Type["Bot"]): """ :说明: @@ -74,7 +73,8 @@ class Driver(abc.ABC): * ``name: str``: 适配器名称,用于在连接时进行识别 * ``adapter: Type[Bot]``: 适配器 Class """ - cls._adapters[name] = adapter + self._adapters[name] = adapter + adapter.register(self, self.config) logger.opt( colors=True).debug(f'Succeeded to load adapter "{name}"') From b0a71b461fbebbc895ebc880236d33b3d39d90e2 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 18 Jan 2021 14:38:08 +0800 Subject: [PATCH 18/86] :heavy_plus_sign: missing aiofiles dependency for docs plugin --- packages/nonebot-plugin-docs/pyproject.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/nonebot-plugin-docs/pyproject.toml b/packages/nonebot-plugin-docs/pyproject.toml index 7f3a49bc..6f5bc9ea 100644 --- a/packages/nonebot-plugin-docs/pyproject.toml +++ b/packages/nonebot-plugin-docs/pyproject.toml @@ -14,6 +14,7 @@ include = ["nonebot_plugin_docs/dist/**/*"] [tool.poetry.dependencies] python = "^3.7" nonebot2 = "^2.0.0-alpha.1" +aiofiles = "^0.6.0" [tool.poetry.dev-dependencies] From 8973e66ec52aa4036d6420a365210a2fcb558944 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 18 Jan 2021 14:43:06 +0800 Subject: [PATCH 19/86] :construction_worker: update ci add cache --- .github/workflows/build_docs.yml | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/.github/workflows/build_docs.yml b/.github/workflows/build_docs.yml index 8f4b0dc2..8fdc2d9a 100644 --- a/.github/workflows/build_docs.yml +++ b/.github/workflows/build_docs.yml @@ -19,10 +19,17 @@ jobs: python-version: 3.8 architecture: "x64" - - name: Install Dependences + - uses: Gr1N/setup-poetry@v4 + + - uses: actions/cache@v1 + with: + path: ~/.cache/pypoetry/virtualenvs + key: ${{ runner.os }}-poetry-${{ hashFiles('poetry.lock') }} + restore-keys: | + ${{ runner.os }}-poetry- + + - name: Set up dependencies run: | - python -m pip install --upgrade pip - pip install poetry poetry install - name: Build Doc From a028766cf8a439c668d4096c797097f1fba8c108 Mon Sep 17 00:00:00 2001 From: StarHeart <947371563@qq.com> Date: Thu, 21 Jan 2021 07:41:12 +0800 Subject: [PATCH 20/86] Update creating-a-matcher.md --- archive/2.0.0a8.post2/guide/creating-a-matcher.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/archive/2.0.0a8.post2/guide/creating-a-matcher.md b/archive/2.0.0a8.post2/guide/creating-a-matcher.md index 182885fe..ac74f6c1 100644 --- a/archive/2.0.0a8.post2/guide/creating-a-matcher.md +++ b/archive/2.0.0a8.post2/guide/creating-a-matcher.md @@ -128,7 +128,7 @@ def check(arg1, args2): async def _checker(bot: Bot, event: Event, state: T_State) -> bool: return bool(arg1 + arg2) - return Rule(_check) + return Rule(_checker) ``` `Rule` 和 `RuleChecker` 之间可以使用 `与 &` 互相组合: From de0bca5c51fde600c3ee6db34dee399bd646b4b9 Mon Sep 17 00:00:00 2001 From: StarHeartHunt Date: Wed, 20 Jan 2021 23:42:48 +0000 Subject: [PATCH 21/86] :memo: update api docs --- docs/api/adapters/README.md | 37 ++++++++++++++++++++----------------- docs/api/drivers/README.md | 2 +- 2 files changed, 21 insertions(+), 18 deletions(-) diff --git a/docs/api/adapters/README.md b/docs/api/adapters/README.md index 96638ad5..42498ab2 100644 --- a/docs/api/adapters/README.md +++ b/docs/api/adapters/README.md @@ -17,21 +17,25 @@ sidebarDepth: 0 Bot 基类。用于处理上报消息,并提供 API 调用接口。 -### _abstract_ `__init__(driver, connection_type, config, self_id, *, websocket=None)` +### `driver` + +Driver 对象 + + +### `config` + +Config 配置对象 + + +### _abstract_ `__init__(connection_type, self_id, *, websocket=None)` * **参数** - * `driver: Driver`: Driver 对象 - - * `connection_type: str`: http 或者 websocket - * `config: Config`: Config 对象 - - * `self_id: str`: 机器人 ID @@ -39,21 +43,11 @@ Bot 基类。用于处理上报消息,并提供 API 调用接口。 -### `driver` - -Driver 对象 - - ### `connection_type` 连接类型 -### `config` - -Config 配置对象 - - ### `self_id` 机器人 ID @@ -69,6 +63,15 @@ Websocket 连接对象 Adapter 类型 +### _classmethod_ `register(driver, config)` + + +* **说明** + + register 方法会在 driver.register_adapter 时被调用,用于初始化相关配置 + + + ### _abstract async classmethod_ `check_permission(driver, connection_type, headers, body)` diff --git a/docs/api/drivers/README.md b/docs/api/drivers/README.md index 313717cb..77485ed2 100644 --- a/docs/api/drivers/README.md +++ b/docs/api/drivers/README.md @@ -120,7 +120,7 @@ Driver 基类。将后端框架封装,以满足适配器使用。 -### _classmethod_ `register_adapter(name, adapter)` +### `register_adapter(name, adapter)` * **说明** From fbf2eb638e7b757d453e2eeb29e16d7e36082fd1 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Thu, 21 Jan 2021 11:14:35 +0800 Subject: [PATCH 22/86] :pencil2: fix typo --- docs/guide/creating-a-matcher.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/guide/creating-a-matcher.md b/docs/guide/creating-a-matcher.md index 182885fe..ac74f6c1 100644 --- a/docs/guide/creating-a-matcher.md +++ b/docs/guide/creating-a-matcher.md @@ -128,7 +128,7 @@ def check(arg1, args2): async def _checker(bot: Bot, event: Event, state: T_State) -> bool: return bool(arg1 + arg2) - return Rule(_check) + return Rule(_checker) ``` `Rule` 和 `RuleChecker` 之间可以使用 `与 &` 互相组合: From 109125b583820c05ec1f2dd81f830c6b7b89095f Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Thu, 21 Jan 2021 12:41:52 +0800 Subject: [PATCH 23/86] :bug: remove args in creating bot --- nonebot/drivers/fastapi.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nonebot/drivers/fastapi.py b/nonebot/drivers/fastapi.py index 24a430cc..284b738b 100644 --- a/nonebot/drivers/fastapi.py +++ b/nonebot/drivers/fastapi.py @@ -165,7 +165,7 @@ class Driver(BaseDriver): logger.warning("There's already a reverse websocket connection," "so the event may be handled twice.") - bot = BotClass(self, "http", self.config, x_self_id) + bot = BotClass("http", x_self_id) asyncio.create_task(bot.handle_message(data)) return Response("", 204) @@ -198,7 +198,7 @@ class Driver(BaseDriver): await ws.close(code=status.WS_1008_POLICY_VIOLATION) return - bot = BotClass(self, "websocket", self.config, x_self_id, websocket=ws) + bot = BotClass("websocket", x_self_id, websocket=ws) await ws.accept() logger.opt(colors=True).info( From eb330c3260ede6e7bfac6ca8a8ae5d228f0110cb Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sun, 24 Jan 2021 14:36:11 +0800 Subject: [PATCH 24/86] :bug: fix plugin store pagination error --- docs/.vuepress/components/Plugins.vue | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/.vuepress/components/Plugins.vue b/docs/.vuepress/components/Plugins.vue index 5855fe67..59e6a449 100644 --- a/docs/.vuepress/components/Plugins.vue +++ b/docs/.vuepress/components/Plugins.vue @@ -44,7 +44,7 @@ @@ -126,6 +126,9 @@ export default { plugin.author.indexOf(this.filterText) != -1 ); }); + }, + displayPlugins() { + return this.filteredPlugins.slice((this.page - 1) * 10, this.page * 10); } }, methods: { From 853b797cd9f0c1ae95ab2fe76f0bcffd3f7a9481 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sun, 24 Jan 2021 18:16:18 +0800 Subject: [PATCH 25/86] :bug: change USER perm and temp matcher type --- nonebot/matcher.py | 4 ++-- nonebot/permission.py | 3 +-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/nonebot/matcher.py b/nonebot/matcher.py index a3531932..b82164e0 100644 --- a/nonebot/matcher.py +++ b/nonebot/matcher.py @@ -526,7 +526,7 @@ class Matcher(metaclass=MatcherMeta): except RejectedException: self.handlers.insert(0, handler) # type: ignore Matcher.new( - self.type, + "message", Rule(), USER(event.get_session_id(), perm=self.permission), # type:ignore @@ -539,7 +539,7 @@ class Matcher(metaclass=MatcherMeta): expire_time=datetime.now() + bot.config.session_expire_timeout) except PausedException: Matcher.new( - self.type, + "message", Rule(), USER(event.get_session_id(), perm=self.permission), # type:ignore diff --git a/nonebot/permission.py b/nonebot/permission.py index 751dae8b..04337c67 100644 --- a/nonebot/permission.py +++ b/nonebot/permission.py @@ -127,8 +127,7 @@ def USER(*user: str, perm: Permission = Permission()): """ async def _user(bot: "Bot", event: "Event") -> bool: - return event.get_type() == "message" and event.get_session_id( - ) in user and await perm(bot, event) + return event.get_session_id() in user and await perm(bot, event) return Permission(_user) From f8304406c52deafa5a91cbb66dd35077ce1a76cd Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 25 Jan 2021 18:15:25 +0800 Subject: [PATCH 26/86] :alembic: add new builtin plugin --- nonebot/plugin.py | 4 ++-- nonebot/plugin.pyi | 2 +- nonebot/plugins/{base.py => echo.py} | 0 nonebot/plugins/single_session.py | 20 ++++++++++++++++++++ 4 files changed, 23 insertions(+), 3 deletions(-) rename nonebot/plugins/{base.py => echo.py} (100%) create mode 100644 nonebot/plugins/single_session.py diff --git a/nonebot/plugin.py b/nonebot/plugin.py index 560d8009..f496e192 100644 --- a/nonebot/plugin.py +++ b/nonebot/plugin.py @@ -933,7 +933,7 @@ def load_plugins(*plugin_dir: str) -> Set[Plugin]: return loaded_plugins -def load_builtin_plugins() -> Optional[Plugin]: +def load_builtin_plugins(name: str = "echo") -> Optional[Plugin]: """ :说明: @@ -943,7 +943,7 @@ def load_builtin_plugins() -> Optional[Plugin]: - ``Plugin`` """ - return load_plugin("nonebot.plugins.base") + return load_plugin(f"nonebot.plugins.{name}") def get_plugin(name: str) -> Optional[Plugin]: diff --git a/nonebot/plugin.pyi b/nonebot/plugin.pyi index db31ad3d..85d925bf 100644 --- a/nonebot/plugin.pyi +++ b/nonebot/plugin.pyi @@ -168,7 +168,7 @@ def load_plugins(*plugin_dir: str) -> Set[Plugin]: ... -def load_builtin_plugins(): +def load_builtin_plugins(name: str = ...): ... diff --git a/nonebot/plugins/base.py b/nonebot/plugins/echo.py similarity index 100% rename from nonebot/plugins/base.py rename to nonebot/plugins/echo.py diff --git a/nonebot/plugins/single_session.py b/nonebot/plugins/single_session.py new file mode 100644 index 00000000..20eca034 --- /dev/null +++ b/nonebot/plugins/single_session.py @@ -0,0 +1,20 @@ +from typing import Dict, Optional + +from nonebot.typing import T_State +from nonebot.matcher import Matcher +from nonebot.adapters import Bot, Event +from nonebot.message import run_preprocessor, run_postprocessor, IgnoredException + +_running_matcher: Dict[str, bool] = {} + + +@run_preprocessor +async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State): + # TODO + pass + + +@run_postprocessor +async def _(matcher: Matcher, exception: Optional[Exception], bot: Bot, event: Event, state: T_State): + # TODO + pass From 2e75671d5617297a951b19748893d78afefa9e27 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 26 Jan 2021 15:03:37 +0800 Subject: [PATCH 27/86] :alembic: add processor to ensure single matcher --- nonebot/plugins/single_session.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/nonebot/plugins/single_session.py b/nonebot/plugins/single_session.py index 20eca034..8516b0c1 100644 --- a/nonebot/plugins/single_session.py +++ b/nonebot/plugins/single_session.py @@ -5,16 +5,22 @@ from nonebot.matcher import Matcher from nonebot.adapters import Bot, Event from nonebot.message import run_preprocessor, run_postprocessor, IgnoredException -_running_matcher: Dict[str, bool] = {} +_running_matcher: Dict[str, int] = {} @run_preprocessor async def _(matcher: Matcher, bot: Bot, event: Event, state: T_State): - # TODO - pass + session_id = event.get_session_id() + event_id = id(event) + + if _running_matcher.get(session_id, None) != event_id: + raise IgnoredException("Annother matcher running") + + _running_matcher[session_id] = event_id @run_postprocessor async def _(matcher: Matcher, exception: Optional[Exception], bot: Bot, event: Event, state: T_State): - # TODO - pass + session_id = event.get_session_id() + if session_id in _running_matcher: + del _running_matcher[session_id] From 5e3f1b5435ab8909e4673b4f6462ceacc866429b Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Wed, 27 Jan 2021 11:39:34 +0800 Subject: [PATCH 28/86] :sparkles: new common config loading from .env --- docs/guide/basic-configuration.md | 5 ++++- nonebot/__init__.py | 1 + nonebot/config.py | 32 ++++++++++++++++++++++++++++++- tests/.env | 1 + 4 files changed, 37 insertions(+), 2 deletions(-) diff --git a/docs/guide/basic-configuration.md b/docs/guide/basic-configuration.md index 0cd9156a..84ed8fe0 100644 --- a/docs/guide/basic-configuration.md +++ b/docs/guide/basic-configuration.md @@ -13,11 +13,14 @@ NoneBot 在启动时将会从系统环境变量或者 `.env` 文件中寻找变量 `ENVIRONMENT` (大小写不敏感),默认值为 `prod`。 这将引导 NoneBot 从系统环境变量或者 `.env.{ENVIRONMENT}` 文件中进一步加载具体配置。 +`.env` 文件是基础环境配置文件,该文件中的配置项在不同环境下都会被加载,但会被 `.env.{ENVIRONMENT}` 文件中的配置所覆盖。 + 现在,我们在 `.env` 文件中写入当前环境信息: ```bash # .env ENVIRONMENT=dev +CUSTOM_CONFIG=common config # 这个配置项在任何环境中都会被加载 ``` 如你所想,之后 NoneBot 就会从 `.env.dev` 文件中加载环境变量。 @@ -26,7 +29,7 @@ ENVIRONMENT=dev NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 进行配置管理,会从 `.env.{ENVIRONMENT}` 文件中获悉环境配置。 -可以在 NoneBot 初始化时指定加载某个环境配置文件: `nonebot.init(_env_file=".env.dev")`,这将忽略你在 `.env` 中设置的环境信息。 +可以在 NoneBot 初始化时指定加载某个环境配置文件: `nonebot.init(_env_file=".env.dev")`,这将忽略你在 `.env` 中设置的 `ENVIRONMENT` 。 :::warning 提示 由于 `pydantic` 使用 JSON 解析配置项,请确保配置项值为 JSON 格式的数据。如: diff --git a/nonebot/__init__.py b/nonebot/__init__.py index 11dad7cd..54857891 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -175,6 +175,7 @@ def init(*, _env_file: Optional[str] = None, **kwargs): logger.opt( colors=True).info(f"Current Env: {env.environment}") config = Config(**kwargs, + _common_config=env.dict(), _env_file=_env_file or f".env.{env.environment}") default_filter.level = "DEBUG" if config.debug else "INFO" diff --git a/nonebot/config.py b/nonebot/config.py index ae5b6c4b..9fb09e46 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -20,12 +20,41 @@ from datetime import timedelta from ipaddress import IPv4Address from typing import Any, Set, Dict, Union, Mapping, Optional +from pydantic.utils import deep_update from pydantic import BaseSettings, IPvAnyAddress from pydantic.env_settings import SettingsError, env_file_sentinel, read_env_file class BaseConfig(BaseSettings): + def __init__( + __pydantic_self__, # type: ignore + _common_config: Optional[Dict[Any, Any]] = None, + _env_file: Union[Path, str, None] = env_file_sentinel, + _env_file_encoding: Optional[str] = None, + _secrets_dir: Union[Path, str, None] = None, + **values: Any) -> None: + super(BaseSettings, + __pydantic_self__).__init__(**__pydantic_self__._build_values( + values, + _common_config=_common_config, + _env_file=_env_file, + _env_file_encoding=_env_file_encoding, + _secrets_dir=_secrets_dir)) + + def _build_values( + self, + init_kwargs: Dict[str, Any], + _common_config: Optional[Dict[Any, Any]] = None, + _env_file: Union[Path, str, None] = None, + _env_file_encoding: Optional[str] = None, + _secrets_dir: Union[Path, str, None] = None, + ) -> Dict[str, Any]: + return deep_update(self._build_secrets_files(_secrets_dir), + _common_config or {}, + self._build_environ(_env_file, + _env_file_encoding), init_kwargs) + def _build_environ( self, _env_file: Union[Path, str, None] = None, @@ -92,7 +121,7 @@ class BaseConfig(BaseSettings): return self.__dict__.get(name) -class Env(BaseSettings): +class Env(BaseConfig): """ 运行环境配置。大小写不敏感。 @@ -109,6 +138,7 @@ class Env(BaseSettings): """ class Config: + extra = "allow" env_file = ".env" diff --git a/tests/.env b/tests/.env index baf48fa8..9ef1d705 100644 --- a/tests/.env +++ b/tests/.env @@ -1 +1,2 @@ ENVIRONMENT=dev +CUSTOM_CONFIG=common From 115132a188dfd67ede1cc9b32124021c320a782c Mon Sep 17 00:00:00 2001 From: nonebot Date: Wed, 27 Jan 2021 03:46:47 +0000 Subject: [PATCH 29/86] :memo: update api docs --- docs/api/config.md | 2 +- docs/api/plugin.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/api/config.md b/docs/api/config.md index a9c8ab2b..654ea628 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -14,7 +14,7 @@ NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-d ## _class_ `Env` -基类:`pydantic.env_settings.BaseSettings` +基类:`nonebot.config.BaseConfig` 运行环境配置。大小写不敏感。 diff --git a/docs/api/plugin.md b/docs/api/plugin.md index 91e3e763..d1e379b7 100644 --- a/docs/api/plugin.md +++ b/docs/api/plugin.md @@ -1168,7 +1168,7 @@ def something_else(): -## `load_builtin_plugins()` +## `load_builtin_plugins(name='echo')` * **说明** From a6fcc1ea2af05494050763b50766282b2d3e198e Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Wed, 27 Jan 2021 12:08:22 +0800 Subject: [PATCH 30/86] :memo: add group link to doc --- docs/guide/installation.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/docs/guide/installation.md b/docs/guide/installation.md index 9beedaaa..b56da782 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -30,6 +30,12 @@ pip uninstall nonebot nb-cli: [![nb-cli](https://img.shields.io/github/stars/nonebot/nb-cli?style=social)](https://github.com/nonebot/nb-cli) +4. 如果有疑问,可以加群交流 (点击链接直达) + + [![QQ Chat](https://img.shields.io/badge/QQ%E7%BE%A4-768887710-orange?style=social)](https://jq.qq.com/?_wv=1027&k=5OFifDh) + + [![Telegram Chat](https://img.shields.io/badge/telegram-cqhttp-blue?style=social)](https://t.me/cqhttp) + ### 不使用脚手架(纯净安装) ```bash From 06837d4a563cb61160e4c4816e12a373f27fae88 Mon Sep 17 00:00:00 2001 From: Artin Date: Fri, 29 Jan 2021 14:29:29 +0800 Subject: [PATCH 31/86] :memo: add ding-guide --- docs/guide/ding-guide.md | 116 +++++++++++++++++++++++++++++++++- docs/guide/getting-started.md | 2 +- 2 files changed, 116 insertions(+), 2 deletions(-) diff --git a/docs/guide/ding-guide.md b/docs/guide/ding-guide.md index 88c62ca9..45a5a658 100644 --- a/docs/guide/ding-guide.md +++ b/docs/guide/ding-guide.md @@ -1,3 +1,117 @@ # 钉钉机器人使用指南 -~~TODO~~ +基于企业机器人的outgoing(回调)机制,用户@机器人之后,钉钉会将消息内容POST到开发者的消息接收地址。开发者解析出消息内容、发送者身份,根据企业的业务逻辑,组装响应的消息内容返回,钉钉会将响应内容发送到群里。 + +::: warning 只有企业内部机器人支持接收消息 +普通的机器人尚不支持应答机制,该机制指的是群里成员在聊天@机器人的时候,钉钉回调指定的服务地址,即Outgoing机器人。 +::: + +首先你需要有钉钉机器人的相关概念,请参阅相关文档: + +- [群机器人概述](https://developers.dingtalk.com/document/app/overview-of-group-robots) +- [开发企业内部机器人](https://developers.dingtalk.com/document/app/develop-enterprise-internal-robots) + +## 关于 DingAdapter 的说明 + +你需要显式的注册 ding 这个适配器: + +```python{2,6} +import nonebot +from nonebot.adapters.ding import Bot as DingBot + +nonebot.init() +driver = nonebot.get_driver() +driver.register_adapter("ding", DingBot) +nonebot.load_builtin_plugins() + +if __name__ == "__main__": + nonebot.run() +``` + +注册适配器的目的是将 `/ding` 这个路径挂载到程序上,并且和 DingBot 适配器关联起来。之后钉钉把收到的消息回调到 `http://xx.xxx.xxx.xxx:{port}/ding` 时,Nonebot 才知道要用什么适配器去处理该消息。 + +## 第一个命令 + +因为 Nonebot 可以根据你的命令处理函数的类型注解来选择使用什么 Adapter 进行处理,所以你如果需要使用钉钉相关的功能,你的 handler 中 `bot` 类型的注解需要是 DingBot 及其父类。 + +对于 Event 来说也是如此,Event 也可以根据标注来判断,比如一个 handler 的 event 标注位 `PrivateMessageEvent`,那这个 handler 只会处理私聊消息。 + +举个栗子: + +```python +test = on_command("test", to_me()) + + +@test.handle() +async def test_handler1(bot: DingBot, event: PrivateMessageEvent): + await test.finish("PrivateMessageEvent") + + +@test.handle() +async def test_handler2(bot: DingBot, event: GroupMessageEvent): + await test.finish("GroupMessageEvent") +``` + +这样 Nonebot 就会根据不同的类型注解使用不同的 handler 来处理消息。 + +## 多种消息格式 + +发送 markdown 消息: + +```python +@markdown.handle() +async def markdown_handler(bot: DingBot): + message = MessageSegment.markdown( + "Hello, This is NoneBot", + "#### NoneBot \n> Nonebot 是一款高性能的 Python 机器人框架\n> ![screenshot](https://v2.nonebot.dev/logo.png)\n> [GitHub 仓库地址](https://github.com/nonebot/nonebot2) \n" + ) + await markdown.finish(message) +``` + +可以按自己的需要发送原生的格式消息(需要使用 `MessageSegment` 包裹,可以很方便的实现 @ 等操作): + +```python +@raw.handle() +async def raw_handler(bot: DingBot, event: MessageEvent): + message = MessageSegment.raw({ + "msgtype": "text", + "text": { + "content": f"@{event.senderId},你好" + }, + }) + message += MessageSegment.atDingtalkIds(event.senderId) + await raw.send(message) +``` + +其他消息格式请查看 [钉钉适配器的 MessageSegment](https://github.com/nonebot/nonebot2/blob/master/nonebot/adapters/ding/message.py#L8),里面封装了很多有关消息的方法,比如 `code`、`image`、`feedCard` 等。 + +## 创建机器人并连接 + +在钉钉官方文档 「开发企业内部机器人 -> 步骤一:创建机器人应用] 中有详细介绍,这里就省去创建的步骤,介绍一下如何连接上程序。 + +### 本地开发机器人 + +在本地开发机器人的时候可能没有公网 IP,钉钉官方给我们提供一个 [内网穿透工具](https://developers.dingtalk.com/document/resourcedownload/http-intranet-penetration?pnamespace=app),方便开发测试。 + +::: tip +究其根源这是一个魔改版的 ngrok,钉钉提供了一个服务器。 + +本工具不保证稳定性,仅适用于开发测试阶段,禁止当作公网域名使用。如线上应用使用本工具造成稳定性问题,后果由自己承担。如使用本工具传播违法不良信息,钉钉将追究法律责任。 +::: + +官方文档里已经讲了如何使用。我们再以 Windows(终端使用 Powershell) 为例,来演示一下。 + +1. 将仓库 clone 到本地,打开 `windows_64` 文件夹。 +2. 执行 `.\ding.exe -config="./ding.cfg" -subdomain=rcnb 8080` 就可以将 8080 端口暴露到公网中。 + 你访问 http://rcnb.vaiwan.com/xxxxx 都会映射到 http://127.0.0.1:8080/xxxxx。 + +假设我们的机器人监听的端口是 `2333`,并且已经注册了钉钉适配器。那我们就执行 `.\ding.exe -config="./ding.cfg" -subdomain=rcnb 2333`,然后在机器人的后台设置 POST 的地址:`http://rcnb.vaiwan.com/ding`。 +这样钉钉接收到消息之后就会 POST 消息到 `http://rcnb.vaiwan.com/ding` 上,然后这个服务会把消息再转发到我们本地的开发服务器上。 + +### 生产模式 + +生产模式你的机器需要有一个公网 IP,然后到机器人的后台设置 POST 的地址就好了。 + +## 示例 + +关于钉钉机器人能做啥,你可以查看 `https://github.com/nonebot/nonebot2/blob/master/tests/test_plugins/test_ding.py`,里面有一些例子。 diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index d35665a2..b23a0de7 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -12,7 +12,7 @@ nb create 根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`。 -如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下(这里以 CQHTTP 为例): +如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下(这里以 CQHTTP 适配器为例): ```python{4,6,7,10} import nonebot From 27e06dd4e8fbe9e59c0bffa7d8e4173e2a532ba5 Mon Sep 17 00:00:00 2001 From: Artin Date: Fri, 29 Jan 2021 14:31:36 +0800 Subject: [PATCH 32/86] :bug: fix ding adapter 1. fix send `at_sender` 2. fix event parse error 3. `MessageSegment` add `atDingtalkIds`/`code` --- nonebot/adapters/ding/bot.py | 4 +- nonebot/adapters/ding/event.py | 2 +- nonebot/adapters/ding/message.py | 21 ++++++++++ tests/test_plugins/test_ding.py | 68 ++++++++++++++++++++++---------- 4 files changed, 72 insertions(+), 23 deletions(-) diff --git a/nonebot/adapters/ding/bot.py b/nonebot/adapters/ding/bot.py index 0b87f44c..cfe73fde 100644 --- a/nonebot/adapters/ding/bot.py +++ b/nonebot/adapters/ding/bot.py @@ -216,7 +216,9 @@ class Bot(BaseBot): params.update(kwargs) if at_sender and event.conversationType != ConversationType.private: - params["message"] = f"@{event.senderNick} " + msg + params[ + "message"] = f"@{event.senderId} " + msg + MessageSegment.atDingtalkIds( + event.senderId) else: params["message"] = msg diff --git a/nonebot/adapters/ding/event.py b/nonebot/adapters/ding/event.py index 23406df1..7dfdc2e1 100644 --- a/nonebot/adapters/ding/event.py +++ b/nonebot/adapters/ding/event.py @@ -77,7 +77,7 @@ class MessageEvent(Event): conversationId: str senderId: str senderNick: str - senderCorpId: str + senderCorpId: Optional[str] sessionWebhook: str sessionWebhookExpiredTime: int isAdmin: bool diff --git a/nonebot/adapters/ding/message.py b/nonebot/adapters/ding/message.py index f32774e0..5e609e11 100644 --- a/nonebot/adapters/ding/message.py +++ b/nonebot/adapters/ding/message.py @@ -44,6 +44,17 @@ class MessageSegment(BaseMessageSegment): """@指定手机号人员""" return MessageSegment("at", {"atMobiles": list(mobileNumber)}) + @staticmethod + def atDingtalkIds(*dingtalkIds: str) -> "MessageSegment": + """@指定 id,@ 默认会在消息段末尾。 + 所以你可以在消息中使用 @{senderId} 占位,发送出去之后 @ 就会出现在占位的位置: + ```python + message = MessageSegment.text(f"@{event.senderId},你好") + message += MessageSegment.atDingtalkIds(event.senderId) + ``` + """ + return MessageSegment("at", {"atDingtalkIds": list(dingtalkIds)}) + @staticmethod def text(text: str) -> "MessageSegment": """发送 ``text`` 类型消息""" @@ -59,6 +70,16 @@ class MessageSegment(BaseMessageSegment): """"标记 text 文本的 extension 属性,需要与 text 消息段相加。""" return MessageSegment("extension", dict_) + @staticmethod + def code(code_language: str, code: str) -> "Message": + """"发送 code 消息段""" + message = MessageSegment.text(code) + message += MessageSegment.extension({ + "text_type": "code_snippet", + "code_language": code_language + }) + return message + @staticmethod def markdown(title: str, text: str) -> "MessageSegment": """发送 ``markdown`` 类型消息""" diff --git a/tests/test_plugins/test_ding.py b/tests/test_plugins/test_ding.py index fca234eb..96c905d5 100644 --- a/tests/test_plugins/test_ding.py +++ b/tests/test_plugins/test_ding.py @@ -1,3 +1,4 @@ +from nonebot.adapters.ding.event import GroupMessageEvent, PrivateMessageEvent from nonebot.rule import to_me from nonebot.plugin import on_command from nonebot.adapters.ding import Bot as DingBot, MessageSegment, MessageEvent @@ -6,7 +7,7 @@ markdown = on_command("markdown", to_me()) @markdown.handle() -async def test_handler(bot: DingBot): +async def markdown_handler(bot: DingBot): message = MessageSegment.markdown( "Hello, This is NoneBot", "#### NoneBot \n> Nonebot 是一款高性能的 Python 机器人框架\n> ![screenshot](https://v2.nonebot.dev/logo.png)\n> [GitHub 仓库地址](https://github.com/nonebot/nonebot2) \n" @@ -18,7 +19,7 @@ actionCardSingleBtn = on_command("actionCardSingleBtn", to_me()) @actionCardSingleBtn.handle() -async def test_handler(bot: DingBot): +async def actionCardSingleBtn_handler(bot: DingBot): message = MessageSegment.actionCardSingleBtn( title="打造一间咖啡厅", text= @@ -32,7 +33,7 @@ actionCard = on_command("actionCard", to_me()) @actionCard.handle() -async def test_handler(bot: DingBot): +async def actionCard_handler(bot: DingBot): message = MessageSegment.raw({ "msgtype": "actionCard", "actionCard": { @@ -53,14 +54,14 @@ async def test_handler(bot: DingBot): }] } }) - await actionCard.finish(message) + await actionCard.finish(message, at_sender=True) feedCard = on_command("feedCard", to_me()) @feedCard.handle() -async def test_handler(bot: DingBot): +async def feedCard_handler(bot: DingBot): message = MessageSegment.raw({ "msgtype": "feedCard", "feedCard": { @@ -88,9 +89,11 @@ atme = on_command("atme", to_me()) @atme.handle() -async def test_handler(bot: DingBot, event: MessageEvent): - message = f"@{event.senderNick} at you" + MessageSegment.atMobiles( - "13800000001") +async def atme_handler(bot: DingBot, event: MessageEvent): + message = f"@{event.senderId} manually at you" + MessageSegment.atDingtalkIds( + event.senderId) + await atme.send("matcher send auto at you", at_sender=True) + await bot.send(event, "bot send auto at you", at_sender=True) await atme.finish(message) @@ -98,7 +101,7 @@ image = on_command("image", to_me()) @image.handle() -async def test_handler(bot: DingBot, event: MessageEvent): +async def image_handler(bot: DingBot, event: MessageEvent): message = MessageSegment.image( "https://static-aliyun-doc.oss-accelerate.aliyuncs.com/assets/img/zh-CN/0634199951/p158167.png" ) @@ -109,7 +112,7 @@ textAdd = on_command("t", to_me()) @textAdd.handle() -async def test_handler(bot: DingBot, event: MessageEvent): +async def textAdd_handler(bot: DingBot, event: MessageEvent): message = "第一段消息\n" + MessageSegment.text("asdawefaefa\n") await textAdd.send(message) @@ -129,17 +132,8 @@ code = on_command("code", to_me()) @code.handle() -async def test_handler(bot: DingBot, event: MessageEvent): - raw = MessageSegment.raw({ - "msgtype": "text", - "text": { - "content": 'print("hello world")' - }, - "extension": { - "text_type": "code_snippet", - "code_language": "Python", - } - }) +async def code_handler(bot: DingBot, event: MessageEvent): + raw = MessageSegment.code("Python", 'print("hello world")') await code.send(raw) message = MessageSegment.text("""using System; @@ -158,3 +152,35 @@ namespace HelloWorld "code_language": "C#" }) await code.finish(message) + + +test_message = on_command("test_message", to_me()) + + +@test_message.handle() +async def test_message_handler1(bot: DingBot, event: PrivateMessageEvent): + await test_message.finish("PrivateMessageEvent") + + +@test_message.handle() +async def test_message_handler2(bot: DingBot, event: GroupMessageEvent): + await test_message.finish("GroupMessageEvent") + + +hello = on_command("hello", to_me()) + + +@hello.handle() +async def hello_handler(bot: DingBot, event: MessageEvent): + message = MessageSegment.raw({ + "msgtype": "text", + "text": { + "content": 'hello ' + }, + }) + message += MessageSegment.atDingtalkIds(event.senderId) + await hello.send(message) + + message = MessageSegment.text(f"@{event.senderId},你好") + message += MessageSegment.atDingtalkIds(event.senderId) + await hello.finish(message) From 5f6a2fffc558cfacac5f9708c3267633ec423309 Mon Sep 17 00:00:00 2001 From: Artin Date: Fri, 29 Jan 2021 14:41:04 +0800 Subject: [PATCH 33/86] :memo: update ding-guide --- docs/guide/ding-guide.md | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/guide/ding-guide.md b/docs/guide/ding-guide.md index 45a5a658..c23c6827 100644 --- a/docs/guide/ding-guide.md +++ b/docs/guide/ding-guide.md @@ -54,6 +54,8 @@ async def test_handler2(bot: DingBot, event: GroupMessageEvent): 这样 Nonebot 就会根据不同的类型注解使用不同的 handler 来处理消息。 +可以查看 Nonebot 官方的这个例子:,更详细的了解一个 Bot 的结构。 + ## 多种消息格式 发送 markdown 消息: @@ -83,11 +85,11 @@ async def raw_handler(bot: DingBot, event: MessageEvent): await raw.send(message) ``` -其他消息格式请查看 [钉钉适配器的 MessageSegment](https://github.com/nonebot/nonebot2/blob/master/nonebot/adapters/ding/message.py#L8),里面封装了很多有关消息的方法,比如 `code`、`image`、`feedCard` 等。 +其他消息格式请查看 [钉钉适配器的 MessageSegment](https://github.com/nonebot/nonebot2/blob/dev/nonebot/adapters/ding/message.py#L8),里面封装了很多有关消息的方法,比如 `code`、`image`、`feedCard` 等。 ## 创建机器人并连接 -在钉钉官方文档 「开发企业内部机器人 -> 步骤一:创建机器人应用] 中有详细介绍,这里就省去创建的步骤,介绍一下如何连接上程序。 +在钉钉官方文档 [「开发企业内部机器人 -> 步骤一:创建机器人应用」](https://developers.dingtalk.com/document/app/develop-enterprise-internal-robots/title-ufs-4gh-poh) 中有详细介绍,这里就省去创建的步骤,介绍一下如何连接上程序。 ### 本地开发机器人 @@ -103,7 +105,7 @@ async def raw_handler(bot: DingBot, event: MessageEvent): 1. 将仓库 clone 到本地,打开 `windows_64` 文件夹。 2. 执行 `.\ding.exe -config="./ding.cfg" -subdomain=rcnb 8080` 就可以将 8080 端口暴露到公网中。 - 你访问 http://rcnb.vaiwan.com/xxxxx 都会映射到 http://127.0.0.1:8080/xxxxx。 + 你访问 都会映射到 。 假设我们的机器人监听的端口是 `2333`,并且已经注册了钉钉适配器。那我们就执行 `.\ding.exe -config="./ding.cfg" -subdomain=rcnb 2333`,然后在机器人的后台设置 POST 的地址:`http://rcnb.vaiwan.com/ding`。 这样钉钉接收到消息之后就会 POST 消息到 `http://rcnb.vaiwan.com/ding` 上,然后这个服务会把消息再转发到我们本地的开发服务器上。 @@ -114,4 +116,4 @@ async def raw_handler(bot: DingBot, event: MessageEvent): ## 示例 -关于钉钉机器人能做啥,你可以查看 `https://github.com/nonebot/nonebot2/blob/master/tests/test_plugins/test_ding.py`,里面有一些例子。 +关于钉钉机器人能做啥,你可以查看 `https://github.com/nonebot/nonebot2/blob/dev/tests/test_plugins/test_ding.py`,里面有一些例子。 From 8574b2ec72365ab07bf21b7d9a2ac85cb5378599 Mon Sep 17 00:00:00 2001 From: Mix Date: Fri, 29 Jan 2021 17:37:44 +0800 Subject: [PATCH 34/86] :construction: start working on mirai-api-http adapter --- nonebot/adapters/mirai/__init__.py | 1 + nonebot/adapters/mirai/bot.py | 39 ++++++++++++++++++++++++++++++ nonebot/adapters/mirai/message.py | 1 + 3 files changed, 41 insertions(+) create mode 100644 nonebot/adapters/mirai/__init__.py create mode 100644 nonebot/adapters/mirai/bot.py create mode 100644 nonebot/adapters/mirai/message.py diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py new file mode 100644 index 00000000..c832d378 --- /dev/null +++ b/nonebot/adapters/mirai/__init__.py @@ -0,0 +1 @@ +from .bot import MiraiBot \ No newline at end of file diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py new file mode 100644 index 00000000..8b192b37 --- /dev/null +++ b/nonebot/adapters/mirai/bot.py @@ -0,0 +1,39 @@ +from pprint import pprint +from typing import Optional + +from nonebot.adapters import Bot as BaseBot +from nonebot.drivers import Driver, WebSocket +from nonebot.typing import overrides + + +class MiraiBot(BaseBot): + + def __init__(self, + connection_type: str, + self_id: str, + *, + websocket: Optional["WebSocket"] = None): + super().__init__(connection_type, self_id, websocket=websocket) + + @property + @overrides(BaseBot) + def type(self) -> str: + return "mirai" + + @classmethod + @overrides(BaseBot) + async def check_permission(cls, driver: "Driver", connection_type: str, + headers: dict, body: Optional[dict]) -> str: + return '' + + @overrides(BaseBot) + async def handle_message(self, message: dict): + pprint(message) + + @overrides(BaseBot) + async def call_api(self, api: str, **data): + return super().call_api(api, **data) + + @overrides(BaseBot) + async def send(self, event: "Event", message: str, **kwargs): + return super().send(event, message, **kwargs) diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py new file mode 100644 index 00000000..edf1b6d0 --- /dev/null +++ b/nonebot/adapters/mirai/message.py @@ -0,0 +1 @@ +from nonebot.adapters import Message \ No newline at end of file From 5a9798121c7a8e8861d298b39870824d7f5fa9fb Mon Sep 17 00:00:00 2001 From: Mix Date: Fri, 29 Jan 2021 17:38:39 +0800 Subject: [PATCH 35/86] :construction: add some support for mirai basic events --- nonebot/adapters/mirai/event/__init__.py | 0 nonebot/adapters/mirai/event/base.py | 65 +++++++++++ nonebot/adapters/mirai/event/constants.py | 31 ++++++ nonebot/adapters/mirai/event/notice.py | 130 ++++++++++++++++++++++ nonebot/adapters/mirai/event/request.py | 1 + 5 files changed, 227 insertions(+) create mode 100644 nonebot/adapters/mirai/event/__init__.py create mode 100644 nonebot/adapters/mirai/event/base.py create mode 100644 nonebot/adapters/mirai/event/constants.py create mode 100644 nonebot/adapters/mirai/event/notice.py create mode 100644 nonebot/adapters/mirai/event/request.py diff --git a/nonebot/adapters/mirai/event/__init__.py b/nonebot/adapters/mirai/event/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py new file mode 100644 index 00000000..7b18c39a --- /dev/null +++ b/nonebot/adapters/mirai/event/base.py @@ -0,0 +1,65 @@ +from enum import Enum + +from pydantic import BaseModel, Field +from typing_extensions import Literal + +from nonebot.adapters import Event as BaseEvent +from nonebot.adapters import Message as BaseMessage +from nonebot.typing import overrides + +from .constants import EVENT_TYPES + + +class SenderPermission(str, Enum): + OWNER = 'OWNER' + ADMINISTRATOR = 'ADMINISTRATOR' + MEMBER = 'MEMBER' + + +class SenderGroup(BaseModel): + id: int + name: str + permission: SenderPermission + + +class SenderInfo(BaseModel): + id: int + name: str = Field(alias='memberName') + permission: SenderPermission + group: SenderGroup + + +class Event(BaseEvent): + type: str + + @overrides(BaseEvent) + def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: + return EVENT_TYPES.get(self.type, 'meta_event') + + @overrides(BaseEvent) + def get_event_name(self) -> str: + return self.type + + @overrides(BaseEvent) + def get_event_description(self) -> str: + return str(self.dict()) + + @overrides(BaseEvent) + def get_message(self) -> BaseMessage: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def get_plaintext(self) -> str: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def get_user_id(self) -> str: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def get_session_id(self) -> str: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def is_tome(self) -> bool: + return False diff --git a/nonebot/adapters/mirai/event/constants.py b/nonebot/adapters/mirai/event/constants.py new file mode 100644 index 00000000..1ede39a8 --- /dev/null +++ b/nonebot/adapters/mirai/event/constants.py @@ -0,0 +1,31 @@ +from typing import List, Dict +from typing_extensions import Literal + +EventType = Literal["message", "notice", "request", "meta_event"] + +_EVENT_CLASSIFY: Dict[EventType, List[str]] = { + # XXX Reference: https://github.com/project-mirai/mirai-api-http/blob/v1.9.7/docs/EventType.md + 'meta_event': [ + 'BotOnlineEvent', 'BotOfflineEventActive', 'BotOfflineEventForce', + 'BotOfflineEventDropped', 'BotReloginEvent' + ], + 'notice': [ + 'BotGroupPermissionChangeEvent', 'BotMuteEvent', 'BotUnmuteEvent', + 'BotJoinGroupEvent', 'BotLeaveEventActive', 'BotLeaveEventKick', + 'GroupRecallEvent', 'FriendRecallEvent', 'GroupNameChangeEvent', + 'GroupEntranceAnnouncementChangeEvent', 'GroupMuteAllEvent', + 'GroupAllowAnonymousChatEvent', 'GroupAllowConfessTalkEvent', + 'GroupAllowMemberInviteEvent', 'MemberJoinEvent', + 'MemberLeaveEventKick', 'MemberLeaveEventQuit', 'MemberCardChangeEvent', + 'MemberSpecialTitleChangeEvent', 'MemberPermissionChangeEvent', + 'MemberMuteEvent', 'MemberUnmuteEvent' + ], + 'request': [ + 'NewFriendRequestEvent', 'MemberJoinRequestEvent', + 'BotInvitedJoinGroupRequestEvent' + ], + 'message': ['GroupMessage', 'FriendMessage', 'TempMessage'] +} +EVENT_TYPES: Dict[str, EventType] = {} +for event_type, events in _EVENT_CLASSIFY.items(): + _EVENT_TYPES.update({k: event_type for k in events}) # type: ignore diff --git a/nonebot/adapters/mirai/event/notice.py b/nonebot/adapters/mirai/event/notice.py new file mode 100644 index 00000000..536bc12b --- /dev/null +++ b/nonebot/adapters/mirai/event/notice.py @@ -0,0 +1,130 @@ +from typing import Optional, Any + +from pydantic import Field + +from .base import Event, SenderGroup, SenderInfo, SenderPermission + + +class BaseNoticeEvent(Event): + pass + + +class BaseMuteEvent(BaseNoticeEvent): + operator: SenderInfo + + +class BotMuteEvent(BaseMuteEvent): + pass + + +class BotUnmuteEvent(BaseMuteEvent): + pass + + +class MemberMuteEvent(BaseMuteEvent): + duration_seconds: int = Field(alias='durationSeconds') + member: SenderInfo + operator: Optional[SenderInfo] = None + + +class MemberUnmuteEvent(BaseMuteEvent): + member: SenderInfo + operator: Optional[SenderInfo] = None + + +class BotJoinGroupEvent(BaseNoticeEvent): + group: SenderGroup + + +class BotLeaveEventActive(BotJoinGroupEvent): + pass + + +class BotLeaveEventKick(BotJoinGroupEvent): + pass + + +class MemberJoinEvent(BaseNoticeEvent): + member: SenderInfo + + +class MemberLeaveEventQuit(MemberJoinEvent): + pass + + +class MemberLeaveEventKick(MemberJoinEvent): + operator: Optional[SenderInfo] = None + + +class FriendRecallEvent(BaseNoticeEvent): + author_id: int = Field(alias='authorId') + message_id: int = Field(alias='messageId') + time: int + operator: int + + +class GroupRecallEvent(FriendRecallEvent): + group: SenderGroup + operator: Optional[SenderInfo] = None + + +class GroupStateChangeEvent(BaseNoticeEvent): + origin: Any + current: Any + group: SenderGroup + operator: Optional[SenderInfo] = None + + +class GroupNameChangeEvent(GroupStateChangeEvent): + origin: str + current: str + + +class GroupEntranceAnnouncementChangeEvent(GroupStateChangeEvent): + origin: str + current: str + + +class GroupMuteAllEvent(GroupStateChangeEvent): + origin: bool + current: bool + + +class GroupAllowAnonymousChatEvent(GroupStateChangeEvent): + origin: bool + current: bool + + +class GroupAllowConfessTalkEvent(GroupStateChangeEvent): + origin: bool + current: bool + + +class GroupAllowMemberInviteEvent(GroupStateChangeEvent): + origin: bool + current: bool + + +class MemberStateChangeEvent(BaseNoticeEvent): + member: SenderInfo + operator: Optional[SenderInfo] = None + + +class MemberCardChangeEvent(MemberStateChangeEvent): + origin: str + current: str + + +class MemberSpecialTitleChangeEvent(MemberStateChangeEvent): + origin: str + current: str + + +class BotGroupPermissionChangeEvent(MemberStateChangeEvent): + origin: SenderPermission + current: SenderPermission + + +class MemberPermissionChangeEvent(MemberStateChangeEvent): + origin: SenderPermission + current: SenderPermission diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py new file mode 100644 index 00000000..7e813f29 --- /dev/null +++ b/nonebot/adapters/mirai/event/request.py @@ -0,0 +1 @@ +from .base import Event From 0bb0d16d939aadd9c6a62b28e007067146d98dcc Mon Sep 17 00:00:00 2001 From: Mix Date: Fri, 29 Jan 2021 21:19:13 +0800 Subject: [PATCH 36/86] :construction: basically completed event serialize --- nonebot/adapters/mirai/bot.py | 9 +- nonebot/adapters/mirai/event/__init__.py | 4 + nonebot/adapters/mirai/event/base.py | 51 +++++++++-- nonebot/adapters/mirai/event/constants.py | 31 ------- nonebot/adapters/mirai/event/message.py | 40 +++++++++ nonebot/adapters/mirai/event/notice.py | 22 ++--- nonebot/adapters/mirai/event/request.py | 25 ++++++ nonebot/adapters/mirai/message.py | 101 +++++++++++++++++++++- 8 files changed, 233 insertions(+), 50 deletions(-) delete mode 100644 nonebot/adapters/mirai/event/constants.py create mode 100644 nonebot/adapters/mirai/event/message.py diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 8b192b37..d5034cd4 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -2,9 +2,13 @@ from pprint import pprint from typing import Optional from nonebot.adapters import Bot as BaseBot +from nonebot.adapters import Event as BaseEvent from nonebot.drivers import Driver, WebSocket +from nonebot.message import handle_event from nonebot.typing import overrides +from .event import Event + class MiraiBot(BaseBot): @@ -28,12 +32,13 @@ class MiraiBot(BaseBot): @overrides(BaseBot) async def handle_message(self, message: dict): - pprint(message) + event = Event.new(message) + await handle_event(self, event) @overrides(BaseBot) async def call_api(self, api: str, **data): return super().call_api(api, **data) @overrides(BaseBot) - async def send(self, event: "Event", message: str, **kwargs): + async def send(self, event: "BaseEvent", message: str, **kwargs): return super().send(event, message, **kwargs) diff --git a/nonebot/adapters/mirai/event/__init__.py b/nonebot/adapters/mirai/event/__init__.py index e69de29b..903f4eb8 100644 --- a/nonebot/adapters/mirai/event/__init__.py +++ b/nonebot/adapters/mirai/event/__init__.py @@ -0,0 +1,4 @@ +from .base import Event, SenderInfo, PrivateSenderInfo, SenderGroup +from .message import * +from .notice import * +from .request import * \ No newline at end of file diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 7b18c39a..451a858e 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -1,13 +1,12 @@ from enum import Enum - -from pydantic import BaseModel, Field +from typing import Dict, Any, Optional, Type +from pydantic import BaseModel, Field, ValidationError from typing_extensions import Literal from nonebot.adapters import Event as BaseEvent from nonebot.adapters import Message as BaseMessage from nonebot.typing import overrides - -from .constants import EVENT_TYPES +from nonebot.log import logger class SenderPermission(str, Enum): @@ -29,12 +28,54 @@ class SenderInfo(BaseModel): group: SenderGroup +class PrivateSenderInfo(BaseModel): + id: int + nickname: str + remark: str + + class Event(BaseEvent): type: str + @classmethod + def new(cls, data: Dict[str, Any]) -> "Event": + type = data['type'] + + def all_subclasses(cls: Type[Event]): + return set(cls.__subclasses__()).union( + [s for c in cls.__subclasses__() for s in all_subclasses(c)]) + + event_class: Optional[Type[Event]] = None + for subclass in all_subclasses(cls): + if subclass.__name__ != type: + continue + event_class = subclass + + if event_class is None: + return Event.parse_obj(data) + + while issubclass(event_class, Event): + try: + return event_class.parse_obj(data) + except ValidationError as e: + logger.info( + f'Failed to parse {data} to class {event_class.__name__}: {e}. ' + 'Fallback to parent class.') + event_class = event_class.__base__ + + raise ValueError(f'Failed to serialize {data}.') + @overrides(BaseEvent) def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: - return EVENT_TYPES.get(self.type, 'meta_event') + from . import message, notice, request + if isinstance(self, message.MessageEvent): + return 'message' + elif isinstance(self, notice.NoticeEvent): + return 'notice' + elif isinstance(self, request.RequestEvent): + return 'request' + else: + return 'meta_event' @overrides(BaseEvent) def get_event_name(self) -> str: diff --git a/nonebot/adapters/mirai/event/constants.py b/nonebot/adapters/mirai/event/constants.py deleted file mode 100644 index 1ede39a8..00000000 --- a/nonebot/adapters/mirai/event/constants.py +++ /dev/null @@ -1,31 +0,0 @@ -from typing import List, Dict -from typing_extensions import Literal - -EventType = Literal["message", "notice", "request", "meta_event"] - -_EVENT_CLASSIFY: Dict[EventType, List[str]] = { - # XXX Reference: https://github.com/project-mirai/mirai-api-http/blob/v1.9.7/docs/EventType.md - 'meta_event': [ - 'BotOnlineEvent', 'BotOfflineEventActive', 'BotOfflineEventForce', - 'BotOfflineEventDropped', 'BotReloginEvent' - ], - 'notice': [ - 'BotGroupPermissionChangeEvent', 'BotMuteEvent', 'BotUnmuteEvent', - 'BotJoinGroupEvent', 'BotLeaveEventActive', 'BotLeaveEventKick', - 'GroupRecallEvent', 'FriendRecallEvent', 'GroupNameChangeEvent', - 'GroupEntranceAnnouncementChangeEvent', 'GroupMuteAllEvent', - 'GroupAllowAnonymousChatEvent', 'GroupAllowConfessTalkEvent', - 'GroupAllowMemberInviteEvent', 'MemberJoinEvent', - 'MemberLeaveEventKick', 'MemberLeaveEventQuit', 'MemberCardChangeEvent', - 'MemberSpecialTitleChangeEvent', 'MemberPermissionChangeEvent', - 'MemberMuteEvent', 'MemberUnmuteEvent' - ], - 'request': [ - 'NewFriendRequestEvent', 'MemberJoinRequestEvent', - 'BotInvitedJoinGroupRequestEvent' - ], - 'message': ['GroupMessage', 'FriendMessage', 'TempMessage'] -} -EVENT_TYPES: Dict[str, EventType] = {} -for event_type, events in _EVENT_CLASSIFY.items(): - _EVENT_TYPES.update({k: event_type for k in events}) # type: ignore diff --git a/nonebot/adapters/mirai/event/message.py b/nonebot/adapters/mirai/event/message.py new file mode 100644 index 00000000..f680b0a2 --- /dev/null +++ b/nonebot/adapters/mirai/event/message.py @@ -0,0 +1,40 @@ +from typing import TYPE_CHECKING + +from pydantic import Field +from .base import Event, SenderInfo, PrivateSenderInfo + +from ..message import MessageChain +from nonebot.typing import overrides + + +class MessageEvent(Event): + message_chain: MessageChain = Field(alias='messageChain') + sender: SenderInfo + + @overrides(Event) + def get_message(self) -> MessageChain: + return self.message_chain + + @overrides(Event) + def get_plaintext(self) -> str: + return self.message_chain.__str__() + + @overrides(Event) + def get_user_id(self) -> str: + return str(self.sender.id) + + @overrides(Event) + def get_session_id(self) -> str: + return self.get_user_id() + + +class GroupMessage(MessageEvent): + pass + + +class FriendMessage(MessageEvent): + sender: PrivateSenderInfo + + +class TempMessage(MessageEvent): + pass \ No newline at end of file diff --git a/nonebot/adapters/mirai/event/notice.py b/nonebot/adapters/mirai/event/notice.py index 536bc12b..ae144b91 100644 --- a/nonebot/adapters/mirai/event/notice.py +++ b/nonebot/adapters/mirai/event/notice.py @@ -5,34 +5,34 @@ from pydantic import Field from .base import Event, SenderGroup, SenderInfo, SenderPermission -class BaseNoticeEvent(Event): +class NoticeEvent(Event): pass -class BaseMuteEvent(BaseNoticeEvent): +class MuteEvent(NoticeEvent): operator: SenderInfo -class BotMuteEvent(BaseMuteEvent): +class BotMuteEvent(MuteEvent): pass -class BotUnmuteEvent(BaseMuteEvent): +class BotUnmuteEvent(MuteEvent): pass -class MemberMuteEvent(BaseMuteEvent): +class MemberMuteEvent(MuteEvent): duration_seconds: int = Field(alias='durationSeconds') member: SenderInfo operator: Optional[SenderInfo] = None -class MemberUnmuteEvent(BaseMuteEvent): +class MemberUnmuteEvent(MuteEvent): member: SenderInfo operator: Optional[SenderInfo] = None -class BotJoinGroupEvent(BaseNoticeEvent): +class BotJoinGroupEvent(NoticeEvent): group: SenderGroup @@ -44,7 +44,7 @@ class BotLeaveEventKick(BotJoinGroupEvent): pass -class MemberJoinEvent(BaseNoticeEvent): +class MemberJoinEvent(NoticeEvent): member: SenderInfo @@ -56,7 +56,7 @@ class MemberLeaveEventKick(MemberJoinEvent): operator: Optional[SenderInfo] = None -class FriendRecallEvent(BaseNoticeEvent): +class FriendRecallEvent(NoticeEvent): author_id: int = Field(alias='authorId') message_id: int = Field(alias='messageId') time: int @@ -68,7 +68,7 @@ class GroupRecallEvent(FriendRecallEvent): operator: Optional[SenderInfo] = None -class GroupStateChangeEvent(BaseNoticeEvent): +class GroupStateChangeEvent(NoticeEvent): origin: Any current: Any group: SenderGroup @@ -105,7 +105,7 @@ class GroupAllowMemberInviteEvent(GroupStateChangeEvent): current: bool -class MemberStateChangeEvent(BaseNoticeEvent): +class MemberStateChangeEvent(NoticeEvent): member: SenderInfo operator: Optional[SenderInfo] = None diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py index 7e813f29..44a70c17 100644 --- a/nonebot/adapters/mirai/event/request.py +++ b/nonebot/adapters/mirai/event/request.py @@ -1 +1,26 @@ +from pydantic import Field + from .base import Event + + +class RequestEvent(Event): + event_id: int = Field(alias='eventId') + message: str + nick: str + + +class NewFriendRequestEvent(RequestEvent): + from_id: int = Field(alias='fromId') + group_id: int = Field(0, alias='groupId') + + +class MemberJoinRequestEvent(RequestEvent): + from_id: int = Field(alias='fromId') + group_id: int = Field(alias='groupId') + group_name: str = Field(alias='groupName') + + +class BotInvitedJoinGroupRequestEvent(RequestEvent): + from_id: int = Field(alias='fromId') + group_id: int = Field(alias='groupId') + group_name: str = Field(alias='groupName') diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py index edf1b6d0..06fc0d28 100644 --- a/nonebot/adapters/mirai/message.py +++ b/nonebot/adapters/mirai/message.py @@ -1 +1,100 @@ -from nonebot.adapters import Message \ No newline at end of file +from enum import Enum +from typing import Any, Dict, List, Union, Iterable + +from pydantic import validate_arguments + +from nonebot.adapters import Message as BaseMessage +from nonebot.adapters import MessageSegment as BaseMessageSegment +from nonebot.typing import overrides + + +class MessageType(str, Enum): + SOURCE = 'Source' + QUOTE = 'Quote' + AT = 'At' + AT_ALL = 'AtAll' + FACE = 'Face' + PLAIN = 'Plain' + IMAGE = 'Image' + FLASH_IMAGE = 'FlashImage' + VOICE = 'Voice' + XML = 'Xml' + JSON = 'Json' + APP = 'App' + POKE = 'Poke' + + +class MessageSegment(BaseMessageSegment): + type: MessageType + data: Dict[str, Any] + + @overrides(BaseMessageSegment) + @validate_arguments + def __init__(self, type: MessageType, **data): + super().__init__(type=type, data=data) + + @overrides(BaseMessageSegment) + def __str__(self) -> str: + if self.is_text(): + return self.data.get('text', '') + return '[mirai:%s]' % ','.join([ + self.type.value, + *map( + lambda s: '%s=%r' % s, + self.data.items(), + ), + ]) + + @overrides(BaseMessageSegment) + def __add__(self, other) -> "MessageChain": + return MessageChain(self) + other + + @overrides(BaseMessageSegment) + def __radd__(self, other) -> "MessageChain": + return MessageChain(other) + self + + @overrides(BaseMessageSegment) + def is_text(self) -> bool: + return self.type == MessageType.PLAIN + + def as_dict(self) -> Dict[str, Any]: + return {'type': self.type.value, **self.data} + + +class MessageChain(BaseMessage): + + @overrides(BaseMessage) + def __init__(self, message: Union[List[Dict[str, Any]], MessageSegment], + **kwargs): + super().__init__(**kwargs) + if isinstance(message, MessageSegment): + self.append(message) + elif isinstance(message, Iterable): + self.extend(self._construct(message)) + else: + raise ValueError( + f'Type {type(message).__name__} is not supported in mirai adapter.' + ) + + @overrides(BaseMessage) + def _construct( + self, message: Iterable[Union[Dict[str, Any], MessageSegment]] + ) -> List[MessageSegment]: + if isinstance(message, str): + raise ValueError( + "String operation is not supported in mirai adapter") + return [ + *map( + lambda segment: segment if isinstance(segment, MessageSegment) + else MessageSegment(**segment), message) + ] + + def export(self) -> List[Dict[str, Any]]: + chain: List[Dict[str, Any]] = [] + for segment in self.copy(): + segment: MessageSegment + chain.append({'type': segment.type.value, **segment.data}) + return chain + + def __repr__(self) -> str: + return f'<{self.__class__.__name__} {[*self.copy()]}>' From 02af1c1227418610a41a470adf3546fa348bb6b1 Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 05:58:30 +0800 Subject: [PATCH 37/86] :construction: finish forward websocket receive --- nonebot/adapters/mirai/bot.py | 134 ++++++++++++++++++++++++++++--- nonebot/adapters/mirai/config.py | 13 +++ nonebot/drivers/__init__.py | 4 +- 3 files changed, 139 insertions(+), 12 deletions(-) create mode 100644 nonebot/adapters/mirai/config.py diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index d5034cd4..fba54a69 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -1,22 +1,89 @@ -from pprint import pprint -from typing import Optional +import asyncio +import json +from ipaddress import IPv4Address +from typing import (Any, Callable, Coroutine, Dict, NoReturn, Optional, Set, + TypeVar) + +import httpx +import websockets from nonebot.adapters import Bot as BaseBot from nonebot.adapters import Event as BaseEvent -from nonebot.drivers import Driver, WebSocket +from nonebot.drivers import Driver +from nonebot.drivers import WebSocket as BaseWebSocket +from nonebot.exception import RequestDenied +from nonebot.log import logger from nonebot.message import handle_event from nonebot.typing import overrides +from .config import Config from .event import Event +WebsocketHandlerFunction = Callable[[Dict[str, Any]], Coroutine[Any, Any, None]] +WebsocketHandler_T = TypeVar('WebsocketHandler_T', + bound=WebsocketHandlerFunction) + + +class WebSocket(BaseWebSocket): + + @classmethod + async def new(cls, *, host: IPv4Address, port: int, + session_key: str) -> "WebSocket": + listen_address = httpx.URL(f'ws://{host}:{port}/all', + params={'sessionKey': session_key}) + websocket = await websockets.connect(uri=str(listen_address)) + return cls(websocket) + + @overrides(BaseWebSocket) + def __init__(self, websocket: websockets.WebSocketClientProtocol): + self.event_handlers: Set[WebsocketHandlerFunction] = set() + super().__init__(websocket) + + @property + @overrides(BaseWebSocket) + def websocket(self) -> websockets.WebSocketClientProtocol: + return self._websocket + + @overrides(BaseWebSocket) + async def send(self, data: Dict[str, Any]): + return await self.websocket.send(json.dumps(data)) + + @overrides(BaseWebSocket) + async def receive(self) -> Dict[str, Any]: + received = await self.websocket.recv() + return json.loads(received) + + async def _dispatcher(self): + while not self.websocket.closed: + try: + data = await self.receive() + except websockets.ConnectionClosedOK: + break + except Exception as e: + logger.exception(f'Websocket client listened {self.websocket} ' + f'failed to receive data: {e}') + continue + asyncio.ensure_future( + asyncio.gather(*map(lambda f: f(data), self.event_handlers), + return_exceptions=True)) + + @overrides(BaseWebSocket) + async def accept(self): + asyncio.ensure_future(self._dispatcher()) + + @overrides(BaseWebSocket) + async def close(self): + await self.websocket.close() + + def handle(self, callable: WebsocketHandler_T) -> WebsocketHandler_T: + self.event_handlers.add(callable) + return callable + class MiraiBot(BaseBot): - def __init__(self, - connection_type: str, - self_id: str, - *, - websocket: Optional["WebSocket"] = None): + def __init__(self, connection_type: str, self_id: str, *, + websocket: WebSocket): super().__init__(connection_type, self_id, websocket=websocket) @property @@ -27,8 +94,55 @@ class MiraiBot(BaseBot): @classmethod @overrides(BaseBot) async def check_permission(cls, driver: "Driver", connection_type: str, - headers: dict, body: Optional[dict]) -> str: - return '' + headers: dict, body: Optional[dict]) -> NoReturn: + raise RequestDenied( + status_code=501, + reason=f'Connection {connection_type} not implented') + + @classmethod + @overrides(BaseBot) + def register(cls, driver: "Driver", config: "Config", qq: int): + config = Config.parse_obj(config.dict()) + assert config.auth_key and config.host and config.port, f'Current config {config!r} is invalid' + + super().register(driver, config) # type: ignore + + @driver.on_startup + async def _startup(): + async with httpx.AsyncClient( + base_url=f'http://{config.host}:{config.port}') as client: + response = await client.get('/about') + info = response.json() + logger.debug(f'Mirai API returned info: {info}') + response = await client.post('/auth', + json={'authKey': config.auth_key}) + status = response.json() + assert status['code'] == 0 + session_key = status['session'] + response = await client.post('/verify', + json={ + 'sessionKey': session_key, + 'qq': qq + }) + assert response.json()['code'] == 0 + + websocket = await WebSocket.new( + host=config.host, # type: ignore + port=config.port, # type: ignore + session_key=session_key) + bot = cls(connection_type='forward_ws', + self_id=str(qq), + websocket=websocket) + websocket.handle(bot.handle_message) + driver._clients[str(qq)] = bot + await websocket.accept() + + @driver.on_shutdown + async def _shutdown(): + bot = driver._clients.pop(str(qq), None) + if bot is None: + return + await bot.websocket.close() #type:ignore @overrides(BaseBot) async def handle_message(self, message: dict): diff --git a/nonebot/adapters/mirai/config.py b/nonebot/adapters/mirai/config.py new file mode 100644 index 00000000..942cf9fa --- /dev/null +++ b/nonebot/adapters/mirai/config.py @@ -0,0 +1,13 @@ +from ipaddress import IPv4Address +from typing import Optional + +from pydantic import BaseModel, Extra, Field + + +class Config(BaseModel): + auth_key: Optional[str] = Field(None, alias='mirai_auth_key') + host: Optional[IPv4Address] = Field(None, alias='mirai_host') + port: Optional[int] = Field(None, alias='mirai_port') + + class Config: + extra = Extra.ignore diff --git a/nonebot/drivers/__init__.py b/nonebot/drivers/__init__.py index 986d59a3..134b2078 100644 --- a/nonebot/drivers/__init__.py +++ b/nonebot/drivers/__init__.py @@ -62,7 +62,7 @@ class Driver(abc.ABC): :说明: 已连接的 Bot """ - def register_adapter(self, name: str, adapter: Type["Bot"]): + def register_adapter(self, name: str, adapter: Type["Bot"], **kwargs): """ :说明: @@ -74,7 +74,7 @@ class Driver(abc.ABC): * ``adapter: Type[Bot]``: 适配器 Class """ self._adapters[name] = adapter - adapter.register(self, self.config) + adapter.register(self, self.config, **kwargs) logger.opt( colors=True).debug(f'Succeeded to load adapter "{name}"') From 5de41a18f976838ba70addbfc7fc9b744b5c3940 Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 06:10:04 +0800 Subject: [PATCH 38/86] :art: sort imports in file --- nonebot/adapters/mirai/bot.py | 1 + nonebot/adapters/mirai/event/base.py | 9 +++++++-- nonebot/adapters/mirai/event/message.py | 7 ++++--- nonebot/adapters/mirai/event/notice.py | 2 +- nonebot/adapters/mirai/message.py | 2 +- 5 files changed, 14 insertions(+), 7 deletions(-) diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index fba54a69..6190bedb 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -58,6 +58,7 @@ class WebSocket(BaseWebSocket): try: data = await self.receive() except websockets.ConnectionClosedOK: + logger.debug(f'Websocket connection {self.websocket} closed') break except Exception as e: logger.exception(f'Websocket client listened {self.websocket} ' diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 451a858e..7a6cae39 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -1,12 +1,14 @@ +import json from enum import Enum -from typing import Dict, Any, Optional, Type +from typing import Any, Dict, Optional, Type + from pydantic import BaseModel, Field, ValidationError from typing_extensions import Literal from nonebot.adapters import Event as BaseEvent from nonebot.adapters import Message as BaseMessage -from nonebot.typing import overrides from nonebot.log import logger +from nonebot.typing import overrides class SenderPermission(str, Enum): @@ -104,3 +106,6 @@ class Event(BaseEvent): @overrides(BaseEvent) def is_tome(self) -> bool: return False + + def normalize_dict(self, **kwargs) -> Dict[str, Any]: + return json.loads(self.json(**kwargs)) diff --git a/nonebot/adapters/mirai/event/message.py b/nonebot/adapters/mirai/event/message.py index f680b0a2..9c478e28 100644 --- a/nonebot/adapters/mirai/event/message.py +++ b/nonebot/adapters/mirai/event/message.py @@ -1,10 +1,11 @@ from typing import TYPE_CHECKING from pydantic import Field -from .base import Event, SenderInfo, PrivateSenderInfo + +from nonebot.typing import overrides from ..message import MessageChain -from nonebot.typing import overrides +from .base import Event, PrivateSenderInfo, SenderInfo class MessageEvent(Event): @@ -37,4 +38,4 @@ class FriendMessage(MessageEvent): class TempMessage(MessageEvent): - pass \ No newline at end of file + pass diff --git a/nonebot/adapters/mirai/event/notice.py b/nonebot/adapters/mirai/event/notice.py index ae144b91..b758d9c5 100644 --- a/nonebot/adapters/mirai/event/notice.py +++ b/nonebot/adapters/mirai/event/notice.py @@ -1,4 +1,4 @@ -from typing import Optional, Any +from typing import Any, Optional from pydantic import Field diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py index 06fc0d28..7562b6be 100644 --- a/nonebot/adapters/mirai/message.py +++ b/nonebot/adapters/mirai/message.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import Any, Dict, List, Union, Iterable +from typing import Any, Dict, Iterable, List, Union from pydantic import validate_arguments From e2f837055e457f61105e1e5bfbf53c48df783933 Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 10:55:06 +0800 Subject: [PATCH 39/86] :heavy_plus_sign: add dependency of websockets --- poetry.lock | 2 +- pyproject.toml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/poetry.lock b/poetry.lock index dc0b527f..2e9e5611 100644 --- a/poetry.lock +++ b/poetry.lock @@ -784,7 +784,7 @@ reference = "aliyun" [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "55439e671ff8c89285f2cf645189c1bf3e3bd53638bbb31ed505727a041d1012" +content-hash = "0038c5b3aa4a382184c1ef5b37a668ce37d8246c8fdf18deb71dccc8bf97be62" [metadata.files] alabaster = [ diff --git a/pyproject.toml b/pyproject.toml index 23f8e799..87a5e573 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,7 @@ pygtrie = "^2.4.1" fastapi = "^0.63.0" uvicorn = "^0.11.5" pydantic = {extras = ["dotenv", "typing_extensions"], version = "^1.7.3"} +websockets = "^8.1" [tool.poetry.dev-dependencies] yapf = "^0.30.0" From b140ebd1494af7963de12532ee3a4d1f3c6b449b Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Sat, 30 Jan 2021 10:56:58 +0800 Subject: [PATCH 40/86] :bug: fix wrong data in CQ:share #170 --- nonebot/adapters/cqhttp/message.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nonebot/adapters/cqhttp/message.py b/nonebot/adapters/cqhttp/message.py index ce1190c8..07c463c5 100644 --- a/nonebot/adapters/cqhttp/message.py +++ b/nonebot/adapters/cqhttp/message.py @@ -177,12 +177,12 @@ class MessageSegment(BaseMessageSegment): def share(url: str = "", title: str = "", content: Optional[str] = None, - img_url: Optional[str] = None) -> "MessageSegment": + image: Optional[str] = None) -> "MessageSegment": return MessageSegment("share", { "url": url, "title": title, "content": content, - "img_url": img_url + "image": image }) @staticmethod From 8b3eb4e0760b348ffec39b48cf82ea084d3a0d1a Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 13:36:31 +0800 Subject: [PATCH 41/86] :zap: add retry for mirai adapter when websocket connection down --- nonebot/adapters/mirai/bot.py | 118 +++++++++++++++++++++++++--------- 1 file changed, 87 insertions(+), 31 deletions(-) diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 6190bedb..70166eff 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -9,6 +9,7 @@ import websockets from nonebot.adapters import Bot as BaseBot from nonebot.adapters import Event as BaseEvent +from nonebot.config import Config from nonebot.drivers import Driver from nonebot.drivers import WebSocket as BaseWebSocket from nonebot.exception import RequestDenied @@ -16,7 +17,7 @@ from nonebot.log import logger from nonebot.message import handle_event from nonebot.typing import overrides -from .config import Config +from .config import Config as MiraiConfig from .event import Event WebsocketHandlerFunction = Callable[[Dict[str, Any]], Coroutine[Any, Any, None]] @@ -24,6 +25,32 @@ WebsocketHandler_T = TypeVar('WebsocketHandler_T', bound=WebsocketHandlerFunction) +async def _ws_authorization(client: httpx.AsyncClient, *, auth_key: str, + qq: int) -> str: + + async def request(method: str, *, path: str, **kwargs) -> Dict[str, Any]: + response = await client.request(method, path, **kwargs) + response.raise_for_status() + return response.json() + + about = await request('GET', path='/about') + logger.opt(colors=True).debug('Mirai API HTTP backend version: ' + f'{about["data"]["version"]}') + + status = await request('POST', path='/auth', json={'authKey': auth_key}) + assert status['code'] == 0 + session_key = status['session'] + + verify = await request('POST', + path='/verify', + json={ + 'sessionKey': session_key, + 'qq': qq + }) + assert verify['code'] == 0, verify['msg'] + return session_key + + class WebSocket(BaseWebSocket): @classmethod @@ -44,6 +71,11 @@ class WebSocket(BaseWebSocket): def websocket(self) -> websockets.WebSocketClientProtocol: return self._websocket + @property + @overrides(BaseWebSocket) + def closed(self) -> bool: + return self.websocket.closed + @overrides(BaseWebSocket) async def send(self, data: Dict[str, Any]): return await self.websocket.send(json.dumps(data)) @@ -54,23 +86,26 @@ class WebSocket(BaseWebSocket): return json.loads(received) async def _dispatcher(self): - while not self.websocket.closed: + while not self.closed: try: data = await self.receive() except websockets.ConnectionClosedOK: logger.debug(f'Websocket connection {self.websocket} closed') break - except Exception as e: + except websockets.ConnectionClosedError: + logger.exception(f'Websocket connection {self.websocket} ' + 'connection closed abnormally:') + break + except json.JSONDecodeError as e: logger.exception(f'Websocket client listened {self.websocket} ' - f'failed to receive data: {e}') + f'failed to decode data: {e}') continue - asyncio.ensure_future( - asyncio.gather(*map(lambda f: f(data), self.event_handlers), - return_exceptions=True)) + asyncio.gather(*map(lambda f: f(data), self.event_handlers), + return_exceptions=True) @overrides(BaseWebSocket) async def accept(self): - asyncio.ensure_future(self._dispatcher()) + asyncio.create_task(self._dispatcher()) @overrides(BaseWebSocket) async def close(self): @@ -92,6 +127,10 @@ class MiraiBot(BaseBot): def type(self) -> str: return "mirai" + @property + def alive(self) -> bool: + return not self.websocket.closed + @classmethod @overrides(BaseBot) async def check_permission(cls, driver: "Driver", connection_type: str, @@ -103,33 +142,26 @@ class MiraiBot(BaseBot): @classmethod @overrides(BaseBot) def register(cls, driver: "Driver", config: "Config", qq: int): - config = Config.parse_obj(config.dict()) - assert config.auth_key and config.host and config.port, f'Current config {config!r} is invalid' + cls.mirai_config = MiraiConfig(**config.dict()) + cls.active = True + assert cls.mirai_config.auth_key is not None + assert cls.mirai_config.host is not None + assert cls.mirai_config.port is not None + super().register(driver, config) - super().register(driver, config) # type: ignore - - @driver.on_startup - async def _startup(): + async def _bot_connection(): async with httpx.AsyncClient( - base_url=f'http://{config.host}:{config.port}') as client: - response = await client.get('/about') - info = response.json() - logger.debug(f'Mirai API returned info: {info}') - response = await client.post('/auth', - json={'authKey': config.auth_key}) - status = response.json() - assert status['code'] == 0 - session_key = status['session'] - response = await client.post('/verify', - json={ - 'sessionKey': session_key, - 'qq': qq - }) - assert response.json()['code'] == 0 + base_url= + f'http://{cls.mirai_config.host}:{cls.mirai_config.port}' + ) as client: + session_key = await _ws_authorization( + client, + auth_key=cls.mirai_config.auth_key, # type: ignore + qq=qq) # type: ignore websocket = await WebSocket.new( - host=config.host, # type: ignore - port=config.port, # type: ignore + host=cls.mirai_config.host, # type: ignore + port=cls.mirai_config.port, # type: ignore session_key=session_key) bot = cls(connection_type='forward_ws', self_id=str(qq), @@ -138,8 +170,32 @@ class MiraiBot(BaseBot): driver._clients[str(qq)] = bot await websocket.accept() + async def _connection_ensure(): + if str(qq) not in driver._clients: + await _bot_connection() + elif not driver._clients[str(qq)].alive: + driver._clients.pop(str(qq), None) + await _bot_connection() + + @driver.on_startup + async def _startup(): + + async def _checker(): + while cls.active: + try: + await _connection_ensure() + except Exception as e: + logger.opt(colors=True).warning( + 'Failed to create mirai connection to ' + f'{qq}, reason: {e}. ' + 'Will retry after 3 seconds') + await asyncio.sleep(3) + + asyncio.create_task(_checker()) + @driver.on_shutdown async def _shutdown(): + cls.active = False bot = driver._clients.pop(str(qq), None) if bot is None: return From 5b3ef53301ee3b125595fb7b0eda653625326b7d Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 13:45:55 +0800 Subject: [PATCH 42/86] :art: add support for on_bot_* event handler --- nonebot/adapters/mirai/bot.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 70166eff..08f6ea4e 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -121,6 +121,8 @@ class MiraiBot(BaseBot): def __init__(self, connection_type: str, self_id: str, *, websocket: WebSocket): super().__init__(connection_type, self_id, websocket=websocket) + websocket.handle(self.handle_message) + self.driver._bot_connect(self) @property @overrides(BaseBot) @@ -213,3 +215,6 @@ class MiraiBot(BaseBot): @overrides(BaseBot) async def send(self, event: "BaseEvent", message: str, **kwargs): return super().send(event, message, **kwargs) + + def __del__(self): + self.driver._bot_disconnect(self) From c82ceefc8b503476fc41d1c5494a91209d2084af Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 19:11:17 +0800 Subject: [PATCH 43/86] :rewind: revert call method to http post, add api handle --- nonebot/adapters/mirai/__init__.py | 4 +- nonebot/adapters/mirai/bot.py | 233 ++++++++------------------- nonebot/adapters/mirai/bot_ws.py | 220 +++++++++++++++++++++++++ nonebot/adapters/mirai/event/base.py | 1 + 4 files changed, 293 insertions(+), 165 deletions(-) create mode 100644 nonebot/adapters/mirai/bot_ws.py diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py index c832d378..991f30fd 100644 --- a/nonebot/adapters/mirai/__init__.py +++ b/nonebot/adapters/mirai/__init__.py @@ -1 +1,3 @@ -from .bot import MiraiBot \ No newline at end of file +from .bot import MiraiBot +from .event import * +from .message import MessageChain, MessageSegment diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 08f6ea4e..338dd144 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -1,128 +1,74 @@ -import asyncio -import json +from typing import Any, Dict, Optional, Tuple +from datetime import datetime, timedelta from ipaddress import IPv4Address -from typing import (Any, Callable, Coroutine, Dict, NoReturn, Optional, Set, - TypeVar) import httpx -import websockets from nonebot.adapters import Bot as BaseBot from nonebot.adapters import Event as BaseEvent from nonebot.config import Config -from nonebot.drivers import Driver -from nonebot.drivers import WebSocket as BaseWebSocket +from nonebot.drivers import Driver, WebSocket from nonebot.exception import RequestDenied from nonebot.log import logger from nonebot.message import handle_event from nonebot.typing import overrides from .config import Config as MiraiConfig -from .event import Event - -WebsocketHandlerFunction = Callable[[Dict[str, Any]], Coroutine[Any, Any, None]] -WebsocketHandler_T = TypeVar('WebsocketHandler_T', - bound=WebsocketHandlerFunction) +from .event import Event, FriendMessage, TempMessage, GroupMessage -async def _ws_authorization(client: httpx.AsyncClient, *, auth_key: str, - qq: int) -> str: +class SessionManager: + sessions: Dict[int, Tuple[str, datetime, httpx.AsyncClient]] = {} + session_expiry: timedelta = timedelta(minutes=15) - async def request(method: str, *, path: str, **kwargs) -> Dict[str, Any]: - response = await client.request(method, path, **kwargs) + def __init__(self, session_key: str, client: httpx.AsyncClient): + self.session_key, self.client = session_key, client + + async def post(self, path: str, *, params: Optional[Dict[str, Any]] = None): + params = {**(params or {}), 'sessionKey': self.session_key} + response = await self.client.post(path, json=params) response.raise_for_status() return response.json() - about = await request('GET', path='/about') - logger.opt(colors=True).debug('Mirai API HTTP backend version: ' - f'{about["data"]["version"]}') - - status = await request('POST', path='/auth', json={'authKey': auth_key}) - assert status['code'] == 0 - session_key = status['session'] - - verify = await request('POST', - path='/verify', - json={ - 'sessionKey': session_key, - 'qq': qq - }) - assert verify['code'] == 0, verify['msg'] - return session_key - - -class WebSocket(BaseWebSocket): + @classmethod + async def new(cls, self_id: int, *, host: IPv4Address, port: int, + auth_key: str): + if self_id in cls.sessions: + manager = cls.get(self_id) + if manager is not None: + return manager + client = httpx.AsyncClient(base_url=f'http://{host}:{port}') + response = await client.post('/auth', json={'authKey': auth_key}) + response.raise_for_status() + auth = response.json() + assert auth['code'] == 0 + session_key = auth['session'] + response = await client.post('/verify', + json={ + 'sessionKey': session_key, + 'qq': self_id + }) + assert response.json()['code'] == 0 + cls.sessions[self_id] = session_key, datetime.now(), client + return cls(session_key, client) @classmethod - async def new(cls, *, host: IPv4Address, port: int, - session_key: str) -> "WebSocket": - listen_address = httpx.URL(f'ws://{host}:{port}/all', - params={'sessionKey': session_key}) - websocket = await websockets.connect(uri=str(listen_address)) - return cls(websocket) - - @overrides(BaseWebSocket) - def __init__(self, websocket: websockets.WebSocketClientProtocol): - self.event_handlers: Set[WebsocketHandlerFunction] = set() - super().__init__(websocket) - - @property - @overrides(BaseWebSocket) - def websocket(self) -> websockets.WebSocketClientProtocol: - return self._websocket - - @property - @overrides(BaseWebSocket) - def closed(self) -> bool: - return self.websocket.closed - - @overrides(BaseWebSocket) - async def send(self, data: Dict[str, Any]): - return await self.websocket.send(json.dumps(data)) - - @overrides(BaseWebSocket) - async def receive(self) -> Dict[str, Any]: - received = await self.websocket.recv() - return json.loads(received) - - async def _dispatcher(self): - while not self.closed: - try: - data = await self.receive() - except websockets.ConnectionClosedOK: - logger.debug(f'Websocket connection {self.websocket} closed') - break - except websockets.ConnectionClosedError: - logger.exception(f'Websocket connection {self.websocket} ' - 'connection closed abnormally:') - break - except json.JSONDecodeError as e: - logger.exception(f'Websocket client listened {self.websocket} ' - f'failed to decode data: {e}') - continue - asyncio.gather(*map(lambda f: f(data), self.event_handlers), - return_exceptions=True) - - @overrides(BaseWebSocket) - async def accept(self): - asyncio.create_task(self._dispatcher()) - - @overrides(BaseWebSocket) - async def close(self): - await self.websocket.close() - - def handle(self, callable: WebsocketHandler_T) -> WebsocketHandler_T: - self.event_handlers.add(callable) - return callable + def get(cls, self_id: int): + key, time, client = cls.sessions[self_id] + if datetime.now() - time > cls.session_expiry: + return None + return cls(key, client) class MiraiBot(BaseBot): - def __init__(self, connection_type: str, self_id: str, *, - websocket: WebSocket): + def __init__(self, + connection_type: str, + self_id: str, + *, + websocket: Optional[WebSocket] = None): super().__init__(connection_type, self_id, websocket=websocket) - websocket.handle(self.handle_message) - self.driver._bot_connect(self) + self.api = SessionManager.get(int(self_id)) @property @overrides(BaseBot) @@ -136,85 +82,44 @@ class MiraiBot(BaseBot): @classmethod @overrides(BaseBot) async def check_permission(cls, driver: "Driver", connection_type: str, - headers: dict, body: Optional[dict]) -> NoReturn: - raise RequestDenied( - status_code=501, - reason=f'Connection {connection_type} not implented') + headers: dict, body: Optional[dict]) -> str: + if connection_type == 'ws': + raise RequestDenied( + status_code=501, + reason='Websocket connection is not implemented') + self_id: Optional[str] = headers.get('bot') + if self_id is None: + raise RequestDenied(status_code=400, + reason='Header `Bot` is required.') + self_id = str(self_id).strip() + await SessionManager.new( + int(self_id), + host=cls.mirai_config.host, # type: ignore + port=cls.mirai_config.port, #type: ignore + auth_key=cls.mirai_config.auth_key) # type: ignore + return self_id @classmethod @overrides(BaseBot) - def register(cls, driver: "Driver", config: "Config", qq: int): + def register(cls, driver: "Driver", config: "Config"): cls.mirai_config = MiraiConfig(**config.dict()) - cls.active = True assert cls.mirai_config.auth_key is not None assert cls.mirai_config.host is not None assert cls.mirai_config.port is not None super().register(driver, config) - async def _bot_connection(): - async with httpx.AsyncClient( - base_url= - f'http://{cls.mirai_config.host}:{cls.mirai_config.port}' - ) as client: - session_key = await _ws_authorization( - client, - auth_key=cls.mirai_config.auth_key, # type: ignore - qq=qq) # type: ignore - - websocket = await WebSocket.new( - host=cls.mirai_config.host, # type: ignore - port=cls.mirai_config.port, # type: ignore - session_key=session_key) - bot = cls(connection_type='forward_ws', - self_id=str(qq), - websocket=websocket) - websocket.handle(bot.handle_message) - driver._clients[str(qq)] = bot - await websocket.accept() - - async def _connection_ensure(): - if str(qq) not in driver._clients: - await _bot_connection() - elif not driver._clients[str(qq)].alive: - driver._clients.pop(str(qq), None) - await _bot_connection() - - @driver.on_startup - async def _startup(): - - async def _checker(): - while cls.active: - try: - await _connection_ensure() - except Exception as e: - logger.opt(colors=True).warning( - 'Failed to create mirai connection to ' - f'{qq}, reason: {e}. ' - 'Will retry after 3 seconds') - await asyncio.sleep(3) - - asyncio.create_task(_checker()) - - @driver.on_shutdown - async def _shutdown(): - cls.active = False - bot = driver._clients.pop(str(qq), None) - if bot is None: - return - await bot.websocket.close() #type:ignore - @overrides(BaseBot) async def handle_message(self, message: dict): - event = Event.new(message) - await handle_event(self, event) + await handle_event(bot=self, + event=Event.new({ + **message, + 'self_id': self.self_id, + })) @overrides(BaseBot) async def call_api(self, api: str, **data): - return super().call_api(api, **data) + return await self.api.post('/' + api, params=data) @overrides(BaseBot) async def send(self, event: "BaseEvent", message: str, **kwargs): - return super().send(event, message, **kwargs) - - def __del__(self): - self.driver._bot_disconnect(self) + pass diff --git a/nonebot/adapters/mirai/bot_ws.py b/nonebot/adapters/mirai/bot_ws.py new file mode 100644 index 00000000..d9803c47 --- /dev/null +++ b/nonebot/adapters/mirai/bot_ws.py @@ -0,0 +1,220 @@ +import asyncio +import json +from ipaddress import IPv4Address +from typing import (Any, Callable, Coroutine, Dict, NoReturn, Optional, Set, + TypeVar) + +import httpx +import websockets + +from nonebot.adapters import Bot as BaseBot +from nonebot.adapters import Event as BaseEvent +from nonebot.config import Config +from nonebot.drivers import Driver +from nonebot.drivers import WebSocket as BaseWebSocket +from nonebot.exception import RequestDenied +from nonebot.log import logger +from nonebot.message import handle_event +from nonebot.typing import overrides + +from .config import Config as MiraiConfig +from .event import Event + +WebsocketHandlerFunction = Callable[[Dict[str, Any]], Coroutine[Any, Any, None]] +WebsocketHandler_T = TypeVar('WebsocketHandler_T', + bound=WebsocketHandlerFunction) + + +async def _ws_authorization(client: httpx.AsyncClient, *, auth_key: str, + qq: int) -> str: + + async def request(method: str, *, path: str, **kwargs) -> Dict[str, Any]: + response = await client.request(method, path, **kwargs) + response.raise_for_status() + return response.json() + + about = await request('GET', path='/about') + logger.opt(colors=True).debug('Mirai API HTTP backend version: ' + f'{about["data"]["version"]}') + + status = await request('POST', path='/auth', json={'authKey': auth_key}) + assert status['code'] == 0 + session_key = status['session'] + + verify = await request('POST', + path='/verify', + json={ + 'sessionKey': session_key, + 'qq': qq + }) + assert verify['code'] == 0, verify['msg'] + return session_key + + +class WebSocket(BaseWebSocket): + + @classmethod + async def new(cls, *, host: IPv4Address, port: int, + session_key: str) -> "WebSocket": + listen_address = httpx.URL(f'ws://{host}:{port}/all', + params={'sessionKey': session_key}) + websocket = await websockets.connect(uri=str(listen_address)) + return cls(websocket) + + @overrides(BaseWebSocket) + def __init__(self, websocket: websockets.WebSocketClientProtocol): + self.event_handlers: Set[WebsocketHandlerFunction] = set() + super().__init__(websocket) + + @property + @overrides(BaseWebSocket) + def websocket(self) -> websockets.WebSocketClientProtocol: + return self._websocket + + @property + @overrides(BaseWebSocket) + def closed(self) -> bool: + return self.websocket.closed + + @overrides(BaseWebSocket) + async def send(self, data: Dict[str, Any]): + return await self.websocket.send(json.dumps(data)) + + @overrides(BaseWebSocket) + async def receive(self) -> Dict[str, Any]: + received = await self.websocket.recv() + return json.loads(received) + + async def _dispatcher(self): + while not self.closed: + try: + data = await self.receive() + except websockets.ConnectionClosedOK: + logger.debug(f'Websocket connection {self.websocket} closed') + break + except websockets.ConnectionClosedError: + logger.exception(f'Websocket connection {self.websocket} ' + 'connection closed abnormally:') + break + except json.JSONDecodeError as e: + logger.exception(f'Websocket client listened {self.websocket} ' + f'failed to decode data: {e}') + continue + asyncio.gather(*map(lambda f: f(data), self.event_handlers), + return_exceptions=True) + + @overrides(BaseWebSocket) + async def accept(self): + asyncio.create_task(self._dispatcher()) + + @overrides(BaseWebSocket) + async def close(self): + await self.websocket.close() + + def handle(self, callable: WebsocketHandler_T) -> WebsocketHandler_T: + self.event_handlers.add(callable) + return callable + + +class MiraiWebsocketBot(BaseBot): + + def __init__(self, connection_type: str, self_id: str, *, + websocket: WebSocket): + super().__init__(connection_type, self_id, websocket=websocket) + websocket.handle(self.handle_message) + self.driver._bot_connect(self) + + @property + @overrides(BaseBot) + def type(self) -> str: + return "mirai" + + @property + def alive(self) -> bool: + return not self.websocket.closed + + @classmethod + @overrides(BaseBot) + async def check_permission(cls, driver: "Driver", connection_type: str, + headers: dict, body: Optional[dict]) -> NoReturn: + raise RequestDenied( + status_code=501, + reason=f'Connection {connection_type} not implented') + + @classmethod + @overrides(BaseBot) + def register(cls, driver: "Driver", config: "Config", qq: int): + cls.mirai_config = MiraiConfig(**config.dict()) + cls.active = True + assert cls.mirai_config.auth_key is not None + assert cls.mirai_config.host is not None + assert cls.mirai_config.port is not None + super().register(driver, config) + + async def _bot_connection(): + async with httpx.AsyncClient( + base_url= + f'http://{cls.mirai_config.host}:{cls.mirai_config.port}' + ) as client: + session_key = await _ws_authorization( + client, + auth_key=cls.mirai_config.auth_key, # type: ignore + qq=qq) # type: ignore + + websocket = await WebSocket.new( + host=cls.mirai_config.host, # type: ignore + port=cls.mirai_config.port, # type: ignore + session_key=session_key) + bot = cls(connection_type='forward_ws', + self_id=str(qq), + websocket=websocket) + websocket.handle(bot.handle_message) + driver._clients[str(qq)] = bot + await websocket.accept() + + async def _connection_ensure(): + if str(qq) not in driver._clients: + await _bot_connection() + elif not driver._clients[str(qq)].alive: + driver._clients.pop(str(qq), None) + await _bot_connection() + + @driver.on_startup + async def _startup(): + + async def _checker(): + while cls.active: + try: + await _connection_ensure() + except Exception as e: + logger.opt(colors=True).warning( + 'Failed to create mirai connection to ' + f'{qq}, reason: {e}. ' + 'Will retry after 3 seconds') + await asyncio.sleep(3) + + asyncio.create_task(_checker()) + + @driver.on_shutdown + async def _shutdown(): + cls.active = False + bot = driver._clients.pop(str(qq), None) + if bot is None: + return + await bot.websocket.close() #type:ignore + + @overrides(BaseBot) + async def handle_message(self, message: dict): + event = Event.new(message) + await handle_event(self, event) + + @overrides(BaseBot) + async def call_api(self, api: str, **data): + return super().call_api(api, **data) + + @overrides(BaseBot) + async def send(self, event: "BaseEvent", message: str, **kwargs): + return super().send(event, message, **kwargs) + + def __del__(self): + self.driver._bot_disconnect(self) diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 7a6cae39..6fbb30ff 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -37,6 +37,7 @@ class PrivateSenderInfo(BaseModel): class Event(BaseEvent): + self_id: int type: str @classmethod From 95f27824ee1994753102c39354ccbbaf0f8aa70e Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 20:40:00 +0800 Subject: [PATCH 44/86] :construction: add api methods define --- nonebot/adapters/mirai/bot.py | 199 +++++++++++++++++++++++- nonebot/adapters/mirai/event/message.py | 28 +++- 2 files changed, 214 insertions(+), 13 deletions(-) diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 338dd144..e89eb245 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -1,6 +1,7 @@ -from typing import Any, Dict, Optional, Tuple from datetime import datetime, timedelta +from io import BytesIO from ipaddress import IPv4Address +from typing import Any, Dict, List, NoReturn, Optional, Tuple import httpx @@ -14,7 +15,8 @@ from nonebot.message import handle_event from nonebot.typing import overrides from .config import Config as MiraiConfig -from .event import Event, FriendMessage, TempMessage, GroupMessage +from .event import Event, FriendMessage, GroupMessage, TempMessage +from .message import MessageChain, MessageSegment class SessionManager: @@ -24,12 +26,41 @@ class SessionManager: def __init__(self, session_key: str, client: httpx.AsyncClient): self.session_key, self.client = session_key, client - async def post(self, path: str, *, params: Optional[Dict[str, Any]] = None): + async def post(self, + path: str, + *, + params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: params = {**(params or {}), 'sessionKey': self.session_key} response = await self.client.post(path, json=params) response.raise_for_status() return response.json() + async def request(self, + path: str, + *, + params: Optional[Dict[str, + Any]] = None) -> Dict[str, Any]: + response = await self.client.get(path, + params={ + **(params or {}), 'sessionKey': + self.session_key + }) + response.raise_for_status() + return response.json() + + async def upload(self, path: str, *, type: str, + file: Tuple[str, BytesIO]) -> Dict[str, Any]: + file_type, file_io = file + response = await self.client.post(path, + data={ + 'sessionKey': self.session_key, + 'type': type + }, + files={file_type: file_io}, + timeout=6) + response.raise_for_status() + return response.json() + @classmethod async def new(cls, self_id: int, *, host: IPv4Address, port: int, auth_key: str): @@ -117,9 +148,163 @@ class MiraiBot(BaseBot): })) @overrides(BaseBot) - async def call_api(self, api: str, **data): - return await self.api.post('/' + api, params=data) + async def call_api(self, api: str, **data) -> NoReturn: + raise NotImplementedError @overrides(BaseBot) - async def send(self, event: "BaseEvent", message: str, **kwargs): - pass + async def __getattr__(self, key: str) -> NoReturn: + raise NotImplementedError + + @overrides(BaseBot) + async def send(self, + event: Event, + message: MessageChain, + at_sender: bool = False, + **kwargs): + if isinstance(event, FriendMessage): + return await self.send_friend_message(target=event.sender.id, + message_chain=message) + elif isinstance(event, GroupMessage): + return await self.send_group_message(target=event.sender.group.id, + message_chain=message) + elif isinstance(event, TempMessage): + return await self.send_temp_message(qq=event.sender.id, + group=event.sender.group.id, + message_chain=message) + else: + raise ValueError(f'Unsupported event type {event!r}.') + + async def send_friend_message(self, target: int, + message_chain: MessageChain): + return await self.api.post('sendFriendMessage', + params={ + 'target': target, + 'messageChain': message_chain.export() + }) + + async def send_temp_message(self, qq: int, group: int, + message_chain: MessageChain): + return await self.api.post('sendTempMessage', + params={ + 'qq': qq, + 'group': group, + 'messageChain': message_chain.export() + }) + + async def send_group_message(self, target: int, + message_chain: MessageChain): + return await self.api.post('sendGroupMessage', + params={ + 'target': target, + 'messageChain': message_chain.export() + }) + + async def recall(self, target: int): + return await self.api.post('recall', params={'target': target}) + + async def send_image_message(self, target: int, qq: int, group: int, + urls: List[str]): + return await self.api.post('sendImageMessage', + params={ + 'target': target, + 'qq': qq, + 'group': group, + 'urls': urls + }) + + async def upload_image(self, type: str, img: BytesIO): + return await self.api.upload('uploadImage', + type=type, + file=('img', img)) + + async def upload_voice(self, type: str, voice: BytesIO): + return await self.api.upload('uploadVoice', + type=type, + file=('voice', voice)) + + async def fetch_message(self): + return await self.api.request('fetchMessage') + + async def fetch_latest_message(self): + return await self.api.request('fetchLatestMessage') + + async def peek_message(self, count: int): + return await self.api.request('peekMessage', params={'count': count}) + + async def peek_latest_message(self, count: int): + return await self.api.request('peekLatestMessage', + params={'count': count}) + + async def messsage_from_id(self, id: int): + return await self.api.request('messageFromId', params={'id': id}) + + async def count_message(self): + return await self.api.request('countMessage') + + async def friend_list(self) -> List[Dict[str, Any]]: + return await self.api.request('friendList') # type: ignore + + async def group_list(self) -> List[Dict[str, Any]]: + return await self.api.request('groupList') # type: ignore + + async def member_list(self, target: int) -> List[Dict[str, Any]]: + return await self.api.request('memberList', + params={'target': target}) # type: ignore + + async def mute(self, target: int, member_id: int, time: int): + return await self.api.post('mute', + params={ + 'target': target, + 'memberId': member_id, + 'time': time + }) + + async def unmute(self, target: int, member_id: int): + return await self.api.post('unmute', + params={ + 'target': target, + 'memberId': member_id + }) + + async def kick(self, target: int, member_id: int, msg: str): + return await self.api.post('kick', + params={ + 'target': target, + 'memberId': member_id, + 'msg': msg + }) + + async def quit(self, target: int): + return await self.api.post('quit', params={'target': target}) + + async def mute_all(self, target: int): + return await self.api.post('muteAll', params={'target': target}) + + async def unmute_all(self, target: int): + return await self.api.post('unmuteAll', params={'target': target}) + + async def group_config(self, target: int): + return await self.api.request('groupConfig', params={'target': target}) + + async def modify_group_config(self, target: int, config: Dict[str, Any]): + return await self.api.post('groupConfig', + params={ + 'target': target, + 'config': config + }) + + async def member_info(self, target: int, member_id: int): + return await self.api.request('memberInfo', + params={ + 'target': target, + 'memberId': member_id + }) + + async def modify_member_info(self, target: int, member_id: int, + info: Dict[str, Any]): + return await self.api.post('memberInfo', + params={ + 'target': target, + 'memberId': member_id, + 'info': info + }) diff --git a/nonebot/adapters/mirai/event/message.py b/nonebot/adapters/mirai/event/message.py index 9c478e28..1cfca586 100644 --- a/nonebot/adapters/mirai/event/message.py +++ b/nonebot/adapters/mirai/event/message.py @@ -1,4 +1,4 @@ -from typing import TYPE_CHECKING +from typing import Any from pydantic import Field @@ -10,7 +10,7 @@ from .base import Event, PrivateSenderInfo, SenderInfo class MessageEvent(Event): message_chain: MessageChain = Field(alias='messageChain') - sender: SenderInfo + sender: Any @overrides(Event) def get_message(self) -> MessageChain: @@ -22,20 +22,36 @@ class MessageEvent(Event): @overrides(Event) def get_user_id(self) -> str: - return str(self.sender.id) + raise NotImplementedError @overrides(Event) def get_session_id(self) -> str: - return self.get_user_id() + raise NotImplementedError class GroupMessage(MessageEvent): - pass + sender: SenderInfo + + @overrides(MessageEvent) + def get_session_id(self) -> str: + return f'group_{self.sender.group.id}_' + self.get_user_id() class FriendMessage(MessageEvent): sender: PrivateSenderInfo + @overrides(MessageEvent) + def get_user_id(self) -> str: + return str(self.sender.id) + + @overrides + def get_session_id(self) -> str: + return 'friend_' + self.get_user_id() + class TempMessage(MessageEvent): - pass + sender: SenderInfo + + @overrides + def get_session_id(self) -> str: + return f'temp_{self.sender.group.id}_' + self.get_user_id() From 73be9151b0c265ca0afc15333f4baa5bc1e2932f Mon Sep 17 00:00:00 2001 From: Mix Date: Sat, 30 Jan 2021 21:51:51 +0800 Subject: [PATCH 45/86] :children_crossing: add factory classmethods in MessageSegment at mirai adapter --- nonebot/adapters/mirai/bot.py | 50 ++++++++++---- nonebot/adapters/mirai/event/message.py | 2 +- nonebot/adapters/mirai/message.py | 86 +++++++++++++++++++++++-- 3 files changed, 118 insertions(+), 20 deletions(-) diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index e89eb245..2414dca8 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -10,6 +10,7 @@ from nonebot.adapters import Event as BaseEvent from nonebot.config import Config from nonebot.drivers import Driver, WebSocket from nonebot.exception import RequestDenied +from nonebot.exception import ActionFailed as BaseActionFailed from nonebot.log import logger from nonebot.message import handle_event from nonebot.typing import overrides @@ -19,6 +20,17 @@ from .event import Event, FriendMessage, GroupMessage, TempMessage from .message import MessageChain, MessageSegment +class ActionFailed(BaseActionFailed): + + def __init__(self, code: int, message: str = ''): + super().__init__('mirai') + self.code = code + self.message = message + + def __repr__(self): + return f"{self.__class__.__name__}(code={self.code}, message={self.message!r})" + + class SessionManager: sessions: Dict[int, Tuple[str, datetime, httpx.AsyncClient]] = {} session_expiry: timedelta = timedelta(minutes=15) @@ -26,14 +38,22 @@ class SessionManager: def __init__(self, session_key: str, client: httpx.AsyncClient): self.session_key, self.client = session_key, client + @staticmethod + def _raise_code(data: Dict[str, Any]) -> Dict[str, Any]: + code = data.get('code', 0) + logger.debug(f'Mirai API returned data: {data}') + if code != 0: + raise ActionFailed(code, message=data['msg']) + return data + async def post(self, path: str, *, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: params = {**(params or {}), 'sessionKey': self.session_key} - response = await self.client.post(path, json=params) + response = await self.client.post(path, json=params, timeout=3) response.raise_for_status() - return response.json() + return self._raise_code(response.json()) async def request(self, path: str, @@ -44,9 +64,10 @@ class SessionManager: params={ **(params or {}), 'sessionKey': self.session_key - }) + }, + timeout=3) response.raise_for_status() - return response.json() + return self._raise_code(response.json()) async def upload(self, path: str, *, type: str, file: Tuple[str, BytesIO]) -> Dict[str, Any]: @@ -59,7 +80,7 @@ class SessionManager: files={file_type: file_io}, timeout=6) response.raise_for_status() - return response.json() + return self._raise_code(response.json()) @classmethod async def new(cls, self_id: int, *, host: IPv4Address, port: int, @@ -152,7 +173,7 @@ class MiraiBot(BaseBot): raise NotImplementedError @overrides(BaseBot) - async def __getattr__(self, key: str) -> NoReturn: + def __getattr__(self, key: str) -> NoReturn: raise NotImplementedError @overrides(BaseBot) @@ -165,8 +186,10 @@ class MiraiBot(BaseBot): return await self.send_friend_message(target=event.sender.id, message_chain=message) elif isinstance(event, GroupMessage): - return await self.send_group_message(target=event.sender.group.id, - message_chain=message) + return await self.send_group_message( + group=event.sender.group.id, + message_chain=message if not at_sender else + (MessageSegment.at(target=event.sender.id) + message)) elif isinstance(event, TempMessage): return await self.send_temp_message(qq=event.sender.id, group=event.sender.group.id, @@ -191,12 +214,15 @@ class MiraiBot(BaseBot): 'messageChain': message_chain.export() }) - async def send_group_message(self, target: int, - message_chain: MessageChain): + async def send_group_message(self, + group: int, + message_chain: MessageChain, + quote: Optional[int] = None): return await self.api.post('sendGroupMessage', params={ - 'target': target, - 'messageChain': message_chain.export() + 'group': group, + 'messageChain': message_chain.export(), + 'quote': quote }) async def recall(self, target: int): diff --git a/nonebot/adapters/mirai/event/message.py b/nonebot/adapters/mirai/event/message.py index 1cfca586..10574d5e 100644 --- a/nonebot/adapters/mirai/event/message.py +++ b/nonebot/adapters/mirai/event/message.py @@ -18,7 +18,7 @@ class MessageEvent(Event): @overrides(Event) def get_plaintext(self) -> str: - return self.message_chain.__str__() + return self.message_chain.extract_plain_text() @overrides(Event) def get_user_id(self) -> str: diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py index 7562b6be..ef3949a6 100644 --- a/nonebot/adapters/mirai/message.py +++ b/nonebot/adapters/mirai/message.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import Any, Dict, Iterable, List, Union +from typing import Any, Dict, Iterable, List, Optional, Union from pydantic import validate_arguments @@ -31,7 +31,8 @@ class MessageSegment(BaseMessageSegment): @overrides(BaseMessageSegment) @validate_arguments def __init__(self, type: MessageType, **data): - super().__init__(type=type, data=data) + super().__init__(type=type, + data={k: v for k, v in data.items() if v is not None}) @overrides(BaseMessageSegment) def __str__(self) -> str: @@ -60,6 +61,79 @@ class MessageSegment(BaseMessageSegment): def as_dict(self) -> Dict[str, Any]: return {'type': self.type.value, **self.data} + @classmethod + def source(cls, id: int, time: int): + return cls(type=MessageType.SOURCE, id=id, time=time) + + @classmethod + def quote(cls, id: int, group_id: int, sender_id: int, target_id: int, + origin: "MessageChain"): + return cls(type=MessageType.QUOTE, + id=id, + groupId=group_id, + senderId=sender_id, + targetId=target_id, + origin=origin.export()) + + @classmethod + def at(cls, target: int): + return cls(type=MessageType.AT, target=target) + + @classmethod + def at_all(cls): + return cls(type=MessageType.AT_ALL) + + @classmethod + def face(cls, face_id: Optional[int] = None, name: Optional[str] = None): + return cls(type=MessageType.FACE, faceId=face_id, name=name) + + @classmethod + def plain(cls, text: str): + return cls(type=MessageType.PLAIN, text=text) + + @classmethod + def image(cls, + image_id: Optional[str] = None, + url: Optional[str] = None, + path: Optional[str] = None): + return cls(type=MessageType.IMAGE, imageId=image_id, url=url, path=path) + + @classmethod + def flash_image(cls, + image_id: Optional[str] = None, + url: Optional[str] = None, + path: Optional[str] = None): + return cls(type=MessageType.FLASH_IMAGE, + imageId=image_id, + url=url, + path=path) + + @classmethod + def voice(cls, + voice_id: Optional[str] = None, + url: Optional[str] = None, + path: Optional[str] = None): + return cls(type=MessageType.FLASH_IMAGE, + imageId=voice_id, + url=url, + path=path) + + @classmethod + def xml(cls, xml: str): + return cls(type=MessageType.XML, xml=xml) + + @classmethod + def json(cls, json: str): + return cls(type=MessageType.JSON, json=json) + + @classmethod + def app(cls, content: str): + return cls(type=MessageType.APP, content=content) + + @classmethod + def poke(cls, name: str): + return cls(type=MessageType.POKE, name=name) + class MessageChain(BaseMessage): @@ -90,11 +164,9 @@ class MessageChain(BaseMessage): ] def export(self) -> List[Dict[str, Any]]: - chain: List[Dict[str, Any]] = [] - for segment in self.copy(): - segment: MessageSegment - chain.append({'type': segment.type.value, **segment.data}) - return chain + return [ + *map(lambda segment: segment.as_dict(), self.copy()) # type: ignore + ] def __repr__(self) -> str: return f'<{self.__class__.__name__} {[*self.copy()]}>' From 3f56da9245da9d53ab1155511c7e426400709806 Mon Sep 17 00:00:00 2001 From: Mix Date: Sun, 31 Jan 2021 16:02:59 +0800 Subject: [PATCH 46/86] :construction: add support of reverse post and forward ws for mirai adapter --- nonebot/adapters/mirai/__init__.py | 1 + nonebot/adapters/mirai/bot.py | 38 ++++++----- nonebot/adapters/mirai/bot_ws.py | 94 ++++++++-------------------- nonebot/adapters/mirai/event/base.py | 2 +- nonebot/adapters/mirai/message.py | 12 ++-- 5 files changed, 57 insertions(+), 90 deletions(-) diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py index 991f30fd..1107af38 100644 --- a/nonebot/adapters/mirai/__init__.py +++ b/nonebot/adapters/mirai/__init__.py @@ -1,3 +1,4 @@ from .bot import MiraiBot +from .bot_ws import MiraiWebsocketBot from .event import * from .message import MessageChain, MessageSegment diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 2414dca8..ebb9b768 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -1,19 +1,19 @@ from datetime import datetime, timedelta from io import BytesIO from ipaddress import IPv4Address -from typing import Any, Dict, List, NoReturn, Optional, Tuple +from typing import Any, Dict, List, NoReturn, Optional, Tuple, Union import httpx from nonebot.adapters import Bot as BaseBot -from nonebot.adapters import Event as BaseEvent from nonebot.config import Config from nonebot.drivers import Driver, WebSocket -from nonebot.exception import RequestDenied from nonebot.exception import ActionFailed as BaseActionFailed +from nonebot.exception import RequestDenied from nonebot.log import logger from nonebot.message import handle_event from nonebot.typing import overrides +from nonebot.utils import escape_tag from .config import Config as MiraiConfig from .event import Event, FriendMessage, GroupMessage, TempMessage @@ -41,7 +41,8 @@ class SessionManager: @staticmethod def _raise_code(data: Dict[str, Any]) -> Dict[str, Any]: code = data.get('code', 0) - logger.debug(f'Mirai API returned data: {data}') + logger.opt(colors=True).debug('Mirai API returned data: ' + f'{escape_tag(str(data))}') if code != 0: raise ActionFailed(code, message=data['msg']) return data @@ -85,10 +86,10 @@ class SessionManager: @classmethod async def new(cls, self_id: int, *, host: IPv4Address, port: int, auth_key: str): - if self_id in cls.sessions: - manager = cls.get(self_id) - if manager is not None: - return manager + session = cls.get(self_id) + if session is not None: + return session + client = httpx.AsyncClient(base_url=f'http://{host}:{port}') response = await client.post('/auth', json={'authKey': auth_key}) response.raise_for_status() @@ -102,10 +103,13 @@ class SessionManager: }) assert response.json()['code'] == 0 cls.sessions[self_id] = session_key, datetime.now(), client + return cls(session_key, client) @classmethod def get(cls, self_id: int): + if self_id not in cls.sessions: + return None key, time, client = cls.sessions[self_id] if datetime.now() - time > cls.session_expiry: return None @@ -114,6 +118,7 @@ class SessionManager: class MiraiBot(BaseBot): + @overrides(BaseBot) def __init__(self, connection_type: str, self_id: str, @@ -179,17 +184,20 @@ class MiraiBot(BaseBot): @overrides(BaseBot) async def send(self, event: Event, - message: MessageChain, - at_sender: bool = False, - **kwargs): + message: Union[MessageChain, MessageSegment, str], + at_sender: bool = False): + if isinstance(message, MessageSegment): + message = MessageChain(message) + elif isinstance(message, str): + message = MessageChain(MessageSegment.plain(message)) if isinstance(event, FriendMessage): return await self.send_friend_message(target=event.sender.id, message_chain=message) elif isinstance(event, GroupMessage): - return await self.send_group_message( - group=event.sender.group.id, - message_chain=message if not at_sender else - (MessageSegment.at(target=event.sender.id) + message)) + if at_sender: + message = MessageSegment.at(event.sender.id) + message + return await self.send_group_message(group=event.sender.group.id, + message_chain=message) elif isinstance(event, TempMessage): return await self.send_temp_message(qq=event.sender.id, group=event.sender.group.id, diff --git a/nonebot/adapters/mirai/bot_ws.py b/nonebot/adapters/mirai/bot_ws.py index d9803c47..d20d81dd 100644 --- a/nonebot/adapters/mirai/bot_ws.py +++ b/nonebot/adapters/mirai/bot_ws.py @@ -7,50 +7,21 @@ from typing import (Any, Callable, Coroutine, Dict, NoReturn, Optional, Set, import httpx import websockets -from nonebot.adapters import Bot as BaseBot -from nonebot.adapters import Event as BaseEvent from nonebot.config import Config from nonebot.drivers import Driver from nonebot.drivers import WebSocket as BaseWebSocket from nonebot.exception import RequestDenied from nonebot.log import logger -from nonebot.message import handle_event from nonebot.typing import overrides +from .bot import MiraiBot, SessionManager from .config import Config as MiraiConfig -from .event import Event WebsocketHandlerFunction = Callable[[Dict[str, Any]], Coroutine[Any, Any, None]] WebsocketHandler_T = TypeVar('WebsocketHandler_T', bound=WebsocketHandlerFunction) -async def _ws_authorization(client: httpx.AsyncClient, *, auth_key: str, - qq: int) -> str: - - async def request(method: str, *, path: str, **kwargs) -> Dict[str, Any]: - response = await client.request(method, path, **kwargs) - response.raise_for_status() - return response.json() - - about = await request('GET', path='/about') - logger.opt(colors=True).debug('Mirai API HTTP backend version: ' - f'{about["data"]["version"]}') - - status = await request('POST', path='/auth', json={'authKey': auth_key}) - assert status['code'] == 0 - session_key = status['session'] - - verify = await request('POST', - path='/verify', - json={ - 'sessionKey': session_key, - 'qq': qq - }) - assert verify['code'] == 0, verify['msg'] - return session_key - - class WebSocket(BaseWebSocket): @classmethod @@ -59,6 +30,7 @@ class WebSocket(BaseWebSocket): listen_address = httpx.URL(f'ws://{host}:{port}/all', params={'sessionKey': session_key}) websocket = await websockets.connect(uri=str(listen_address)) + await (await websocket.ping()) return cls(websocket) @overrides(BaseWebSocket) @@ -116,25 +88,24 @@ class WebSocket(BaseWebSocket): return callable -class MiraiWebsocketBot(BaseBot): +class MiraiWebsocketBot(MiraiBot): + @overrides(MiraiBot) def __init__(self, connection_type: str, self_id: str, *, websocket: WebSocket): super().__init__(connection_type, self_id, websocket=websocket) - websocket.handle(self.handle_message) - self.driver._bot_connect(self) @property - @overrides(BaseBot) + @overrides(MiraiBot) def type(self) -> str: - return "mirai" + return "mirai-ws" @property def alive(self) -> bool: return not self.websocket.closed @classmethod - @overrides(BaseBot) + @overrides(MiraiBot) async def check_permission(cls, driver: "Driver", connection_type: str, headers: dict, body: Optional[dict]) -> NoReturn: raise RequestDenied( @@ -142,7 +113,7 @@ class MiraiWebsocketBot(BaseBot): reason=f'Connection {connection_type} not implented') @classmethod - @overrides(BaseBot) + @overrides(MiraiBot) def register(cls, driver: "Driver", config: "Config", qq: int): cls.mirai_config = MiraiConfig(**config.dict()) cls.active = True @@ -152,32 +123,33 @@ class MiraiWebsocketBot(BaseBot): super().register(driver, config) async def _bot_connection(): - async with httpx.AsyncClient( - base_url= - f'http://{cls.mirai_config.host}:{cls.mirai_config.port}' - ) as client: - session_key = await _ws_authorization( - client, - auth_key=cls.mirai_config.auth_key, # type: ignore - qq=qq) # type: ignore - + session: SessionManager = await SessionManager.new( + qq, + host=cls.mirai_config.host, # type: ignore + port=cls.mirai_config.port, # type: ignore + auth_key=cls.mirai_config.auth_key # type: ignore + ) websocket = await WebSocket.new( host=cls.mirai_config.host, # type: ignore port=cls.mirai_config.port, # type: ignore - session_key=session_key) + session_key=session.session_key) bot = cls(connection_type='forward_ws', self_id=str(qq), websocket=websocket) websocket.handle(bot.handle_message) - driver._clients[str(qq)] = bot await websocket.accept() + return bot async def _connection_ensure(): - if str(qq) not in driver._clients: - await _bot_connection() - elif not driver._clients[str(qq)].alive: - driver._clients.pop(str(qq), None) - await _bot_connection() + self_id = str(qq) + if self_id not in driver._clients: + bot = await _bot_connection() + driver._bot_connect(bot) + else: + bot = driver._clients[self_id] + if not bot.alive: + driver._bot_disconnect(bot) + return @driver.on_startup async def _startup(): @@ -202,19 +174,3 @@ class MiraiWebsocketBot(BaseBot): if bot is None: return await bot.websocket.close() #type:ignore - - @overrides(BaseBot) - async def handle_message(self, message: dict): - event = Event.new(message) - await handle_event(self, event) - - @overrides(BaseBot) - async def call_api(self, api: str, **data): - return super().call_api(api, **data) - - @overrides(BaseBot) - async def send(self, event: "BaseEvent", message: str, **kwargs): - return super().send(event, message, **kwargs) - - def __del__(self): - self.driver._bot_disconnect(self) diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 6fbb30ff..3b6916f5 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -86,7 +86,7 @@ class Event(BaseEvent): @overrides(BaseEvent) def get_event_description(self) -> str: - return str(self.dict()) + return str(self.normalize_dict()) @overrides(BaseEvent) def get_message(self) -> BaseMessage: diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py index ef3949a6..a577a807 100644 --- a/nonebot/adapters/mirai/message.py +++ b/nonebot/adapters/mirai/message.py @@ -135,10 +135,11 @@ class MessageSegment(BaseMessageSegment): return cls(type=MessageType.POKE, name=name) -class MessageChain(BaseMessage): +class MessageChain(BaseMessage): #type:List[MessageSegment] @overrides(BaseMessage) - def __init__(self, message: Union[List[Dict[str, Any]], MessageSegment], + def __init__(self, message: Union[List[Dict[str, Any]], + Iterable[MessageSegment], MessageSegment], **kwargs): super().__init__(**kwargs) if isinstance(message, MessageSegment): @@ -152,15 +153,16 @@ class MessageChain(BaseMessage): @overrides(BaseMessage) def _construct( - self, message: Iterable[Union[Dict[str, Any], MessageSegment]] + self, message: Union[List[Dict[str, Any]], Iterable[MessageSegment]] ) -> List[MessageSegment]: if isinstance(message, str): raise ValueError( "String operation is not supported in mirai adapter") return [ *map( - lambda segment: segment if isinstance(segment, MessageSegment) - else MessageSegment(**segment), message) + lambda x: x + if isinstance(x, MessageSegment) else MessageSegment(**x), + message) ] def export(self) -> List[Dict[str, Any]]: From 20b299c75802aefbf7198a80631a1fe7a1f9de9e Mon Sep 17 00:00:00 2001 From: Mix Date: Sun, 31 Jan 2021 17:01:04 +0800 Subject: [PATCH 47/86] :children_crossing: add .approve and .reject method for request event in mirai adapter --- nonebot/adapters/mirai/event/request.py | 71 +++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py index 44a70c17..27fea4d8 100644 --- a/nonebot/adapters/mirai/event/request.py +++ b/nonebot/adapters/mirai/event/request.py @@ -1,7 +1,13 @@ +from typing import TYPE_CHECKING +from typing_extensions import Literal + from pydantic import Field from .base import Event +if TYPE_CHECKING: + from ..bot import MiraiBot as Bot + class RequestEvent(Event): event_id: int = Field(alias='eventId') @@ -13,14 +19,79 @@ class NewFriendRequestEvent(RequestEvent): from_id: int = Field(alias='fromId') group_id: int = Field(0, alias='groupId') + async def approve(self, bot: "Bot"): + return await bot.api.post('/resp/newFriendRequestEvent', + params={ + 'eventId': self.event_id, + 'groupId': self.group_id, + 'fromId': self.from_id, + 'operate': 0 + }) + + async def reject(self, + bot: "Bot", + operate: Literal[1, 2] = 1, + message: str = ''): + assert operate > 0 + return await bot.api.post('/resp/newFriendRequestEvent', + params={ + 'eventId': self.event_id, + 'groupId': self.group_id, + 'fromId': self.from_id, + 'operate': operate, + 'message': message + }) + class MemberJoinRequestEvent(RequestEvent): from_id: int = Field(alias='fromId') group_id: int = Field(alias='groupId') group_name: str = Field(alias='groupName') + async def approve(self, bot: "Bot"): + return await bot.api.post('/resp/memberJoinRequestEvent', + params={ + 'eventId': self.event_id, + 'groupId': self.group_id, + 'fromId': self.from_id, + 'operate': 0 + }) + + async def reject(self, + bot: "Bot", + operate: Literal[1, 2, 3, 4] = 1, + message: str = ''): + assert operate > 0 + return await bot.api.post('/resp/memberJoinRequestEvent', + params={ + 'eventId': self.event_id, + 'groupId': self.group_id, + 'fromId': self.from_id, + 'operate': operate, + 'message': message + }) + class BotInvitedJoinGroupRequestEvent(RequestEvent): from_id: int = Field(alias='fromId') group_id: int = Field(alias='groupId') group_name: str = Field(alias='groupName') + + async def approve(self, bot: "Bot"): + return await bot.api.post('/resp/botInvitedJoinGroupRequestEvent', + params={ + 'eventId': self.event_id, + 'groupId': self.group_id, + 'fromId': self.from_id, + 'operate': 0 + }) + + async def reject(self, bot: "Bot", message: str = ""): + return await bot.api.post('/resp/botInvitedJoinGroupRequestEvent', + params={ + 'eventId': self.event_id, + 'groupId': self.group_id, + 'fromId': self.from_id, + 'operate': 1, + 'message': message + }) From 7b04854b43b9de63ce9929d463fc5b31be666318 Mon Sep 17 00:00:00 2001 From: nonebot Date: Sun, 31 Jan 2021 09:56:46 +0000 Subject: [PATCH 48/86] :memo: update api docs --- docs/api/drivers/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/drivers/README.md b/docs/api/drivers/README.md index 77485ed2..673697b4 100644 --- a/docs/api/drivers/README.md +++ b/docs/api/drivers/README.md @@ -120,7 +120,7 @@ Driver 基类。将后端框架封装,以满足适配器使用。 -### `register_adapter(name, adapter)` +### `register_adapter(name, adapter, **kwargs)` * **说明** From a39785d6d9d27284091e5ff3ba4351a3cdb26c21 Mon Sep 17 00:00:00 2001 From: Mix Date: Sun, 31 Jan 2021 18:00:32 +0800 Subject: [PATCH 49/86] :bulb: add some comments in mirai adapter --- nonebot/adapters/mirai/bot.py | 92 +++++++++++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index ebb9b768..27e91066 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -72,6 +72,7 @@ class SessionManager: async def upload(self, path: str, *, type: str, file: Tuple[str, BytesIO]) -> Dict[str, Any]: + file_type, file_io = file response = await self.client.post(path, data={ @@ -186,6 +187,21 @@ class MiraiBot(BaseBot): event: Event, message: Union[MessageChain, MessageSegment, str], at_sender: bool = False): + """ + :说明: + + 根据 ``event`` 向触发事件的主题发送信息 + + :参数: + + * ``event: Event``: Event对象 + * ``message: Union[MessageChain, MessageSegment, str]``: 要发送的消息 + * ``at_sender: bool``: 是否 @ 事件主题 + + :返回: + + - ``Any``: API 调用返回数据 + """ if isinstance(message, MessageSegment): message = MessageChain(message) elif isinstance(message, str): @@ -207,6 +223,20 @@ class MiraiBot(BaseBot): async def send_friend_message(self, target: int, message_chain: MessageChain): + """ + :说明: + + 使用此方法向指定好友发送消息 + + :参数: + + * ``target: int``: 发送消息目标好友的 QQ 号 + * ``message_chain: MessageChain``: 消息链,是一个消息对象构成的数组 + + :返回: + + - ``Any``: API 调用返回数据 + """ return await self.api.post('sendFriendMessage', params={ 'target': target, @@ -215,6 +245,21 @@ class MiraiBot(BaseBot): async def send_temp_message(self, qq: int, group: int, message_chain: MessageChain): + """ + :说明: + + 使用此方法向临时会话对象发送消息 + + :参数: + + * ``qq: int``: 临时会话对象 QQ 号 + * ``group: int``: 临时会话群号 + * ``message_chain: MessageChain``: 消息链,是一个消息对象构成的数组 + + :返回: + + - ``Any``: API 调用返回数据 + """ return await self.api.post('sendTempMessage', params={ 'qq': qq, @@ -226,6 +271,21 @@ class MiraiBot(BaseBot): group: int, message_chain: MessageChain, quote: Optional[int] = None): + """ + :说明: + + 使用此方法向指定群发送消息 + + :参数: + + * ``group: int``: 发送消息目标群的群号 + * ``message_chain: MessageChain``: 消息链,是一个消息对象构成的数组 + * ``quote: Optional[int]``: 引用一条消息的 message_id 进行回复 + + :返回: + + - ``Any``: API 调用返回数据 + """ return await self.api.post('sendGroupMessage', params={ 'group': group, @@ -234,10 +294,42 @@ class MiraiBot(BaseBot): }) async def recall(self, target: int): + """ + :说明: + + 使用此方法撤回指定消息。对于bot发送的消息,有2分钟时间限制。对于撤回群聊中群员的消息,需要有相应权限 + + :参数: + + * ``target: int``: 需要撤回的消息的message_id + + :返回: + + - ``Any``: API 调用返回数据 + """ return await self.api.post('recall', params={'target': target}) async def send_image_message(self, target: int, qq: int, group: int, urls: List[str]): + """ + :说明: + + 使用此方法向指定对象(群或好友)发送图片消息 + 除非需要通过此手段获取image_id,否则不推荐使用该接口 + + > 当qq和group同时存在时,表示发送临时会话图片,qq为临时会话对象QQ号,group为临时会话发起的群号 + + :参数: + + * ``target: int``: [description] + * ``qq: int``: [description] + * ``group: int``: [description] + * ``urls: List[str]``: [description] + + :返回: + + - ``[type]``: [description] + """ return await self.api.post('sendImageMessage', params={ 'target': target, From 858639bebe592c15fa98ccbbc698ce717e6f0395 Mon Sep 17 00:00:00 2001 From: Mix Date: Sun, 31 Jan 2021 22:43:43 +0800 Subject: [PATCH 50/86] :bulb: :memo: add some comments in code, add document build struct for mirai adapter --- docs_build/README.rst | 1 + docs_build/adapters/mirai.rst | 72 +++++++ nonebot/adapters/mirai/bot.py | 276 ++++++++++++++++++++++-- nonebot/adapters/mirai/event/request.py | 69 ++++++ 4 files changed, 400 insertions(+), 18 deletions(-) create mode 100644 docs_build/adapters/mirai.rst diff --git a/docs_build/README.rst b/docs_build/README.rst index 95ffcc2d..4a273041 100644 --- a/docs_build/README.rst +++ b/docs_build/README.rst @@ -18,3 +18,4 @@ NoneBot Api Reference - `nonebot.adapters `_ - `nonebot.adapters.cqhttp `_ - `nonebot.adapters.ding `_ + - `nonebot.adapters.mirai `_ diff --git a/docs_build/adapters/mirai.rst b/docs_build/adapters/mirai.rst new file mode 100644 index 00000000..1f6e3eaf --- /dev/null +++ b/docs_build/adapters/mirai.rst @@ -0,0 +1,72 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +NoneBot.adapters.mirai 模块 +=========================== + +.. automodule:: nonebot.adapters.mirai + +NoneBot.adapters.mirai.bot 模块 +===================================== + +.. automodule:: nonebot.adapters.mirai.bot + :members: + :show-inheritance: + +NoneBot.adapters.mirai.bot_ws 模块 +===================================== + +.. automodule:: nonebot.adapters.mirai.bot_ws + :members: + :show-inheritance: + +NoneBot.adapters.mirai.config 模块 +===================================== + +.. automodule:: nonebot.adapters.mirai.config + :members: + :show-inheritance: + +NoneBot.adapters.mirai.message 模块 +==================================== + +.. automodule:: nonebot.adapters.mirai.message + :members: + :show-inheritance: + +NoneBot.adapters.mirai.event 模块 +==================================== + +.. automodule:: nonebot.adapters.mirai.event + :members: + :show-inheritance: + +NoneBot.adapters.mirai.event.base 模块 +==================================== + +.. automodule:: nonebot.adapters.mirai.event.base + :members: + :show-inheritance: + +NoneBot.adapters.mirai.event.message 模块 +==================================== + +.. automodule:: nonebot.adapters.mirai.event.message + :members: + :show-inheritance: + +NoneBot.adapters.mirai.event.notice 模块 +==================================== + +.. automodule:: nonebot.adapters.mirai.event.notice + :members: + :show-inheritance: + +NoneBot.adapters.mirai.event.request 模块 +==================================== + +.. automodule:: nonebot.adapters.mirai.event.request + :members: + :show-inheritance: \ No newline at end of file diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 27e91066..81c7f7b7 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -22,13 +22,13 @@ from .message import MessageChain, MessageSegment class ActionFailed(BaseActionFailed): - def __init__(self, code: int, message: str = ''): + def __init__(self, **kwargs): super().__init__('mirai') - self.code = code - self.message = message + self.data = kwargs.copy() def __repr__(self): - return f"{self.__class__.__name__}(code={self.code}, message={self.message!r})" + return self.__class__.__name__ + '(%s)' % ', '.join( + map(lambda m: '%s=%r' % m, self.data.items())) class SessionManager: @@ -44,7 +44,7 @@ class SessionManager: logger.opt(colors=True).debug('Mirai API returned data: ' f'{escape_tag(str(data))}') if code != 0: - raise ActionFailed(code, message=data['msg']) + raise ActionFailed(**data) return data async def post(self, @@ -310,7 +310,7 @@ class MiraiBot(BaseBot): return await self.api.post('recall', params={'target': target}) async def send_image_message(self, target: int, qq: int, group: int, - urls: List[str]): + urls: List[str]) -> List[str]: """ :说明: @@ -321,14 +321,14 @@ class MiraiBot(BaseBot): :参数: - * ``target: int``: [description] - * ``qq: int``: [description] - * ``group: int``: [description] - * ``urls: List[str]``: [description] + * ``target: int``: 发送对象的QQ号或群号,可能存在歧义 + * ``qq: int``: 发送对象的QQ号 + * ``group: int``: 发送对象的群号 + * ``urls: List[str]``: 是一个url字符串构成的数组 :返回: - - ``[type]``: [description] + - ``List[str]``: 一个包含图片imageId的数组 """ return await self.api.post('sendImageMessage', params={ @@ -336,48 +336,174 @@ class MiraiBot(BaseBot): 'qq': qq, 'group': group, 'urls': urls - }) + }) # type: ignore async def upload_image(self, type: str, img: BytesIO): + """ + :说明: + + 使用此方法上传图片文件至服务器并返回Image_id + + :参数: + + * ``type: str``: "friend" 或 "group" 或 "temp" + * ``img: BytesIO``: 图片的BytesIO对象 + + :返回: + + - ``Any``: API 调用返回数据 + """ return await self.api.upload('uploadImage', type=type, file=('img', img)) async def upload_voice(self, type: str, voice: BytesIO): + """ + :说明: + + 使用此方法上传语音文件至服务器并返回voice_id + + :参数: + + * ``type: str``: 当前仅支持 "group" + * ``voice: BytesIO``: 语音的BytesIO对象 + + :返回: + + - ``Any``: API 调用返回数据 + """ return await self.api.upload('uploadVoice', type=type, file=('voice', voice)) - async def fetch_message(self): - return await self.api.request('fetchMessage') + async def fetch_message(self, count: int = 10): + """ + :说明: - async def fetch_latest_message(self): - return await self.api.request('fetchLatestMessage') + 使用此方法获取bot接收到的最老消息和最老各类事件 + (会从MiraiApiHttp消息记录中删除) - async def peek_message(self, count: int): + :参数: + + * ``count: int``: 获取消息和事件的数量 + """ + return await self.api.request('fetchMessage', params={'count': count}) + + async def fetch_latest_message(self, count: int = 10): + """ + :说明: + + 使用此方法获取bot接收到的最新消息和最新各类事件 + (会从MiraiApiHttp消息记录中删除) + + :参数: + + * ``count: int``: 获取消息和事件的数量 + """ + return await self.api.request('fetchLatestMessage', + params={'count': count}) + + async def peek_message(self, count: int = 10): + """ + :说明: + + 使用此方法获取bot接收到的最老消息和最老各类事件 + (不会从MiraiApiHttp消息记录中删除) + + :参数: + + * ``count: int``: 获取消息和事件的数量 + """ return await self.api.request('peekMessage', params={'count': count}) - async def peek_latest_message(self, count: int): + async def peek_latest_message(self, count: int = 10): + """ + :说明: + + 使用此方法获取bot接收到的最新消息和最新各类事件 + (不会从MiraiApiHttp消息记录中删除) + + :参数: + + * ``count: int``: 获取消息和事件的数量 + """ return await self.api.request('peekLatestMessage', params={'count': count}) async def messsage_from_id(self, id: int): + """ + :说明: + + 通过messageId获取一条被缓存的消息 + 使用此方法获取bot接收到的消息和各类事件 + + :参数: + + * ``id: int``: 获取消息的message_id + """ return await self.api.request('messageFromId', params={'id': id}) async def count_message(self): + """ + :说明: + + 使用此方法获取bot接收并缓存的消息总数,注意不包含被删除的 + """ return await self.api.request('countMessage') async def friend_list(self) -> List[Dict[str, Any]]: + """ + :说明: + + 使用此方法获取bot的好友列表 + + :返回: + + - ``List[Dict[str, Any]]``: 返回的好友列表数据 + """ return await self.api.request('friendList') # type: ignore async def group_list(self) -> List[Dict[str, Any]]: + """ + :说明: + + 使用此方法获取bot的群列表 + + :返回: + + - ``List[Dict[str, Any]]``: 返回的群列表数据 + """ return await self.api.request('groupList') # type: ignore async def member_list(self, target: int) -> List[Dict[str, Any]]: + """ + :说明: + + 使用此方法获取bot指定群种的成员列表 + + :参数: + + * ``target: int``: 指定群的群号 + + :返回: + + - ``List[Dict[str, Any]]``: 返回的群成员列表数据 + """ return await self.api.request('memberList', params={'target': target}) # type: ignore async def mute(self, target: int, member_id: int, time: int): + """ + :说明: + + 使用此方法指定群禁言指定群员(需要有相关权限) + + :参数: + + * ``target: int``: 指定群的群号 + * ``member_id: int``: 指定群员QQ号 + * ``time: int``: 禁言时长,单位为秒,最多30天 + """ return await self.api.post('mute', params={ 'target': target, @@ -386,6 +512,16 @@ class MiraiBot(BaseBot): }) async def unmute(self, target: int, member_id: int): + """ + :说明: + + 使用此方法指定群解除群成员禁言(需要有相关权限) + + :参数: + + * ``target: int``: 指定群的群号 + * ``member_id: int``: 指定群员QQ号 + """ return await self.api.post('unmute', params={ 'target': target, @@ -393,6 +529,17 @@ class MiraiBot(BaseBot): }) async def kick(self, target: int, member_id: int, msg: str): + """ + :说明: + + 使用此方法移除指定群成员(需要有相关权限) + + :参数: + + * ``target: int``: 指定群的群号 + * ``member_id: int``: 指定群员QQ号 + * ``msg: str``: 信息 + """ return await self.api.post('kick', params={ 'target': target, @@ -401,18 +548,77 @@ class MiraiBot(BaseBot): }) async def quit(self, target: int): + """ + :说明: + + 使用此方法使Bot退出群聊 + + :参数: + + * ``target: int``: 退出的群号 + """ return await self.api.post('quit', params={'target': target}) async def mute_all(self, target: int): + """ + :说明: + + 使用此方法令指定群进行全体禁言(需要有相关权限) + + :参数: + + * ``target: int``: 指定群的群号 + """ return await self.api.post('muteAll', params={'target': target}) async def unmute_all(self, target: int): + """ + :说明: + + 使用此方法令指定群解除全体禁言(需要有相关权限) + + :参数: + + * ``target: int``: 指定群的群号 + """ return await self.api.post('unmuteAll', params={'target': target}) async def group_config(self, target: int): + """ + :说明: + + 使用此方法获取群设置 + + :参数: + + * ``target: int``: 指定群的群号 + + :返回: + + .. code-block:: json + + { + "name": "群名称", + "announcement": "群公告", + "confessTalk": true, + "allowMemberInvite": true, + "autoApprove": true, + "anonymousChat": true + } + """ return await self.api.request('groupConfig', params={'target': target}) async def modify_group_config(self, target: int, config: Dict[str, Any]): + """ + :说明: + + 使用此方法修改群设置(需要有相关权限) + + :参数: + + * ``target: int``: 指定群的群号 + * ``config: Dict[str, Any]``: 群设置, 格式见 ``group_config`` 的返回值 + """ return await self.api.post('groupConfig', params={ 'target': target, @@ -420,6 +626,25 @@ class MiraiBot(BaseBot): }) async def member_info(self, target: int, member_id: int): + """ + :说明: + + 使用此方法获取群员资料 + + :参数: + + * ``target: int``: 指定群的群号 + * ``member_id: int``: 群员QQ号 + + :返回: + + .. code-block:: json + + { + "name": "群名片", + "specialTitle": "群头衔" + } + """ return await self.api.request('memberInfo', params={ 'target': target, @@ -428,6 +653,21 @@ class MiraiBot(BaseBot): async def modify_member_info(self, target: int, member_id: int, info: Dict[str, Any]): + """ + :说明: + + 使用此方法修改群员资料(需要有相关权限) + + :参数: + + * ``target: int``: 指定群的群号 + * ``member_id: int``: 群员QQ号 + * ``info: Dict[str, Any]``: 群员资料, 格式见 ``member_info`` 的返回值 + + :返回: + + - ``[type]``: [description] + """ return await self.api.post('memberInfo', params={ 'target': target, diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py index 27fea4d8..39c64298 100644 --- a/nonebot/adapters/mirai/event/request.py +++ b/nonebot/adapters/mirai/event/request.py @@ -20,6 +20,15 @@ class NewFriendRequestEvent(RequestEvent): group_id: int = Field(0, alias='groupId') async def approve(self, bot: "Bot"): + """ + :说明: + + 通过此人的好友申请 + + :参数: + + * ``bot: Bot``: 当前的 ``Bot`` 对象 + """ return await bot.api.post('/resp/newFriendRequestEvent', params={ 'eventId': self.event_id, @@ -32,6 +41,23 @@ class NewFriendRequestEvent(RequestEvent): bot: "Bot", operate: Literal[1, 2] = 1, message: str = ''): + """ + :说明: + + 拒绝此人的好友申请 + + :参数: + + * ``bot: Bot``: 当前的 ``Bot`` 对象 + * ``operate: Literal[1, 2]``: 响应的操作类型 + - ``1``: 拒绝添加好友 + - ``2``: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + * ``message: str``: 回复的信息 + + :返回: + + - ``[type]``: [description] + """ assert operate > 0 return await bot.api.post('/resp/newFriendRequestEvent', params={ @@ -49,6 +75,15 @@ class MemberJoinRequestEvent(RequestEvent): group_name: str = Field(alias='groupName') async def approve(self, bot: "Bot"): + """ + :说明: + + 通过此人的加群申请 + + :参数: + + * ``bot: Bot``: 当前的 ``Bot`` 对象 + """ return await bot.api.post('/resp/memberJoinRequestEvent', params={ 'eventId': self.event_id, @@ -61,6 +96,21 @@ class MemberJoinRequestEvent(RequestEvent): bot: "Bot", operate: Literal[1, 2, 3, 4] = 1, message: str = ''): + """ + :说明: + + 拒绝(忽略)此人的加群申请 + + :参数: + + * ``bot: Bot``: 当前的 ``Bot`` 对象 + * ``operate: Literal[1, 2, 3, 4]``: 响应的操作类型 + - ``1``: 拒绝入群 + - ``2``: 忽略请求 + - ``3``: 拒绝入群并添加黑名单,不再接收该用户的入群申请 + - ``4``: 忽略入群并添加黑名单,不再接收该用户的入群申请 + * ``message: str``: 回复的信息 + """ assert operate > 0 return await bot.api.post('/resp/memberJoinRequestEvent', params={ @@ -78,6 +128,15 @@ class BotInvitedJoinGroupRequestEvent(RequestEvent): group_name: str = Field(alias='groupName') async def approve(self, bot: "Bot"): + """ + :说明: + + 通过这份被邀请入群申请 + + :参数: + + * ``bot: Bot``: 当前的 ``Bot`` 对象 + """ return await bot.api.post('/resp/botInvitedJoinGroupRequestEvent', params={ 'eventId': self.event_id, @@ -87,6 +146,16 @@ class BotInvitedJoinGroupRequestEvent(RequestEvent): }) async def reject(self, bot: "Bot", message: str = ""): + """ + :说明: + + 拒绝这份被邀请入群申请 + + :参数: + + * ``bot: Bot``: 当前的 ``Bot`` 对象 + * ``message: str``: 邀请消息 + """ return await bot.api.post('/resp/botInvitedJoinGroupRequestEvent', params={ 'eventId': self.event_id, From ceeb37f8ecdfdc76bc69b05d0f9988749402350c Mon Sep 17 00:00:00 2001 From: nonebot Date: Sun, 31 Jan 2021 14:45:07 +0000 Subject: [PATCH 51/86] :memo: update api docs --- docs/api/README.md | 3 +++ docs/api/adapters/mirai.md | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 docs/api/adapters/mirai.md diff --git a/docs/api/README.md b/docs/api/README.md index 243733f8..36e9803e 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -50,3 +50,6 @@ * [nonebot.adapters.ding](adapters/ding.html) + + + * [nonebot.adapters.mirai](adapters/mirai.html) diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md new file mode 100644 index 00000000..33fbdbf0 --- /dev/null +++ b/docs/api/adapters/mirai.md @@ -0,0 +1,38 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.mirai 模块 + +# NoneBot.adapters.mirai.bot 模块 + +# NoneBot.adapters.mirai.bot_ws 模块 + +# NoneBot.adapters.mirai.config 模块 + +# NoneBot.adapters.mirai.message 模块 + + +## _class_ `MessageType` + +基类:`str`, `enum.Enum` + +An enumeration. + +# NoneBot.adapters.mirai.event 模块 + +# NoneBot.adapters.mirai.event.base 模块 + + +## _class_ `SenderPermission` + +基类:`str`, `enum.Enum` + +An enumeration. + +# NoneBot.adapters.mirai.event.message 模块 + +# NoneBot.adapters.mirai.event.notice 模块 + +# NoneBot.adapters.mirai.event.request 模块 From 7c9cbe7b58b4017c4b60ff327ee3904fd799744a Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 00:01:31 +0800 Subject: [PATCH 52/86] :speech_balloon: :bulb: rename some dataclass, add comments for events in mirai adapter --- docs_build/adapters/mirai.rst | 25 +++++--- nonebot/adapters/mirai/bot.py | 7 +-- nonebot/adapters/mirai/bot_ws.py | 3 + nonebot/adapters/mirai/event/__init__.py | 2 +- nonebot/adapters/mirai/event/base.py | 35 +++++++++--- nonebot/adapters/mirai/event/message.py | 12 ++-- nonebot/adapters/mirai/event/meta.py | 31 ++++++++++ nonebot/adapters/mirai/event/notice.py | 72 ++++++++++++++++-------- nonebot/adapters/mirai/event/request.py | 6 +- 9 files changed, 143 insertions(+), 50 deletions(-) create mode 100644 nonebot/adapters/mirai/event/meta.py diff --git a/docs_build/adapters/mirai.rst b/docs_build/adapters/mirai.rst index 1f6e3eaf..6f15695b 100644 --- a/docs_build/adapters/mirai.rst +++ b/docs_build/adapters/mirai.rst @@ -9,63 +9,70 @@ NoneBot.adapters.mirai 模块 .. automodule:: nonebot.adapters.mirai NoneBot.adapters.mirai.bot 模块 -===================================== +=============================== .. automodule:: nonebot.adapters.mirai.bot :members: :show-inheritance: NoneBot.adapters.mirai.bot_ws 模块 -===================================== +================================== .. automodule:: nonebot.adapters.mirai.bot_ws :members: :show-inheritance: NoneBot.adapters.mirai.config 模块 -===================================== +================================== .. automodule:: nonebot.adapters.mirai.config :members: :show-inheritance: NoneBot.adapters.mirai.message 模块 -==================================== +=================================== .. automodule:: nonebot.adapters.mirai.message :members: :show-inheritance: NoneBot.adapters.mirai.event 模块 -==================================== +================================= .. automodule:: nonebot.adapters.mirai.event :members: :show-inheritance: NoneBot.adapters.mirai.event.base 模块 -==================================== +====================================== .. automodule:: nonebot.adapters.mirai.event.base :members: :show-inheritance: +NoneBot.adapters.mirai.event.meta 模块 +====================================== + +.. automodule:: nonebot.adapters.mirai.event.meta + :members: + :show-inheritance: + NoneBot.adapters.mirai.event.message 模块 -==================================== +========================================= .. automodule:: nonebot.adapters.mirai.event.message :members: :show-inheritance: NoneBot.adapters.mirai.event.notice 模块 -==================================== +========================================= .. automodule:: nonebot.adapters.mirai.event.notice :members: :show-inheritance: NoneBot.adapters.mirai.event.request 模块 -==================================== +========================================= .. automodule:: nonebot.adapters.mirai.event.request :members: diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 81c7f7b7..ee718997 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -118,6 +118,9 @@ class SessionManager: class MiraiBot(BaseBot): + """ + mirai-api-http 协议 Bot 适配。 + """ @overrides(BaseBot) def __init__(self, @@ -663,10 +666,6 @@ class MiraiBot(BaseBot): * ``target: int``: 指定群的群号 * ``member_id: int``: 群员QQ号 * ``info: Dict[str, Any]``: 群员资料, 格式见 ``member_info`` 的返回值 - - :返回: - - - ``[type]``: [description] """ return await self.api.post('memberInfo', params={ diff --git a/nonebot/adapters/mirai/bot_ws.py b/nonebot/adapters/mirai/bot_ws.py index d20d81dd..560534b6 100644 --- a/nonebot/adapters/mirai/bot_ws.py +++ b/nonebot/adapters/mirai/bot_ws.py @@ -89,6 +89,9 @@ class WebSocket(BaseWebSocket): class MiraiWebsocketBot(MiraiBot): + """ + mirai-api-http 正向 Websocket 协议 Bot 适配。 + """ @overrides(MiraiBot) def __init__(self, connection_type: str, self_id: str, *, diff --git a/nonebot/adapters/mirai/event/__init__.py b/nonebot/adapters/mirai/event/__init__.py index 903f4eb8..8b96ecca 100644 --- a/nonebot/adapters/mirai/event/__init__.py +++ b/nonebot/adapters/mirai/event/__init__.py @@ -1,4 +1,4 @@ -from .base import Event, SenderInfo, PrivateSenderInfo, SenderGroup +from .base import Event, GroupChatInfo, GroupInfo, UserPermission, PrivateChatInfo from .message import * from .notice import * from .request import * \ No newline at end of file diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 3b6916f5..5b1cf7fc 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -11,37 +11,53 @@ from nonebot.log import logger from nonebot.typing import overrides -class SenderPermission(str, Enum): +class UserPermission(str, Enum): + """ + 用户权限枚举类 + + - ``OWNER``: 群主 + - ``ADMINISTRATOR``: 群管理 + - ``MEMBER``: 普通群成员 + """ OWNER = 'OWNER' ADMINISTRATOR = 'ADMINISTRATOR' MEMBER = 'MEMBER' -class SenderGroup(BaseModel): +class GroupInfo(BaseModel): id: int name: str - permission: SenderPermission + permission: UserPermission -class SenderInfo(BaseModel): +class GroupChatInfo(BaseModel): id: int name: str = Field(alias='memberName') - permission: SenderPermission - group: SenderGroup + permission: UserPermission + group: GroupInfo -class PrivateSenderInfo(BaseModel): +class PrivateChatInfo(BaseModel): id: int nickname: str remark: str class Event(BaseEvent): + """ + mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 `mirai-api-http 文档`_ + + .. _mirai-api-http 文档: + https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md + """ self_id: int type: str @classmethod def new(cls, data: Dict[str, Any]) -> "Event": + """ + 此事件类的工厂函数, 能够通过事件数据选择合适的子类进行序列化 + """ type = data['type'] def all_subclasses(cls: Type[Event]): @@ -70,7 +86,7 @@ class Event(BaseEvent): @overrides(BaseEvent) def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: - from . import message, notice, request + from . import message, notice, request, meta if isinstance(self, message.MessageEvent): return 'message' elif isinstance(self, notice.NoticeEvent): @@ -109,4 +125,7 @@ class Event(BaseEvent): return False def normalize_dict(self, **kwargs) -> Dict[str, Any]: + """ + 返回可以被json正常反序列化的结构体 + """ return json.loads(self.json(**kwargs)) diff --git a/nonebot/adapters/mirai/event/message.py b/nonebot/adapters/mirai/event/message.py index 10574d5e..6021ea64 100644 --- a/nonebot/adapters/mirai/event/message.py +++ b/nonebot/adapters/mirai/event/message.py @@ -5,10 +5,11 @@ from pydantic import Field from nonebot.typing import overrides from ..message import MessageChain -from .base import Event, PrivateSenderInfo, SenderInfo +from .base import Event, GroupChatInfo, PrivateChatInfo class MessageEvent(Event): + """消息事件基类""" message_chain: MessageChain = Field(alias='messageChain') sender: Any @@ -30,7 +31,8 @@ class MessageEvent(Event): class GroupMessage(MessageEvent): - sender: SenderInfo + """群消息事件""" + sender: GroupChatInfo @overrides(MessageEvent) def get_session_id(self) -> str: @@ -38,7 +40,8 @@ class GroupMessage(MessageEvent): class FriendMessage(MessageEvent): - sender: PrivateSenderInfo + """好友消息事件""" + sender: PrivateChatInfo @overrides(MessageEvent) def get_user_id(self) -> str: @@ -50,7 +53,8 @@ class FriendMessage(MessageEvent): class TempMessage(MessageEvent): - sender: SenderInfo + """临时会话消息事件""" + sender: GroupChatInfo @overrides def get_session_id(self) -> str: diff --git a/nonebot/adapters/mirai/event/meta.py b/nonebot/adapters/mirai/event/meta.py new file mode 100644 index 00000000..e42baf72 --- /dev/null +++ b/nonebot/adapters/mirai/event/meta.py @@ -0,0 +1,31 @@ +from .base import Event + + +class MetaEvent(Event): + """元事件基类""" + qq: int + + +class BotOnlineEvent(MetaEvent): + """Bot登录成功""" + pass + + +class BotOfflineEventActive(MetaEvent): + """Bot主动离线""" + pass + + +class BotOfflineEventForce(MetaEvent): + """Bot被挤下线""" + pass + + +class BotOfflineEventDropped(MetaEvent): + """Bot被服务器断开或因网络问题而掉线""" + pass + + +class BotReloginEvent(MetaEvent): + """Bot主动重新登录""" + pass \ No newline at end of file diff --git a/nonebot/adapters/mirai/event/notice.py b/nonebot/adapters/mirai/event/notice.py index b758d9c5..276b12d1 100644 --- a/nonebot/adapters/mirai/event/notice.py +++ b/nonebot/adapters/mirai/event/notice.py @@ -2,61 +2,74 @@ from typing import Any, Optional from pydantic import Field -from .base import Event, SenderGroup, SenderInfo, SenderPermission +from .base import Event, GroupChatInfo, GroupInfo, UserPermission class NoticeEvent(Event): + """通知事件基类""" pass class MuteEvent(NoticeEvent): - operator: SenderInfo + """禁言类事件基类""" + operator: GroupChatInfo class BotMuteEvent(MuteEvent): + """Bot被禁言""" pass class BotUnmuteEvent(MuteEvent): + """Bot被取消禁言""" pass class MemberMuteEvent(MuteEvent): + """群成员被禁言事件(该成员不是Bot)""" duration_seconds: int = Field(alias='durationSeconds') - member: SenderInfo - operator: Optional[SenderInfo] = None + member: GroupChatInfo + operator: Optional[GroupChatInfo] = None class MemberUnmuteEvent(MuteEvent): - member: SenderInfo - operator: Optional[SenderInfo] = None + """群成员被取消禁言事件(该成员不是Bot)""" + member: GroupChatInfo + operator: Optional[GroupChatInfo] = None class BotJoinGroupEvent(NoticeEvent): - group: SenderGroup + """Bot加入了一个新群""" + group: GroupInfo class BotLeaveEventActive(BotJoinGroupEvent): + """Bot主动退出一个群""" pass class BotLeaveEventKick(BotJoinGroupEvent): + """Bot被踢出一个群""" pass class MemberJoinEvent(NoticeEvent): - member: SenderInfo - - -class MemberLeaveEventQuit(MemberJoinEvent): - pass + """新人入群的事件""" + member: GroupChatInfo class MemberLeaveEventKick(MemberJoinEvent): - operator: Optional[SenderInfo] = None + """成员被踢出群(该成员不是Bot)""" + operator: Optional[GroupChatInfo] = None + + +class MemberLeaveEventQuit(MemberJoinEvent): + """成员主动离群(该成员不是Bot)""" + pass class FriendRecallEvent(NoticeEvent): + """好友消息撤回""" author_id: int = Field(alias='authorId') message_id: int = Field(alias='messageId') time: int @@ -64,67 +77,80 @@ class FriendRecallEvent(NoticeEvent): class GroupRecallEvent(FriendRecallEvent): - group: SenderGroup - operator: Optional[SenderInfo] = None + """群消息撤回""" + group: GroupInfo + operator: Optional[GroupChatInfo] = None class GroupStateChangeEvent(NoticeEvent): + """群变化事件基类""" origin: Any current: Any - group: SenderGroup - operator: Optional[SenderInfo] = None + group: GroupInfo + operator: Optional[GroupChatInfo] = None class GroupNameChangeEvent(GroupStateChangeEvent): + """某个群名改变""" origin: str current: str class GroupEntranceAnnouncementChangeEvent(GroupStateChangeEvent): + """某群入群公告改变""" origin: str current: str class GroupMuteAllEvent(GroupStateChangeEvent): + """全员禁言""" origin: bool current: bool class GroupAllowAnonymousChatEvent(GroupStateChangeEvent): + """匿名聊天""" origin: bool current: bool class GroupAllowConfessTalkEvent(GroupStateChangeEvent): + """坦白说""" origin: bool current: bool class GroupAllowMemberInviteEvent(GroupStateChangeEvent): + """允许群员邀请好友加群""" origin: bool current: bool class MemberStateChangeEvent(NoticeEvent): - member: SenderInfo - operator: Optional[SenderInfo] = None + """群成员变化事件基类""" + member: GroupChatInfo + operator: Optional[GroupChatInfo] = None class MemberCardChangeEvent(MemberStateChangeEvent): + """群名片改动""" origin: str current: str class MemberSpecialTitleChangeEvent(MemberStateChangeEvent): + """群头衔改动(只有群主有操作限权)""" origin: str current: str class BotGroupPermissionChangeEvent(MemberStateChangeEvent): - origin: SenderPermission - current: SenderPermission + """Bot在群里的权限被改变""" + origin: UserPermission + current: UserPermission class MemberPermissionChangeEvent(MemberStateChangeEvent): - origin: SenderPermission - current: SenderPermission + """成员权限改变的事件(该成员不是Bot)""" + origin: UserPermission + current: UserPermission diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py index 39c64298..cea13aae 100644 --- a/nonebot/adapters/mirai/event/request.py +++ b/nonebot/adapters/mirai/event/request.py @@ -1,7 +1,7 @@ from typing import TYPE_CHECKING -from typing_extensions import Literal from pydantic import Field +from typing_extensions import Literal from .base import Event @@ -10,12 +10,14 @@ if TYPE_CHECKING: class RequestEvent(Event): + """请求事件基类""" event_id: int = Field(alias='eventId') message: str nick: str class NewFriendRequestEvent(RequestEvent): + """添加好友申请""" from_id: int = Field(alias='fromId') group_id: int = Field(0, alias='groupId') @@ -70,6 +72,7 @@ class NewFriendRequestEvent(RequestEvent): class MemberJoinRequestEvent(RequestEvent): + """用户入群申请(Bot需要有管理员权限)""" from_id: int = Field(alias='fromId') group_id: int = Field(alias='groupId') group_name: str = Field(alias='groupName') @@ -123,6 +126,7 @@ class MemberJoinRequestEvent(RequestEvent): class BotInvitedJoinGroupRequestEvent(RequestEvent): + """Bot被邀请入群申请""" from_id: int = Field(alias='fromId') group_id: int = Field(alias='groupId') group_name: str = Field(alias='groupName') From 7fdfd89525622e192f9b1e4acf4dfc4408b45f44 Mon Sep 17 00:00:00 2001 From: nonebot Date: Sun, 31 Jan 2021 16:02:54 +0000 Subject: [PATCH 53/86] :memo: update api docs --- docs/api/adapters/mirai.md | 1034 +++++++++++++++++++++++++++++++++++- 1 file changed, 1032 insertions(+), 2 deletions(-) diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index 33fbdbf0..98b1a640 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -7,8 +7,607 @@ sidebarDepth: 0 # NoneBot.adapters.mirai.bot 模块 + +## _class_ `MiraiBot` + +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) + +mirai-api-http 协议 Bot 适配。 + + +### _async_ `send(event, message, at_sender=False)` + + +* **说明** + + 根据 `event` 向触发事件的主题发送信息 + + + +* **参数** + + + * `event: Event`: Event对象 + + + * `message: Union[MessageChain, MessageSegment, str]`: 要发送的消息 + + + * `at_sender: bool`: 是否 @ 事件主题 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +### _async_ `send_friend_message(target, message_chain)` + + +* **说明** + + 使用此方法向指定好友发送消息 + + + +* **参数** + + + * `target: int`: 发送消息目标好友的 QQ 号 + + + * `message_chain: MessageChain`: 消息链,是一个消息对象构成的数组 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +### _async_ `send_temp_message(qq, group, message_chain)` + + +* **说明** + + 使用此方法向临时会话对象发送消息 + + + +* **参数** + + + * `qq: int`: 临时会话对象 QQ 号 + + + * `group: int`: 临时会话群号 + + + * `message_chain: MessageChain`: 消息链,是一个消息对象构成的数组 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +### _async_ `send_group_message(group, message_chain, quote=None)` + + +* **说明** + + 使用此方法向指定群发送消息 + + + +* **参数** + + + * `group: int`: 发送消息目标群的群号 + + + * `message_chain: MessageChain`: 消息链,是一个消息对象构成的数组 + + + * `quote: Optional[int]`: 引用一条消息的 message_id 进行回复 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +### _async_ `recall(target)` + + +* **说明** + + 使用此方法撤回指定消息。对于bot发送的消息,有2分钟时间限制。对于撤回群聊中群员的消息,需要有相应权限 + + + +* **参数** + + + * `target: int`: 需要撤回的消息的message_id + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +### _async_ `send_image_message(target, qq, group, urls)` + + +* **说明** + + 使用此方法向指定对象(群或好友)发送图片消息 + 除非需要通过此手段获取image_id,否则不推荐使用该接口 + + > 当qq和group同时存在时,表示发送临时会话图片,qq为临时会话对象QQ号,group为临时会话发起的群号 + + + +* **参数** + + + * `target: int`: 发送对象的QQ号或群号,可能存在歧义 + + + * `qq: int`: 发送对象的QQ号 + + + * `group: int`: 发送对象的群号 + + + * `urls: List[str]`: 是一个url字符串构成的数组 + + + +* **返回** + + + * `List[str]`: 一个包含图片imageId的数组 + + + +### _async_ `upload_image(type, img)` + + +* **说明** + + 使用此方法上传图片文件至服务器并返回Image_id + + + +* **参数** + + + * `type: str`: "friend" 或 "group" 或 "temp" + + + * `img: BytesIO`: 图片的BytesIO对象 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +### _async_ `upload_voice(type, voice)` + + +* **说明** + + 使用此方法上传语音文件至服务器并返回voice_id + + + +* **参数** + + + * `type: str`: 当前仅支持 "group" + + + * `voice: BytesIO`: 语音的BytesIO对象 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +### _async_ `fetch_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最老消息和最老各类事件 + (会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### _async_ `fetch_latest_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最新消息和最新各类事件 + (会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### _async_ `peek_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最老消息和最老各类事件 + (不会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### _async_ `peek_latest_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最新消息和最新各类事件 + (不会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### _async_ `messsage_from_id(id)` + + +* **说明** + + 通过messageId获取一条被缓存的消息 + 使用此方法获取bot接收到的消息和各类事件 + + + +* **参数** + + + * `id: int`: 获取消息的message_id + + + +### _async_ `count_message()` + + +* **说明** + + 使用此方法获取bot接收并缓存的消息总数,注意不包含被删除的 + + + +### _async_ `friend_list()` + + +* **说明** + + 使用此方法获取bot的好友列表 + + + +* **返回** + + + * `List[Dict[str, Any]]`: 返回的好友列表数据 + + + +### _async_ `group_list()` + + +* **说明** + + 使用此方法获取bot的群列表 + + + +* **返回** + + + * `List[Dict[str, Any]]`: 返回的群列表数据 + + + +### _async_ `member_list(target)` + + +* **说明** + + 使用此方法获取bot指定群种的成员列表 + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +* **返回** + + + * `List[Dict[str, Any]]`: 返回的群成员列表数据 + + + +### _async_ `mute(target, member_id, time)` + + +* **说明** + + 使用此方法指定群禁言指定群员(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 指定群员QQ号 + + + * `time: int`: 禁言时长,单位为秒,最多30天 + + + +### _async_ `unmute(target, member_id)` + + +* **说明** + + 使用此方法指定群解除群成员禁言(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 指定群员QQ号 + + + +### _async_ `kick(target, member_id, msg)` + + +* **说明** + + 使用此方法移除指定群成员(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 指定群员QQ号 + + + * `msg: str`: 信息 + + + +### _async_ `quit(target)` + + +* **说明** + + 使用此方法使Bot退出群聊 + + + +* **参数** + + + * `target: int`: 退出的群号 + + + +### _async_ `mute_all(target)` + + +* **说明** + + 使用此方法令指定群进行全体禁言(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +### _async_ `unmute_all(target)` + + +* **说明** + + 使用此方法令指定群解除全体禁言(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +### _async_ `group_config(target)` + + +* **说明** + + 使用此方法获取群设置 + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +* **返回** + + +```json +{ + "name": "群名称", + "announcement": "群公告", + "confessTalk": true, + "allowMemberInvite": true, + "autoApprove": true, + "anonymousChat": true +} +``` + + +### _async_ `modify_group_config(target, config)` + + +* **说明** + + 使用此方法修改群设置(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `config: Dict[str, Any]`: 群设置, 格式见 `group_config` 的返回值 + + + +### _async_ `member_info(target, member_id)` + + +* **说明** + + 使用此方法获取群员资料 + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 群员QQ号 + + + +* **返回** + + +```json +{ + "name": "群名片", + "specialTitle": "群头衔" +} +``` + + +### _async_ `modify_member_info(target, member_id, info)` + + +* **说明** + + 使用此方法修改群员资料(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 群员QQ号 + + + * `info: Dict[str, Any]`: 群员资料, 格式见 `member_info` 的返回值 + + # NoneBot.adapters.mirai.bot_ws 模块 + +## _class_ `MiraiWebsocketBot` + +基类:`nonebot.adapters.mirai.bot.MiraiBot` + +mirai-api-http 正向 Websocket 协议 Bot 适配。 + # NoneBot.adapters.mirai.config 模块 # NoneBot.adapters.mirai.message 模块 @@ -25,14 +624,445 @@ An enumeration. # NoneBot.adapters.mirai.event.base 模块 -## _class_ `SenderPermission` +## _class_ `UserPermission` 基类:`str`, `enum.Enum` -An enumeration. +用户权限枚举类 + +> +> * `OWNER`: 群主 + + +> * `ADMINISTRATOR`: 群管理 + + +> * `MEMBER`: 普通群成员 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 [mirai-api-http 文档](https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md) + + +### _classmethod_ `new(data)` + +此事件类的工厂函数, 能够通过事件数据选择合适的子类进行序列化 + + +### `normalize_dict(**kwargs)` + +返回可以被json正常反序列化的结构体 + +# NoneBot.adapters.mirai.event.meta 模块 + + +## _class_ `MetaEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +元事件基类 + + +## _class_ `BotOnlineEvent` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot登录成功 + + +## _class_ `BotOfflineEventActive` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot主动离线 + + +## _class_ `BotOfflineEventForce` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot被挤下线 + + +## _class_ `BotOfflineEventDropped` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot被服务器断开或因网络问题而掉线 + + +## _class_ `BotReloginEvent` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot主动重新登录 # NoneBot.adapters.mirai.event.message 模块 + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +消息事件基类 + + +## _class_ `GroupMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +群消息事件 + + +## _class_ `FriendMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +好友消息事件 + + +## _class_ `TempMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +临时会话消息事件 + # NoneBot.adapters.mirai.event.notice 模块 + +## _class_ `NoticeEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +通知事件基类 + + +## _class_ `MuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +禁言类事件基类 + + +## _class_ `BotMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被禁言 + + +## _class_ `BotUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被取消禁言 + + +## _class_ `MemberMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被禁言事件(该成员不是Bot) + + +## _class_ `MemberUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被取消禁言事件(该成员不是Bot) + + +## _class_ `BotJoinGroupEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +Bot加入了一个新群 + + +## _class_ `BotLeaveEventActive` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot主动退出一个群 + + +## _class_ `BotLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot被踢出一个群 + + +## _class_ `MemberJoinEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +新人入群的事件 + + +## _class_ `MemberLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员被踢出群(该成员不是Bot) + + +## _class_ `MemberLeaveEventQuit` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员主动离群(该成员不是Bot) + + +## _class_ `FriendRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +好友消息撤回 + + +## _class_ `GroupRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.FriendRecallEvent` + +群消息撤回 + + +## _class_ `GroupStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群变化事件基类 + + +## _class_ `GroupNameChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某个群名改变 + + +## _class_ `GroupEntranceAnnouncementChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某群入群公告改变 + + +## _class_ `GroupMuteAllEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +全员禁言 + + +## _class_ `GroupAllowAnonymousChatEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +匿名聊天 + + +## _class_ `GroupAllowConfessTalkEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +坦白说 + + +## _class_ `GroupAllowMemberInviteEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +允许群员邀请好友加群 + + +## _class_ `MemberStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群成员变化事件基类 + + +## _class_ `MemberCardChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群名片改动 + + +## _class_ `MemberSpecialTitleChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群头衔改动(只有群主有操作限权) + + +## _class_ `BotGroupPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +Bot在群里的权限被改变 + + +## _class_ `MemberPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +成员权限改变的事件(该成员不是Bot) + # NoneBot.adapters.mirai.event.request 模块 + + +## _class_ `RequestEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +请求事件基类 + + +## _class_ `NewFriendRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +添加好友申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2]`: 响应的操作类型 + - `1`: 拒绝添加好友 + - `2`: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + + + * `message: str`: 回复的信息 + + + +* **返回** + + + * `[type]`: [description] + + + +## _class_ `MemberJoinRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +用户入群申请(Bot需要有管理员权限) + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝(忽略)此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2, 3, 4]`: 响应的操作类型 + - `1`: 拒绝入群 + - `2`: 忽略请求 + - `3`: 拒绝入群并添加黑名单,不再接收该用户的入群申请 + - `4`: 忽略入群并添加黑名单,不再接收该用户的入群申请 + + + * `message: str`: 回复的信息 + + + +## _class_ `BotInvitedJoinGroupRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +Bot被邀请入群申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, message='')` + + +* **说明** + + 拒绝这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `message: str`: 邀请消息 From 56592fc4134d97a0fe0196b8c0be7d8d2c77bb8d Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 01:04:30 +0800 Subject: [PATCH 54/86] :construction: :bulb: add comments for message etc. in mirai adapter --- nonebot/adapters/mirai/__init__.py | 10 ++ nonebot/adapters/mirai/bot.py | 77 ++++++++++--- nonebot/adapters/mirai/bot_ws.py | 27 ++++- nonebot/adapters/mirai/config.py | 9 ++ nonebot/adapters/mirai/event/__init__.py | 7 ++ nonebot/adapters/mirai/event/base.py | 4 +- nonebot/adapters/mirai/event/request.py | 4 - nonebot/adapters/mirai/message.py | 140 ++++++++++++++++++++++- 8 files changed, 250 insertions(+), 28 deletions(-) diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py index 1107af38..b209657e 100644 --- a/nonebot/adapters/mirai/__init__.py +++ b/nonebot/adapters/mirai/__init__.py @@ -1,3 +1,13 @@ +""" +Mirai-API-HTTP 协议适配 +============================ + +协议详情请看: `mirai-api-http 文档`_ + +.. mirai-api-http 文档: + https://github.com/project-mirai/mirai-api-http/tree/master/docs +""" + from .bot import MiraiBot from .bot_ws import MiraiWebsocketBot from .event import * diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index ee718997..74c4f602 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -32,6 +32,7 @@ class ActionFailed(BaseActionFailed): class SessionManager: + """Bot会话管理器, 提供API主动调用接口""" sessions: Dict[int, Tuple[str, datetime, httpx.AsyncClient]] = {} session_expiry: timedelta = timedelta(minutes=15) @@ -40,19 +41,39 @@ class SessionManager: @staticmethod def _raise_code(data: Dict[str, Any]) -> Dict[str, Any]: - code = data.get('code', 0) - logger.opt(colors=True).debug('Mirai API returned data: ' - f'{escape_tag(str(data))}') - if code != 0: - raise ActionFailed(**data) + logger.opt(colors=True).debug( + f'Mirai API returned data: {escape_tag(str(data))}') + if isinstance(data, dict) and ('code' in data): + if data['code'] != 0: + raise ActionFailed(**data) return data async def post(self, path: str, *, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: - params = {**(params or {}), 'sessionKey': self.session_key} - response = await self.client.post(path, json=params, timeout=3) + """ + :说明: + + 以POST方式主动提交API请求 + + :参数: + + * ``path: str``: 对应API路径 + * ``params: Optional[Dict[str, Any]]``: 请求参数 (无需sessionKey) + + :返回: + + - ``Dict[str, Any]``: API 返回值 + """ + response = await self.client.post( + path, + json={ + **(params or {}), + 'sessionKey': self.session_key, + }, + timeout=3, + ) response.raise_for_status() return self._raise_code(response.json()) @@ -61,12 +82,28 @@ class SessionManager: *, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: - response = await self.client.get(path, - params={ - **(params or {}), 'sessionKey': - self.session_key - }, - timeout=3) + """ + :说明: + + 以GET方式主动提交API请求 + + :参数: + + * ``path: str``: 对应API路径 + * ``params: Optional[Dict[str, Any]]``: 请求参数 (无需sessionKey) + + :返回: + + - ``Dict[str, Any]``: API 返回值 + """ + response = await self.client.get( + path, + params={ + **(params or {}), + 'sessionKey': self.session_key, + }, + timeout=3, + ) response.raise_for_status() return self._raise_code(response.json()) @@ -108,11 +145,11 @@ class SessionManager: return cls(session_key, client) @classmethod - def get(cls, self_id: int): + def get(cls, self_id: int, check_expire: bool = True): if self_id not in cls.sessions: return None key, time, client = cls.sessions[self_id] - if datetime.now() - time > cls.session_expiry: + if check_expire and (datetime.now() - time > cls.session_expiry): return None return cls(key, client) @@ -129,7 +166,6 @@ class MiraiBot(BaseBot): *, websocket: Optional[WebSocket] = None): super().__init__(connection_type, self_id, websocket=websocket) - self.api = SessionManager.get(int(self_id)) @property @overrides(BaseBot) @@ -140,6 +176,13 @@ class MiraiBot(BaseBot): def alive(self) -> bool: return not self.websocket.closed + @property + def api(self) -> SessionManager: + """返回该Bot对象的会话管理实例以提供API主动调用""" + api = SessionManager.get(self_id=int(self.self_id)) + assert api is not None, 'SessionManager has not been initialized' + return api + @classmethod @overrides(BaseBot) async def check_permission(cls, driver: "Driver", connection_type: str, @@ -179,10 +222,12 @@ class MiraiBot(BaseBot): @overrides(BaseBot) async def call_api(self, api: str, **data) -> NoReturn: + """由于Mirai的HTTP API特殊性, 该API暂时无法实现""" raise NotImplementedError @overrides(BaseBot) def __getattr__(self, key: str) -> NoReturn: + """由于Mirai的HTTP API特殊性, 该API暂时无法实现""" raise NotImplementedError @overrides(BaseBot) diff --git a/nonebot/adapters/mirai/bot_ws.py b/nonebot/adapters/mirai/bot_ws.py index 560534b6..ccce63b3 100644 --- a/nonebot/adapters/mirai/bot_ws.py +++ b/nonebot/adapters/mirai/bot_ws.py @@ -107,6 +107,12 @@ class MiraiWebsocketBot(MiraiBot): def alive(self) -> bool: return not self.websocket.closed + @property + def api(self) -> SessionManager: + api = SessionManager.get(self_id=int(self.self_id), check_expire=False) + assert api is not None, 'SessionManager has not been initialized' + return api + @classmethod @overrides(MiraiBot) async def check_permission(cls, driver: "Driver", connection_type: str, @@ -118,12 +124,23 @@ class MiraiWebsocketBot(MiraiBot): @classmethod @overrides(MiraiBot) def register(cls, driver: "Driver", config: "Config", qq: int): - cls.mirai_config = MiraiConfig(**config.dict()) - cls.active = True - assert cls.mirai_config.auth_key is not None - assert cls.mirai_config.host is not None - assert cls.mirai_config.port is not None + """ + :说明: + + 注册该Adapter + + :参数: + + * ``driver: Driver``: 程序所使用的``Driver`` + * ``config: Config``: 程序配置对象 + * ``qq: int``: 要使用的Bot的QQ号 **注意: 在使用正向Websocket时必须指定该值!** + + :返回: + + - ``[type]``: [description] + """ super().register(driver, config) + cls.active = True async def _bot_connection(): session: SessionManager = await SessionManager.new( diff --git a/nonebot/adapters/mirai/config.py b/nonebot/adapters/mirai/config.py index 942cf9fa..a907dd17 100644 --- a/nonebot/adapters/mirai/config.py +++ b/nonebot/adapters/mirai/config.py @@ -5,6 +5,15 @@ from pydantic import BaseModel, Extra, Field class Config(BaseModel): + """ + Mirai 配置类 + + :必填: + + - ``mirai_auth_key``: mirai-api-http的auth_key + - ``mirai_host``: mirai-api-http的地址 + - ``mirai_port``: mirai-api-http的端口 + """ auth_key: Optional[str] = Field(None, alias='mirai_auth_key') host: Optional[IPv4Address] = Field(None, alias='mirai_host') port: Optional[int] = Field(None, alias='mirai_port') diff --git a/nonebot/adapters/mirai/event/__init__.py b/nonebot/adapters/mirai/event/__init__.py index 8b96ecca..c0024e19 100644 --- a/nonebot/adapters/mirai/event/__init__.py +++ b/nonebot/adapters/mirai/event/__init__.py @@ -1,3 +1,10 @@ +""" +\:\:\:warning 警告 +事件中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 + +部分字段可能与文档在符号上不一致 +\:\:\: +""" from .base import Event, GroupChatInfo, GroupInfo, UserPermission, PrivateChatInfo from .message import * from .notice import * diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 5b1cf7fc..662b856d 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -45,9 +45,9 @@ class PrivateChatInfo(BaseModel): class Event(BaseEvent): """ - mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 `mirai-api-http 文档`_ + mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 `mirai-api-http 事件类型`_ - .. _mirai-api-http 文档: + .. _mirai-api-http 事件类型: https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md """ self_id: int diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py index cea13aae..18d466ee 100644 --- a/nonebot/adapters/mirai/event/request.py +++ b/nonebot/adapters/mirai/event/request.py @@ -55,10 +55,6 @@ class NewFriendRequestEvent(RequestEvent): - ``1``: 拒绝添加好友 - ``2``: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 * ``message: str``: 回复的信息 - - :返回: - - - ``[type]``: [description] """ assert operate > 0 return await bot.api.post('/resp/newFriendRequestEvent', diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py index a577a807..265b3b3b 100644 --- a/nonebot/adapters/mirai/message.py +++ b/nonebot/adapters/mirai/message.py @@ -9,6 +9,7 @@ from nonebot.typing import overrides class MessageType(str, Enum): + """消息类型枚举类""" SOURCE = 'Source' QUOTE = 'Quote' AT = 'At' @@ -25,6 +26,13 @@ class MessageType(str, Enum): class MessageSegment(BaseMessageSegment): + """ + CQHTTP 协议 MessageSegment 适配。具体方法参考 `mirai-api-http 消息类型`_ + + .. _mirai-api-http 消息类型: + https://github.com/project-mirai/mirai-api-http/blob/master/docs/MessageType.md + """ + type: MessageType data: Dict[str, Any] @@ -59,6 +67,7 @@ class MessageSegment(BaseMessageSegment): return self.type == MessageType.PLAIN def as_dict(self) -> Dict[str, Any]: + """导出可以被正常json序列化的结构体""" return {'type': self.type.value, **self.data} @classmethod @@ -68,6 +77,19 @@ class MessageSegment(BaseMessageSegment): @classmethod def quote(cls, id: int, group_id: int, sender_id: int, target_id: int, origin: "MessageChain"): + """ + :说明: + + 生成回复引用消息段 + + :参数: + + * ``id: int``: 被引用回复的原消息的message_id + * ``group_id: int``: 被引用回复的原消息所接收的群号,当为好友消息时为0 + * ``sender_id: int``: 被引用回复的原消息的发送者的QQ号 + * ``target_id: int``: 被引用回复的原消息的接收者者的QQ号(或群号) + * ``origin: MessageChain``: 被引用回复的原消息的消息链对象 + """ return cls(type=MessageType.QUOTE, id=id, groupId=group_id, @@ -77,18 +99,51 @@ class MessageSegment(BaseMessageSegment): @classmethod def at(cls, target: int): + """ + :说明: + + @某个人 + + :参数: + + * ``target: int``: 群员QQ号 + """ return cls(type=MessageType.AT, target=target) @classmethod def at_all(cls): + """ + :说明: + + @全体成员 + """ return cls(type=MessageType.AT_ALL) @classmethod def face(cls, face_id: Optional[int] = None, name: Optional[str] = None): + """ + :说明: + + 发送QQ表情 + + :参数: + + * ``face_id: Optional[int]``: QQ表情编号,可选,优先高于name + * ``name: Optional[str]``: QQ表情拼音,可选 + """ return cls(type=MessageType.FACE, faceId=face_id, name=name) @classmethod def plain(cls, text: str): + """ + :说明: + + 纯文本消息 + + :参数: + + * ``text: str``: 文字消息 + """ return cls(type=MessageType.PLAIN, text=text) @classmethod @@ -96,6 +151,21 @@ class MessageSegment(BaseMessageSegment): image_id: Optional[str] = None, url: Optional[str] = None, path: Optional[str] = None): + """ + :说明: + + 图片消息 + + :参数: + + * ``image_id: Optional[str]``: 图片的image_id,群图片与好友图片格式不同。不为空时将忽略url属性 + * ``url: Optional[str]``: 图片的URL,发送时可作网络图片的链接 + * ``path: Optional[str]``: 图片的路径,发送本地图片 + + :返回: + + - ``[type]``: [description] + """ return cls(type=MessageType.IMAGE, imageId=image_id, url=url, path=path) @classmethod @@ -103,6 +173,15 @@ class MessageSegment(BaseMessageSegment): image_id: Optional[str] = None, url: Optional[str] = None, path: Optional[str] = None): + """ + :说明: + + 闪照消息 + + :参数: + + 同 ``image`` + """ return cls(type=MessageType.FLASH_IMAGE, imageId=image_id, url=url, @@ -113,6 +192,17 @@ class MessageSegment(BaseMessageSegment): voice_id: Optional[str] = None, url: Optional[str] = None, path: Optional[str] = None): + """ + :说明: + + 语音消息 + + :参数: + + * ``voice_id: Optional[str]``: 语音的voice_id,不为空时将忽略url属性 + * ``url: Optional[str]``: 语音的URL,发送时可作网络语音的链接 + * ``path: Optional[str]``: 语音的路径,发送本地语音 + """ return cls(type=MessageType.FLASH_IMAGE, imageId=voice_id, url=url, @@ -120,22 +210,69 @@ class MessageSegment(BaseMessageSegment): @classmethod def xml(cls, xml: str): + """ + :说明: + + XML消息 + + :参数: + + * ``xml: str``: XML文本 + """ return cls(type=MessageType.XML, xml=xml) @classmethod def json(cls, json: str): + """ + :说明: + + Json消息 + + :参数: + + * ``json: str``: Json文本 + """ return cls(type=MessageType.JSON, json=json) @classmethod def app(cls, content: str): + """ + :说明: + + 应用程序消息 + + :参数: + + * ``content: str``: 内容 + """ return cls(type=MessageType.APP, content=content) @classmethod def poke(cls, name: str): + """ + :说明: + + 戳一戳消息 + + :参数: + + * ``name: str``: 戳一戳的类型 + - "Poke": 戳一戳 + - "ShowLove": 比心 + - "Like": 点赞 + - "Heartbroken": 心碎 + - "SixSixSix": 666 + - "FangDaZhao": 放大招 + """ return cls(type=MessageType.POKE, name=name) -class MessageChain(BaseMessage): #type:List[MessageSegment] +class MessageChain(BaseMessage): + """ + Mirai 协议 Messaqge 适配 + + 由于Mirai协议的Message实现较为特殊, 故使用MessageChain命名 + """ @overrides(BaseMessage) def __init__(self, message: Union[List[Dict[str, Any]], @@ -166,6 +303,7 @@ class MessageChain(BaseMessage): #type:List[MessageSegment] ] def export(self) -> List[Dict[str, Any]]: + """导出为可以被正常json序列化的数组""" return [ *map(lambda segment: segment.as_dict(), self.copy()) # type: ignore ] From 923cbd3b8c5a592fccc652e471e2681a583c633c Mon Sep 17 00:00:00 2001 From: nonebot Date: Sun, 31 Jan 2021 17:05:56 +0000 Subject: [PATCH 55/86] :memo: update api docs --- docs/api/adapters/mirai.md | 396 ++++++++++++++++++++++++++++++++++++- 1 file changed, 387 insertions(+), 9 deletions(-) diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index 98b1a640..9911ffec 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -5,9 +5,79 @@ sidebarDepth: 0 # NoneBot.adapters.mirai 模块 +## Mirai-API-HTTP 协议适配 + +协议详情请看: + +``` +`mirai-api-http 文档`_ +``` + + + # NoneBot.adapters.mirai.bot 模块 +## _class_ `SessionManager` + +基类:`object` + +Bot会话管理器, 提供API主动调用接口 + + +### _async_ `post(path, *, params=None)` + + +* **说明** + + 以POST方式主动提交API请求 + + + +* **参数** + + + * `path: str`: 对应API路径 + + + * `params: Optional[Dict[str, Any]]`: 请求参数 (无需sessionKey) + + + +* **返回** + + + * `Dict[str, Any]`: API 返回值 + + + +### _async_ `request(path, *, params=None)` + + +* **说明** + + 以GET方式主动提交API请求 + + + +* **参数** + + + * `path: str`: 对应API路径 + + + * `params: Optional[Dict[str, Any]]`: 请求参数 (无需sessionKey) + + + +* **返回** + + + * `Dict[str, Any]`: API 返回值 + + + ## _class_ `MiraiBot` 基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) @@ -15,6 +85,16 @@ sidebarDepth: 0 mirai-api-http 协议 Bot 适配。 +### _property_ `api` + +返回该Bot对象的会话管理实例以提供API主动调用 + + +### _async_ `call_api(api, **data)` + +由于Mirai的HTTP API特殊性, 该API暂时无法实现 + + ### _async_ `send(event, message, at_sender=False)` @@ -608,8 +688,57 @@ mirai-api-http 协议 Bot 适配。 mirai-api-http 正向 Websocket 协议 Bot 适配。 + +### _classmethod_ `register(driver, config, qq)` + + +* **说明** + + 注册该Adapter + + + +* **参数** + + + * `driver: Driver`: 程序所使用的\`\`Driver\`\` + + + * `config: Config`: 程序配置对象 + + + * `qq: int`: 要使用的Bot的QQ号 **注意: 在使用正向Websocket时必须指定该值!** + + + +* **返回** + + + * `[type]`: [description] + + # NoneBot.adapters.mirai.config 模块 + +## _class_ `Config` + +基类:`pydantic.main.BaseModel` + +Mirai 配置类 + + +* **必填** + + + * `mirai_auth_key`: mirai-api-http的auth_key + + + * `mirai_host`: mirai-api-http的地址 + + + * `mirai_port`: mirai-api-http的端口 + + # NoneBot.adapters.mirai.message 模块 @@ -617,10 +746,266 @@ mirai-api-http 正向 Websocket 协议 Bot 适配。 基类:`str`, `enum.Enum` -An enumeration. +消息类型枚举类 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) + +CQHTTP 协议 MessageSegment 适配。具体方法参考 [mirai-api-http 消息类型](https://github.com/project-mirai/mirai-api-http/blob/master/docs/MessageType.md) + + +### `as_dict()` + +导出可以被正常json序列化的结构体 + + +### _classmethod_ `quote(id, group_id, sender_id, target_id, origin)` + + +* **说明** + + 生成回复引用消息段 + + + +* **参数** + + + * `id: int`: 被引用回复的原消息的message_id + + + * `group_id: int`: 被引用回复的原消息所接收的群号,当为好友消息时为0 + + + * `sender_id: int`: 被引用回复的原消息的发送者的QQ号 + + + * `target_id: int`: 被引用回复的原消息的接收者者的QQ号(或群号) + + + * `origin: MessageChain`: 被引用回复的原消息的消息链对象 + + + +### _classmethod_ `at(target)` + + +* **说明** + + @某个人 + + + +* **参数** + + + * `target: int`: 群员QQ号 + + + +### _classmethod_ `at_all()` + + +* **说明** + + @全体成员 + + + +### _classmethod_ `face(face_id=None, name=None)` + + +* **说明** + + 发送QQ表情 + + + +* **参数** + + + * `face_id: Optional[int]`: QQ表情编号,可选,优先高于name + + + * `name: Optional[str]`: QQ表情拼音,可选 + + + +### _classmethod_ `plain(text)` + + +* **说明** + + 纯文本消息 + + + +* **参数** + + + * `text: str`: 文字消息 + + + +### _classmethod_ `image(image_id=None, url=None, path=None)` + + +* **说明** + + 图片消息 + + + +* **参数** + + + * `image_id: Optional[str]`: 图片的image_id,群图片与好友图片格式不同。不为空时将忽略url属性 + + + * `url: Optional[str]`: 图片的URL,发送时可作网络图片的链接 + + + * `path: Optional[str]`: 图片的路径,发送本地图片 + + + +* **返回** + + + * `[type]`: [description] + + + +### _classmethod_ `flash_image(image_id=None, url=None, path=None)` + + +* **说明** + + 闪照消息 + + + +* **参数** + + 同 `image` + + + +### _classmethod_ `voice(voice_id=None, url=None, path=None)` + + +* **说明** + + 语音消息 + + + +* **参数** + + + * `voice_id: Optional[str]`: 语音的voice_id,不为空时将忽略url属性 + + + * `url: Optional[str]`: 语音的URL,发送时可作网络语音的链接 + + + * `path: Optional[str]`: 语音的路径,发送本地语音 + + + +### _classmethod_ `xml(xml)` + + +* **说明** + + XML消息 + + + +* **参数** + + + * `xml: str`: XML文本 + + + +### _classmethod_ `json(json)` + + +* **说明** + + Json消息 + + + +* **参数** + + + * `json: str`: Json文本 + + + +### _classmethod_ `app(content)` + + +* **说明** + + 应用程序消息 + + + +* **参数** + + + * `content: str`: 内容 + + + +### _classmethod_ `poke(name)` + + +* **说明** + + 戳一戳消息 + + + +* **参数** + + + * `name: str`: 戳一戳的类型 + - "Poke": 戳一戳 + - "ShowLove": 比心 + - "Like": 点赞 + - "Heartbroken": 心碎 + - "SixSixSix": 666 + - "FangDaZhao": 放大招 + + + +## _class_ `MessageChain` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +Mirai 协议 Messaqge 适配 + +由于Mirai协议的Message实现较为特殊, 故使用MessageChain命名 + + +### `export()` + +导出为可以被正常json序列化的数组 # NoneBot.adapters.mirai.event 模块 +:::warning 警告 +事件中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 + +部分字段可能与文档在符号上不一致 +::: + # NoneBot.adapters.mirai.event.base 模块 @@ -644,7 +1029,7 @@ An enumeration. 基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) -mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 [mirai-api-http 文档](https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md) +mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 [mirai-api-http 事件类型](https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md) ### _classmethod_ `new(data)` @@ -971,13 +1356,6 @@ Bot在群里的权限被改变 -* **返回** - - - * `[type]`: [description] - - - ## _class_ `MemberJoinRequestEvent` 基类:`nonebot.adapters.mirai.event.request.RequestEvent` From f6c24ec92f880cf595a8727d019cb7f61f997a6d Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 1 Feb 2021 11:42:05 +0800 Subject: [PATCH 56/86] :bug: change matcher check-run --- nonebot/message.py | 59 ++++++++++++++++------------------------------ nonebot/rule.py | 7 +++++- 2 files changed, 26 insertions(+), 40 deletions(-) diff --git a/nonebot/message.py b/nonebot/message.py index c6974b2c..cb64a4e0 100644 --- a/nonebot/message.py +++ b/nonebot/message.py @@ -99,47 +99,30 @@ def run_postprocessor(func: T_RunPostProcessor) -> T_RunPostProcessor: return func -async def _check_matcher(priority: int, bot: "Bot", event: "Event", - state: T_State) -> Iterable[Type[Matcher]]: - current_matchers = matchers[priority].copy() - - async def _check(Matcher: Type[Matcher], bot: "Bot", event: "Event", - state: T_State) -> Optional[Type[Matcher]]: +async def _check_matcher(priority: int, Matcher: Type[Matcher], bot: "Bot", + event: "Event", state: T_State) -> None: + if Matcher.expire_time and datetime.now() > Matcher.expire_time: try: - if (not Matcher.expire_time or datetime.now() <= Matcher.expire_time - ) and await Matcher.check_perm( - bot, event) and await Matcher.check_rule(bot, event, state): - return Matcher - except Exception as e: - logger.opt(colors=True, exception=e).error( - f"Rule check failed for {Matcher}." - ) - return None - - async def _check_expire(Matcher: Type[Matcher]) -> Optional[Type[Matcher]]: - if Matcher.expire_time and datetime.now() > Matcher.expire_time: - return Matcher - return None - - checking_tasks = [ - _check(Matcher, bot, event, state) for Matcher in current_matchers - ] - checking_expire_tasks = [ - _check_expire(Matcher) for Matcher in current_matchers - ] - results = await asyncio.gather(*checking_tasks) - expired = await asyncio.gather(*checking_expire_tasks) - for expired_matcher in filter(lambda x: x, expired): - try: - matchers[priority].remove(expired_matcher) # type: ignore + matchers[priority].remove(Matcher) except Exception: pass - for temp_matcher in filter(lambda x: x and x.temp, results): + return + + try: + if not await Matcher.check_perm( + bot, event) or not await Matcher.check_rule(bot, event, state): + return + except Exception as e: + logger.opt(colors=True, exception=e).error( + f"Rule check failed for {Matcher}.") + + if Matcher.temp: try: - matchers[priority].remove(temp_matcher) # type: ignore + matchers[priority].remove(Matcher) except Exception: pass - return filter(lambda x: x, results) # type: ignore + + await _run_matcher(Matcher, bot, event, state) async def _run_matcher(Matcher: Type[Matcher], bot: "Bot", event: "Event", @@ -244,11 +227,9 @@ async def handle_event(bot: "Bot", event: "Event"): if show_log: logger.debug(f"Checking for matchers in priority {priority}...") - run_matchers = await _check_matcher(priority, bot, event, state) - pending_tasks = [ - _run_matcher(matcher, bot, event, state.copy()) - for matcher in run_matchers + _check_matcher(priority, matcher, bot, event, state.copy()) + for matcher in matchers[priority] ] results = await asyncio.gather(*pending_tasks, return_exceptions=True) diff --git a/nonebot/rule.py b/nonebot/rule.py index d2b8f1fd..6ef79461 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -282,7 +282,8 @@ def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: 根据正则表达式进行匹配。 - 可以通过 ``state["_matched"]`` 获取正则表达式匹配成功的文本。 + 可以通过 ``state["_matched"]`` ``state["_matched_groups"]`` ``state["_matched_dict"]`` + 获取正则表达式匹配成功的文本。 :参数: @@ -302,9 +303,13 @@ def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: matched = pattern.search(str(event.get_message())) if matched: state["_matched"] = matched.group() + state["_matched_groups"] = matched.groups() + state["_matched_dict"] = matched.groupdict() return True else: state["_matched"] = None + state["_matched_groups"] = None + state["_matched_dict"] = None return False return Rule(_regex) From 616e07cd2d108c5f01bb4e165a738c9193a7523d Mon Sep 17 00:00:00 2001 From: nonebot Date: Mon, 1 Feb 2021 03:49:26 +0000 Subject: [PATCH 57/86] :memo: update api docs --- docs/api/adapters/ding.md | 15 +++++++++++++++ docs/api/rule.md | 3 ++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/api/adapters/ding.md b/docs/api/adapters/ding.md index 32fbb891..c64125ac 100644 --- a/docs/api/adapters/ding.md +++ b/docs/api/adapters/ding.md @@ -197,6 +197,16 @@ sidebarDepth: 0 @指定手机号人员 +### _static_ `atDingtalkIds(*dingtalkIds)` + +@指定 id,@ 默认会在消息段末尾。 +所以你可以在消息中使用 @{senderId} 占位,发送出去之后 @ 就会出现在占位的位置: +``python +message = MessageSegment.text(f"@{event.senderId},你好") +message += MessageSegment.atDingtalkIds(event.senderId) +`` + + ### _static_ `text(text)` 发送 `text` 类型消息 @@ -212,6 +222,11 @@ sidebarDepth: 0 "标记 text 文本的 extension 属性,需要与 text 消息段相加。 +### _static_ `code(code_language, code)` + +"发送 code 消息段 + + ### _static_ `markdown(title, text)` 发送 `markdown` 类型消息 diff --git a/docs/api/rule.md b/docs/api/rule.md index cb3fd05f..61be1f68 100644 --- a/docs/api/rule.md +++ b/docs/api/rule.md @@ -177,7 +177,8 @@ Rule(async_function, run_sync(sync_function)) 根据正则表达式进行匹配。 - 可以通过 `state["_matched"]` 获取正则表达式匹配成功的文本。 + 可以通过 `state["_matched"]` `state["_matched_groups"]` `state["_matched_dict"]` + 获取正则表达式匹配成功的文本。 From 8fe562e864df0ff3012785c99dbb69eb53bdc550 Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 13:19:37 +0800 Subject: [PATCH 58/86] :bulb: :children_crossing: complete comments and optimize usage in mirai adapter --- nonebot/adapters/mirai/__init__.py | 12 +- nonebot/adapters/mirai/bot.py | 176 +++++++++++++++-------------- nonebot/adapters/mirai/utils.py | 89 +++++++++++++++ 3 files changed, 189 insertions(+), 88 deletions(-) create mode 100644 nonebot/adapters/mirai/utils.py diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py index b209657e..75afaff8 100644 --- a/nonebot/adapters/mirai/__init__.py +++ b/nonebot/adapters/mirai/__init__.py @@ -4,8 +4,18 @@ Mirai-API-HTTP 协议适配 协议详情请看: `mirai-api-http 文档`_ -.. mirai-api-http 文档: +\:\:\: tip +该Adapter目前仍然处在早期实验性阶段, 并未经过充分测试 + +如果你在使用过程中遇到了任何问题, 请前往 `Issue页面`_ 为我们提供反馈 +\:\:\: + +.. _mirai-api-http 文档: https://github.com/project-mirai/mirai-api-http/tree/master/docs + +.. _Issue页面 + https://github.com/nonebot/nonebot2/issues + """ from .bot import MiraiBot diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 74c4f602..ed0b9ae1 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -1,34 +1,23 @@ from datetime import datetime, timedelta +from functools import wraps from io import BytesIO from ipaddress import IPv4Address -from typing import Any, Dict, List, NoReturn, Optional, Tuple, Union +from typing import (Any, Dict, List, NoReturn, Optional, Tuple, Union) import httpx from nonebot.adapters import Bot as BaseBot from nonebot.config import Config from nonebot.drivers import Driver, WebSocket -from nonebot.exception import ActionFailed as BaseActionFailed -from nonebot.exception import RequestDenied +from nonebot.exception import ApiNotAvailable, RequestDenied from nonebot.log import logger from nonebot.message import handle_event from nonebot.typing import overrides -from nonebot.utils import escape_tag from .config import Config as MiraiConfig from .event import Event, FriendMessage, GroupMessage, TempMessage from .message import MessageChain, MessageSegment - - -class ActionFailed(BaseActionFailed): - - def __init__(self, **kwargs): - super().__init__('mirai') - self.data = kwargs.copy() - - def __repr__(self): - return self.__class__.__name__ + '(%s)' % ', '.join( - map(lambda m: '%s=%r' % m, self.data.items())) +from .utils import catch_network_error, argument_validation class SessionManager: @@ -39,19 +28,11 @@ class SessionManager: def __init__(self, session_key: str, client: httpx.AsyncClient): self.session_key, self.client = session_key, client - @staticmethod - def _raise_code(data: Dict[str, Any]) -> Dict[str, Any]: - logger.opt(colors=True).debug( - f'Mirai API returned data: {escape_tag(str(data))}') - if isinstance(data, dict) and ('code' in data): - if data['code'] != 0: - raise ActionFailed(**data) - return data - + @catch_network_error async def post(self, path: str, *, - params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + params: Optional[Dict[str, Any]] = None) -> Any: """ :说明: @@ -75,13 +56,13 @@ class SessionManager: timeout=3, ) response.raise_for_status() - return self._raise_code(response.json()) + return response.json() + @catch_network_error async def request(self, path: str, *, - params: Optional[Dict[str, - Any]] = None) -> Dict[str, Any]: + params: Optional[Dict[str, Any]] = None) -> Any: """ :说明: @@ -91,10 +72,6 @@ class SessionManager: * ``path: str``: 对应API路径 * ``params: Optional[Dict[str, Any]]``: 请求参数 (无需sessionKey) - - :返回: - - - ``Dict[str, Any]``: API 返回值 """ response = await self.client.get( path, @@ -105,25 +82,34 @@ class SessionManager: timeout=3, ) response.raise_for_status() - return self._raise_code(response.json()) + return response.json() - async def upload(self, path: str, *, type: str, - file: Tuple[str, BytesIO]) -> Dict[str, Any]: + @catch_network_error + async def upload(self, path: str, *, params: Dict[str, Any]) -> Any: + """ + :说明: - file_type, file_io = file - response = await self.client.post(path, - data={ - 'sessionKey': self.session_key, - 'type': type - }, - files={file_type: file_io}, - timeout=6) + 以表单(``multipart/form-data``)形式主动提交API请求 + + :参数: + + * ``path: str``: 对应API路径 + * ``params: Dict[str, Any]``: 请求参数 (无需sessionKey) + """ + files = {k: v for k, v in params.items() if isinstance(v, BytesIO)} + form = {k: v for k, v in params.items() if k not in files} + response = await self.client.post( + path, + data=form, + files=files, + timeout=6, + ) response.raise_for_status() - return self._raise_code(response.json()) + return response.json() @classmethod async def new(cls, self_id: int, *, host: IPv4Address, port: int, - auth_key: str): + auth_key: str) -> "SessionManager": session = cls.get(self_id) if session is not None: return session @@ -145,7 +131,9 @@ class SessionManager: return cls(session_key, client) @classmethod - def get(cls, self_id: int, check_expire: bool = True): + def get(cls, + self_id: int, + check_expire: bool = True) -> Optional["SessionManager"]: if self_id not in cls.sessions: return None key, time, client = cls.sessions[self_id] @@ -157,6 +145,13 @@ class SessionManager: class MiraiBot(BaseBot): """ mirai-api-http 协议 Bot 适配。 + + \:\:\: warning + API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 + + 部分字段可能与文档在符号上不一致 + \:\:\: + """ @overrides(BaseBot) @@ -207,9 +202,9 @@ class MiraiBot(BaseBot): @overrides(BaseBot) def register(cls, driver: "Driver", config: "Config"): cls.mirai_config = MiraiConfig(**config.dict()) - assert cls.mirai_config.auth_key is not None - assert cls.mirai_config.host is not None - assert cls.mirai_config.port is not None + if (cls.mirai_config.auth_key and cls.mirai_config.host and + cls.mirai_config.port) is None: + raise ApiNotAvailable('mirai') super().register(driver, config) @overrides(BaseBot) @@ -222,7 +217,12 @@ class MiraiBot(BaseBot): @overrides(BaseBot) async def call_api(self, api: str, **data) -> NoReturn: - """由于Mirai的HTTP API特殊性, 该API暂时无法实现""" + """ + 由于Mirai的HTTP API特殊性, 该API暂时无法实现 + \:\:\: tip + 你可以使用 ``MiraiBot.api`` 中提供的调用方法来代替 + \:\:\: + """ raise NotImplementedError @overrides(BaseBot) @@ -231,6 +231,7 @@ class MiraiBot(BaseBot): raise NotImplementedError @overrides(BaseBot) + @argument_validation async def send(self, event: Event, message: Union[MessageChain, MessageSegment, str], @@ -245,10 +246,6 @@ class MiraiBot(BaseBot): * ``event: Event``: Event对象 * ``message: Union[MessageChain, MessageSegment, str]``: 要发送的消息 * ``at_sender: bool``: 是否 @ 事件主题 - - :返回: - - - ``Any``: API 调用返回数据 """ if isinstance(message, MessageSegment): message = MessageChain(message) @@ -269,6 +266,7 @@ class MiraiBot(BaseBot): else: raise ValueError(f'Unsupported event type {event!r}.') + @argument_validation async def send_friend_message(self, target: int, message_chain: MessageChain): """ @@ -280,10 +278,6 @@ class MiraiBot(BaseBot): * ``target: int``: 发送消息目标好友的 QQ 号 * ``message_chain: MessageChain``: 消息链,是一个消息对象构成的数组 - - :返回: - - - ``Any``: API 调用返回数据 """ return await self.api.post('sendFriendMessage', params={ @@ -291,6 +285,7 @@ class MiraiBot(BaseBot): 'messageChain': message_chain.export() }) + @argument_validation async def send_temp_message(self, qq: int, group: int, message_chain: MessageChain): """ @@ -303,10 +298,6 @@ class MiraiBot(BaseBot): * ``qq: int``: 临时会话对象 QQ 号 * ``group: int``: 临时会话群号 * ``message_chain: MessageChain``: 消息链,是一个消息对象构成的数组 - - :返回: - - - ``Any``: API 调用返回数据 """ return await self.api.post('sendTempMessage', params={ @@ -315,6 +306,7 @@ class MiraiBot(BaseBot): 'messageChain': message_chain.export() }) + @argument_validation async def send_group_message(self, group: int, message_chain: MessageChain, @@ -329,10 +321,6 @@ class MiraiBot(BaseBot): * ``group: int``: 发送消息目标群的群号 * ``message_chain: MessageChain``: 消息链,是一个消息对象构成的数组 * ``quote: Optional[int]``: 引用一条消息的 message_id 进行回复 - - :返回: - - - ``Any``: API 调用返回数据 """ return await self.api.post('sendGroupMessage', params={ @@ -341,6 +329,7 @@ class MiraiBot(BaseBot): 'quote': quote }) + @argument_validation async def recall(self, target: int): """ :说明: @@ -350,13 +339,10 @@ class MiraiBot(BaseBot): :参数: * ``target: int``: 需要撤回的消息的message_id - - :返回: - - - ``Any``: API 调用返回数据 """ return await self.api.post('recall', params={'target': target}) + @argument_validation async def send_image_message(self, target: int, qq: int, group: int, urls: List[str]) -> List[str]: """ @@ -384,8 +370,9 @@ class MiraiBot(BaseBot): 'qq': qq, 'group': group, 'urls': urls - }) # type: ignore + }) + @argument_validation async def upload_image(self, type: str, img: BytesIO): """ :说明: @@ -396,15 +383,14 @@ class MiraiBot(BaseBot): * ``type: str``: "friend" 或 "group" 或 "temp" * ``img: BytesIO``: 图片的BytesIO对象 - - :返回: - - - ``Any``: API 调用返回数据 """ return await self.api.upload('uploadImage', - type=type, - file=('img', img)) + params={ + 'type': type, + 'img': img + }) + @argument_validation async def upload_voice(self, type: str, voice: BytesIO): """ :说明: @@ -415,15 +401,14 @@ class MiraiBot(BaseBot): * ``type: str``: 当前仅支持 "group" * ``voice: BytesIO``: 语音的BytesIO对象 - - :返回: - - - ``Any``: API 调用返回数据 """ return await self.api.upload('uploadVoice', - type=type, - file=('voice', voice)) + params={ + 'type': type, + 'voice': voice + }) + @argument_validation async def fetch_message(self, count: int = 10): """ :说明: @@ -437,6 +422,7 @@ class MiraiBot(BaseBot): """ return await self.api.request('fetchMessage', params={'count': count}) + @argument_validation async def fetch_latest_message(self, count: int = 10): """ :说明: @@ -451,6 +437,7 @@ class MiraiBot(BaseBot): return await self.api.request('fetchLatestMessage', params={'count': count}) + @argument_validation async def peek_message(self, count: int = 10): """ :说明: @@ -464,6 +451,7 @@ class MiraiBot(BaseBot): """ return await self.api.request('peekMessage', params={'count': count}) + @argument_validation async def peek_latest_message(self, count: int = 10): """ :说明: @@ -478,6 +466,7 @@ class MiraiBot(BaseBot): return await self.api.request('peekLatestMessage', params={'count': count}) + @argument_validation async def messsage_from_id(self, id: int): """ :说明: @@ -491,6 +480,7 @@ class MiraiBot(BaseBot): """ return await self.api.request('messageFromId', params={'id': id}) + @argument_validation async def count_message(self): """ :说明: @@ -499,6 +489,7 @@ class MiraiBot(BaseBot): """ return await self.api.request('countMessage') + @argument_validation async def friend_list(self) -> List[Dict[str, Any]]: """ :说明: @@ -509,8 +500,9 @@ class MiraiBot(BaseBot): - ``List[Dict[str, Any]]``: 返回的好友列表数据 """ - return await self.api.request('friendList') # type: ignore + return await self.api.request('friendList') + @argument_validation async def group_list(self) -> List[Dict[str, Any]]: """ :说明: @@ -521,8 +513,9 @@ class MiraiBot(BaseBot): - ``List[Dict[str, Any]]``: 返回的群列表数据 """ - return await self.api.request('groupList') # type: ignore + return await self.api.request('groupList') + @argument_validation async def member_list(self, target: int) -> List[Dict[str, Any]]: """ :说明: @@ -537,9 +530,9 @@ class MiraiBot(BaseBot): - ``List[Dict[str, Any]]``: 返回的群成员列表数据 """ - return await self.api.request('memberList', - params={'target': target}) # type: ignore + return await self.api.request('memberList', params={'target': target}) + @argument_validation async def mute(self, target: int, member_id: int, time: int): """ :说明: @@ -559,6 +552,7 @@ class MiraiBot(BaseBot): 'time': time }) + @argument_validation async def unmute(self, target: int, member_id: int): """ :说明: @@ -576,6 +570,7 @@ class MiraiBot(BaseBot): 'memberId': member_id }) + @argument_validation async def kick(self, target: int, member_id: int, msg: str): """ :说明: @@ -595,6 +590,7 @@ class MiraiBot(BaseBot): 'msg': msg }) + @argument_validation async def quit(self, target: int): """ :说明: @@ -607,6 +603,7 @@ class MiraiBot(BaseBot): """ return await self.api.post('quit', params={'target': target}) + @argument_validation async def mute_all(self, target: int): """ :说明: @@ -619,6 +616,7 @@ class MiraiBot(BaseBot): """ return await self.api.post('muteAll', params={'target': target}) + @argument_validation async def unmute_all(self, target: int): """ :说明: @@ -631,6 +629,7 @@ class MiraiBot(BaseBot): """ return await self.api.post('unmuteAll', params={'target': target}) + @argument_validation async def group_config(self, target: int): """ :说明: @@ -656,6 +655,7 @@ class MiraiBot(BaseBot): """ return await self.api.request('groupConfig', params={'target': target}) + @argument_validation async def modify_group_config(self, target: int, config: Dict[str, Any]): """ :说明: @@ -673,6 +673,7 @@ class MiraiBot(BaseBot): 'config': config }) + @argument_validation async def member_info(self, target: int, member_id: int): """ :说明: @@ -699,6 +700,7 @@ class MiraiBot(BaseBot): 'memberId': member_id }) + @argument_validation async def modify_member_info(self, target: int, member_id: int, info: Dict[str, Any]): """ diff --git a/nonebot/adapters/mirai/utils.py b/nonebot/adapters/mirai/utils.py new file mode 100644 index 00000000..0a4b4a1b --- /dev/null +++ b/nonebot/adapters/mirai/utils.py @@ -0,0 +1,89 @@ +from functools import wraps +from typing import Callable, Coroutine, TypeVar + +import httpx +from pydantic import ValidationError, validate_arguments, Extra + +import nonebot.exception as exception +from nonebot.log import logger +from nonebot.utils import escape_tag + +_AsyncCallable = TypeVar("_AsyncCallable", bound=Callable[..., Coroutine]) +_AnyCallable = TypeVar("_AnyCallable", bound=Callable) + + +class ActionFailed(exception.ActionFailed): + """ + :说明: + + API 请求成功返回数据,但 API 操作失败。 + """ + + def __init__(self, **kwargs): + super().__init__('mirai') + self.data = kwargs.copy() + + def __repr__(self): + return self.__class__.__name__ + '(%s)' % ', '.join( + map(lambda m: '%s=%r' % m, self.data.items())) + + +class InvalidArgument(exception.AdapterException): + """ + :说明: + + 调用API的参数出错 + """ + + def __init__(self, **kwargs): + super().__init__('mirai') + + +def catch_network_error(function: _AsyncCallable) -> _AsyncCallable: + """ + :说明: + + 捕捉函数抛出的httpx网络异常并释放``NetworkError``异常 + 处理返回数据, 在code不为0时释放``ActionFailed``异常 + + \:\:\: warning + 此装饰器只支持使用了httpx的异步函数 + \:\:\: + """ + + @wraps(function) + async def wrapper(*args, **kwargs): + try: + data = await function(*args, **kwargs) + except httpx.HTTPError: + raise exception.NetworkError('mirai') + logger.opt(colors=True).debug('Mirai API returned data: ' + f'{escape_tag(str(data))}') + if isinstance(data, dict): + if data.get('code', 0) != 0: + raise ActionFailed(**data) + return data + + return wrapper # type: ignore + + +def argument_validation(function: _AnyCallable) -> _AnyCallable: + """ + :说明: + + 通过函数签名中的类型注解来对传入参数进行运行时校验 + 会在参数出错时释放``InvalidArgument``异常 + """ + function = validate_arguments(config={ + 'arbitrary_types_allowed': True, + 'extra': Extra.forbid + })(function) + + @wraps(function) + def wrapper(*args, **kwargs): + try: + return function(*args, **kwargs) + except ValidationError: + raise InvalidArgument + + return wrapper # type: ignore From 35d34a787b131cda40c9222562a7e4effcc86907 Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 13:20:09 +0800 Subject: [PATCH 59/86] :memo: update document building struct to fit changes in mirai adapter --- docs/.vuepress/config.js | 116 ++++++++++++++++++---------------- docs_build/adapters/mirai.rst | 7 ++ 2 files changed, 67 insertions(+), 56 deletions(-) diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 516d7ce0..6d684ad9 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -1,11 +1,11 @@ const path = require("path"); -module.exports = context => ({ +module.exports = (context) => ({ base: process.env.VUEPRESS_BASE || "/", title: "NoneBot", description: "基于 酷Q 的 Python 异步 QQ 机器人框架", markdown: { - lineNumbers: true + lineNumbers: true, }, /** * Extra tags to be injected to the page HTML `` @@ -21,26 +21,26 @@ module.exports = context => ({ ["meta", { name: "apple-mobile-web-app-capable", content: "yes" }], [ "meta", - { name: "apple-mobile-web-app-status-bar-style", content: "black" } + { name: "apple-mobile-web-app-status-bar-style", content: "black" }, ], [ "link", - { rel: "apple-touch-icon", href: "/icons/apple-touch-icon-180x180.png" } + { rel: "apple-touch-icon", href: "/icons/apple-touch-icon-180x180.png" }, ], [ "link", { rel: "mask-icon", href: "/icons/safari-pinned-tab.svg", - color: "#ea5252" - } + color: "#ea5252", + }, ], [ "meta", { name: "msapplication-TileImage", - content: "/icons/mstile-150x150.png" - } + content: "/icons/mstile-150x150.png", + }, ], ["meta", { name: "msapplication-TileColor", content: "#ea5252" }], [ @@ -48,16 +48,16 @@ module.exports = context => ({ { rel: "stylesheet", href: - "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css" - } - ] + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css", + }, + ], ], locales: { "/": { lang: "zh-CN", title: "NoneBot", - description: "基于 酷Q 的 Python 异步 QQ 机器人框架" - } + description: "基于 酷Q 的 Python 异步 QQ 机器人框架", + }, }, theme: "nonebot", @@ -83,7 +83,7 @@ module.exports = context => ({ { text: "进阶", link: "/advanced/" }, { text: "API", link: "/api/" }, { text: "插件广场", link: "/plugin-store" }, - { text: "更新日志", link: "/changelog" } + { text: "更新日志", link: "/changelog" }, ], sidebarDepth: 2, sidebar: { @@ -97,8 +97,8 @@ module.exports = context => ({ "installation", "getting-started", "creating-a-project", - "basic-configuration" - ] + "basic-configuration", + ], }, { title: "编写插件", @@ -109,15 +109,15 @@ module.exports = context => ({ "creating-a-plugin", "creating-a-matcher", "creating-a-handler", - "end-or-start" - ] + "end-or-start", + ], }, { title: "协议适配", collapsable: false, sidebar: "auto", - children: ["cqhttp-guide", "ding-guide"] - } + children: ["cqhttp-guide", "ding-guide"], + }, ], "/advanced/": [ { @@ -130,15 +130,15 @@ module.exports = context => ({ "permission", "runtime-hook", "export-and-require", - "overloaded-handlers" - ] + "overloaded-handlers", + ], }, { title: "发布", collapsable: false, sidebar: "auto", - children: ["publish-plugin"] - } + children: ["publish-plugin"], + }, ], "/api/": [ { @@ -148,74 +148,78 @@ module.exports = context => ({ children: [ { title: "nonebot 模块", - path: "nonebot" + path: "nonebot", }, { title: "nonebot.config 模块", - path: "config" + path: "config", }, { title: "nonebot.plugin 模块", - path: "plugin" + path: "plugin", }, { title: "nonebot.message 模块", - path: "message" + path: "message", }, { title: "nonebot.matcher 模块", - path: "matcher" + path: "matcher", }, { title: "nonebot.rule 模块", - path: "rule" + path: "rule", }, { title: "nonebot.permission 模块", - path: "permission" + path: "permission", }, { title: "nonebot.log 模块", - path: "log" + path: "log", }, { title: "nonebot.utils 模块", - path: "utils" + path: "utils", }, { title: "nonebot.typing 模块", - path: "typing" + path: "typing", }, { title: "nonebot.exception 模块", - path: "exception" + path: "exception", }, { title: "nonebot.drivers 模块", - path: "drivers/" + path: "drivers/", }, { title: "nonebot.drivers.fastapi 模块", - path: "drivers/fastapi" + path: "drivers/fastapi", }, { title: "nonebot.adapters 模块", - path: "adapters/" + path: "adapters/", }, { title: "nonebot.adapters.cqhttp 模块", - path: "adapters/cqhttp" + path: "adapters/cqhttp", }, { title: "nonebot.adapters.ding 模块", - path: "adapters/ding" - } - ] - } - ] - } - } - } + path: "adapters/ding", + }, + { + title: "nonebot.adapters.mirai 模块", + path: "adapters/mirai", + }, + ], + }, + ], + }, + }, + }, }, plugins: [ @@ -227,9 +231,9 @@ module.exports = context => ({ serviceWorker: true, updatePopup: { message: "发现新内容", - buttonText: "刷新" - } - } + buttonText: "刷新", + }, + }, ], [ "versioning", @@ -238,16 +242,16 @@ module.exports = context => ({ pagesSourceDir: path.resolve(context.sourceDir, "..", "pages"), onNewVersion(version, versionDestPath) { console.log(`Created version ${version} in ${versionDestPath}`); - } - } + }, + }, ], [ "container", { type: "vue", before: '
',
-        after: "
" - } - ] - ] + after: "", + }, + ], + ], }); diff --git a/docs_build/adapters/mirai.rst b/docs_build/adapters/mirai.rst index 6f15695b..a2f6a9c6 100644 --- a/docs_build/adapters/mirai.rst +++ b/docs_build/adapters/mirai.rst @@ -36,6 +36,13 @@ NoneBot.adapters.mirai.message 模块 :members: :show-inheritance: +NoneBot.adapters.mirai.utils 模块 +=================================== + +.. automodule:: nonebot.adapters.mirai.utils + :members: + :show-inheritance: + NoneBot.adapters.mirai.event 模块 ================================= From 6a273a8eeabec6a1d725e71defa18e0a603238a9 Mon Sep 17 00:00:00 2001 From: nonebot Date: Mon, 1 Feb 2021 05:21:33 +0000 Subject: [PATCH 60/86] :memo: update api docs --- docs/api/adapters/mirai.md | 190 +++++++++++++++++++++---------------- 1 file changed, 108 insertions(+), 82 deletions(-) diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index 9911ffec..c320d75c 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -7,15 +7,21 @@ sidebarDepth: 0 ## Mirai-API-HTTP 协议适配 -协议详情请看: +协议详情请看: [mirai-api-http 文档](https://github.com/project-mirai/mirai-api-http/tree/master/docs) + +::: tip +该Adapter目前仍然处在早期实验性阶段, 并未经过充分测试 + +如果你在使用过程中遇到了任何问题, 请前往 ``` -`mirai-api-http 文档`_ +`Issue页面`_ ``` + 为我们提供反馈 +::: - + # NoneBot.adapters.mirai.bot 模块 @@ -71,10 +77,22 @@ Bot会话管理器, 提供API主动调用接口 -* **返回** +### _async_ `upload(path, *, params)` + + +* **说明** + + 以表单(`multipart/form-data`)形式主动提交API请求 + + + +* **参数** - * `Dict[str, Any]`: API 返回值 + * `path: str`: 对应API路径 + + + * `params: Dict[str, Any]`: 请求参数 (无需sessionKey) @@ -84,6 +102,12 @@ Bot会话管理器, 提供API主动调用接口 mirai-api-http 协议 Bot 适配。 +::: warning +API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 + +部分字段可能与文档在符号上不一致 +::: + ### _property_ `api` @@ -93,9 +117,12 @@ mirai-api-http 协议 Bot 适配。 ### _async_ `call_api(api, **data)` 由于Mirai的HTTP API特殊性, 该API暂时无法实现 +::: tip +你可以使用 `MiraiBot.api` 中提供的调用方法来代替 +::: -### _async_ `send(event, message, at_sender=False)` +### `send(event, message, at_sender=False)` * **说明** @@ -117,14 +144,7 @@ mirai-api-http 协议 Bot 适配。 -* **返回** - - - * `Any`: API 调用返回数据 - - - -### _async_ `send_friend_message(target, message_chain)` +### `send_friend_message(target, message_chain)` * **说明** @@ -143,14 +163,7 @@ mirai-api-http 协议 Bot 适配。 -* **返回** - - - * `Any`: API 调用返回数据 - - - -### _async_ `send_temp_message(qq, group, message_chain)` +### `send_temp_message(qq, group, message_chain)` * **说明** @@ -172,14 +185,7 @@ mirai-api-http 协议 Bot 适配。 -* **返回** - - - * `Any`: API 调用返回数据 - - - -### _async_ `send_group_message(group, message_chain, quote=None)` +### `send_group_message(group, message_chain, quote=None)` * **说明** @@ -201,14 +207,7 @@ mirai-api-http 协议 Bot 适配。 -* **返回** - - - * `Any`: API 调用返回数据 - - - -### _async_ `recall(target)` +### `recall(target)` * **说明** @@ -224,14 +223,7 @@ mirai-api-http 协议 Bot 适配。 -* **返回** - - - * `Any`: API 调用返回数据 - - - -### _async_ `send_image_message(target, qq, group, urls)` +### `send_image_message(target, qq, group, urls)` * **说明** @@ -266,7 +258,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `upload_image(type, img)` +### `upload_image(type, img)` * **说明** @@ -285,14 +277,7 @@ mirai-api-http 协议 Bot 适配。 -* **返回** - - - * `Any`: API 调用返回数据 - - - -### _async_ `upload_voice(type, voice)` +### `upload_voice(type, voice)` * **说明** @@ -311,14 +296,7 @@ mirai-api-http 协议 Bot 适配。 -* **返回** - - - * `Any`: API 调用返回数据 - - - -### _async_ `fetch_message(count=10)` +### `fetch_message(count=10)` * **说明** @@ -335,7 +313,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `fetch_latest_message(count=10)` +### `fetch_latest_message(count=10)` * **说明** @@ -352,7 +330,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `peek_message(count=10)` +### `peek_message(count=10)` * **说明** @@ -369,7 +347,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `peek_latest_message(count=10)` +### `peek_latest_message(count=10)` * **说明** @@ -386,7 +364,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `messsage_from_id(id)` +### `messsage_from_id(id)` * **说明** @@ -403,7 +381,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `count_message()` +### `count_message()` * **说明** @@ -412,7 +390,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `friend_list()` +### `friend_list()` * **说明** @@ -428,7 +406,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `group_list()` +### `group_list()` * **说明** @@ -444,7 +422,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `member_list(target)` +### `member_list(target)` * **说明** @@ -467,7 +445,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `mute(target, member_id, time)` +### `mute(target, member_id, time)` * **说明** @@ -489,7 +467,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `unmute(target, member_id)` +### `unmute(target, member_id)` * **说明** @@ -508,7 +486,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `kick(target, member_id, msg)` +### `kick(target, member_id, msg)` * **说明** @@ -530,7 +508,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `quit(target)` +### `quit(target)` * **说明** @@ -546,7 +524,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `mute_all(target)` +### `mute_all(target)` * **说明** @@ -562,7 +540,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `unmute_all(target)` +### `unmute_all(target)` * **说明** @@ -578,7 +556,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `group_config(target)` +### `group_config(target)` * **说明** @@ -609,7 +587,7 @@ mirai-api-http 协议 Bot 适配。 ``` -### _async_ `modify_group_config(target, config)` +### `modify_group_config(target, config)` * **说明** @@ -628,7 +606,7 @@ mirai-api-http 协议 Bot 适配。 -### _async_ `member_info(target, member_id)` +### `member_info(target, member_id)` * **说明** @@ -658,7 +636,7 @@ mirai-api-http 协议 Bot 适配。 ``` -### _async_ `modify_member_info(target, member_id, info)` +### `modify_member_info(target, member_id, info)` * **说明** @@ -998,6 +976,54 @@ Mirai 协议 Messaqge 适配 导出为可以被正常json序列化的数组 +# NoneBot.adapters.mirai.utils 模块 + + +## _exception_ `ActionFailed` + +基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed) + + +* **说明** + + API 请求成功返回数据,但 API 操作失败。 + + + +## _exception_ `InvalidArgument` + +基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException) + + +* **说明** + + 调用API的参数出错 + + + +## `catch_network_error(function)` + + +* **说明** + + 捕捉函数抛出的httpx网络异常并释放\`\`NetworkError\`\`异常 + 处理返回数据, 在code不为0时释放\`\`ActionFailed\`\`异常 + + +::: warning +此装饰器只支持使用了httpx的异步函数 +::: + + +## `argument_validation(function)` + + +* **说明** + + 通过函数签名中的类型注解来对传入参数进行运行时校验 + 会在参数出错时释放\`\`InvalidArgument\`\`异常 + + # NoneBot.adapters.mirai.event 模块 :::warning 警告 From b67d2ebce6a5e6eef9f325906a69873c16086738 Mon Sep 17 00:00:00 2001 From: StarHeart <947371563@qq.com> Date: Mon, 1 Feb 2021 13:45:31 +0800 Subject: [PATCH 61/86] Update scheduler.md --- archive/2.0.0a8.post2/advanced/scheduler.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/archive/2.0.0a8.post2/advanced/scheduler.md b/archive/2.0.0a8.post2/advanced/scheduler.md index 86280b5f..a1939089 100644 --- a/archive/2.0.0a8.post2/advanced/scheduler.md +++ b/archive/2.0.0a8.post2/advanced/scheduler.md @@ -96,10 +96,14 @@ scheduler = require('nonebot_plugin_apscheduler').scheduler 对于大多数情况,我们需要在 `nonebot2` 项目被启动时启动定时任务,则此处设为 `true` +### 在 `.env` 中添加 + ```bash APSCHEDULER_AUTOSTART=true ``` +### 在 `bot.py` 中添加 + ```python nonebot.init(apscheduler_autostart=True) ``` @@ -116,10 +120,14 @@ nonebot.init(apscheduler_autostart=True) > 官方文档在绝大多数时候能提供最准确和最具时效性的指南 +### 在 `.env` 中添加 + ```bash APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"} ``` +### 在 `bot.py` 中添加 + ```python nonebot.init(apscheduler_config={ "apscheduler.timezone": "Asia/Shanghai" From d2a62ebd3dd73c23c60d9cff27b9a52169b557a8 Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 13:50:14 +0800 Subject: [PATCH 62/86] :pencil: :bulb: fix some typo and style in mirai adapter --- nonebot/adapters/mirai/__init__.py | 2 +- nonebot/adapters/mirai/bot.py | 7 +++++-- nonebot/adapters/mirai/bot_ws.py | 1 - nonebot/adapters/mirai/event/__init__.py | 7 ++++--- nonebot/adapters/mirai/event/base.py | 10 ++++++---- nonebot/adapters/mirai/event/request.py | 16 ++++++++++------ nonebot/adapters/mirai/utils.py | 8 +++++--- 7 files changed, 31 insertions(+), 20 deletions(-) diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py index 75afaff8..15bc12d0 100644 --- a/nonebot/adapters/mirai/__init__.py +++ b/nonebot/adapters/mirai/__init__.py @@ -13,7 +13,7 @@ Mirai-API-HTTP 协议适配 .. _mirai-api-http 文档: https://github.com/project-mirai/mirai-api-http/tree/master/docs -.. _Issue页面 +.. _Issue页面: https://github.com/nonebot/nonebot2/issues """ diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index ed0b9ae1..6c4023e2 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -218,7 +218,10 @@ class MiraiBot(BaseBot): @overrides(BaseBot) async def call_api(self, api: str, **data) -> NoReturn: """ + \:\:\: danger 由于Mirai的HTTP API特殊性, 该API暂时无法实现 + \:\:\: + \:\:\: tip 你可以使用 ``MiraiBot.api`` 中提供的调用方法来代替 \:\:\: @@ -239,13 +242,13 @@ class MiraiBot(BaseBot): """ :说明: - 根据 ``event`` 向触发事件的主题发送信息 + 根据 ``event`` 向触发事件的主体发送信息 :参数: * ``event: Event``: Event对象 * ``message: Union[MessageChain, MessageSegment, str]``: 要发送的消息 - * ``at_sender: bool``: 是否 @ 事件主题 + * ``at_sender: bool``: 是否 @ 事件主体 """ if isinstance(message, MessageSegment): message = MessageChain(message) diff --git a/nonebot/adapters/mirai/bot_ws.py b/nonebot/adapters/mirai/bot_ws.py index ccce63b3..c10382ba 100644 --- a/nonebot/adapters/mirai/bot_ws.py +++ b/nonebot/adapters/mirai/bot_ws.py @@ -15,7 +15,6 @@ from nonebot.log import logger from nonebot.typing import overrides from .bot import MiraiBot, SessionManager -from .config import Config as MiraiConfig WebsocketHandlerFunction = Callable[[Dict[str, Any]], Coroutine[Any, Any, None]] WebsocketHandler_T = TypeVar('WebsocketHandler_T', diff --git a/nonebot/adapters/mirai/event/__init__.py b/nonebot/adapters/mirai/event/__init__.py index c0024e19..cc763f65 100644 --- a/nonebot/adapters/mirai/event/__init__.py +++ b/nonebot/adapters/mirai/event/__init__.py @@ -1,11 +1,12 @@ """ -\:\:\:warning 警告 +\:\:\: warning 事件中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 部分字段可能与文档在符号上不一致 \:\:\: """ -from .base import Event, GroupChatInfo, GroupInfo, UserPermission, PrivateChatInfo +from .base import (Event, GroupChatInfo, GroupInfo, PrivateChatInfo, + UserPermission) from .message import * from .notice import * -from .request import * \ No newline at end of file +from .request import * diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 662b856d..1362bd74 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -13,11 +13,13 @@ from nonebot.typing import overrides class UserPermission(str, Enum): """ - 用户权限枚举类 + :说明: - - ``OWNER``: 群主 - - ``ADMINISTRATOR``: 群管理 - - ``MEMBER``: 普通群成员 + 用户权限枚举类 + + * ``OWNER``: 群主 + * ``ADMINISTRATOR``: 群管理 + * ``MEMBER``: 普通群成员 """ OWNER = 'OWNER' ADMINISTRATOR = 'ADMINISTRATOR' diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py index 18d466ee..623c52dd 100644 --- a/nonebot/adapters/mirai/event/request.py +++ b/nonebot/adapters/mirai/event/request.py @@ -52,8 +52,10 @@ class NewFriendRequestEvent(RequestEvent): * ``bot: Bot``: 当前的 ``Bot`` 对象 * ``operate: Literal[1, 2]``: 响应的操作类型 - - ``1``: 拒绝添加好友 - - ``2``: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + + * ``1``: 拒绝添加好友 + * ``2``: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + * ``message: str``: 回复的信息 """ assert operate > 0 @@ -104,10 +106,12 @@ class MemberJoinRequestEvent(RequestEvent): * ``bot: Bot``: 当前的 ``Bot`` 对象 * ``operate: Literal[1, 2, 3, 4]``: 响应的操作类型 - - ``1``: 拒绝入群 - - ``2``: 忽略请求 - - ``3``: 拒绝入群并添加黑名单,不再接收该用户的入群申请 - - ``4``: 忽略入群并添加黑名单,不再接收该用户的入群申请 + + * ``1``: 拒绝入群 + * ``2``: 忽略请求 + * ``3``: 拒绝入群并添加黑名单,不再接收该用户的入群申请 + * ``4``: 忽略入群并添加黑名单,不再接收该用户的入群申请 + * ``message: str``: 回复的信息 """ assert operate > 0 diff --git a/nonebot/adapters/mirai/utils.py b/nonebot/adapters/mirai/utils.py index 0a4b4a1b..30adf42d 100644 --- a/nonebot/adapters/mirai/utils.py +++ b/nonebot/adapters/mirai/utils.py @@ -43,8 +43,9 @@ def catch_network_error(function: _AsyncCallable) -> _AsyncCallable: """ :说明: - 捕捉函数抛出的httpx网络异常并释放``NetworkError``异常 - 处理返回数据, 在code不为0时释放``ActionFailed``异常 + 捕捉函数抛出的httpx网络异常并释放 ``NetworkError`` 异常 + + 处理返回数据, 在code不为0时释放 ``ActionFailed`` 异常 \:\:\: warning 此装饰器只支持使用了httpx的异步函数 @@ -72,7 +73,8 @@ def argument_validation(function: _AnyCallable) -> _AnyCallable: :说明: 通过函数签名中的类型注解来对传入参数进行运行时校验 - 会在参数出错时释放``InvalidArgument``异常 + + 会在参数出错时释放 ``InvalidArgument`` 异常 """ function = validate_arguments(config={ 'arbitrary_types_allowed': True, From 6c0b20e5b7694ddc05c3797ff26c962aac392e61 Mon Sep 17 00:00:00 2001 From: nonebot Date: Mon, 1 Feb 2021 05:51:45 +0000 Subject: [PATCH 63/86] :memo: update api docs --- docs/api/adapters/mirai.md | 54 ++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 20 deletions(-) diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index c320d75c..b669222b 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -12,16 +12,9 @@ sidebarDepth: 0 ::: tip 该Adapter目前仍然处在早期实验性阶段, 并未经过充分测试 -如果你在使用过程中遇到了任何问题, 请前往 - -``` -`Issue页面`_ -``` - - 为我们提供反馈 +如果你在使用过程中遇到了任何问题, 请前往 [Issue页面](https://github.com/nonebot/nonebot2/issues) 为我们提供反馈 ::: - # NoneBot.adapters.mirai.bot 模块 @@ -116,7 +109,10 @@ API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则 ### _async_ `call_api(api, **data)` +::: danger 由于Mirai的HTTP API特殊性, 该API暂时无法实现 +::: + ::: tip 你可以使用 `MiraiBot.api` 中提供的调用方法来代替 ::: @@ -127,7 +123,7 @@ API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则 * **说明** - 根据 `event` 向触发事件的主题发送信息 + 根据 `event` 向触发事件的主体发送信息 @@ -140,7 +136,7 @@ API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则 * `message: Union[MessageChain, MessageSegment, str]`: 要发送的消息 - * `at_sender: bool`: 是否 @ 事件主题 + * `at_sender: bool`: 是否 @ 事件主体 @@ -1006,8 +1002,9 @@ Mirai 协议 Messaqge 适配 * **说明** - 捕捉函数抛出的httpx网络异常并释放\`\`NetworkError\`\`异常 - 处理返回数据, 在code不为0时释放\`\`ActionFailed\`\`异常 + 捕捉函数抛出的httpx网络异常并释放 `NetworkError` 异常 + + 处理返回数据, 在code不为0时释放 `ActionFailed` 异常 ::: warning @@ -1021,12 +1018,13 @@ Mirai 协议 Messaqge 适配 * **说明** 通过函数签名中的类型注解来对传入参数进行运行时校验 - 会在参数出错时释放\`\`InvalidArgument\`\`异常 + + 会在参数出错时释放 `InvalidArgument` 异常 # NoneBot.adapters.mirai.event 模块 -:::warning 警告 +::: warning 事件中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 部分字段可能与文档在符号上不一致 @@ -1039,6 +1037,10 @@ Mirai 协议 Messaqge 适配 基类:`str`, `enum.Enum` + +* **说明** + + 用户权限枚举类 > @@ -1374,8 +1376,12 @@ Bot在群里的权限被改变 * `operate: Literal[1, 2]`: 响应的操作类型 - - `1`: 拒绝添加好友 - - `2`: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + + + * `1`: 拒绝添加好友 + + + * `2`: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 * `message: str`: 回复的信息 @@ -1421,10 +1427,18 @@ Bot在群里的权限被改变 * `operate: Literal[1, 2, 3, 4]`: 响应的操作类型 - - `1`: 拒绝入群 - - `2`: 忽略请求 - - `3`: 拒绝入群并添加黑名单,不再接收该用户的入群申请 - - `4`: 忽略入群并添加黑名单,不再接收该用户的入群申请 + + + * `1`: 拒绝入群 + + + * `2`: 忽略请求 + + + * `3`: 拒绝入群并添加黑名单,不再接收该用户的入群申请 + + + * `4`: 忽略入群并添加黑名单,不再接收该用户的入群申请 * `message: str`: 回复的信息 From 5a63827f2243f2226f5079a0e80e8c9eca5d7e95 Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 14:24:45 +0800 Subject: [PATCH 64/86] :speech_balloon: :bulb: rename MiraiBot to Bot, fix a comment style --- nonebot/adapters/mirai/__init__.py | 4 ++-- nonebot/adapters/mirai/bot.py | 2 +- nonebot/adapters/mirai/bot_ws.py | 17 +++++++++-------- nonebot/adapters/mirai/event/__init__.py | 17 +++++++++++++++++ nonebot/adapters/mirai/event/request.py | 2 +- nonebot/adapters/mirai/message.py | 14 ++++++++------ 6 files changed, 38 insertions(+), 18 deletions(-) diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py index 15bc12d0..c083a8a7 100644 --- a/nonebot/adapters/mirai/__init__.py +++ b/nonebot/adapters/mirai/__init__.py @@ -18,7 +18,7 @@ Mirai-API-HTTP 协议适配 """ -from .bot import MiraiBot -from .bot_ws import MiraiWebsocketBot +from .bot import Bot +from .bot_ws import WebsocketBot from .event import * from .message import MessageChain, MessageSegment diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 6c4023e2..3182d7a8 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -142,7 +142,7 @@ class SessionManager: return cls(key, client) -class MiraiBot(BaseBot): +class Bot(BaseBot): """ mirai-api-http 协议 Bot 适配。 diff --git a/nonebot/adapters/mirai/bot_ws.py b/nonebot/adapters/mirai/bot_ws.py index c10382ba..fdf35c0c 100644 --- a/nonebot/adapters/mirai/bot_ws.py +++ b/nonebot/adapters/mirai/bot_ws.py @@ -14,7 +14,7 @@ from nonebot.exception import RequestDenied from nonebot.log import logger from nonebot.typing import overrides -from .bot import MiraiBot, SessionManager +from .bot import SessionManager, Bot WebsocketHandlerFunction = Callable[[Dict[str, Any]], Coroutine[Any, Any, None]] WebsocketHandler_T = TypeVar('WebsocketHandler_T', @@ -71,8 +71,9 @@ class WebSocket(BaseWebSocket): logger.exception(f'Websocket client listened {self.websocket} ' f'failed to decode data: {e}') continue - asyncio.gather(*map(lambda f: f(data), self.event_handlers), - return_exceptions=True) + asyncio.gather( + *map(lambda f: f(data), self.event_handlers), #type: ignore + return_exceptions=True) @overrides(BaseWebSocket) async def accept(self): @@ -87,18 +88,18 @@ class WebSocket(BaseWebSocket): return callable -class MiraiWebsocketBot(MiraiBot): +class WebsocketBot(Bot): """ mirai-api-http 正向 Websocket 协议 Bot 适配。 """ - @overrides(MiraiBot) + @overrides(Bot) def __init__(self, connection_type: str, self_id: str, *, websocket: WebSocket): super().__init__(connection_type, self_id, websocket=websocket) @property - @overrides(MiraiBot) + @overrides(Bot) def type(self) -> str: return "mirai-ws" @@ -113,7 +114,7 @@ class MiraiWebsocketBot(MiraiBot): return api @classmethod - @overrides(MiraiBot) + @overrides(Bot) async def check_permission(cls, driver: "Driver", connection_type: str, headers: dict, body: Optional[dict]) -> NoReturn: raise RequestDenied( @@ -121,7 +122,7 @@ class MiraiWebsocketBot(MiraiBot): reason=f'Connection {connection_type} not implented') @classmethod - @overrides(MiraiBot) + @overrides(Bot) def register(cls, driver: "Driver", config: "Config", qq: int): """ :说明: diff --git a/nonebot/adapters/mirai/event/__init__.py b/nonebot/adapters/mirai/event/__init__.py index cc763f65..1cf92096 100644 --- a/nonebot/adapters/mirai/event/__init__.py +++ b/nonebot/adapters/mirai/event/__init__.py @@ -10,3 +10,20 @@ from .base import (Event, GroupChatInfo, GroupInfo, PrivateChatInfo, from .message import * from .notice import * from .request import * + +__all__ = [ + 'Event', 'GroupChatInfo', 'GroupInfo', 'PrivateChatInfo', 'UserPermission', + 'MessageChain', 'MessageEvent', 'GroupMessage', 'FriendMessage', + 'TempMessage', 'NoticeEvent', 'MuteEvent', 'BotMuteEvent', 'BotUnmuteEvent', + 'MemberMuteEvent', 'MemberUnmuteEvent', 'BotJoinGroupEvent', + 'BotLeaveEventActive', 'BotLeaveEventKick', 'MemberJoinEvent', + 'MemberLeaveEventKick', 'MemberLeaveEventQuit', 'FriendRecallEvent', + 'GroupRecallEvent', 'GroupStateChangeEvent', 'GroupNameChangeEvent', + 'GroupEntranceAnnouncementChangeEvent', 'GroupMuteAllEvent', + 'GroupAllowAnonymousChatEvent', 'GroupAllowConfessTalkEvent', + 'GroupAllowMemberInviteEvent', 'MemberStateChangeEvent', + 'MemberCardChangeEvent', 'MemberSpecialTitleChangeEvent', + 'BotGroupPermissionChangeEvent', 'MemberPermissionChangeEvent', + 'RequestEvent', 'NewFriendRequestEvent', 'MemberJoinRequestEvent', + 'BotInvitedJoinGroupRequestEvent' +] diff --git a/nonebot/adapters/mirai/event/request.py b/nonebot/adapters/mirai/event/request.py index 623c52dd..3bf82f01 100644 --- a/nonebot/adapters/mirai/event/request.py +++ b/nonebot/adapters/mirai/event/request.py @@ -6,7 +6,7 @@ from typing_extensions import Literal from .base import Event if TYPE_CHECKING: - from ..bot import MiraiBot as Bot + from ..bot import Bot class RequestEvent(Event): diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py index 265b3b3b..f1aff156 100644 --- a/nonebot/adapters/mirai/message.py +++ b/nonebot/adapters/mirai/message.py @@ -257,12 +257,14 @@ class MessageSegment(BaseMessageSegment): :参数: * ``name: str``: 戳一戳的类型 - - "Poke": 戳一戳 - - "ShowLove": 比心 - - "Like": 点赞 - - "Heartbroken": 心碎 - - "SixSixSix": 666 - - "FangDaZhao": 放大招 + + * ``Poke``: 戳一戳 + * ``ShowLove``: 比心 + * ``Like``: 点赞 + * ``Heartbroken``: 心碎 + * ``SixSixSix``: 666 + * ``FangDaZhao``: 放大招 + """ return cls(type=MessageType.POKE, name=name) From c0fa137fed42529712fd6df3b267435a4357d28b Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 16:31:51 +0800 Subject: [PATCH 65/86] :children_crossing: add support of rule `to_me` in mirai adapter --- nonebot/adapters/mirai/bot.py | 24 ++++++--- nonebot/adapters/mirai/event/base.py | 4 +- nonebot/adapters/mirai/event/message.py | 21 +++++++- nonebot/adapters/mirai/utils.py | 71 +++++++++++++++++++++++-- 4 files changed, 107 insertions(+), 13 deletions(-) diff --git a/nonebot/adapters/mirai/bot.py b/nonebot/adapters/mirai/bot.py index 3182d7a8..0a1262c7 100644 --- a/nonebot/adapters/mirai/bot.py +++ b/nonebot/adapters/mirai/bot.py @@ -13,11 +13,12 @@ from nonebot.exception import ApiNotAvailable, RequestDenied from nonebot.log import logger from nonebot.message import handle_event from nonebot.typing import overrides +from nonebot.utils import escape_tag from .config import Config as MiraiConfig from .event import Event, FriendMessage, GroupMessage, TempMessage from .message import MessageChain, MessageSegment -from .utils import catch_network_error, argument_validation +from .utils import catch_network_error, argument_validation, check_tome, Log class SessionManager: @@ -209,11 +210,22 @@ class Bot(BaseBot): @overrides(BaseBot) async def handle_message(self, message: dict): - await handle_event(bot=self, - event=Event.new({ - **message, - 'self_id': self.self_id, - })) + Log.debug(f'received message {message}') + try: + await handle_event( + bot=self, + event=await check_tome( + bot=self, + event=Event.new({ + **message, + 'self_id': self.self_id, + }), + ), + ) + except Exception as e: + logger.opt(colors=True, exception=e).exception( + 'Failed to handle message ' + f'{escape_tag(str(message))}: ') @overrides(BaseBot) async def call_api(self, api: str, **data) -> NoReturn: diff --git a/nonebot/adapters/mirai/event/base.py b/nonebot/adapters/mirai/event/base.py index 1362bd74..4a7b3809 100644 --- a/nonebot/adapters/mirai/event/base.py +++ b/nonebot/adapters/mirai/event/base.py @@ -80,8 +80,8 @@ class Event(BaseEvent): return event_class.parse_obj(data) except ValidationError as e: logger.info( - f'Failed to parse {data} to class {event_class.__name__}: {e}. ' - 'Fallback to parent class.') + f'Failed to parse {data} to class {event_class.__name__}: ' + f'{e.errors()!r}. Fallback to parent class.') event_class = event_class.__base__ raise ValueError(f'Failed to serialize {data}.') diff --git a/nonebot/adapters/mirai/event/message.py b/nonebot/adapters/mirai/event/message.py index 6021ea64..26d534d4 100644 --- a/nonebot/adapters/mirai/event/message.py +++ b/nonebot/adapters/mirai/event/message.py @@ -33,11 +33,20 @@ class MessageEvent(Event): class GroupMessage(MessageEvent): """群消息事件""" sender: GroupChatInfo + to_me: bool = False @overrides(MessageEvent) def get_session_id(self) -> str: return f'group_{self.sender.group.id}_' + self.get_user_id() + @overrides(MessageEvent) + def get_user_id(self) -> str: + return str(self.sender.id) + + @overrides(MessageEvent) + def is_tome(self) -> bool: + return self.to_me + class FriendMessage(MessageEvent): """好友消息事件""" @@ -47,15 +56,23 @@ class FriendMessage(MessageEvent): def get_user_id(self) -> str: return str(self.sender.id) - @overrides + @overrides(MessageEvent) def get_session_id(self) -> str: return 'friend_' + self.get_user_id() + @overrides(MessageEvent) + def is_tome(self) -> bool: + return True + class TempMessage(MessageEvent): """临时会话消息事件""" sender: GroupChatInfo - @overrides + @overrides(MessageEvent) def get_session_id(self) -> str: return f'temp_{self.sender.group.id}_' + self.get_user_id() + + @overrides(MessageEvent) + def is_tome(self) -> bool: + return True diff --git a/nonebot/adapters/mirai/utils.py b/nonebot/adapters/mirai/utils.py index 30adf42d..cb2b5e2d 100644 --- a/nonebot/adapters/mirai/utils.py +++ b/nonebot/adapters/mirai/utils.py @@ -1,17 +1,44 @@ +import re from functools import wraps -from typing import Callable, Coroutine, TypeVar +from typing import TYPE_CHECKING, Any, Callable, Coroutine, Optional, TypeVar import httpx -from pydantic import ValidationError, validate_arguments, Extra +from pydantic import Extra, ValidationError, validate_arguments import nonebot.exception as exception from nonebot.log import logger -from nonebot.utils import escape_tag +from nonebot.utils import escape_tag, logger_wrapper + +from .event import Event, GroupMessage +from .message import MessageSegment, MessageType + +if TYPE_CHECKING: + from .bot import Bot _AsyncCallable = TypeVar("_AsyncCallable", bound=Callable[..., Coroutine]) _AnyCallable = TypeVar("_AnyCallable", bound=Callable) +class Log: + _log = logger_wrapper('MIRAI') + + @classmethod + def info(cls, message: Any): + cls._log('INFO', str(message)) + + @classmethod + def debug(cls, message: Any): + cls._log('DEBUG', str(message)) + + @classmethod + def warn(cls, message: Any): + cls._log('WARNING', str(message)) + + @classmethod + def error(cls, message: Any, exception: Optional[Exception] = None): + cls._log('ERROR', str(message), exception=exception) + + class ActionFailed(exception.ActionFailed): """ :说明: @@ -89,3 +116,41 @@ def argument_validation(function: _AnyCallable) -> _AnyCallable: raise InvalidArgument return wrapper # type: ignore + + +async def check_tome(bot: "Bot", event: "Event") -> "Event": + if not isinstance(event, GroupMessage): + return event + + def _is_at(event: GroupMessage) -> bool: + for segment in event.message_chain: + segment: MessageSegment + if segment.type != MessageType.AT: + continue + if segment.data['target'] == event.self_id: + return True + return False + + def _is_nick(event: GroupMessage) -> bool: + text = event.get_plaintext() + if not text: + return False + nick_regex = '|'.join( + {i.strip() for i in bot.config.nickname if i.strip()}) + matched = re.search(rf"^({nick_regex})([\s,,]*|$)", text, re.IGNORECASE) + if matched is None: + return False + Log.info(f'User is calling me {matched.group(1)}') + return True + + def _is_reply(event: GroupMessage) -> bool: + for segment in event.message_chain: + segment: MessageSegment + if segment.type != MessageType.QUOTE: + continue + if segment.data['senderId'] == event.self_id: + return True + return False + + event.to_me = any([_is_at(event), _is_reply(event), _is_nick(event)]) + return event From da1218221ce2d9f506464f6b6a64e05df85b3782 Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 16:37:42 +0800 Subject: [PATCH 66/86] :white_check_mark: add specified test for mirai adapter --- tests/.env.dev | 4 ++++ tests/bot.py | 2 ++ tests/test_plugins/test_mirai.py | 13 +++++++++++++ 3 files changed, 19 insertions(+) create mode 100644 tests/test_plugins/test_mirai.py diff --git a/tests/.env.dev b/tests/.env.dev index 9b69f65a..33e6f835 100644 --- a/tests/.env.dev +++ b/tests/.env.dev @@ -11,3 +11,7 @@ COMMAND_SEP=["/", "."] CUSTOM_CONFIG1=config in env CUSTOM_CONFIG3= + +MIRAI_AUTH_KEY=12345678 +MIRAI_HOST=127.0.0.1 +MIRAI_PORT=8080 \ No newline at end of file diff --git a/tests/bot.py b/tests/bot.py index 6e45e051..849aee27 100644 --- a/tests/bot.py +++ b/tests/bot.py @@ -6,6 +6,7 @@ sys.path.insert(0, os.path.abspath("..")) import nonebot from nonebot.adapters.cqhttp import Bot from nonebot.adapters.ding import Bot as DingBot +from nonebot.adapters.mirai import Bot as MiraiBot from nonebot.log import logger, default_format # test custom log @@ -20,6 +21,7 @@ app = nonebot.get_asgi() driver = nonebot.get_driver() driver.register_adapter("cqhttp", Bot) driver.register_adapter("ding", DingBot) +driver.register_adapter("mirai", MiraiBot) # load builtin plugin nonebot.load_builtin_plugins() diff --git a/tests/test_plugins/test_mirai.py b/tests/test_plugins/test_mirai.py new file mode 100644 index 00000000..a5da93ae --- /dev/null +++ b/tests/test_plugins/test_mirai.py @@ -0,0 +1,13 @@ +from nonebot.plugin import on_message +from nonebot.adapters.mirai import Bot, MessageEvent + +message_test = on_message() + + +@message_test.handle() +async def _message(bot: Bot, event: MessageEvent): + text = event.get_plaintext() + if not text: + return + reversed_text = ''.join(reversed(text)) + await bot.send(event, reversed_text, at_sender=True) From f2ab618083f5d43c32d914d2269c1eeec38a1ee0 Mon Sep 17 00:00:00 2001 From: nonebot Date: Mon, 1 Feb 2021 08:39:38 +0000 Subject: [PATCH 67/86] :memo: update api docs --- docs/api/adapters/mirai.md | 448 ++++++++++++++++++++++++++++++++++++- 1 file changed, 439 insertions(+), 9 deletions(-) diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index b669222b..34aae0c9 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -89,7 +89,7 @@ Bot会话管理器, 提供API主动调用接口 -## _class_ `MiraiBot` +## _class_ `Bot` 基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) @@ -656,9 +656,9 @@ API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则 # NoneBot.adapters.mirai.bot_ws 模块 -## _class_ `MiraiWebsocketBot` +## _class_ `WebsocketBot` -基类:`nonebot.adapters.mirai.bot.MiraiBot` +基类:`nonebot.adapters.mirai.bot.Bot` mirai-api-http 正向 Websocket 协议 Bot 适配。 @@ -950,12 +950,24 @@ CQHTTP 协议 MessageSegment 适配。具体方法参考 [mirai-api-http 消息 * `name: str`: 戳一戳的类型 - - "Poke": 戳一戳 - - "ShowLove": 比心 - - "Like": 点赞 - - "Heartbroken": 心碎 - - "SixSixSix": 666 - - "FangDaZhao": 放大招 + + + * `Poke`: 戳一戳 + + + * `ShowLove`: 比心 + + + * `Like`: 点赞 + + + * `Heartbroken`: 心碎 + + + * `SixSixSix`: 666 + + + * `FangDaZhao`: 放大招 @@ -1030,6 +1042,424 @@ Mirai 协议 Messaqge 适配 部分字段可能与文档在符号上不一致 ::: + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 [mirai-api-http 事件类型](https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md) + + +### _classmethod_ `new(data)` + +此事件类的工厂函数, 能够通过事件数据选择合适的子类进行序列化 + + +### `normalize_dict(**kwargs)` + +返回可以被json正常反序列化的结构体 + + +## _class_ `UserPermission` + +基类:`str`, `enum.Enum` + + +* **说明** + + +用户权限枚举类 + +> +> * `OWNER`: 群主 + + +> * `ADMINISTRATOR`: 群管理 + + +> * `MEMBER`: 普通群成员 + + +## _class_ `MessageChain` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +Mirai 协议 Messaqge 适配 + +由于Mirai协议的Message实现较为特殊, 故使用MessageChain命名 + + +### `export()` + +导出为可以被正常json序列化的数组 + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +消息事件基类 + + +## _class_ `GroupMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +群消息事件 + + +## _class_ `FriendMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +好友消息事件 + + +## _class_ `TempMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +临时会话消息事件 + + +## _class_ `NoticeEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +通知事件基类 + + +## _class_ `MuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +禁言类事件基类 + + +## _class_ `BotMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被禁言 + + +## _class_ `BotUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被取消禁言 + + +## _class_ `MemberMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被禁言事件(该成员不是Bot) + + +## _class_ `MemberUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被取消禁言事件(该成员不是Bot) + + +## _class_ `BotJoinGroupEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +Bot加入了一个新群 + + +## _class_ `BotLeaveEventActive` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot主动退出一个群 + + +## _class_ `BotLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot被踢出一个群 + + +## _class_ `MemberJoinEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +新人入群的事件 + + +## _class_ `MemberLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员被踢出群(该成员不是Bot) + + +## _class_ `MemberLeaveEventQuit` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员主动离群(该成员不是Bot) + + +## _class_ `FriendRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +好友消息撤回 + + +## _class_ `GroupRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.FriendRecallEvent` + +群消息撤回 + + +## _class_ `GroupStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群变化事件基类 + + +## _class_ `GroupNameChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某个群名改变 + + +## _class_ `GroupEntranceAnnouncementChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某群入群公告改变 + + +## _class_ `GroupMuteAllEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +全员禁言 + + +## _class_ `GroupAllowAnonymousChatEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +匿名聊天 + + +## _class_ `GroupAllowConfessTalkEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +坦白说 + + +## _class_ `GroupAllowMemberInviteEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +允许群员邀请好友加群 + + +## _class_ `MemberStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群成员变化事件基类 + + +## _class_ `MemberCardChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群名片改动 + + +## _class_ `MemberSpecialTitleChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群头衔改动(只有群主有操作限权) + + +## _class_ `BotGroupPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +Bot在群里的权限被改变 + + +## _class_ `MemberPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +成员权限改变的事件(该成员不是Bot) + + +## _class_ `RequestEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +请求事件基类 + + +## _class_ `NewFriendRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +添加好友申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2]`: 响应的操作类型 + + + * `1`: 拒绝添加好友 + + + * `2`: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + + + * `message: str`: 回复的信息 + + + +## _class_ `MemberJoinRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +用户入群申请(Bot需要有管理员权限) + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝(忽略)此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2, 3, 4]`: 响应的操作类型 + + + * `1`: 拒绝入群 + + + * `2`: 忽略请求 + + + * `3`: 拒绝入群并添加黑名单,不再接收该用户的入群申请 + + + * `4`: 忽略入群并添加黑名单,不再接收该用户的入群申请 + + + * `message: str`: 回复的信息 + + + +## _class_ `BotInvitedJoinGroupRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +Bot被邀请入群申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, message='')` + + +* **说明** + + 拒绝这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `message: str`: 邀请消息 + + # NoneBot.adapters.mirai.event.base 模块 From ad3a08f514018ecc563804b345330877d7fd4296 Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 16:53:06 +0800 Subject: [PATCH 68/86] :bulb: :wastebasket: remove some invalid comments in mirai adapter --- nonebot/adapters/mirai/bot_ws.py | 4 ---- nonebot/adapters/mirai/message.py | 4 ---- 2 files changed, 8 deletions(-) diff --git a/nonebot/adapters/mirai/bot_ws.py b/nonebot/adapters/mirai/bot_ws.py index fdf35c0c..9dabe356 100644 --- a/nonebot/adapters/mirai/bot_ws.py +++ b/nonebot/adapters/mirai/bot_ws.py @@ -134,10 +134,6 @@ class WebsocketBot(Bot): * ``driver: Driver``: 程序所使用的``Driver`` * ``config: Config``: 程序配置对象 * ``qq: int``: 要使用的Bot的QQ号 **注意: 在使用正向Websocket时必须指定该值!** - - :返回: - - - ``[type]``: [description] """ super().register(driver, config) cls.active = True diff --git a/nonebot/adapters/mirai/message.py b/nonebot/adapters/mirai/message.py index f1aff156..26fb198c 100644 --- a/nonebot/adapters/mirai/message.py +++ b/nonebot/adapters/mirai/message.py @@ -161,10 +161,6 @@ class MessageSegment(BaseMessageSegment): * ``image_id: Optional[str]``: 图片的image_id,群图片与好友图片格式不同。不为空时将忽略url属性 * ``url: Optional[str]``: 图片的URL,发送时可作网络图片的链接 * ``path: Optional[str]``: 图片的路径,发送本地图片 - - :返回: - - - ``[type]``: [description] """ return cls(type=MessageType.IMAGE, imageId=image_id, url=url, path=path) From f446411f084f6b81f1f278dfe57cb7bd51eadac5 Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 18:28:27 +0800 Subject: [PATCH 69/86] :memo: add start guide for mirai adapter --- docs/.vuepress/config.js | 2 +- docs/api/adapters/mirai.md | 14 --- docs/guide/getting-started.md | 1 + docs/guide/mirai-guide.md | 187 ++++++++++++++++++++++++++++++++++ 4 files changed, 189 insertions(+), 15 deletions(-) create mode 100644 docs/guide/mirai-guide.md diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 6d684ad9..889b4bfe 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -116,7 +116,7 @@ module.exports = (context) => ({ title: "协议适配", collapsable: false, sidebar: "auto", - children: ["cqhttp-guide", "ding-guide"], + children: ["cqhttp-guide", "ding-guide", "mirai-guide"], }, ], "/advanced/": [ diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index 34aae0c9..1b2e709d 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -684,13 +684,6 @@ mirai-api-http 正向 Websocket 协议 Bot 适配。 * `qq: int`: 要使用的Bot的QQ号 **注意: 在使用正向Websocket时必须指定该值!** - -* **返回** - - - * `[type]`: [description] - - # NoneBot.adapters.mirai.config 模块 @@ -845,13 +838,6 @@ CQHTTP 协议 MessageSegment 适配。具体方法参考 [mirai-api-http 消息 -* **返回** - - - * `[type]`: [description] - - - ### _classmethod_ `flash_image(image_id=None, url=None, path=None)` diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index d35665a2..71445c39 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -63,6 +63,7 @@ python bot.py - [配置 CQHTTP](./cqhttp-guide.md) - [配置钉钉](./ding-guide.md) +- [配置 mirai-api-http](./mirai-guide.md) NoneBot 接受的上报地址与 `Driver` 有关,默认使用的 `FastAPI Driver` 所接受的上报地址有: diff --git a/docs/guide/mirai-guide.md b/docs/guide/mirai-guide.md new file mode 100644 index 00000000..d3544179 --- /dev/null +++ b/docs/guide/mirai-guide.md @@ -0,0 +1,187 @@ +# Mirai-API-HTTP 协议使用指南 + +::: warning + +Mirai-API-HTTP 的适配现在仍然处于早期阶段, 可能没有进行过充分的测试 + +请在生产环境中谨慎使用 + +::: + +::: tip + +为了你的使用之旅更加顺畅, 我们建议您在配置之前具有以下的前置知识 + +- 对服务端/客户端(C/S)模型的基本了解 +- 对 Web 服务配置基础的认知 +- 对`YAML`语法的一点点了解 + +::: + +**为了便捷起见, 以下内容均以缩写 `MAH` 代替 `mirai-api-http`** + +## 配置 MAH 客户端 + +正如你可能刚刚在[CQHTTP 协议使用指南](./cqhttp-guide.md)中所读到的: + +> 单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 + +这次, 我们将采用在实现上有别于 onebot即 CQHTTP协议的另外一种无头 QQ API 协议, 即 MAH + +为了配置 MAH 端, 我们现在需要移步到[MAH 的项目地址](https://github.com/project-mirai/mirai-api-http), 来看看它是如何配置的 + +根据[项目提供的 README](https://github.com/project-mirai/mirai-api-http/blob/056beedba31d6ad06426997a1d3fde861a7f8ba3/README.md),配置 MAH 大概需要以下几步 + +1. 下载并安装 Java 运行环境, 你可以有以下几种选择: + + - [由 Oracle 提供的 Java 运行环境](https://java.com/zh-CN/download/manual.jsp) **在没有特殊需求的情况下推荐** + - [由 Zulu 编译的 OpenJRE 环境](https://www.azul.com/downloads/zulu-community/?version=java-8-lts&architecture=x86-64-bit&package=jre) + +2. 下载[Mirai Console Loader](https://github.com/iTXTech/mirai-console-loader) + + - 请按照文档 README 中的步骤下载并安装 + +3. 安装 MAH: + + - 在 Mirai Console Loader 目录下执行该指令 + + - ```shell + ./mcl --update-package net.mamoe:mirai-api-http --channel stable --type plugin + ``` + + 注意: 该指令的前缀`./mcl`可能根据操作系统以及使用 java 环境的不同而变化 + +4. 修改配置文件 + + ::: tip + + 在此之前, 你可能需要了解我们为 MAH 设计的两种通信方式 + + - 正向 Websocket + - NoneBot 作为纯粹的客户端,通过 websocket 监听事件下发 + - 优势 + 1. 网络配置简单, 特别是在使用 Docker 等网络隔离的容器时 + 2. 在初步测试中连接性较好 + - 劣势 + 1. 与 NoneBot 本身的架构不同, 可能稳定性较差 + 2. 需要在注册 adapter 时显式指定 qq, 对于需要开源的程序来讲不利 + - POST 消息上报 + - NoneBot 在接受消息上报时作为服务端, 发送消息时作为客户端 + - 优势 + 1. 与 NoneBot 本身架构相符, 性能和稳定性较强 + 2. 无需在任何地方指定 QQ, 即插即用 + - 劣势 + 1. 由于同时作为客户端和服务端, 配置较为复杂 + 2. 在测试中网络连接性较差 (未确认原因) + + ::: + + - 这是当使用正向 Websocket 时的配置举例 + + - MAH 的`setting.yml`文件 + + - ```yaml + # 省略了部分无需修改的部分 + + host: "0.0.0.0" # 监听地址 + port: 8080 # 监听端口 + authKey: 1234567890 # 访问密钥, 最少八位 + enableWebsocket: true # 必须为true + ``` + + - `.env`文件 + + - ```shell + MIRAI_AUTH_KEY=1234567890 + MIRAI_HOST=127.0.0.1 # 当MAH运行在本机时 + MIRAI_PORT=8080 # MAH的监听端口 + ``` + + - `bot.py`文件 + + - ```python + import nonebot + from nonebot.adapters.mirai import WebsocketBot + + nonebot.init() + nonebot.get_driver().register_adapter('mirai-ws', WebsocketBot, qq=12345678) # qq参数需要填在mah中登录的qq + nonebot.load_builtin_plugins() # 加载 nonebot 内置插件 + nonebot.run() + ``` + + - 这是当使用 POST 消息上报时的配置文件 + + - MAH 的`setting.yml`文件 + + - ```yaml + # 省略了部分无需修改的部分 + + host: '0.0.0.0' # 监听地址 + port: 8080 # 监听端口 + authKey: 1234567890 # 访问密钥, 最少八位 + + ## 消息上报 + report: + enable: true # 必须为true + groupMessage: + report: true # 群消息上报 + friendMessage: + report: true # 好友消息上报 + tempMessage: + report: true # 临时会话上报 + eventMessage: + report: true # 事件上报 + destinations: + - 'http://127.0.0.1:2333/mirai/http' #上报地址, 请按照实际情况修改 + # 上报时的额外Header + extraHeaders: {} + ``` + + - `.env`文件 + + - ```shell + HOST=127.0.0.1 # 当MAH运行在本机时 + PORT=2333 + + MIRAI_AUTH_KEY=1234567890 + MIRAI_HOST=127.0.0.1 # 当MAH运行在本机时 + MIRAI_PORT=8080 # MAH的监听端口 + ``` + + - `bot.py`文件 + + - ```python + import nonebot + from nonebot.adapters.mirai import Bot + + nonebot.init() + nonebot.get_driver().register_adapter('mirai', Bot) + nonebot.load_builtin_plugins() # 加载 nonebot 内置插件 + nonebot.run() + ``` + +## 历史性的第一次对话 + +现在, 先启动 NoneBot, 再启动 MAH + +如果你的配置文件一切正常, 你将在控制台看到类似于下列的日志 + +```log +02-01 18:25:12 [INFO] nonebot | NoneBot is initializing... +02-01 18:25:12 [INFO] nonebot | Current Env: prod +02-01 18:25:12 [DEBUG] nonebot | Loaded Config: {'driver': 'nonebot.drivers.fastapi', 'host': IPv4Address('127.0.0.1'), 'port': 8080, 'debug': True, 'api_root': {}, 'api_timeout': 30.0, 'access_token': None, 'secret': None, 'superusers': set(), 'nickname': set(), 'command_start': {'/'}, 'command_sep': {'.'}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'mirai_port': 8080, 'environment': 'prod', 'mirai_auth_key': 12345678, 'mirai_host': '127.0.0.1'} +02-01 18:25:12 [DEBUG] nonebot | Succeeded to load adapter "mirai" +02-01 18:25:12 [INFO] nonebot | Succeeded to import "nonebot.plugins.echo" +02-01 18:25:12 [INFO] nonebot | Running NoneBot... +02-01 18:25:12 [DEBUG] nonebot | Loaded adapters: mirai +02-01 18:25:12 [INFO] uvicorn | Started server process [183155] +02-01 18:25:12 [INFO] uvicorn | Waiting for application startup. +02-01 18:25:12 [INFO] uvicorn | Application startup complete. +02-01 18:25:12 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:2333 (Press CTRL+C to quit) +02-01 18:25:14 [INFO] uvicorn | 127.0.0.1:37794 - "POST /mirai/http HTTP/1.1" 204 +02-01 18:25:14 [DEBUG] nonebot | MIRAI | received message {'type': 'BotOnlineEvent', 'qq': 1234567} +02-01 18:25:14 [INFO] nonebot | MIRAI 1234567 | [BotOnlineEvent]: {'self_id': 1234567, 'type': 'BotOnlineEvent', 'qq': 1234567} +02-01 18:25:14 [DEBUG] nonebot | Checking for matchers in priority 1... +``` + +恭喜你, 你的配置已经成功! From d6ae1ca01cd06856dc712f2ddcce4287bef857cb Mon Sep 17 00:00:00 2001 From: Mix Date: Mon, 1 Feb 2021 19:16:36 +0800 Subject: [PATCH 70/86] :page_facing_up: add agpl v3 license for mirai adapter --- docs/api/adapters/mirai.md | 6 + docs/guide/mirai-guide.md | 8 + nonebot/adapters/mirai/LICENSE | 661 +++++++++++++++++++++++++++++ nonebot/adapters/mirai/__init__.py | 9 + 4 files changed, 684 insertions(+) create mode 100644 nonebot/adapters/mirai/LICENSE diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index 1b2e709d..3e53e9e7 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -15,6 +15,12 @@ sidebarDepth: 0 如果你在使用过程中遇到了任何问题, 请前往 [Issue页面](https://github.com/nonebot/nonebot2/issues) 为我们提供反馈 ::: +::: danger +Mirai-API-HTTP 的适配器以 [AGPLv3许可](https://opensource.org/licenses/AGPL-3.0) 单独开源 + +这意味着在使用该适配器时需要\*\*开源您的完整程序代码\*\* +::: + # NoneBot.adapters.mirai.bot 模块 diff --git a/docs/guide/mirai-guide.md b/docs/guide/mirai-guide.md index d3544179..bd11083c 100644 --- a/docs/guide/mirai-guide.md +++ b/docs/guide/mirai-guide.md @@ -18,6 +18,14 @@ Mirai-API-HTTP 的适配现在仍然处于早期阶段, 可能没有进行过充 ::: +::: danger + +Mirai-API-HTTP 的适配器以 [AGPLv3 许可](https://opensource.org/licenses/AGPL-3.0) 单独开源 + +这意味着在使用该适配器时需要 **以该许可开源您的完整程序代码** + +::: + **为了便捷起见, 以下内容均以缩写 `MAH` 代替 `mirai-api-http`** ## 配置 MAH 客户端 diff --git a/nonebot/adapters/mirai/LICENSE b/nonebot/adapters/mirai/LICENSE new file mode 100644 index 00000000..be3f7b28 --- /dev/null +++ b/nonebot/adapters/mirai/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/nonebot/adapters/mirai/__init__.py b/nonebot/adapters/mirai/__init__.py index c083a8a7..2b09e365 100644 --- a/nonebot/adapters/mirai/__init__.py +++ b/nonebot/adapters/mirai/__init__.py @@ -10,12 +10,21 @@ Mirai-API-HTTP 协议适配 如果你在使用过程中遇到了任何问题, 请前往 `Issue页面`_ 为我们提供反馈 \:\:\: +\:\:\: danger +Mirai-API-HTTP 的适配器以 `AGPLv3许可`_ 单独开源 + +这意味着在使用该适配器时需要 **以该许可开源您的完整程序代码** +\:\:\: + .. _mirai-api-http 文档: https://github.com/project-mirai/mirai-api-http/tree/master/docs .. _Issue页面: https://github.com/nonebot/nonebot2/issues +.. _AGPLv3许可: + https://opensource.org/licenses/AGPL-3.0 + """ from .bot import Bot From 9b79c83c3d8af6a8e461c01d74f38c289a7f0295 Mon Sep 17 00:00:00 2001 From: nonebot Date: Mon, 1 Feb 2021 11:30:11 +0000 Subject: [PATCH 71/86] :memo: update api docs --- docs/api/adapters/mirai.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/adapters/mirai.md b/docs/api/adapters/mirai.md index 3e53e9e7..4b568152 100644 --- a/docs/api/adapters/mirai.md +++ b/docs/api/adapters/mirai.md @@ -18,7 +18,7 @@ sidebarDepth: 0 ::: danger Mirai-API-HTTP 的适配器以 [AGPLv3许可](https://opensource.org/licenses/AGPL-3.0) 单独开源 -这意味着在使用该适配器时需要\*\*开源您的完整程序代码\*\* +这意味着在使用该适配器时需要 **以该许可开源您的完整程序代码** ::: # NoneBot.adapters.mirai.bot 模块 From 00858416f93bec661a6638841dbdb978a8fbe344 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 1 Feb 2021 20:58:12 +0800 Subject: [PATCH 72/86] :art: format code and bump dependency --- docs/.vuepress/config.js | 114 ++++++++++++++++++------------------ nonebot/drivers/__init__.py | 4 +- poetry.lock | 48 +++++++-------- pyproject.toml | 2 +- 4 files changed, 84 insertions(+), 84 deletions(-) diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 889b4bfe..3b011655 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -1,11 +1,11 @@ const path = require("path"); -module.exports = (context) => ({ +module.exports = context => ({ base: process.env.VUEPRESS_BASE || "/", title: "NoneBot", description: "基于 酷Q 的 Python 异步 QQ 机器人框架", markdown: { - lineNumbers: true, + lineNumbers: true }, /** * Extra tags to be injected to the page HTML `` @@ -21,26 +21,26 @@ module.exports = (context) => ({ ["meta", { name: "apple-mobile-web-app-capable", content: "yes" }], [ "meta", - { name: "apple-mobile-web-app-status-bar-style", content: "black" }, + { name: "apple-mobile-web-app-status-bar-style", content: "black" } ], [ "link", - { rel: "apple-touch-icon", href: "/icons/apple-touch-icon-180x180.png" }, + { rel: "apple-touch-icon", href: "/icons/apple-touch-icon-180x180.png" } ], [ "link", { rel: "mask-icon", href: "/icons/safari-pinned-tab.svg", - color: "#ea5252", - }, + color: "#ea5252" + } ], [ "meta", { name: "msapplication-TileImage", - content: "/icons/mstile-150x150.png", - }, + content: "/icons/mstile-150x150.png" + } ], ["meta", { name: "msapplication-TileColor", content: "#ea5252" }], [ @@ -48,16 +48,16 @@ module.exports = (context) => ({ { rel: "stylesheet", href: - "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css", - }, - ], + "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5/css/all.min.css" + } + ] ], locales: { "/": { lang: "zh-CN", title: "NoneBot", - description: "基于 酷Q 的 Python 异步 QQ 机器人框架", - }, + description: "基于 酷Q 的 Python 异步 QQ 机器人框架" + } }, theme: "nonebot", @@ -83,7 +83,7 @@ module.exports = (context) => ({ { text: "进阶", link: "/advanced/" }, { text: "API", link: "/api/" }, { text: "插件广场", link: "/plugin-store" }, - { text: "更新日志", link: "/changelog" }, + { text: "更新日志", link: "/changelog" } ], sidebarDepth: 2, sidebar: { @@ -97,8 +97,8 @@ module.exports = (context) => ({ "installation", "getting-started", "creating-a-project", - "basic-configuration", - ], + "basic-configuration" + ] }, { title: "编写插件", @@ -109,15 +109,15 @@ module.exports = (context) => ({ "creating-a-plugin", "creating-a-matcher", "creating-a-handler", - "end-or-start", - ], + "end-or-start" + ] }, { title: "协议适配", collapsable: false, sidebar: "auto", - children: ["cqhttp-guide", "ding-guide", "mirai-guide"], - }, + children: ["cqhttp-guide", "ding-guide", "mirai-guide"] + } ], "/advanced/": [ { @@ -130,15 +130,15 @@ module.exports = (context) => ({ "permission", "runtime-hook", "export-and-require", - "overloaded-handlers", - ], + "overloaded-handlers" + ] }, { title: "发布", collapsable: false, sidebar: "auto", - children: ["publish-plugin"], - }, + children: ["publish-plugin"] + } ], "/api/": [ { @@ -148,78 +148,78 @@ module.exports = (context) => ({ children: [ { title: "nonebot 模块", - path: "nonebot", + path: "nonebot" }, { title: "nonebot.config 模块", - path: "config", + path: "config" }, { title: "nonebot.plugin 模块", - path: "plugin", + path: "plugin" }, { title: "nonebot.message 模块", - path: "message", + path: "message" }, { title: "nonebot.matcher 模块", - path: "matcher", + path: "matcher" }, { title: "nonebot.rule 模块", - path: "rule", + path: "rule" }, { title: "nonebot.permission 模块", - path: "permission", + path: "permission" }, { title: "nonebot.log 模块", - path: "log", + path: "log" }, { title: "nonebot.utils 模块", - path: "utils", + path: "utils" }, { title: "nonebot.typing 模块", - path: "typing", + path: "typing" }, { title: "nonebot.exception 模块", - path: "exception", + path: "exception" }, { title: "nonebot.drivers 模块", - path: "drivers/", + path: "drivers/" }, { title: "nonebot.drivers.fastapi 模块", - path: "drivers/fastapi", + path: "drivers/fastapi" }, { title: "nonebot.adapters 模块", - path: "adapters/", + path: "adapters/" }, { title: "nonebot.adapters.cqhttp 模块", - path: "adapters/cqhttp", + path: "adapters/cqhttp" }, { title: "nonebot.adapters.ding 模块", - path: "adapters/ding", + path: "adapters/ding" }, { title: "nonebot.adapters.mirai 模块", - path: "adapters/mirai", - }, - ], - }, - ], - }, - }, - }, + path: "adapters/mirai" + } + ] + } + ] + } + } + } }, plugins: [ @@ -231,9 +231,9 @@ module.exports = (context) => ({ serviceWorker: true, updatePopup: { message: "发现新内容", - buttonText: "刷新", - }, - }, + buttonText: "刷新" + } + } ], [ "versioning", @@ -242,16 +242,16 @@ module.exports = (context) => ({ pagesSourceDir: path.resolve(context.sourceDir, "..", "pages"), onNewVersion(version, versionDestPath) { console.log(`Created version ${version} in ${versionDestPath}`); - }, - }, + } + } ], [ "container", { type: "vue", before: '
',
-        after: "
", - }, - ], - ], + after: "" + } + ] + ] }); diff --git a/nonebot/drivers/__init__.py b/nonebot/drivers/__init__.py index 134b2078..986d59a3 100644 --- a/nonebot/drivers/__init__.py +++ b/nonebot/drivers/__init__.py @@ -62,7 +62,7 @@ class Driver(abc.ABC): :说明: 已连接的 Bot """ - def register_adapter(self, name: str, adapter: Type["Bot"], **kwargs): + def register_adapter(self, name: str, adapter: Type["Bot"]): """ :说明: @@ -74,7 +74,7 @@ class Driver(abc.ABC): * ``adapter: Type[Bot]``: 适配器 Class """ self._adapters[name] = adapter - adapter.register(self, self.config, **kwargs) + adapter.register(self, self.config) logger.opt( colors=True).debug(f'Succeeded to load adapter "{name}"') diff --git a/poetry.lock b/poetry.lock index 2e9e5611..9523412b 100644 --- a/poetry.lock +++ b/poetry.lock @@ -143,7 +143,7 @@ reference = "aliyun" [[package]] name = "httpcore" -version = "0.12.2" +version = "0.12.3" description = "A minimal low-level HTTP client." category = "main" optional = false @@ -228,7 +228,7 @@ reference = "aliyun" [[package]] name = "jinja2" -version = "2.11.2" +version = "2.11.3" description = "A very fast and expressive template engine." category = "dev" optional = false @@ -280,7 +280,7 @@ reference = "aliyun" [[package]] name = "packaging" -version = "20.8" +version = "20.9" description = "Core utilities for Python packages" category = "dev" optional = false @@ -334,7 +334,7 @@ reference = "aliyun" [[package]] name = "pygments" -version = "2.7.3" +version = "2.7.4" description = "Pygments is a syntax highlighting package written in Python." category = "dev" optional = false @@ -347,7 +347,7 @@ reference = "aliyun" [[package]] name = "pygtrie" -version = "2.4.1" +version = "2.4.2" description = "A pure Python trie data structure implementation." category = "main" optional = false @@ -457,8 +457,8 @@ reference = "aliyun" [[package]] name = "snowballstemmer" -version = "2.0.0" -description = "This package provides 26 stemmers for 25 languages generated from Snowball algorithms." +version = "2.1.0" +description = "This package provides 29 stemmers for 28 languages generated from Snowball algorithms." category = "dev" optional = false python-versions = "*" @@ -470,7 +470,7 @@ reference = "aliyun" [[package]] name = "sphinx" -version = "3.4.1" +version = "3.4.3" description = "Python documentation generator" category = "dev" optional = false @@ -687,7 +687,7 @@ reference = "aliyun" [[package]] name = "urllib3" -version = "1.26.2" +version = "1.26.3" description = "HTTP library with thread-safe connection pooling, file post, and more." category = "dev" optional = false @@ -828,8 +828,8 @@ html2text = [ {file = "html2text-2020.1.16.tar.gz", hash = "sha256:e296318e16b059ddb97f7a8a1d6a5c1d7af4544049a01e261731d2d5cc277bbb"}, ] httpcore = [ - {file = "httpcore-0.12.2-py3-none-any.whl", hash = "sha256:420700af11db658c782f7e8fda34f9dcd95e3ee93944dd97d78cb70247e0cd06"}, - {file = "httpcore-0.12.2.tar.gz", hash = "sha256:dd1d762d4f7c2702149d06be2597c35fb154c5eff9789a8c5823fbcf4d2978d6"}, + {file = "httpcore-0.12.3-py3-none-any.whl", hash = "sha256:93e822cd16c32016b414b789aeff4e855d0ccbfc51df563ee34d4dbadbb3bcdc"}, + {file = "httpcore-0.12.3.tar.gz", hash = "sha256:37ae835fb370049b2030c3290e12ed298bf1473c41bb72ca4aa78681eba9b7c9"}, ] httptools = [ {file = "httptools-0.1.1-cp35-cp35m-macosx_10_13_x86_64.whl", hash = "sha256:a2719e1d7a84bb131c4f1e0cb79705034b48de6ae486eb5297a139d6a3296dce"}, @@ -858,8 +858,8 @@ imagesize = [ {file = "imagesize-1.2.0.tar.gz", hash = "sha256:b1f6b5a4eab1f73479a50fb79fcf729514a900c341d8503d62a62dbc4127a2b1"}, ] jinja2 = [ - {file = "Jinja2-2.11.2-py2.py3-none-any.whl", hash = "sha256:f0a4641d3cf955324a89c04f3d94663aa4d638abe8f733ecd3582848e1c37035"}, - {file = "Jinja2-2.11.2.tar.gz", hash = "sha256:89aab215427ef59c34ad58735269eb58b1a5808103067f7bb9d5836c651b3bb0"}, + {file = "Jinja2-2.11.3-py2.py3-none-any.whl", hash = "sha256:03e47ad063331dd6a3f04a43eddca8a966a26ba0c5b7207a9a9e4e08f1b29419"}, + {file = "Jinja2-2.11.3.tar.gz", hash = "sha256:a6d58433de0ae800347cab1fa3043cebbabe8baa9d29e668f1c768cb87a333c6"}, ] loguru = [ {file = "loguru-0.5.3-py3-none-any.whl", hash = "sha256:f8087ac396b5ee5f67c963b495d615ebbceac2796379599820e324419d53667c"}, @@ -901,8 +901,8 @@ markupsafe = [ {file = "MarkupSafe-1.1.1.tar.gz", hash = "sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b"}, ] packaging = [ - {file = "packaging-20.8-py2.py3-none-any.whl", hash = "sha256:24e0da08660a87484d1602c30bb4902d74816b6985b93de36926f5bc95741858"}, - {file = "packaging-20.8.tar.gz", hash = "sha256:78598185a7008a470d64526a8059de9aaa449238f280fc9eb6b13ba6c4109093"}, + {file = "packaging-20.9-py2.py3-none-any.whl", hash = "sha256:67714da7f7bc052e064859c05c595155bd1ee9f69f76557e21f051443c20947a"}, + {file = "packaging-20.9.tar.gz", hash = "sha256:5b327ac1320dc863dca72f4514ecc086f31186744b84a230374cc1fd776feae5"}, ] pydantic = [ {file = "pydantic-1.7.3-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:c59ea046aea25be14dc22d69c97bee629e6d48d2b2ecb724d7fe8806bf5f61cd"}, @@ -933,11 +933,11 @@ pydash = [ {file = "pydash-4.9.2.tar.gz", hash = "sha256:11d8f3c92d92a004e042fdb226b10dba28f4e311546b0de89d983e91539d5e55"}, ] pygments = [ - {file = "Pygments-2.7.3-py3-none-any.whl", hash = "sha256:f275b6c0909e5dafd2d6269a656aa90fa58ebf4a74f8fcf9053195d226b24a08"}, - {file = "Pygments-2.7.3.tar.gz", hash = "sha256:ccf3acacf3782cbed4a989426012f1c535c9a90d3a7fc3f16d231b9372d2b716"}, + {file = "Pygments-2.7.4-py3-none-any.whl", hash = "sha256:bc9591213a8f0e0ca1a5e68a479b4887fdc3e75d0774e5c71c31920c427de435"}, + {file = "Pygments-2.7.4.tar.gz", hash = "sha256:df49d09b498e83c1a73128295860250b0b7edd4c723a32e9bc0d295c7c2ec337"}, ] pygtrie = [ - {file = "pygtrie-2.4.1.tar.gz", hash = "sha256:4367b87d92eaf475107421dce0295a9d4d72156702908c96c430a426b654aee7"}, + {file = "pygtrie-2.4.2.tar.gz", hash = "sha256:43205559d28863358dbbf25045029f58e2ab357317a59b11f11ade278ac64692"}, ] pyparsing = [ {file = "pyparsing-2.4.7-py2.py3-none-any.whl", hash = "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b"}, @@ -964,12 +964,12 @@ sniffio = [ {file = "sniffio-1.2.0.tar.gz", hash = "sha256:c4666eecec1d3f50960c6bdf61ab7bc350648da6c126e3cf6898d8cd4ddcd3de"}, ] snowballstemmer = [ - {file = "snowballstemmer-2.0.0-py2.py3-none-any.whl", hash = "sha256:209f257d7533fdb3cb73bdbd24f436239ca3b2fa67d56f6ff88e86be08cc5ef0"}, - {file = "snowballstemmer-2.0.0.tar.gz", hash = "sha256:df3bac3df4c2c01363f3dd2cfa78cce2840a79b9f1c2d2de9ce8d31683992f52"}, + {file = "snowballstemmer-2.1.0-py2.py3-none-any.whl", hash = "sha256:b51b447bea85f9968c13b650126a888aabd4cb4463fca868ec596826325dedc2"}, + {file = "snowballstemmer-2.1.0.tar.gz", hash = "sha256:e997baa4f2e9139951b6f4c631bad912dfd3c792467e2f03d7239464af90e914"}, ] sphinx = [ - {file = "Sphinx-3.4.1-py3-none-any.whl", hash = "sha256:aeef652b14629431c82d3fe994ce39ead65b3fe87cf41b9a3714168ff8b83376"}, - {file = "Sphinx-3.4.1.tar.gz", hash = "sha256:e450cb205ff8924611085183bf1353da26802ae73d9251a8fcdf220a8f8712ef"}, + {file = "Sphinx-3.4.3-py3-none-any.whl", hash = "sha256:c314c857e7cd47c856d2c5adff514ac2e6495f8b8e0f886a8a37e9305dfea0d8"}, + {file = "Sphinx-3.4.3.tar.gz", hash = "sha256:41cad293f954f7d37f803d97eb184158cfd90f51195131e94875bc07cd08b93c"}, ] sphinx-markdown-builder = [] sphinxcontrib-applehelp = [ @@ -1012,8 +1012,8 @@ untokenize = [ {file = "untokenize-0.1.1.tar.gz", hash = "md5:50d325dff09208c624cc603fad33bb0d"}, ] urllib3 = [ - {file = "urllib3-1.26.2-py2.py3-none-any.whl", hash = "sha256:d8ff90d979214d7b4f8ce956e80f4028fc6860e4431f731ea4a8c08f23f99473"}, - {file = "urllib3-1.26.2.tar.gz", hash = "sha256:19188f96923873c92ccb987120ec4acaa12f0461fa9ce5d3d0772bc965a39e08"}, + {file = "urllib3-1.26.3-py2.py3-none-any.whl", hash = "sha256:1b465e494e3e0d8939b50680403e3aedaa2bc434b7d5af64dfd3c958d7f5ae80"}, + {file = "urllib3-1.26.3.tar.gz", hash = "sha256:de3eedaad74a2683334e282005cd8d7f22f4d55fa690a2a1020a416cb0a47e73"}, ] uvicorn = [ {file = "uvicorn-0.11.8-py3-none-any.whl", hash = "sha256:4b70ddb4c1946e39db9f3082d53e323dfd50634b95fd83625d778729ef1730ef"}, diff --git a/pyproject.toml b/pyproject.toml index 87a5e573..39854210 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -29,8 +29,8 @@ loguru = "^0.5.1" pygtrie = "^2.4.1" fastapi = "^0.63.0" uvicorn = "^0.11.5" -pydantic = {extras = ["dotenv", "typing_extensions"], version = "^1.7.3"} websockets = "^8.1" +pydantic = {extras = ["dotenv", "typing_extensions"], version = "^1.7.3"} [tool.poetry.dev-dependencies] yapf = "^0.30.0" From 02a780f3b0f4b783e9b8343ff441471774553d4b Mon Sep 17 00:00:00 2001 From: nonebot Date: Mon, 1 Feb 2021 13:00:25 +0000 Subject: [PATCH 73/86] :memo: update api docs --- docs/api/drivers/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/api/drivers/README.md b/docs/api/drivers/README.md index 673697b4..77485ed2 100644 --- a/docs/api/drivers/README.md +++ b/docs/api/drivers/README.md @@ -120,7 +120,7 @@ Driver 基类。将后端框架封装,以满足适配器使用。 -### `register_adapter(name, adapter, **kwargs)` +### `register_adapter(name, adapter)` * **说明** From 27c6457c2053d38a7a7f40f2167c206b41c890d8 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Mon, 1 Feb 2021 21:11:41 +0800 Subject: [PATCH 74/86] :memo: update README --- README.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/README.md b/README.md index 10633bdd..1bb43a02 100644 --- a/README.md +++ b/README.md @@ -110,3 +110,9 @@ NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义 如果你在使用过程中发现任何问题,可以 [提交 issue](https://github.com/nonebot/nonebot2/issues/new) 或自行 fork 修改后提交 pull request。 如果你要提交 pull request,请确保你的代码风格和项目已有的代码保持一致,遵循 [PEP 8](https://www.python.org/dev/peps/pep-0008/),变量命名清晰,有适当的注释。 + +## 许可证 + +`NoneBot` 采用 `MIT` 协议开源,协议文件参考 [LICENSE](./LICENSE)。 + +特别的,由于 `mirai` 使用 `AGPLv3` 协议并要求使用 `mirai` 的软件同样以 `AGPLv3` 协议开源,本项目 `mirai` 适配器部分(即 [`nonebot/adapters/mirai/`](./nonebot/adapters/mirai/) 目录)以 `AGPLv3` 协议开源,协议文件参考 [LICENSE](./nonebot/adapters/mirai/LICENSE)。 From f8fb36a1f788777a4eadad9fde817327d05a3491 Mon Sep 17 00:00:00 2001 From: AkiraXie Date: Mon, 1 Feb 2021 22:28:48 +0800 Subject: [PATCH 75/86] :zap:Support shell-like command --- nonebot/plugin.py | 56 ++++++++++++++++++++++++++++++++++++-- nonebot/plugin.pyi | 10 +++++++ nonebot/rule.py | 68 ++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 132 insertions(+), 2 deletions(-) diff --git a/nonebot/plugin.py b/nonebot/plugin.py index de4073c9..562811fd 100644 --- a/nonebot/plugin.py +++ b/nonebot/plugin.py @@ -9,6 +9,7 @@ import re import sys import pkgutil import importlib +from argparse import ArgumentParser from types import ModuleType from dataclasses import dataclass from importlib._bootstrap import _load @@ -19,7 +20,7 @@ from nonebot.log import logger from nonebot.matcher import Matcher from nonebot.permission import Permission from nonebot.typing import T_State, T_StateFactory, T_Handler, T_RuleChecker -from nonebot.rule import Rule, startswith, endswith, keyword, command, regex +from nonebot.rule import Rule, shell_like_command, startswith, endswith, keyword, command, regex if TYPE_CHECKING: from nonebot.adapters import Bot, Event @@ -436,6 +437,56 @@ def on_command(cmd: Union[str, Tuple[str, ...]], return on_message(command(*commands) & rule, handlers=handlers, **kwargs) +def on_shell_like_command(cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, T_RuleChecker]] = None, + aliases: Optional[Set[Union[str, + Tuple[str, ...]]]] = None, + shell_like_argsparser: Optional[ArgumentParser] = None, + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。 + + 与普通的 ``on_command`` 不同的是,在添加 ``shell_like_argsparser`` 参数时, 响应器会自动处理消息, + + 并将 ``shell_like_argsparser`` 处理的参数保存在 ``state["args"]`` 中 + + :参数: + + * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名 + * ``shell_like_argsparser:Optional[ArgumentParser]``: ``argparse.ArgumentParser`` 对象,是一个类 ``shell`` 的 ``argsparser`` + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 + + :返回: + + - ``Type[Matcher]`` + """ + + async def _strip_cmd(bot: "Bot", event: "Event", state: T_State): + message = event.get_message() + segment = message.pop(0) + new_message = message.__class__( + str(segment) + [len(state["_prefix"]["raw_command"]):].strip()) # type: ignore + for new_segment in reversed(new_message): + message.insert(0, new_segment) + + handlers = kwargs.pop("handlers", []) + handlers.insert(0, _strip_cmd) + + commands = set([cmd]) | (aliases or set()) + return on_message(shell_like_command(shell_like_argsparser, *commands) & rule, handlers=handlers, **kwargs) + + def on_regex(pattern: str, flags: Union[int, re.RegexFlag] = 0, rule: Optional[Rule] = None, @@ -917,7 +968,8 @@ def load_plugins(*plugin_dir: str) -> Set[Plugin]: m.module = name plugin = Plugin(name, module, _tmp_matchers.get(), _export.get()) plugins[name] = plugin - logger.opt(colors=True).info(f'Succeeded to import "{name}"') + logger.opt(colors=True).info( + f'Succeeded to import "{name}"') return plugin except Exception as e: logger.opt(colors=True, exception=e).error( diff --git a/nonebot/plugin.pyi b/nonebot/plugin.pyi index db31ad3d..1e8cb810 100644 --- a/nonebot/plugin.pyi +++ b/nonebot/plugin.pyi @@ -1,4 +1,5 @@ import re +from argparse import ArgumentParser from types import ModuleType from contextvars import ContextVar from typing import Any, Set, List, Dict, Type, Tuple, Union, Optional @@ -146,6 +147,15 @@ def on_command(cmd: Union[str, Tuple[str, ...]], ... +def on_shell_like_command(cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, T_RuleChecker]] = None, + aliases: Optional[Set[Union[str, + Tuple[str, ...]]]] = None, + shell_like_argsparser: Optional[ArgumentParser] = None, + **kwargs) -> Type[Matcher]: + ... + + def on_regex(pattern: str, flags: Union[int, re.RegexFlag] = 0, rule: Optional[Rule] = ..., diff --git a/nonebot/rule.py b/nonebot/rule.py index d2b8f1fd..0c0effc4 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -9,10 +9,12 @@ \:\:\: """ +from argparse import ArgumentParser import re import asyncio from itertools import product from typing import Any, Dict, Union, Tuple, Optional, Callable, NoReturn, Awaitable, TYPE_CHECKING +from loguru import logger from pygtrie import CharTrie @@ -276,6 +278,72 @@ def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule: return Rule(_command) +def shell_like_command(shell_like_argsparser: Optional[ArgumentParser] = None, *cmds: Union[str, Tuple[str, ...]]) -> Rule: + """ + :说明: + + 支持 ``shell_like`` 解析参数的命令形式匹配,根据配置里提供的 ``command_start``, ``command_sep`` 判断消息是否为命令。 + + 可以通过 ``state["_prefix"]["command"]`` 获取匹配成功的命令(例:``("test",)``),通过 ``state["_prefix"]["raw_command"]`` 获取匹配成功的原始命令文本(例:``"/test"``)。 + + 添加 ``shell_like_argpsarser`` 参数后, 可以自动处理消息并将结果保存在 ``state["args"]`` 中。 + + + + + :参数: + * ``shell_like_argsparser: Optional[ArgumentParser]``: ``argparse.ArgumentParser`` 对象, 是一个类 ``shell`` 的 ``argsparser`` + + * ``*cmds: Union[str, Tuple[str, ...]]``: 命令内容 + + :示例: + + 使用默认 ``command_start``, ``command_sep`` 配置 + + 命令 ``("test",)`` 可以匹配:``/test`` 开头的消息 + 命令 ``("test", "sub")`` 可以匹配”``/test.sub`` 开头的消息 + + 当 ``shell_like_argsparser`` 的 ``argument`` 为 ``-a`` 时且 ``action`` 为 ``store_true`` , ``state["args"]["a"]`` 将会记录 ``True`` + + \:\:\:tip 提示 + 命令内容与后续消息间无需空格! + \:\:\: + """ + config = get_driver().config + command_start = config.command_start + command_sep = config.command_sep + commands = list(cmds) + for index, command in enumerate(commands): + if isinstance(command, str): + commands[index] = command = (command,) + + if len(command) == 1: + for start in command_start: + TrieRule.add_prefix(f"{start}{command[0]}", command) + else: + for start, sep in product(command_start, command_sep): + TrieRule.add_prefix(f"{start}{sep.join(command)}", command) + + async def _shell_like_command(bot: "Bot", event: "Event", state: T_State) -> bool: + if state["_prefix"]["command"] in commands: + if shell_like_argsparser: + message = str(event.get_message()) + strip_message = message[len( + state["_prefix"]["raw_command"]):].lstrip() + try: + args = shell_like_argsparser.parse_args( + strip_message.split()) + state["args"]=dict() + state["args"].update(**args.__dict__) + except: + pass + return True + else: + return False + + return Rule(_shell_like_command) + + def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: """ :说明: From c8ebaf38b6aae28efadba0dc4a729e04e384ef4d Mon Sep 17 00:00:00 2001 From: AkiraXie Date: Mon, 1 Feb 2021 17:22:53 +0000 Subject: [PATCH 76/86] :memo: update api docs --- docs/api/plugin.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++ docs/api/rule.md | 38 +++++++++++++++++++++++++++++++ 2 files changed, 95 insertions(+) diff --git a/docs/api/plugin.md b/docs/api/plugin.md index 91e3e763..5e958f64 100644 --- a/docs/api/plugin.md +++ b/docs/api/plugin.md @@ -507,6 +507,63 @@ def something_else(): +## `on_shell_like_command(cmd, rule=None, aliases=None, shell_like_argsparser=None, **kwargs)` + + +* **说明** + + 注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 + + 与普通的 `on_command` 不同的是,在添加 `shell_like_argsparser` 参数时, 响应器会自动处理消息, + + 并将 `shell_like_argsparser` 处理的参数保存在 `state["args"]` 中 + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `shell_like_argsparser:Optional[ArgumentParser]`: `argparse.ArgumentParser` 对象,是一个类 `shell` 的 `argsparser` + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + ## `on_regex(pattern, flags=0, rule=None, **kwargs)` diff --git a/docs/api/rule.md b/docs/api/rule.md index cb3fd05f..44f4a098 100644 --- a/docs/api/rule.md +++ b/docs/api/rule.md @@ -170,6 +170,44 @@ Rule(async_function, run_sync(sync_function)) ::: +## `shell_like_command(shell_like_argsparser=None, *cmds)` + + +* **说明** + + 支持 `shell_like` 解析参数的命令形式匹配,根据配置里提供的 `command_start`, `command_sep` 判断消息是否为命令。 + + 可以通过 `state["_prefix"]["command"]` 获取匹配成功的命令(例:`("test",)`),通过 `state["_prefix"]["raw_command"]` 获取匹配成功的原始命令文本(例:`"/test"`)。 + + 添加 `shell_like_argpsarser` 参数后, 可以自动处理消息并将结果保存在 `state["args"]` 中。 + + + +* **参数** + + + * `shell_like_argsparser: Optional[ArgumentParser]`: `argparse.ArgumentParser` 对象, 是一个类 `shell` 的 `argsparser` + + + * `*cmds: Union[str, Tuple[str, ...]]`: 命令内容 + + + +* **示例** + + 使用默认 `command_start`, `command_sep` 配置 + + 命令 `("test",)` 可以匹配:`/test` 开头的消息 + 命令 `("test", "sub")` 可以匹配”`/test.sub` 开头的消息 + + 当 `shell_like_argsparser` 的 `argument` 为 `-a` 时且 `action` 为 `store_true` , `state["args"]["a"]` 将会记录 `True` + + +:::tip 提示 +命令内容与后续消息间无需空格! +::: + + ## `regex(regex, flags=0)` From 9e4e9f29d1b5256e50a4c221e0393f36965a119d Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 11:59:14 +0800 Subject: [PATCH 77/86] :sparkles: rewrite shell command --- nonebot/__init__.py | 2 +- nonebot/exception.py | 17 +++++ nonebot/plugin.py | 103 ++++++++++++++++++++++++++----- nonebot/plugin.pyi | 46 +++++++++++--- nonebot/rule.py | 79 ++++++++++++++++-------- tests/test_plugins/test_shell.py | 15 +++++ 6 files changed, 212 insertions(+), 50 deletions(-) create mode 100644 tests/test_plugins/test_shell.py diff --git a/nonebot/__init__.py b/nonebot/__init__.py index 11dad7cd..dce9c9ec 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -218,6 +218,6 @@ def run(host: Optional[str] = None, from nonebot.plugin import on_message, on_notice, on_request, on_metaevent, CommandGroup, MatcherGroup -from nonebot.plugin import on_startswith, on_endswith, on_keyword, on_command, on_regex +from nonebot.plugin import on_startswith, on_endswith, on_keyword, on_command, on_shell_command, on_regex from nonebot.plugin import load_plugin, load_plugins, load_builtin_plugins from nonebot.plugin import export, require, get_plugin, get_loaded_plugins diff --git a/nonebot/exception.py b/nonebot/exception.py index 815ac714..b8a42aa4 100644 --- a/nonebot/exception.py +++ b/nonebot/exception.py @@ -37,6 +37,23 @@ class IgnoredException(NoneBotException): return self.__repr__() +class ParserExit(NoneBotException): + """ + :说明: + + ``shell command`` 处理消息失败时返回的异常 + + :参数: + + * ``status`` + * ``message`` + """ + + def __init__(self, status=0, message=None): + self.status = status + self.message = message + + class PausedException(NoneBotException): """ :说明: diff --git a/nonebot/plugin.py b/nonebot/plugin.py index 562811fd..1e198179 100644 --- a/nonebot/plugin.py +++ b/nonebot/plugin.py @@ -9,7 +9,6 @@ import re import sys import pkgutil import importlib -from argparse import ArgumentParser from types import ModuleType from dataclasses import dataclass from importlib._bootstrap import _load @@ -20,7 +19,7 @@ from nonebot.log import logger from nonebot.matcher import Matcher from nonebot.permission import Permission from nonebot.typing import T_State, T_StateFactory, T_Handler, T_RuleChecker -from nonebot.rule import Rule, shell_like_command, startswith, endswith, keyword, command, regex +from nonebot.rule import Rule, startswith, endswith, keyword, command, shell_command, ArgumentParser, regex if TYPE_CHECKING: from nonebot.adapters import Bot, Event @@ -437,27 +436,26 @@ def on_command(cmd: Union[str, Tuple[str, ...]], return on_message(command(*commands) & rule, handlers=handlers, **kwargs) -def on_shell_like_command(cmd: Union[str, Tuple[str, ...]], - rule: Optional[Union[Rule, T_RuleChecker]] = None, - aliases: Optional[Set[Union[str, - Tuple[str, ...]]]] = None, - shell_like_argsparser: Optional[ArgumentParser] = None, - **kwargs) -> Type[Matcher]: +def on_shell_command(cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, T_RuleChecker]] = None, + aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, + parser: Optional[ArgumentParser] = None, + **kwargs) -> Type[Matcher]: """ :说明: 注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。 - 与普通的 ``on_command`` 不同的是,在添加 ``shell_like_argsparser`` 参数时, 响应器会自动处理消息, + 与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。 - 并将 ``shell_like_argsparser`` 处理的参数保存在 ``state["args"]`` 中 + 并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中 :参数: * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容 * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名 - * ``shell_like_argsparser:Optional[ArgumentParser]``: ``argparse.ArgumentParser`` 对象,是一个类 ``shell`` 的 ``argsparser`` + * ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象 * ``permission: Optional[Permission]``: 事件响应权限 * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) @@ -484,7 +482,9 @@ def on_shell_like_command(cmd: Union[str, Tuple[str, ...]], handlers.insert(0, _strip_cmd) commands = set([cmd]) | (aliases or set()) - return on_message(shell_like_command(shell_like_argsparser, *commands) & rule, handlers=handlers, **kwargs) + return on_message(shell_command(*commands, parser=parser) & rule, + handlers=handlers, + **kwargs) def on_regex(pattern: str, @@ -564,6 +564,29 @@ class CommandGroup: final_kwargs.update(kwargs) return on_command(cmd, **final_kwargs) + def shell_command(self, cmd: Union[str, Tuple[str, ...]], + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个新的命令。 + + :参数: + + * ``cmd: Union[str, Tuple[str, ...]]``: 命令前缀 + * ``**kwargs``: 其他传递给 ``on_command`` 的参数,将会覆盖命令组默认值 + + :返回: + + - ``Type[Matcher]`` + """ + sub_cmd = (cmd,) if isinstance(cmd, str) else cmd + cmd = self.basecmd + sub_cmd + + final_kwargs = self.base_kwargs.copy() + final_kwargs.update(kwargs) + return on_shell_command(cmd, **final_kwargs) + class MatcherGroup: """事件响应器组合,统一管理。为 ``Matcher`` 创建提供默认属性。""" @@ -851,6 +874,59 @@ class MatcherGroup: handlers=handlers, **kwargs) + def on_shell_command(self, + cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, T_RuleChecker]] = None, + aliases: Optional[Set[Union[str, Tuple[str, + ...]]]] = None, + parser: Optional[ArgumentParser] = None, + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个支持 ``shell_like`` 解析参数的命令消息事件响应器。 + + 与普通的 ``on_command`` 不同的是,在添加 ``parser`` 参数时, 响应器会自动处理消息。 + + 并将用户输入的原始参数列表保存在 ``state["argv"]``, ``parser`` 处理的参数保存在 ``state["args"]`` 中 + + :参数: + + * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名 + * ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 + + :返回: + + - ``Type[Matcher]`` + """ + + async def _strip_cmd(bot: "Bot", event: "Event", state: T_State): + message = event.get_message() + segment = message.pop(0) + new_message = message.__class__( + str(segment) + [len(state["_prefix"]["raw_command"]):].strip()) # type: ignore + for new_segment in reversed(new_message): + message.insert(0, new_segment) + + handlers = kwargs.pop("handlers", []) + handlers.insert(0, _strip_cmd) + + commands = set([cmd]) | (aliases or set()) + return self.on_message(rule=shell_command(*commands, parser=parser) & + rule, + handlers=handlers, + **kwargs) + def on_regex(self, pattern: str, flags: Union[int, re.RegexFlag] = 0, @@ -968,8 +1044,7 @@ def load_plugins(*plugin_dir: str) -> Set[Plugin]: m.module = name plugin = Plugin(name, module, _tmp_matchers.get(), _export.get()) plugins[name] = plugin - logger.opt(colors=True).info( - f'Succeeded to import "{name}"') + logger.opt(colors=True).info(f'Succeeded to import "{name}"') return plugin except Exception as e: logger.opt(colors=True, exception=e).error( diff --git a/nonebot/plugin.pyi b/nonebot/plugin.pyi index 1e8cb810..5fbefa8a 100644 --- a/nonebot/plugin.pyi +++ b/nonebot/plugin.pyi @@ -1,12 +1,11 @@ import re -from argparse import ArgumentParser from types import ModuleType from contextvars import ContextVar from typing import Any, Set, List, Dict, Type, Tuple, Union, Optional -from nonebot.rule import Rule from nonebot.matcher import Matcher from nonebot.permission import Permission +from nonebot.rule import Rule, ArgumentParser from nonebot.typing import T_State, T_StateFactory, T_Handler, T_RuleChecker plugins: Dict[str, "Plugin"] = ... @@ -147,12 +146,11 @@ def on_command(cmd: Union[str, Tuple[str, ...]], ... -def on_shell_like_command(cmd: Union[str, Tuple[str, ...]], - rule: Optional[Union[Rule, T_RuleChecker]] = None, - aliases: Optional[Set[Union[str, - Tuple[str, ...]]]] = None, - shell_like_argsparser: Optional[ArgumentParser] = None, - **kwargs) -> Type[Matcher]: +def on_shell_command(cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, T_RuleChecker]] = None, + aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, + parser: Optional[ArgumentParser] = None, + **kwargs) -> Type[Matcher]: ... @@ -227,6 +225,22 @@ class CommandGroup: state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... + def shell_command( + self, + cmd: Union[str, Tuple[str, ...]], + *, + rule: Optional[Union[Rule, T_RuleChecker]] = ..., + aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., + parser: Optional[ArgumentParser] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: + ... + class MatcherGroup: @@ -361,6 +375,22 @@ class MatcherGroup: state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... + def on_shell_command( + self, + *, + cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, T_RuleChecker]] = ..., + aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., + parser: Optional[ArgumentParser] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: + ... + def on_regex( self, *, diff --git a/nonebot/rule.py b/nonebot/rule.py index 0c0effc4..09a8ff70 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -9,18 +9,19 @@ \:\:\: """ -from argparse import ArgumentParser import re +import shlex import asyncio from itertools import product -from typing import Any, Dict, Union, Tuple, Optional, Callable, NoReturn, Awaitable, TYPE_CHECKING -from loguru import logger +from argparse import Namespace, ArgumentParser as ArgParser +from typing import Any, Dict, Union, Tuple, Optional, Callable, Sequence, NoReturn, Awaitable, TYPE_CHECKING from pygtrie import CharTrie from nonebot import get_driver from nonebot.log import logger from nonebot.utils import run_sync +from nonebot.exception import ParserExit from nonebot.typing import T_State, T_RuleChecker if TYPE_CHECKING: @@ -278,7 +279,28 @@ def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule: return Rule(_command) -def shell_like_command(shell_like_argsparser: Optional[ArgumentParser] = None, *cmds: Union[str, Tuple[str, ...]]) -> Rule: +class ArgumentParser(ArgParser): + + def _print_message(self, message, file=None): + pass + + def exit(self, status=0, message=None): + raise ParserExit(status=status, message=message) + + def parse_args( + self, + args: Optional[Sequence[str]] = None, + namespace: Optional[Namespace] = None + ) -> Union[ParserExit, Namespace]: + try: + return super().parse_args(args=args, + namespace=namespace) # type: ignore + except ParserExit as e: + return e + + +def shell_command(*cmds: Union[str, Tuple[str, ...]], + parser: Optional[ArgumentParser] = None) -> Rule: """ :说明: @@ -286,29 +308,36 @@ def shell_like_command(shell_like_argsparser: Optional[ArgumentParser] = None, * 可以通过 ``state["_prefix"]["command"]`` 获取匹配成功的命令(例:``("test",)``),通过 ``state["_prefix"]["raw_command"]`` 获取匹配成功的原始命令文本(例:``"/test"``)。 - 添加 ``shell_like_argpsarser`` 参数后, 可以自动处理消息并将结果保存在 ``state["args"]`` 中。 - - + 可以通过 ``state["argv"]`` 获取用户输入的原始参数列表 + 添加 ``parser`` 参数后, 可以自动处理消息并将结果保存在 ``state["args"]`` 中。 :参数: - * ``shell_like_argsparser: Optional[ArgumentParser]``: ``argparse.ArgumentParser`` 对象, 是一个类 ``shell`` 的 ``argsparser`` * ``*cmds: Union[str, Tuple[str, ...]]``: 命令内容 + * ``parser: Optional[ArgumentParser]``: ``nonebot.rule.ArgumentParser`` 对象 :示例: - 使用默认 ``command_start``, ``command_sep`` 配置 + 使用默认 ``command_start``, ``command_sep`` 配置,更多示例参考 ``argparse`` 标准库文档。 - 命令 ``("test",)`` 可以匹配:``/test`` 开头的消息 - 命令 ``("test", "sub")`` 可以匹配”``/test.sub`` 开头的消息 - - 当 ``shell_like_argsparser`` 的 ``argument`` 为 ``-a`` 时且 ``action`` 为 ``store_true`` , ``state["args"]["a"]`` 将会记录 ``True`` + .. code-block:: python + + from nonebot.rule import ArgumentParser + + parser = ArgumentParser() + parser.add_argument("-a", type=bool) + + rule = shell_command("ls", parser=parser) \:\:\:tip 提示 命令内容与后续消息间无需空格! \:\:\: """ + if not isinstance(parser, ArgumentParser): + raise TypeError( + "`parser` must be an instance of nonebot.rule.ArgumentParser") + config = get_driver().config command_start = config.command_start command_sep = config.command_sep @@ -324,24 +353,21 @@ def shell_like_command(shell_like_argsparser: Optional[ArgumentParser] = None, * for start, sep in product(command_start, command_sep): TrieRule.add_prefix(f"{start}{sep.join(command)}", command) - async def _shell_like_command(bot: "Bot", event: "Event", state: T_State) -> bool: + async def _shell_command(bot: "Bot", event: "Event", + state: T_State) -> bool: if state["_prefix"]["command"] in commands: - if shell_like_argsparser: - message = str(event.get_message()) - strip_message = message[len( - state["_prefix"]["raw_command"]):].lstrip() - try: - args = shell_like_argsparser.parse_args( - strip_message.split()) - state["args"]=dict() - state["args"].update(**args.__dict__) - except: - pass + message = str(event.get_message()) + strip_message = message[len(state["_prefix"]["raw_command"] + ):].lstrip() + state["argv"] = shlex.split(strip_message) + if parser: + args = parser.parse_args(state["argv"]) + state["args"] = args return True else: return False - return Rule(_shell_like_command) + return Rule(_shell_command) def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: @@ -372,7 +398,6 @@ def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: state["_matched"] = matched.group() return True else: - state["_matched"] = None return False return Rule(_regex) diff --git a/tests/test_plugins/test_shell.py b/tests/test_plugins/test_shell.py new file mode 100644 index 00000000..5afebd6d --- /dev/null +++ b/tests/test_plugins/test_shell.py @@ -0,0 +1,15 @@ +from nonebot.adapters import Bot +from nonebot.typing import T_State +from nonebot import on_shell_command +from nonebot.rule import to_me, ArgumentParser + +parser = ArgumentParser() +parser.add_argument("-a", type=bool) + +shell = on_shell_command("ls", to_me(), parser=parser) + + +@shell.handle() +async def _(bot: Bot, state: T_State): + print(state["argv"]) + print(state["args"]) From 88bbb57c66580d63fadca7ee515268b525a26e53 Mon Sep 17 00:00:00 2001 From: AkiraXie Date: Tue, 2 Feb 2021 04:06:57 +0000 Subject: [PATCH 78/86] :memo: update api docs --- docs/api/exception.md | 21 ++++++++++ docs/api/plugin.md | 91 +++++++++++++++++++++++++++++++++++++++++-- docs/api/rule.md | 24 +++++++----- 3 files changed, 123 insertions(+), 13 deletions(-) diff --git a/docs/api/exception.md b/docs/api/exception.md index ac2d28b2..817c02a9 100644 --- a/docs/api/exception.md +++ b/docs/api/exception.md @@ -40,6 +40,27 @@ sidebarDepth: 0 +## _exception_ `ParserExit` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + `shell command` 处理消息失败时返回的异常 + + + +* **参数** + + + * `status` + + + * `message` + + + ## _exception_ `PausedException` 基类:`nonebot.exception.NoneBotException` diff --git a/docs/api/plugin.md b/docs/api/plugin.md index 24bfb5ab..960521da 100644 --- a/docs/api/plugin.md +++ b/docs/api/plugin.md @@ -507,16 +507,16 @@ def something_else(): -## `on_shell_like_command(cmd, rule=None, aliases=None, shell_like_argsparser=None, **kwargs)` +## `on_shell_command(cmd, rule=None, aliases=None, parser=None, **kwargs)` * **说明** 注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 - 与普通的 `on_command` 不同的是,在添加 `shell_like_argsparser` 参数时, 响应器会自动处理消息, + 与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。 - 并将 `shell_like_argsparser` 处理的参数保存在 `state["args"]` 中 + 并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]` 中 @@ -532,7 +532,7 @@ def something_else(): * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 - * `shell_like_argsparser:Optional[ArgumentParser]`: `argparse.ArgumentParser` 对象,是一个类 `shell` 的 `argsparser` + * `parser: Optional[ArgumentParser]`: `nonebot.rule.ArgumentParser` 对象 * `permission: Optional[Permission]`: 事件响应权限 @@ -680,6 +680,32 @@ def something_else(): +### `shell_command(cmd, **kwargs)` + + +* **说明** + + 注册一个新的命令。 + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 + + + * `**kwargs`: 其他传递给 `on_command` 的参数,将会覆盖命令组默认值 + + + +* **返回** + + + * `Type[Matcher]` + + + ## _class_ `MatcherGroup` 基类:`object` @@ -1127,6 +1153,63 @@ def something_else(): +### `on_shell_command(cmd, rule=None, aliases=None, parser=None, **kwargs)` + + +* **说明** + + +注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 + +与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。 + +并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]` 中 + + +* **参数** + + + +* `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + +* `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + +* `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + +* `parser: Optional[ArgumentParser]`: `nonebot.rule.ArgumentParser` 对象 + + +* `permission: Optional[Permission]`: 事件响应权限 + + +* `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + +* `temp: bool`: 是否为临时事件响应器(仅执行一次) + + +* `priority: int`: 事件响应器优先级 + + +* `block: bool`: 是否阻止事件向更低优先级传递 + + +* `state: Optional[T_State]`: 默认 state + + +* `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + +* **返回** + + + +* `Type[Matcher]` + + ### `on_regex(pattern, flags=0, rule=None, **kwargs)` diff --git a/docs/api/rule.md b/docs/api/rule.md index e9a8ce4d..b569a400 100644 --- a/docs/api/rule.md +++ b/docs/api/rule.md @@ -170,7 +170,7 @@ Rule(async_function, run_sync(sync_function)) ::: -## `shell_like_command(shell_like_argsparser=None, *cmds)` +## `shell_command(*cmds, parser=None)` * **说明** @@ -179,29 +179,35 @@ Rule(async_function, run_sync(sync_function)) 可以通过 `state["_prefix"]["command"]` 获取匹配成功的命令(例:`("test",)`),通过 `state["_prefix"]["raw_command"]` 获取匹配成功的原始命令文本(例:`"/test"`)。 - 添加 `shell_like_argpsarser` 参数后, 可以自动处理消息并将结果保存在 `state["args"]` 中。 + 可以通过 `state["argv"]` 获取用户输入的原始参数列表 + + 添加 `parser` 参数后, 可以自动处理消息并将结果保存在 `state["args"]` 中。 * **参数** - * `shell_like_argsparser: Optional[ArgumentParser]`: `argparse.ArgumentParser` 对象, 是一个类 `shell` 的 `argsparser` - - * `*cmds: Union[str, Tuple[str, ...]]`: 命令内容 + * `parser: Optional[ArgumentParser]`: `nonebot.rule.ArgumentParser` 对象 + + * **示例** - 使用默认 `command_start`, `command_sep` 配置 + 使用默认 `command_start`, `command_sep` 配置,更多示例参考 `argparse` 标准库文档。 - 命令 `("test",)` 可以匹配:`/test` 开头的消息 - 命令 `("test", "sub")` 可以匹配”`/test.sub` 开头的消息 - 当 `shell_like_argsparser` 的 `argument` 为 `-a` 时且 `action` 为 `store_true` , `state["args"]["a"]` 将会记录 `True` +```python +from nonebot.rule import ArgumentParser +parser = ArgumentParser() +parser.add_argument("-a", type=bool) + +rule = shell_command("ls", parser=parser) +``` :::tip 提示 命令内容与后续消息间无需空格! From a54fd2f23582090a5043ba87537e70a263231b24 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 12:15:20 +0800 Subject: [PATCH 79/86] :bulb: update docstring --- nonebot/__init__.py | 1 + nonebot/rule.py | 27 +++++++++++++++------------ 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/nonebot/__init__.py b/nonebot/__init__.py index 9f9a0c37..db0d8277 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -12,6 +12,7 @@ - ``on_endswith`` => ``nonebot.plugin.on_endswith`` - ``on_keyword`` => ``nonebot.plugin.on_keyword`` - ``on_command`` => ``nonebot.plugin.on_command`` +- ``on_shell_command`` => ``nonebot.plugin.on_shell_command`` - ``on_regex`` => ``nonebot.plugin.on_regex`` - ``CommandGroup`` => ``nonebot.plugin.CommandGroup`` - ``Matchergroup`` => ``nonebot.plugin.MatcherGroup`` diff --git a/nonebot/rule.py b/nonebot/rule.py index ca0aa6db..eb00de57 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -280,6 +280,11 @@ def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule: class ArgumentParser(ArgParser): + """ + :说明: + + ``shell_like`` 命令参数解析器,解析出错时不会退出程序。 + """ def _print_message(self, message, file=None): pass @@ -287,16 +292,11 @@ class ArgumentParser(ArgParser): def exit(self, status=0, message=None): raise ParserExit(status=status, message=message) - def parse_args( - self, - args: Optional[Sequence[str]] = None, - namespace: Optional[Namespace] = None - ) -> Union[ParserExit, Namespace]: - try: - return super().parse_args(args=args, - namespace=namespace) # type: ignore - except ParserExit as e: - return e + def parse_args(self, + args: Optional[Sequence[str]] = None, + namespace: Optional[Namespace] = None) -> Namespace: + return super().parse_args(args=args, + namespace=namespace) # type: ignore def shell_command(*cmds: Union[str, Tuple[str, ...]], @@ -361,8 +361,11 @@ def shell_command(*cmds: Union[str, Tuple[str, ...]], ):].lstrip() state["argv"] = shlex.split(strip_message) if parser: - args = parser.parse_args(state["argv"]) - state["args"] = args + try: + args = parser.parse_args(state["argv"]) + state["args"] = args + except ParserExit as e: + state["args"] = e return True else: return False From 223b9bc887b8bd0239ac7ac2a7edab90bc573b95 Mon Sep 17 00:00:00 2001 From: AkiraXie Date: Tue, 2 Feb 2021 04:16:37 +0000 Subject: [PATCH 80/86] :memo: update api docs --- docs/api/nonebot.md | 3 +++ docs/api/rule.md | 11 +++++++++++ 2 files changed, 14 insertions(+) diff --git a/docs/api/nonebot.md b/docs/api/nonebot.md index d2ef4eb4..58f7fbda 100644 --- a/docs/api/nonebot.md +++ b/docs/api/nonebot.md @@ -34,6 +34,9 @@ sidebarDepth: 0 * `on_command` => `nonebot.plugin.on_command` +* `on_shell_command` => `nonebot.plugin.on_shell_command` + + * `on_regex` => `nonebot.plugin.on_regex` diff --git a/docs/api/rule.md b/docs/api/rule.md index b569a400..25a9fe13 100644 --- a/docs/api/rule.md +++ b/docs/api/rule.md @@ -170,6 +170,17 @@ Rule(async_function, run_sync(sync_function)) ::: +## _class_ `ArgumentParser` + +基类:`argparse.ArgumentParser` + + +* **说明** + + `shell_like` 命令参数解析器,解析出错时不会退出程序。 + + + ## `shell_command(*cmds, parser=None)` From 98b67ad8292221c1623d94e94abb91dc3b0ee41b Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 12:39:23 +0800 Subject: [PATCH 81/86] :memo: update docstring --- docs/api/rule.md | 2 +- nonebot/exception.py | 6 ++++++ nonebot/rule.py | 2 +- tests/test_plugins/test_shell.py | 2 +- 4 files changed, 9 insertions(+), 3 deletions(-) diff --git a/docs/api/rule.md b/docs/api/rule.md index 25a9fe13..5c3dfbed 100644 --- a/docs/api/rule.md +++ b/docs/api/rule.md @@ -215,7 +215,7 @@ Rule(async_function, run_sync(sync_function)) from nonebot.rule import ArgumentParser parser = ArgumentParser() -parser.add_argument("-a", type=bool) +parser.add_argument("-a", action="store_true") rule = shell_command("ls", parser=parser) ``` diff --git a/nonebot/exception.py b/nonebot/exception.py index b8a42aa4..7eaab701 100644 --- a/nonebot/exception.py +++ b/nonebot/exception.py @@ -53,6 +53,12 @@ class ParserExit(NoneBotException): self.status = status self.message = message + def __repr__(self): + return f"" + + def __str__(self): + return self.__repr__() + class PausedException(NoneBotException): """ diff --git a/nonebot/rule.py b/nonebot/rule.py index eb00de57..d9f75a24 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -326,7 +326,7 @@ def shell_command(*cmds: Union[str, Tuple[str, ...]], from nonebot.rule import ArgumentParser parser = ArgumentParser() - parser.add_argument("-a", type=bool) + parser.add_argument("-a", action="store_true") rule = shell_command("ls", parser=parser) diff --git a/tests/test_plugins/test_shell.py b/tests/test_plugins/test_shell.py index 5afebd6d..63719b42 100644 --- a/tests/test_plugins/test_shell.py +++ b/tests/test_plugins/test_shell.py @@ -4,7 +4,7 @@ from nonebot import on_shell_command from nonebot.rule import to_me, ArgumentParser parser = ArgumentParser() -parser.add_argument("-a", type=bool) +parser.add_argument("-a", action="store_true") shell = on_shell_command("ls", to_me(), parser=parser) From d913be5c0df0aa45439a288941ad979f5cd4e020 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 12:48:16 +0800 Subject: [PATCH 82/86] :bug: fix matcher --- nonebot/matcher.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/nonebot/matcher.py b/nonebot/matcher.py index b82164e0..0fda9f3d 100644 --- a/nonebot/matcher.py +++ b/nonebot/matcher.py @@ -167,8 +167,9 @@ class Matcher(metaclass=MatcherMeta): rule or Rule(), "permission": permission or Permission(), - "handlers": - handlers or [], + "handlers": [ + cls.process_handler(handler) for handler in handlers + ] if handlers else [], "temp": temp, "expire_time": @@ -204,7 +205,9 @@ class Matcher(metaclass=MatcherMeta): - ``bool``: 是否满足权限 """ - return await cls.permission(bot, event) + event_type = event.get_type() + return (event_type == (cls.type or event_type) and + await cls.permission(bot, event)) @classmethod async def check_rule(cls, bot: "Bot", event: "Event", From 7555051df652fcb2f5c29dde32636f0cfbd06d65 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 13:09:20 +0800 Subject: [PATCH 83/86] :bookmark: Pre Release 2.0.0a9 --- poetry.lock | 264 +++++-------------------------------------------- pyproject.toml | 14 +-- 2 files changed, 31 insertions(+), 247 deletions(-) diff --git a/poetry.lock b/poetry.lock index 9523412b..b89548a3 100644 --- a/poetry.lock +++ b/poetry.lock @@ -6,11 +6,6 @@ category = "dev" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "babel" version = "2.9.0" @@ -22,11 +17,6 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [package.dependencies] pytz = ">=2015.7" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "certifi" version = "2020.12.5" @@ -35,11 +25,6 @@ category = "main" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "chardet" version = "4.0.0" @@ -48,11 +33,6 @@ category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "click" version = "7.1.2" @@ -61,11 +41,6 @@ category = "main" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "colorama" version = "0.4.4" @@ -74,11 +49,6 @@ category = "main" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "docutils" version = "0.16" @@ -87,11 +57,6 @@ category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "fastapi" version = "0.63.0" @@ -110,11 +75,6 @@ dev = ["python-jose[cryptography] (>=3.1.0,<4.0.0)", "passlib[bcrypt] (>=1.7.2,< doc = ["mkdocs (>=1.1.2,<2.0.0)", "mkdocs-material (>=6.1.4,<7.0.0)", "markdown-include (>=0.5.1,<0.6.0)", "mkdocs-markdownextradata-plugin (>=0.1.7,<0.2.0)", "typer-cli (>=0.0.9,<0.0.10)", "pyyaml (>=5.3.1,<6.0.0)"] test = ["pytest (==5.4.3)", "pytest-cov (==2.10.0)", "pytest-asyncio (>=0.14.0,<0.15.0)", "mypy (==0.790)", "flake8 (>=3.8.3,<4.0.0)", "black (==20.8b1)", "isort (>=5.0.6,<6.0.0)", "requests (>=2.24.0,<3.0.0)", "httpx (>=0.14.0,<0.15.0)", "email_validator (>=1.1.1,<2.0.0)", "sqlalchemy (>=1.3.18,<2.0.0)", "peewee (>=3.13.3,<4.0.0)", "databases[sqlite] (>=0.3.2,<0.4.0)", "orjson (>=3.2.1,<4.0.0)", "async_exit_stack (>=1.0.1,<2.0.0)", "async_generator (>=1.10,<2.0.0)", "python-multipart (>=0.0.5,<0.0.6)", "aiofiles (>=0.5.0,<0.6.0)", "flask (>=1.1.2,<2.0.0)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "h11" version = "0.9.0" @@ -123,11 +83,6 @@ category = "main" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "html2text" version = "2020.1.16" @@ -136,11 +91,6 @@ category = "dev" optional = false python-versions = ">=3.5" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "httpcore" version = "0.12.3" @@ -156,11 +106,6 @@ sniffio = ">=1.0.0,<2.0.0" [package.extras] http2 = ["h2 (>=3,<5)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "httptools" version = "0.1.1" @@ -172,11 +117,6 @@ python-versions = "*" [package.extras] test = ["Cython (==0.29.14)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "httpx" version = "0.16.1" @@ -195,11 +135,6 @@ sniffio = "*" brotli = ["brotlipy (>=0.7.0,<0.8.0)"] http2 = ["h2 (>=3.0.0,<4.0.0)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "idna" version = "2.10" @@ -208,11 +143,6 @@ category = "main" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "imagesize" version = "1.2.0" @@ -221,11 +151,6 @@ category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "jinja2" version = "2.11.3" @@ -240,11 +165,6 @@ MarkupSafe = ">=0.23" [package.extras] i18n = ["Babel (>=0.8)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "loguru" version = "0.5.3" @@ -260,11 +180,6 @@ win32-setctime = {version = ">=1.0.0", markers = "sys_platform == \"win32\""} [package.extras] dev = ["codecov (>=2.0.15)", "colorama (>=0.3.4)", "flake8 (>=3.7.7)", "tox (>=3.9.0)", "tox-travis (>=0.12)", "pytest (>=4.6.2)", "pytest-cov (>=2.7.1)", "Sphinx (>=2.2.1)", "sphinx-autobuild (>=0.7.1)", "sphinx-rtd-theme (>=0.4.3)", "black (>=19.10b0)", "isort (>=5.1.1)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "markupsafe" version = "1.1.1" @@ -273,11 +188,6 @@ category = "dev" optional = false python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "packaging" version = "20.9" @@ -289,11 +199,6 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [package.dependencies] pyparsing = ">=2.0.2" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pydantic" version = "1.7.3" @@ -311,11 +216,6 @@ dotenv = ["python-dotenv (>=0.10.4)"] email = ["email-validator (>=1.0.3)"] typing_extensions = ["typing-extensions (>=3.7.2)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pydash" version = "4.9.2" @@ -327,11 +227,6 @@ python-versions = "*" [package.extras] dev = ["coverage", "docformatter", "flake8", "invoke", "mock", "pylint", "pytest", "pytest-cov", "pytest-flake8", "pytest-pylint", "sphinx", "sphinx-rtd-theme", "tox", "twine", "wheel", "black", "flake8-black", "flake8-bugbear", "flake8-isort", "isort"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pygments" version = "2.7.4" @@ -340,11 +235,6 @@ category = "dev" optional = false python-versions = ">=3.5" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pygtrie" version = "2.4.2" @@ -353,11 +243,6 @@ category = "main" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pyparsing" version = "2.4.7" @@ -366,11 +251,6 @@ category = "dev" optional = false python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "python-dotenv" version = "0.15.0" @@ -382,24 +262,14 @@ python-versions = "*" [package.extras] cli = ["click (>=5.0)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pytz" -version = "2020.5" +version = "2021.1" description = "World timezone definitions, modern and historical" category = "dev" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "requests" version = "2.25.1" @@ -418,11 +288,6 @@ urllib3 = ">=1.21.1,<1.27" security = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)"] socks = ["PySocks (>=1.5.6,!=1.5.7)", "win-inet-pton"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "rfc3986" version = "1.4.0" @@ -437,11 +302,6 @@ idna = {version = "*", optional = true, markers = "extra == \"idna2008\""} [package.extras] idna2008 = ["idna"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sniffio" version = "1.2.0" @@ -450,11 +310,6 @@ category = "main" optional = false python-versions = ">=3.5" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "snowballstemmer" version = "2.1.0" @@ -463,11 +318,6 @@ category = "dev" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sphinx" version = "3.4.3" @@ -499,11 +349,6 @@ docs = ["sphinxcontrib-websupport"] lint = ["flake8 (>=3.5.0)", "isort", "mypy (>=0.790)", "docutils-stubs"] test = ["pytest", "pytest-cov", "html5lib", "cython", "typed-ast"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sphinx-markdown-builder" version = "0.5.4" @@ -538,11 +383,6 @@ python-versions = ">=3.5" lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sphinxcontrib-devhelp" version = "1.0.2" @@ -555,11 +395,6 @@ python-versions = ">=3.5" lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sphinxcontrib-htmlhelp" version = "1.0.3" @@ -572,11 +407,6 @@ python-versions = ">=3.5" lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest", "html5lib"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sphinxcontrib-jsmath" version = "1.0.1" @@ -588,11 +418,6 @@ python-versions = ">=3.5" [package.extras] test = ["pytest", "flake8", "mypy"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sphinxcontrib-qthelp" version = "1.0.3" @@ -605,11 +430,6 @@ python-versions = ">=3.5" lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sphinxcontrib-serializinghtml" version = "1.1.4" @@ -622,11 +442,6 @@ python-versions = ">=3.5" lint = ["flake8", "mypy", "docutils-stubs"] test = ["pytest"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "starlette" version = "0.13.6" @@ -638,11 +453,6 @@ python-versions = ">=3.6" [package.extras] full = ["aiofiles", "graphene", "itsdangerous", "jinja2", "python-multipart", "pyyaml", "requests", "ujson"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "typing-extensions" version = "3.7.4.3" @@ -651,11 +461,6 @@ category = "main" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "unify" version = "0.5" @@ -667,11 +472,6 @@ python-versions = "*" [package.dependencies] untokenize = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "untokenize" version = "0.1.1" @@ -680,11 +480,6 @@ category = "dev" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "urllib3" version = "1.26.3" @@ -698,11 +493,6 @@ brotli = ["brotlipy (>=0.6.0)"] secure = ["pyOpenSSL (>=0.14)", "cryptography (>=1.3.4)", "idna (>=2.0.0)", "certifi", "ipaddress"] socks = ["PySocks (>=1.5.6,!=1.5.7,<2.0)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "uvicorn" version = "0.11.8" @@ -721,11 +511,6 @@ websockets = ">=8.0.0,<9.0.0" [package.extras] watchgodreload = ["watchgod (>=0.6,<0.7)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "uvloop" version = "0.14.0" @@ -734,11 +519,6 @@ category = "main" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "websockets" version = "8.1" @@ -747,11 +527,6 @@ category = "main" optional = false python-versions = ">=3.6.1" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "win32-setctime" version = "1.0.3" @@ -763,11 +538,6 @@ python-versions = ">=3.5" [package.extras] dev = ["pytest (>=4.6.2)", "black (>=19.3b0)"] -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "yapf" version = "0.30.0" @@ -776,15 +546,10 @@ category = "dev" optional = false python-versions = "*" -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "0038c5b3aa4a382184c1ef5b37a668ce37d8246c8fdf18deb71dccc8bf97be62" +content-hash = "9aa4fde8078788e6a12866ba4eb5d17ec6237355c663d6ea74040b6e165cdcf1" [metadata.files] alabaster = [ @@ -884,20 +649,39 @@ markupsafe = [ {file = "MarkupSafe-1.1.1-cp35-cp35m-win32.whl", hash = "sha256:6dd73240d2af64df90aa7c4e7481e23825ea70af4b4922f8ede5b9e35f78a3b1"}, {file = "MarkupSafe-1.1.1-cp35-cp35m-win_amd64.whl", hash = "sha256:9add70b36c5666a2ed02b43b335fe19002ee5235efd4b8a89bfcf9005bebac0d"}, {file = "MarkupSafe-1.1.1-cp36-cp36m-macosx_10_6_intel.whl", hash = "sha256:24982cc2533820871eba85ba648cd53d8623687ff11cbb805be4ff7b4c971aff"}, + {file = "MarkupSafe-1.1.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:d53bc011414228441014aa71dbec320c66468c1030aae3a6e29778a3382d96e5"}, {file = "MarkupSafe-1.1.1-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:00bc623926325b26bb9605ae9eae8a215691f33cae5df11ca5424f06f2d1f473"}, {file = "MarkupSafe-1.1.1-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:717ba8fe3ae9cc0006d7c451f0bb265ee07739daf76355d06366154ee68d221e"}, + {file = "MarkupSafe-1.1.1-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:3b8a6499709d29c2e2399569d96719a1b21dcd94410a586a18526b143ec8470f"}, + {file = "MarkupSafe-1.1.1-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:84dee80c15f1b560d55bcfe6d47b27d070b4681c699c572af2e3c7cc90a3b8e0"}, + {file = "MarkupSafe-1.1.1-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:b1dba4527182c95a0db8b6060cc98ac49b9e2f5e64320e2b56e47cb2831978c7"}, {file = "MarkupSafe-1.1.1-cp36-cp36m-win32.whl", hash = "sha256:535f6fc4d397c1563d08b88e485c3496cf5784e927af890fb3c3aac7f933ec66"}, {file = "MarkupSafe-1.1.1-cp36-cp36m-win_amd64.whl", hash = "sha256:b1282f8c00509d99fef04d8ba936b156d419be841854fe901d8ae224c59f0be5"}, {file = "MarkupSafe-1.1.1-cp37-cp37m-macosx_10_6_intel.whl", hash = "sha256:8defac2f2ccd6805ebf65f5eeb132adcf2ab57aa11fdf4c0dd5169a004710e7d"}, + {file = "MarkupSafe-1.1.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:bf5aa3cbcfdf57fa2ee9cd1822c862ef23037f5c832ad09cfea57fa846dec193"}, {file = "MarkupSafe-1.1.1-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:46c99d2de99945ec5cb54f23c8cd5689f6d7177305ebff350a58ce5f8de1669e"}, {file = "MarkupSafe-1.1.1-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:ba59edeaa2fc6114428f1637ffff42da1e311e29382d81b339c1817d37ec93c6"}, + {file = "MarkupSafe-1.1.1-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:6fffc775d90dcc9aed1b89219549b329a9250d918fd0b8fa8d93d154918422e1"}, + {file = "MarkupSafe-1.1.1-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:a6a744282b7718a2a62d2ed9d993cad6f5f585605ad352c11de459f4108df0a1"}, + {file = "MarkupSafe-1.1.1-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:195d7d2c4fbb0ee8139a6cf67194f3973a6b3042d742ebe0a9ed36d8b6f0c07f"}, {file = "MarkupSafe-1.1.1-cp37-cp37m-win32.whl", hash = "sha256:b00c1de48212e4cc9603895652c5c410df699856a2853135b3967591e4beebc2"}, {file = "MarkupSafe-1.1.1-cp37-cp37m-win_amd64.whl", hash = "sha256:9bf40443012702a1d2070043cb6291650a0841ece432556f784f004937f0f32c"}, {file = "MarkupSafe-1.1.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:6788b695d50a51edb699cb55e35487e430fa21f1ed838122d722e0ff0ac5ba15"}, {file = "MarkupSafe-1.1.1-cp38-cp38-manylinux1_i686.whl", hash = "sha256:cdb132fc825c38e1aeec2c8aa9338310d29d337bebbd7baa06889d09a60a1fa2"}, {file = "MarkupSafe-1.1.1-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:13d3144e1e340870b25e7b10b98d779608c02016d5184cfb9927a9f10c689f42"}, + {file = "MarkupSafe-1.1.1-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:acf08ac40292838b3cbbb06cfe9b2cb9ec78fce8baca31ddb87aaac2e2dc3bc2"}, + {file = "MarkupSafe-1.1.1-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:d9be0ba6c527163cbed5e0857c451fcd092ce83947944d6c14bc95441203f032"}, + {file = "MarkupSafe-1.1.1-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:caabedc8323f1e93231b52fc32bdcde6db817623d33e100708d9a68e1f53b26b"}, {file = "MarkupSafe-1.1.1-cp38-cp38-win32.whl", hash = "sha256:596510de112c685489095da617b5bcbbac7dd6384aeebeda4df6025d0256a81b"}, {file = "MarkupSafe-1.1.1-cp38-cp38-win_amd64.whl", hash = "sha256:e8313f01ba26fbbe36c7be1966a7b7424942f670f38e666995b88d012765b9be"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:d73a845f227b0bfe8a7455ee623525ee656a9e2e749e4742706d80a6065d5e2c"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-manylinux1_i686.whl", hash = "sha256:98bae9582248d6cf62321dcb52aaf5d9adf0bad3b40582925ef7c7f0ed85fceb"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:2beec1e0de6924ea551859edb9e7679da6e4870d32cb766240ce17e0a0ba2014"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:7fed13866cf14bba33e7176717346713881f56d9d2bcebab207f7a036f41b850"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:6f1e273a344928347c1290119b493a1f0303c52f5a5eae5f16d74f48c15d4a85"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:feb7b34d6325451ef96bc0e36e1a6c0c1c64bc1fbec4b854f4529e51887b1621"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-win32.whl", hash = "sha256:22c178a091fc6630d0d045bdb5992d2dfe14e3259760e713c490da5323866c39"}, + {file = "MarkupSafe-1.1.1-cp39-cp39-win_amd64.whl", hash = "sha256:b7d644ddb4dbd407d31ffb699f1d140bc35478da613b441c582aeb7c43838dd8"}, {file = "MarkupSafe-1.1.1.tar.gz", hash = "sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b"}, ] packaging = [ @@ -948,8 +732,8 @@ python-dotenv = [ {file = "python_dotenv-0.15.0-py2.py3-none-any.whl", hash = "sha256:0c8d1b80d1a1e91717ea7d526178e3882732420b03f08afea0406db6402e220e"}, ] pytz = [ - {file = "pytz-2020.5-py2.py3-none-any.whl", hash = "sha256:16962c5fb8db4a8f63a26646d8886e9d769b6c511543557bc84e9569fb9a9cb4"}, - {file = "pytz-2020.5.tar.gz", hash = "sha256:180befebb1927b16f6b57101720075a984c019ac16b1b7575673bea42c6c3da5"}, + {file = "pytz-2021.1-py2.py3-none-any.whl", hash = "sha256:eb10ce3e7736052ed3623d49975ce333bcd712c7bb19a58b9e2089d4057d0798"}, + {file = "pytz-2021.1.tar.gz", hash = "sha256:83a4a90894bf38e243cf052c8b58f381bfe9a7a483f6a9cab140bc7f702ac4da"}, ] requests = [ {file = "requests-2.25.1-py2.py3-none-any.whl", hash = "sha256:c210084e36a42ae6b9219e00e48287def368a26d03a048ddad7bfee44f75871e"}, @@ -1009,7 +793,7 @@ unify = [ {file = "unify-0.5.tar.gz", hash = "sha256:8ddce812b2457212b7598fe574c9e6eb3ad69710f445391338270c7f8a71723c"}, ] untokenize = [ - {file = "untokenize-0.1.1.tar.gz", hash = "md5:50d325dff09208c624cc603fad33bb0d"}, + {file = "untokenize-0.1.1.tar.gz", hash = "sha256:3865dbbbb8efb4bb5eaa72f1be7f3e0be00ea8b7f125c69cbd1f5fda926f37a2"}, ] urllib3 = [ {file = "urllib3-1.26.3-py2.py3-none-any.whl", hash = "sha256:1b465e494e3e0d8939b50680403e3aedaa2bc434b7d5af64dfd3c958d7f5ae80"}, diff --git a/pyproject.toml b/pyproject.toml index 39854210..55646c66 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "nonebot2" -version = "2.0.0-alpha.8.post2" +version = "2.0.0-alpha.9" description = "An asynchronous python bot framework." authors = ["yanyongyu "] license = "MIT" @@ -37,11 +37,11 @@ yapf = "^0.30.0" sphinx = "^3.4.1" sphinx-markdown-builder = { git = "https://github.com/nonebot/sphinx-markdown-builder.git" } -[[tool.poetry.source]] -name = "aliyun" -url = "https://mirrors.aliyun.com/pypi/simple/" -default = true +# [[tool.poetry.source]] +# name = "aliyun" +# url = "https://mirrors.aliyun.com/pypi/simple/" +# default = true [build-system] -requires = ["poetry>=0.12"] -build-backend = "poetry.masonry.api" +requires = ["poetry_core>=1.0.0"] +build-backend = "poetry.core.masonry.api" From 8e0572d5d3ebd1edf842bb4e8da2286ba8d1a650 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 13:13:27 +0800 Subject: [PATCH 84/86] :memo: update changelog --- pages/changelog.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/pages/changelog.md b/pages/changelog.md index 3c237913..dac7d888 100644 --- a/pages/changelog.md +++ b/pages/changelog.md @@ -10,6 +10,9 @@ sidebar: auto - 修复 `Message.extract_plain_text` 返回为转义字符串的问题 - 修复命令处理错误地删除了后续空格 - 增加好友添加和加群请求事件 `approve`, `reject` 方法 +- 新增 `mirai-api-http` 协议适配 +- 修复 rule 运行时 state 覆盖问题,隔离 state +- 新增 `shell like command` 支持 ## v2.0.0a8 From e809c7c500b7d129c384ea4e60cdf382c29a22bd Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 13:17:29 +0800 Subject: [PATCH 85/86] :memo: update readme --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 1bb43a02..07724b1a 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,9 @@ _✨ Python 异步机器人框架 ✨_ cqhttp + + + ding @@ -71,6 +74,7 @@ NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义 目前 NoneBot2 内置的协议适配: - [OneBot(CQHTTP) 协议](https://github.com/howmanybots/onebot/blob/master/README.md) (QQ 等) +- [Mirai-API-HTTP 协议](https://github.com/project-mirai/mirai-api-http) - [钉钉](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) _开发中_ - [Telegram](https://core.telegram.org/bots/api) _计划中_ From 461b65700f2b6fe320c38d5fff422a91e75e736f Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Tue, 2 Feb 2021 14:36:51 +0800 Subject: [PATCH 86/86] :memo: archive doc --- archive/2.0.0a9/README.md | 15 + archive/2.0.0a9/advanced/README.md | 7 + .../2.0.0a9/advanced/export-and-require.md | 1 + .../2.0.0a9/advanced/overloaded-handlers.md | 1 + archive/2.0.0a9/advanced/permission.md | 1 + archive/2.0.0a9/advanced/publish-plugin.md | 1 + archive/2.0.0a9/advanced/runtime-hook.md | 1 + archive/2.0.0a9/advanced/scheduler.md | 127 ++ archive/2.0.0a9/api/README.md | 55 + archive/2.0.0a9/api/adapters/README.md | 426 ++++ archive/2.0.0a9/api/adapters/cqhttp.md | 564 +++++ archive/2.0.0a9/api/adapters/ding.md | 308 +++ archive/2.0.0a9/api/adapters/mirai.md | 1908 +++++++++++++++++ archive/2.0.0a9/api/config.md | 285 +++ archive/2.0.0a9/api/drivers/README.md | 318 +++ archive/2.0.0a9/api/drivers/fastapi.md | 68 + archive/2.0.0a9/api/exception.md | 214 ++ archive/2.0.0a9/api/log.md | 42 + archive/2.0.0a9/api/matcher.md | 470 ++++ archive/2.0.0a9/api/message.md | 143 ++ archive/2.0.0a9/api/nonebot.md | 269 +++ archive/2.0.0a9/api/permission.md | 63 + archive/2.0.0a9/api/plugin.md | 1401 ++++++++++++ archive/2.0.0a9/api/rule.md | 266 +++ archive/2.0.0a9/api/typing.md | 214 ++ archive/2.0.0a9/api/utils.md | 84 + archive/2.0.0a9/guide/README.md | 33 + archive/2.0.0a9/guide/basic-configuration.md | 86 + archive/2.0.0a9/guide/cqhttp-guide.md | 101 + archive/2.0.0a9/guide/creating-a-handler.md | 197 ++ archive/2.0.0a9/guide/creating-a-matcher.md | 146 ++ archive/2.0.0a9/guide/creating-a-plugin.md | 119 + archive/2.0.0a9/guide/creating-a-project.md | 51 + archive/2.0.0a9/guide/ding-guide.md | 119 + archive/2.0.0a9/guide/end-or-start.md | 9 + archive/2.0.0a9/guide/getting-started.md | 87 + archive/2.0.0a9/guide/installation.md | 97 + archive/2.0.0a9/guide/loading-a-plugin.md | 116 + archive/2.0.0a9/guide/mirai-guide.md | 195 ++ archive/2.0.0a9/sidebar.config.json | 176 ++ docs/.vuepress/versions.json | 1 + 41 files changed, 8785 insertions(+) create mode 100644 archive/2.0.0a9/README.md create mode 100644 archive/2.0.0a9/advanced/README.md create mode 100644 archive/2.0.0a9/advanced/export-and-require.md create mode 100644 archive/2.0.0a9/advanced/overloaded-handlers.md create mode 100644 archive/2.0.0a9/advanced/permission.md create mode 100644 archive/2.0.0a9/advanced/publish-plugin.md create mode 100644 archive/2.0.0a9/advanced/runtime-hook.md create mode 100644 archive/2.0.0a9/advanced/scheduler.md create mode 100644 archive/2.0.0a9/api/README.md create mode 100644 archive/2.0.0a9/api/adapters/README.md create mode 100644 archive/2.0.0a9/api/adapters/cqhttp.md create mode 100644 archive/2.0.0a9/api/adapters/ding.md create mode 100644 archive/2.0.0a9/api/adapters/mirai.md create mode 100644 archive/2.0.0a9/api/config.md create mode 100644 archive/2.0.0a9/api/drivers/README.md create mode 100644 archive/2.0.0a9/api/drivers/fastapi.md create mode 100644 archive/2.0.0a9/api/exception.md create mode 100644 archive/2.0.0a9/api/log.md create mode 100644 archive/2.0.0a9/api/matcher.md create mode 100644 archive/2.0.0a9/api/message.md create mode 100644 archive/2.0.0a9/api/nonebot.md create mode 100644 archive/2.0.0a9/api/permission.md create mode 100644 archive/2.0.0a9/api/plugin.md create mode 100644 archive/2.0.0a9/api/rule.md create mode 100644 archive/2.0.0a9/api/typing.md create mode 100644 archive/2.0.0a9/api/utils.md create mode 100644 archive/2.0.0a9/guide/README.md create mode 100644 archive/2.0.0a9/guide/basic-configuration.md create mode 100644 archive/2.0.0a9/guide/cqhttp-guide.md create mode 100644 archive/2.0.0a9/guide/creating-a-handler.md create mode 100644 archive/2.0.0a9/guide/creating-a-matcher.md create mode 100644 archive/2.0.0a9/guide/creating-a-plugin.md create mode 100644 archive/2.0.0a9/guide/creating-a-project.md create mode 100644 archive/2.0.0a9/guide/ding-guide.md create mode 100644 archive/2.0.0a9/guide/end-or-start.md create mode 100644 archive/2.0.0a9/guide/getting-started.md create mode 100644 archive/2.0.0a9/guide/installation.md create mode 100644 archive/2.0.0a9/guide/loading-a-plugin.md create mode 100644 archive/2.0.0a9/guide/mirai-guide.md create mode 100644 archive/2.0.0a9/sidebar.config.json diff --git a/archive/2.0.0a9/README.md b/archive/2.0.0a9/README.md new file mode 100644 index 00000000..78cb0fc4 --- /dev/null +++ b/archive/2.0.0a9/README.md @@ -0,0 +1,15 @@ +--- +home: true +heroImage: /logo.png +tagline: An asynchronous bot framework. +actionText: 开始使用 +actionLink: guide/ +features: + - title: 简洁 + details: 提供极其简洁易懂的 API,使你可以毫无压力地开始验证你的绝佳创意,只需编写最少量的代码,即可实现丰富的功能。 + - title: 易于扩展 + details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。 + - title: 高性能 + details: 采用异步 I/O,利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。 +footer: MIT Licensed | Copyright © 2018 - 2020 NoneBot Team +--- diff --git a/archive/2.0.0a9/advanced/README.md b/archive/2.0.0a9/advanced/README.md new file mode 100644 index 00000000..92c6af3e --- /dev/null +++ b/archive/2.0.0a9/advanced/README.md @@ -0,0 +1,7 @@ +# 深入 + +## 它如何工作? + + + +~~未填坑~~ diff --git a/archive/2.0.0a9/advanced/export-and-require.md b/archive/2.0.0a9/advanced/export-and-require.md new file mode 100644 index 00000000..832b0e75 --- /dev/null +++ b/archive/2.0.0a9/advanced/export-and-require.md @@ -0,0 +1 @@ +# 跨插件访问 diff --git a/archive/2.0.0a9/advanced/overloaded-handlers.md b/archive/2.0.0a9/advanced/overloaded-handlers.md new file mode 100644 index 00000000..97ff3116 --- /dev/null +++ b/archive/2.0.0a9/advanced/overloaded-handlers.md @@ -0,0 +1 @@ +# 事件处理函数重载 diff --git a/archive/2.0.0a9/advanced/permission.md b/archive/2.0.0a9/advanced/permission.md new file mode 100644 index 00000000..7190bcdd --- /dev/null +++ b/archive/2.0.0a9/advanced/permission.md @@ -0,0 +1 @@ +# 权限控制 diff --git a/archive/2.0.0a9/advanced/publish-plugin.md b/archive/2.0.0a9/advanced/publish-plugin.md new file mode 100644 index 00000000..68e2e6f9 --- /dev/null +++ b/archive/2.0.0a9/advanced/publish-plugin.md @@ -0,0 +1 @@ +# 发布插件 diff --git a/archive/2.0.0a9/advanced/runtime-hook.md b/archive/2.0.0a9/advanced/runtime-hook.md new file mode 100644 index 00000000..58bca681 --- /dev/null +++ b/archive/2.0.0a9/advanced/runtime-hook.md @@ -0,0 +1 @@ +# 运行时插槽 diff --git a/archive/2.0.0a9/advanced/scheduler.md b/archive/2.0.0a9/advanced/scheduler.md new file mode 100644 index 00000000..86280b5f --- /dev/null +++ b/archive/2.0.0a9/advanced/scheduler.md @@ -0,0 +1,127 @@ +# 定时任务 + +[`APScheduler`](https://apscheduler.readthedocs.io/en/latest/index.html) —— Advanced Python Scheduler + +> Advanced Python Scheduler (APScheduler) is a Python library that lets you schedule your Python code to be executed later, either just once or periodically. You can add new jobs or remove old ones on the fly as you please. If you store your jobs in a database, they will also survive scheduler restarts and maintain their state. When the scheduler is restarted, it will then run all the jobs it should have run while it was offline. + +## 从 v1 迁移 + +`APScheduler` 作为 `nonebot` v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。`nonebot2` 已将 `APScheduler` 独立为 `nonebot_plugin_apscheduler` 插件,你可以在 [插件广场](https://v2.nonebot.dev/plugin-store.html) 中找到它。 + +相比于 `nonebot` v1 ,只需要安装插件并修改 `scheduler` 的导入方式即可完成迁移。 + +## 安装插件 + +### 通过 nb-cli + +如正在使用 `nb-cli` 构建项目,你可以从插件市场复制安装命令或手动输入以下命令以添加 `nonebot_plugin_apscheduler`。 + +```bash +nb plugin install nonebot_plugin_apscheduler +``` + +:::tip 提示 +`nb-cli` 默认通过 `pypi` 安装,你可以使用 `-i [mirror]` 或 `--index [mirror]` 来使用镜像源安装。 +::: + +### 通过 poetry + +执行以下命令以添加 `nonebot_plugin_apscheduler` + +```bash +poetry add nonebot-plugin-apscheduler +``` + +:::tip 提示 +由于稍后我们将使用 `nonebot.require()` 方法进行导入,所以无需额外的 `nonebot.load_plugin()` +::: + +## 快速上手 + +1. 在需要设置定时任务的插件中,通过 `nonebot.require` 从 `nonebot_plugin_apscheduler` 导入 `scheduler` 对象 + +2. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务 + +将上述步骤归纳为最小实现的代码如下: + +```python +from nonebot import require + +scheduler = require('nonebot_plugin_apscheduler').scheduler + +@scheduler.scheduled_job('cron', hour='*/2', id='xxx', args=[1], kwargs={arg2: 2}) +async def run_every_2_hour(arg1, arg2): + pass + +scheduler.add_job(run_every_day_from_program_start, "interval", days=1, id="xxx") +``` + +## 分步进行 + +### 导入 scheduler 对象 + +为了使插件能够实现定时任务,需要先将 `scheduler` 对象导入插件。 + +`nonebot2` 提供了 `nonebot.require` 方法来实现导入其他插件的内容,此处我们使用这个方法来导入 `scheduler` 对象。 + +`nonebot` 使用的 `scheduler` 对象为 `AsyncScheduler` 。 + +> 使用该方法传入的插件本身也需要有对应实现,关于该方法的更多介绍可以参阅 [这里](./export-and-require.md) + +```python +from nonebot import require + +scheduler = require('nonebot_plugin_apscheduler').scheduler +``` + +### 编写定时任务 + +由于本部分为标准的通过 `APScheduler` 配置定时任务,有关指南请参阅 [APScheduler 官方文档](https://apscheduler.readthedocs.io/en/latest/userguide.html#adding-jobs)。 + +### 配置插件选项 + +根据项目的 `.env` 文件设置,向 `.env.*` 或 `bot.py` 文件添加 `nonebot_plugin_apscheduler` 的可选配置项 + +:::warning 注意 +`.env.*` 文件的编写应遵循 nonebot2 对 `.env.*` 文件的编写要求 +::: + +#### `apscheduler_autostart` + +类型:`bool` + +默认值:`True` + +是否自动启动 `APScheduler`。 + +对于大多数情况,我们需要在 `nonebot2` 项目被启动时启动定时任务,则此处设为 `true` + +```bash +APSCHEDULER_AUTOSTART=true +``` + +```python +nonebot.init(apscheduler_autostart=True) +``` + +#### `apscheduler_config` + +类型:`dict` + +默认值:`{"apscheduler.timezone": "Asia/Shanghai"}` + +`APScheduler` 相关配置。修改/增加其中配置项需要确保 `prefix: apscheduler`。 + +对于 `APScheduler` 的相关配置,请参阅 [scheduler-config](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-config) 和 [BaseScheduler](https://apscheduler.readthedocs.io/en/latest/modules/schedulers/base.html#apscheduler.schedulers.base.BaseScheduler) + +> 官方文档在绝大多数时候能提供最准确和最具时效性的指南 + +```bash +APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"} +``` + +```python +nonebot.init(apscheduler_config={ + "apscheduler.timezone": "Asia/Shanghai" +}) +``` diff --git a/archive/2.0.0a9/api/README.md b/archive/2.0.0a9/api/README.md new file mode 100644 index 00000000..36e9803e --- /dev/null +++ b/archive/2.0.0a9/api/README.md @@ -0,0 +1,55 @@ +# NoneBot Api Reference + + +* **模块索引** + + + * [nonebot](nonebot.html) + + + * [nonebot.config](config.html) + + + * [nonebot.plugin](plugin.html) + + + * [nonebot.message](message.html) + + + * [nonebot.matcher](matcher.html) + + + * [nonebot.rule](rule.html) + + + * [nonebot.permission](permission.html) + + + * [nonebot.log](log.html) + + + * [nonebot.utils](utils.html) + + + * [nonebot.typing](typing.html) + + + * [nonebot.exception](exception.html) + + + * [nonebot.drivers](drivers/) + + + * [nonebot.drivers.fastapi](drivers/fastapi.html) + + + * [nonebot.adapters](adapters/) + + + * [nonebot.adapters.cqhttp](adapters/cqhttp.html) + + + * [nonebot.adapters.ding](adapters/ding.html) + + + * [nonebot.adapters.mirai](adapters/mirai.html) diff --git a/archive/2.0.0a9/api/adapters/README.md b/archive/2.0.0a9/api/adapters/README.md new file mode 100644 index 00000000..42498ab2 --- /dev/null +++ b/archive/2.0.0a9/api/adapters/README.md @@ -0,0 +1,426 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters 模块 + +## 协议适配基类 + +各协议请继承以下基类,并使用 `driver.register_adapter` 注册适配器 + + +## _class_ `Bot` + +基类:`abc.ABC` + +Bot 基类。用于处理上报消息,并提供 API 调用接口。 + + +### `driver` + +Driver 对象 + + +### `config` + +Config 配置对象 + + +### _abstract_ `__init__(connection_type, self_id, *, websocket=None)` + + +* **参数** + + + * `connection_type: str`: http 或者 websocket + + + * `self_id: str`: 机器人 ID + + + * `websocket: Optional[WebSocket]`: Websocket 连接对象 + + + +### `connection_type` + +连接类型 + + +### `self_id` + +机器人 ID + + +### `websocket` + +Websocket 连接对象 + + +### _abstract property_ `type` + +Adapter 类型 + + +### _classmethod_ `register(driver, config)` + + +* **说明** + + register 方法会在 driver.register_adapter 时被调用,用于初始化相关配置 + + + +### _abstract async classmethod_ `check_permission(driver, connection_type, headers, body)` + + +* **说明** + + 检查连接请求是否合法的函数,如果合法则返回当前连接 `唯一标识符`,通常为机器人 ID;如果不合法则抛出 `RequestDenied` 异常。 + + + +* **参数** + + + * `driver: Driver`: Driver 对象 + + + * `connection_type: str`: 连接类型 + + + * `headers: dict`: 请求头 + + + * `body: Optional[dict]`: 请求数据,WebSocket 连接该部分为空 + + + +* **返回** + + + * `str`: 连接唯一标识符 + + + +* **异常** + + + * `RequestDenied`: 请求非法 + + + +### _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", message="hello world") +await bot.send_msg(message="hello world") +``` + + +### _abstract async_ `send(event, message, **kwargs)` + + +* **说明** + + 调用机器人基础发送消息接口 + + + +* **参数** + + + * `event: Event`: 上报事件 + + + * `message: Union[str, Message, MessageSegment]`: 要发送的消息 + + + * `**kwargs` + + + +## _class_ `MessageSegment` + +基类:`abc.ABC` + +消息段基类 + + +### `type` + + +* 类型: `str` + + +* 说明: 消息段类型 + + +### `data` + + +* 类型: `Dict[str, Union[str, list]]` + + +* 说明: 消息段数据 + + +## _class_ `Message` + +基类:`list`, `abc.ABC` + +消息数组 + + +### `__init__(message=None, *args, **kwargs)` + + +* **参数** + + + * `message: Union[str, list, dict, MessageSegment, Message, Any]`: 消息内容 + + + +### `append(obj)` + + +* **说明** + + 添加一个消息段到消息数组末尾 + + + +* **参数** + + + * `obj: Union[str, MessageSegment]`: 要添加的消息段 + + + +### `extend(obj)` + + +* **说明** + + 拼接一个消息数组或多个消息段到消息数组末尾 + + + +* **参数** + + + * `obj: Union[Message, Iterable[MessageSegment]]`: 要添加的消息数组 + + + +### `reduce()` + + +* **说明** + + 缩减消息数组,即按 MessageSegment 的实现拼接相邻消息段 + + + +### `extract_plain_text()` + + +* **说明** + + 提取消息内纯文本消息 + + + +## _class_ `Event` + +基类:`abc.ABC`, `pydantic.main.BaseModel` + +Event 基类。提供获取关键信息的方法,其余信息可直接获取。 + + +### _abstract_ `get_type()` + + +* **说明** + + 获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。 + + + +* **返回** + + + * `Literal["message", "notice", "request", "meta_event"]` + + + +### _abstract_ `get_event_name()` + + +* **说明** + + 获取事件名称的方法。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_event_description()` + + +* **说明** + + 获取事件描述的方法,通常为事件具体内容。 + + + +* **返回** + + + * `str` + + + +### `get_log_string()` + + +* **说明** + + 获取事件日志信息的方法,通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 `NoLogException` 异常。 + + + +* **返回** + + + * `str` + + + +* **异常** + + + * `NoLogException` + + + +### _abstract_ `get_user_id()` + + +* **说明** + + 获取事件主体 id 的方法,通常是用户 id 。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_session_id()` + + +* **说明** + + 获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_message()` + + +* **说明** + + 获取事件消息内容的方法。 + + + +* **返回** + + + * `Message` + + + +### `get_plaintext()` + + +* **说明** + + 获取消息纯文本的方法,通常不需要修改,默认通过 `get_message().extract_plain_text` 获取。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `is_tome()` + + +* **说明** + + 获取事件是否与机器人有关的方法。 + + + +* **返回** + + + * `bool` diff --git a/archive/2.0.0a9/api/adapters/cqhttp.md b/archive/2.0.0a9/api/adapters/cqhttp.md new file mode 100644 index 00000000..ca5d91cb --- /dev/null +++ b/archive/2.0.0a9/api/adapters/cqhttp.md @@ -0,0 +1,564 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.cqhttp 模块 + +## CQHTTP (OneBot) v11 协议适配 + +协议详情请看: [CQHTTP](https://github.com/howmanybots/onebot/blob/master/README.md) | [OneBot](https://github.com/howmanybots/onebot/blob/master/README.md) + +# NoneBot.adapters.cqhttp.utils 模块 + + +## `escape(s, *, escape_comma=True)` + + +* **说明** + + 对字符串进行 CQ 码转义。 + + + +* **参数** + + + * `s: str`: 需要转义的字符串 + + + * `escape_comma: bool`: 是否转义逗号(`,`)。 + + + +## `unescape(s)` + + +* **说明** + + 对字符串进行 CQ 码去转义。 + + + +* **参数** + + + * `s: str`: 需要转义的字符串 + + +# NoneBot.adapters.cqhttp.exception 模块 + + +## _exception_ `ActionFailed` + +基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException` + + +* **说明** + + API 请求返回错误信息。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + + +## _exception_ `NetworkError` + +基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException` + + +* **说明** + + 网络错误。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + +# NoneBot.adapters.cqhttp.bot 模块 + + +## _async_ `_check_reply(bot, event)` + + +* **说明** + + 检查消息中存在的回复,去除并赋值 `event.reply`, `event.to_me` + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + +## `_check_at_me(bot, event)` + + +* **说明** + + 检查消息开头或结尾是否存在 @机器人,去除并赋值 `event.to_me` + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + +## `_check_nickname(bot, event)` + + +* **说明** + + 检查消息开头是否存在,去除并赋值 `event.to_me` + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + +## `_handle_api_result(result)` + + +* **说明** + + 处理 API 请求返回值。 + + + +* **参数** + + + * `result: Optional[Dict[str, Any]]`: API 返回数据 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `ActionFailed`: API 调用失败 + + + +## _class_ `Bot` + +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) + +CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 + + +### _property_ `type` + + +* 返回: `"cqhttp"` + + +### _async classmethod_ `check_permission(driver, connection_type, headers, body)` + + +* **说明** + + CQHTTP (OneBot) 协议鉴权。参考 [鉴权](https://github.com/howmanybots/onebot/blob/master/v11/specs/communication/authorization.md) + + + +### _async_ `handle_message(message)` + + +* **说明** + + 调用 [_check_reply](#async-check-reply-bot-event), [_check_at_me](#check-at-me-bot-event), [_check_nickname](#check-nickname-bot-event) 处理事件并转换为 [Event](#class-event) + + + +### _async_ `call_api(api, **data)` + + +* **说明** + + 调用 CQHTTP 协议 API + + + +* **参数** + + + * `api: str`: API 名称 + + + * `**data: Any`: API 参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + + +### _async_ `send(event, message, at_sender=False, **kwargs)` + + +* **说明** + + 根据 `event` 向触发事件的主体发送消息。 + + + +* **参数** + + + * `event: Event`: Event 对象 + + + * `message: Union[str, Message, MessageSegment]`: 要发送的消息 + + + * `at_sender: bool`: 是否 @ 事件主体 + + + * `**kwargs`: 覆盖默认参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `ValueError`: 缺少 `user_id`, `group_id` + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + +# NoneBot.adapters.cqhttp.message 模块 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) + +CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + + +## _class_ `Message` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +CQHTTP 协议 Message 适配。 + +# NoneBot.adapters.cqhttp.permission 模块 + + +## `PRIVATE` + + +* **说明**: 匹配任意私聊消息类型事件 + + +## `PRIVATE_FRIEND` + + +* **说明**: 匹配任意好友私聊消息类型事件 + + +## `PRIVATE_GROUP` + + +* **说明**: 匹配任意群临时私聊消息类型事件 + + +## `PRIVATE_OTHER` + + +* **说明**: 匹配任意其他私聊消息类型事件 + + +## `GROUP` + + +* **说明**: 匹配任意群聊消息类型事件 + + +## `GROUP_MEMBER` + + +* **说明**: 匹配任意群员群聊消息类型事件 + +:::warning 警告 +该权限通过 event.sender 进行判断且不包含管理员以及群主! +::: + + +## `GROUP_ADMIN` + + +* **说明**: 匹配任意群管理员群聊消息类型事件 + + +## `GROUP_OWNER` + + +* **说明**: 匹配任意群主群聊消息类型事件 + +# NoneBot.adapters.cqhttp.event 模块 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +CQHTTP 协议事件,字段与 CQHTTP 一致。各事件字段参考 [CQHTTP 文档](https://github.com/howmanybots/onebot/blob/master/README.md) + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +消息事件 + + +### `to_me` + + +* **说明** + + 消息是否与机器人有关 + + + +* **类型** + + `bool` + + + +### `reply` + + +* **说明** + + 消息中提取的回复消息,内容为 `get_msg` API 返回结果 + + + +* **类型** + + `Optional[Reply]` + + + +## _class_ `PrivateMessageEvent` + +基类:`nonebot.adapters.cqhttp.event.MessageEvent` + +私聊消息 + + +## _class_ `GroupMessageEvent` + +基类:`nonebot.adapters.cqhttp.event.MessageEvent` + +群消息 + + +## _class_ `NoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +通知事件 + + +## _class_ `GroupUploadNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群文件上传事件 + + +## _class_ `GroupAdminNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群管理员变动 + + +## _class_ `GroupDecreaseNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群成员减少事件 + + +## _class_ `GroupIncreaseNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群成员增加事件 + + +## _class_ `GroupBanNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群禁言事件 + + +## _class_ `FriendAddNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +好友添加事件 + + +## _class_ `GroupRecallNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群消息撤回事件 + + +## _class_ `FriendRecallNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +好友消息撤回事件 + + +## _class_ `NotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +提醒事件 + + +## _class_ `PokeNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +戳一戳提醒事件 + + +## _class_ `LuckyKingNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +群红包运气王提醒事件 + + +## _class_ `HonorNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +群荣誉变更提醒事件 + + +## _class_ `RequestEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +请求事件 + + +## _class_ `FriendRequestEvent` + +基类:`nonebot.adapters.cqhttp.event.RequestEvent` + +加好友请求事件 + + +## _class_ `GroupRequestEvent` + +基类:`nonebot.adapters.cqhttp.event.RequestEvent` + +加群请求/邀请事件 + + +## _class_ `MetaEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +元事件 + + +## _class_ `LifecycleMetaEvent` + +基类:`nonebot.adapters.cqhttp.event.MetaEvent` + +生命周期元事件 + + +## _class_ `HeartbeatMetaEvent` + +基类:`nonebot.adapters.cqhttp.event.MetaEvent` + +心跳元事件 + + +## `get_event_model(event_name)` + + +* **说明** + + 根据事件名获取对应 `Event Model` 及 `FallBack Event Model` 列表 + + + +* **返回** + + + * `List[Type[Event]]` diff --git a/archive/2.0.0a9/api/adapters/ding.md b/archive/2.0.0a9/api/adapters/ding.md new file mode 100644 index 00000000..c64125ac --- /dev/null +++ b/archive/2.0.0a9/api/adapters/ding.md @@ -0,0 +1,308 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.ding 模块 + +## 钉钉群机器人 协议适配 + +协议详情请看: [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) + +# NoneBot.adapters.ding.exception 模块 + + +## _exception_ `DingAdapterException` + +基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException) + + +* **说明** + + 钉钉 Adapter 错误基类 + + + +## _exception_ `ActionFailed` + +基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + API 请求返回错误信息。 + + + +* **参数** + + + * `errcode: Optional[int]`: 错误码 + + + * `errmsg: Optional[str]`: 错误信息 + + + +## _exception_ `NetworkError` + +基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 网络错误。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + + +## _exception_ `SessionExpired` + +基类:`nonebot.adapters.ding.exception.ApiNotAvailable`, `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 发消息的 session 已经过期。 + + +# NoneBot.adapters.ding.bot 模块 + + +## _class_ `Bot` + +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) + +钉钉 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 + + +### _property_ `type` + + +* 返回: `"ding"` + + +### _async classmethod_ `check_permission(driver, connection_type, headers, body)` + + +* **说明** + + 钉钉协议鉴权。参考 [鉴权](https://ding-doc.dingtalk.com/doc#/serverapi2/elzz1p) + + + +### _async_ `call_api(api, event=None, **data)` + + +* **说明** + + 调用 钉钉 协议 API + + + +* **参数** + + + * `api: str`: API 名称 + + + * `**data: Any`: API 参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + + +### _async_ `send(event, message, at_sender=False, **kwargs)` + + +* **说明** + + 根据 `event` 向触发事件的主体发送消息。 + + + +* **参数** + + + * `event: Event`: Event 对象 + + + * `message: Union[str, Message, MessageSegment]`: 要发送的消息 + + + * `at_sender: bool`: 是否 @ 事件主体 + + + * `**kwargs`: 覆盖默认参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `ValueError`: 缺少 `user_id`, `group_id` + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + +# NoneBot.adapters.ding.message 模块 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) + +钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + + +### _static_ `atAll()` + +@全体 + + +### _static_ `atMobiles(*mobileNumber)` + +@指定手机号人员 + + +### _static_ `atDingtalkIds(*dingtalkIds)` + +@指定 id,@ 默认会在消息段末尾。 +所以你可以在消息中使用 @{senderId} 占位,发送出去之后 @ 就会出现在占位的位置: +``python +message = MessageSegment.text(f"@{event.senderId},你好") +message += MessageSegment.atDingtalkIds(event.senderId) +`` + + +### _static_ `text(text)` + +发送 `text` 类型消息 + + +### _static_ `image(picURL)` + +发送 `image` 类型消息 + + +### _static_ `extension(dict_)` + +"标记 text 文本的 extension 属性,需要与 text 消息段相加。 + + +### _static_ `code(code_language, code)` + +"发送 code 消息段 + + +### _static_ `markdown(title, text)` + +发送 `markdown` 类型消息 + + +### _static_ `actionCardSingleBtn(title, text, singleTitle, singleURL)` + +发送 `actionCardSingleBtn` 类型消息 + + +### _static_ `actionCardMultiBtns(title, text, btns, hideAvatar=False, btnOrientation='1')` + +发送 `actionCardMultiBtn` 类型消息 + + +* **参数** + + + * `btnOrientation`: 0:按钮竖直排列 1:按钮横向排列 + + + * `btns`: [{ "title": title, "actionURL": actionURL }, ...] + + + +### _static_ `feedCard(links)` + +发送 `feedCard` 类型消息 + + +* **参数** + + + * `links`: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...] + + + +## _class_ `Message` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +钉钉 协议 Message 适配。 + +# NoneBot.adapters.ding.event 模块 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +钉钉协议事件。各事件字段参考 [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) + + +## _class_ `ConversationType` + +基类:`str`, `enum.Enum` + +An enumeration. + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.ding.event.Event` + +消息事件 + + +## _class_ `PrivateMessageEvent` + +基类:`nonebot.adapters.ding.event.MessageEvent` + +私聊消息事件 + + +## _class_ `GroupMessageEvent` + +基类:`nonebot.adapters.ding.event.MessageEvent` + +群消息事件 diff --git a/archive/2.0.0a9/api/adapters/mirai.md b/archive/2.0.0a9/api/adapters/mirai.md new file mode 100644 index 00000000..4b568152 --- /dev/null +++ b/archive/2.0.0a9/api/adapters/mirai.md @@ -0,0 +1,1908 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.mirai 模块 + +## Mirai-API-HTTP 协议适配 + +协议详情请看: [mirai-api-http 文档](https://github.com/project-mirai/mirai-api-http/tree/master/docs) + +::: tip +该Adapter目前仍然处在早期实验性阶段, 并未经过充分测试 + +如果你在使用过程中遇到了任何问题, 请前往 [Issue页面](https://github.com/nonebot/nonebot2/issues) 为我们提供反馈 +::: + +::: danger +Mirai-API-HTTP 的适配器以 [AGPLv3许可](https://opensource.org/licenses/AGPL-3.0) 单独开源 + +这意味着在使用该适配器时需要 **以该许可开源您的完整程序代码** +::: + +# NoneBot.adapters.mirai.bot 模块 + + +## _class_ `SessionManager` + +基类:`object` + +Bot会话管理器, 提供API主动调用接口 + + +### _async_ `post(path, *, params=None)` + + +* **说明** + + 以POST方式主动提交API请求 + + + +* **参数** + + + * `path: str`: 对应API路径 + + + * `params: Optional[Dict[str, Any]]`: 请求参数 (无需sessionKey) + + + +* **返回** + + + * `Dict[str, Any]`: API 返回值 + + + +### _async_ `request(path, *, params=None)` + + +* **说明** + + 以GET方式主动提交API请求 + + + +* **参数** + + + * `path: str`: 对应API路径 + + + * `params: Optional[Dict[str, Any]]`: 请求参数 (无需sessionKey) + + + +### _async_ `upload(path, *, params)` + + +* **说明** + + 以表单(`multipart/form-data`)形式主动提交API请求 + + + +* **参数** + + + * `path: str`: 对应API路径 + + + * `params: Dict[str, Any]`: 请求参数 (无需sessionKey) + + + +## _class_ `Bot` + +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) + +mirai-api-http 协议 Bot 适配。 + +::: warning +API中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 + +部分字段可能与文档在符号上不一致 +::: + + +### _property_ `api` + +返回该Bot对象的会话管理实例以提供API主动调用 + + +### _async_ `call_api(api, **data)` + +::: danger +由于Mirai的HTTP API特殊性, 该API暂时无法实现 +::: + +::: tip +你可以使用 `MiraiBot.api` 中提供的调用方法来代替 +::: + + +### `send(event, message, at_sender=False)` + + +* **说明** + + 根据 `event` 向触发事件的主体发送信息 + + + +* **参数** + + + * `event: Event`: Event对象 + + + * `message: Union[MessageChain, MessageSegment, str]`: 要发送的消息 + + + * `at_sender: bool`: 是否 @ 事件主体 + + + +### `send_friend_message(target, message_chain)` + + +* **说明** + + 使用此方法向指定好友发送消息 + + + +* **参数** + + + * `target: int`: 发送消息目标好友的 QQ 号 + + + * `message_chain: MessageChain`: 消息链,是一个消息对象构成的数组 + + + +### `send_temp_message(qq, group, message_chain)` + + +* **说明** + + 使用此方法向临时会话对象发送消息 + + + +* **参数** + + + * `qq: int`: 临时会话对象 QQ 号 + + + * `group: int`: 临时会话群号 + + + * `message_chain: MessageChain`: 消息链,是一个消息对象构成的数组 + + + +### `send_group_message(group, message_chain, quote=None)` + + +* **说明** + + 使用此方法向指定群发送消息 + + + +* **参数** + + + * `group: int`: 发送消息目标群的群号 + + + * `message_chain: MessageChain`: 消息链,是一个消息对象构成的数组 + + + * `quote: Optional[int]`: 引用一条消息的 message_id 进行回复 + + + +### `recall(target)` + + +* **说明** + + 使用此方法撤回指定消息。对于bot发送的消息,有2分钟时间限制。对于撤回群聊中群员的消息,需要有相应权限 + + + +* **参数** + + + * `target: int`: 需要撤回的消息的message_id + + + +### `send_image_message(target, qq, group, urls)` + + +* **说明** + + 使用此方法向指定对象(群或好友)发送图片消息 + 除非需要通过此手段获取image_id,否则不推荐使用该接口 + + > 当qq和group同时存在时,表示发送临时会话图片,qq为临时会话对象QQ号,group为临时会话发起的群号 + + + +* **参数** + + + * `target: int`: 发送对象的QQ号或群号,可能存在歧义 + + + * `qq: int`: 发送对象的QQ号 + + + * `group: int`: 发送对象的群号 + + + * `urls: List[str]`: 是一个url字符串构成的数组 + + + +* **返回** + + + * `List[str]`: 一个包含图片imageId的数组 + + + +### `upload_image(type, img)` + + +* **说明** + + 使用此方法上传图片文件至服务器并返回Image_id + + + +* **参数** + + + * `type: str`: "friend" 或 "group" 或 "temp" + + + * `img: BytesIO`: 图片的BytesIO对象 + + + +### `upload_voice(type, voice)` + + +* **说明** + + 使用此方法上传语音文件至服务器并返回voice_id + + + +* **参数** + + + * `type: str`: 当前仅支持 "group" + + + * `voice: BytesIO`: 语音的BytesIO对象 + + + +### `fetch_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最老消息和最老各类事件 + (会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### `fetch_latest_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最新消息和最新各类事件 + (会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### `peek_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最老消息和最老各类事件 + (不会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### `peek_latest_message(count=10)` + + +* **说明** + + 使用此方法获取bot接收到的最新消息和最新各类事件 + (不会从MiraiApiHttp消息记录中删除) + + + +* **参数** + + + * `count: int`: 获取消息和事件的数量 + + + +### `messsage_from_id(id)` + + +* **说明** + + 通过messageId获取一条被缓存的消息 + 使用此方法获取bot接收到的消息和各类事件 + + + +* **参数** + + + * `id: int`: 获取消息的message_id + + + +### `count_message()` + + +* **说明** + + 使用此方法获取bot接收并缓存的消息总数,注意不包含被删除的 + + + +### `friend_list()` + + +* **说明** + + 使用此方法获取bot的好友列表 + + + +* **返回** + + + * `List[Dict[str, Any]]`: 返回的好友列表数据 + + + +### `group_list()` + + +* **说明** + + 使用此方法获取bot的群列表 + + + +* **返回** + + + * `List[Dict[str, Any]]`: 返回的群列表数据 + + + +### `member_list(target)` + + +* **说明** + + 使用此方法获取bot指定群种的成员列表 + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +* **返回** + + + * `List[Dict[str, Any]]`: 返回的群成员列表数据 + + + +### `mute(target, member_id, time)` + + +* **说明** + + 使用此方法指定群禁言指定群员(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 指定群员QQ号 + + + * `time: int`: 禁言时长,单位为秒,最多30天 + + + +### `unmute(target, member_id)` + + +* **说明** + + 使用此方法指定群解除群成员禁言(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 指定群员QQ号 + + + +### `kick(target, member_id, msg)` + + +* **说明** + + 使用此方法移除指定群成员(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 指定群员QQ号 + + + * `msg: str`: 信息 + + + +### `quit(target)` + + +* **说明** + + 使用此方法使Bot退出群聊 + + + +* **参数** + + + * `target: int`: 退出的群号 + + + +### `mute_all(target)` + + +* **说明** + + 使用此方法令指定群进行全体禁言(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +### `unmute_all(target)` + + +* **说明** + + 使用此方法令指定群解除全体禁言(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +### `group_config(target)` + + +* **说明** + + 使用此方法获取群设置 + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + +* **返回** + + +```json +{ + "name": "群名称", + "announcement": "群公告", + "confessTalk": true, + "allowMemberInvite": true, + "autoApprove": true, + "anonymousChat": true +} +``` + + +### `modify_group_config(target, config)` + + +* **说明** + + 使用此方法修改群设置(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `config: Dict[str, Any]`: 群设置, 格式见 `group_config` 的返回值 + + + +### `member_info(target, member_id)` + + +* **说明** + + 使用此方法获取群员资料 + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 群员QQ号 + + + +* **返回** + + +```json +{ + "name": "群名片", + "specialTitle": "群头衔" +} +``` + + +### `modify_member_info(target, member_id, info)` + + +* **说明** + + 使用此方法修改群员资料(需要有相关权限) + + + +* **参数** + + + * `target: int`: 指定群的群号 + + + * `member_id: int`: 群员QQ号 + + + * `info: Dict[str, Any]`: 群员资料, 格式见 `member_info` 的返回值 + + +# NoneBot.adapters.mirai.bot_ws 模块 + + +## _class_ `WebsocketBot` + +基类:`nonebot.adapters.mirai.bot.Bot` + +mirai-api-http 正向 Websocket 协议 Bot 适配。 + + +### _classmethod_ `register(driver, config, qq)` + + +* **说明** + + 注册该Adapter + + + +* **参数** + + + * `driver: Driver`: 程序所使用的\`\`Driver\`\` + + + * `config: Config`: 程序配置对象 + + + * `qq: int`: 要使用的Bot的QQ号 **注意: 在使用正向Websocket时必须指定该值!** + + +# NoneBot.adapters.mirai.config 模块 + + +## _class_ `Config` + +基类:`pydantic.main.BaseModel` + +Mirai 配置类 + + +* **必填** + + + * `mirai_auth_key`: mirai-api-http的auth_key + + + * `mirai_host`: mirai-api-http的地址 + + + * `mirai_port`: mirai-api-http的端口 + + +# NoneBot.adapters.mirai.message 模块 + + +## _class_ `MessageType` + +基类:`str`, `enum.Enum` + +消息类型枚举类 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) + +CQHTTP 协议 MessageSegment 适配。具体方法参考 [mirai-api-http 消息类型](https://github.com/project-mirai/mirai-api-http/blob/master/docs/MessageType.md) + + +### `as_dict()` + +导出可以被正常json序列化的结构体 + + +### _classmethod_ `quote(id, group_id, sender_id, target_id, origin)` + + +* **说明** + + 生成回复引用消息段 + + + +* **参数** + + + * `id: int`: 被引用回复的原消息的message_id + + + * `group_id: int`: 被引用回复的原消息所接收的群号,当为好友消息时为0 + + + * `sender_id: int`: 被引用回复的原消息的发送者的QQ号 + + + * `target_id: int`: 被引用回复的原消息的接收者者的QQ号(或群号) + + + * `origin: MessageChain`: 被引用回复的原消息的消息链对象 + + + +### _classmethod_ `at(target)` + + +* **说明** + + @某个人 + + + +* **参数** + + + * `target: int`: 群员QQ号 + + + +### _classmethod_ `at_all()` + + +* **说明** + + @全体成员 + + + +### _classmethod_ `face(face_id=None, name=None)` + + +* **说明** + + 发送QQ表情 + + + +* **参数** + + + * `face_id: Optional[int]`: QQ表情编号,可选,优先高于name + + + * `name: Optional[str]`: QQ表情拼音,可选 + + + +### _classmethod_ `plain(text)` + + +* **说明** + + 纯文本消息 + + + +* **参数** + + + * `text: str`: 文字消息 + + + +### _classmethod_ `image(image_id=None, url=None, path=None)` + + +* **说明** + + 图片消息 + + + +* **参数** + + + * `image_id: Optional[str]`: 图片的image_id,群图片与好友图片格式不同。不为空时将忽略url属性 + + + * `url: Optional[str]`: 图片的URL,发送时可作网络图片的链接 + + + * `path: Optional[str]`: 图片的路径,发送本地图片 + + + +### _classmethod_ `flash_image(image_id=None, url=None, path=None)` + + +* **说明** + + 闪照消息 + + + +* **参数** + + 同 `image` + + + +### _classmethod_ `voice(voice_id=None, url=None, path=None)` + + +* **说明** + + 语音消息 + + + +* **参数** + + + * `voice_id: Optional[str]`: 语音的voice_id,不为空时将忽略url属性 + + + * `url: Optional[str]`: 语音的URL,发送时可作网络语音的链接 + + + * `path: Optional[str]`: 语音的路径,发送本地语音 + + + +### _classmethod_ `xml(xml)` + + +* **说明** + + XML消息 + + + +* **参数** + + + * `xml: str`: XML文本 + + + +### _classmethod_ `json(json)` + + +* **说明** + + Json消息 + + + +* **参数** + + + * `json: str`: Json文本 + + + +### _classmethod_ `app(content)` + + +* **说明** + + 应用程序消息 + + + +* **参数** + + + * `content: str`: 内容 + + + +### _classmethod_ `poke(name)` + + +* **说明** + + 戳一戳消息 + + + +* **参数** + + + * `name: str`: 戳一戳的类型 + + + * `Poke`: 戳一戳 + + + * `ShowLove`: 比心 + + + * `Like`: 点赞 + + + * `Heartbroken`: 心碎 + + + * `SixSixSix`: 666 + + + * `FangDaZhao`: 放大招 + + + +## _class_ `MessageChain` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +Mirai 协议 Messaqge 适配 + +由于Mirai协议的Message实现较为特殊, 故使用MessageChain命名 + + +### `export()` + +导出为可以被正常json序列化的数组 + +# NoneBot.adapters.mirai.utils 模块 + + +## _exception_ `ActionFailed` + +基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed) + + +* **说明** + + API 请求成功返回数据,但 API 操作失败。 + + + +## _exception_ `InvalidArgument` + +基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException) + + +* **说明** + + 调用API的参数出错 + + + +## `catch_network_error(function)` + + +* **说明** + + 捕捉函数抛出的httpx网络异常并释放 `NetworkError` 异常 + + 处理返回数据, 在code不为0时释放 `ActionFailed` 异常 + + +::: warning +此装饰器只支持使用了httpx的异步函数 +::: + + +## `argument_validation(function)` + + +* **说明** + + 通过函数签名中的类型注解来对传入参数进行运行时校验 + + 会在参数出错时释放 `InvalidArgument` 异常 + + +# NoneBot.adapters.mirai.event 模块 + +::: warning +事件中为了使代码更加整洁, 我们采用了与PEP8相符的命名规则取代Mirai原有的驼峰命名 + +部分字段可能与文档在符号上不一致 +::: + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 [mirai-api-http 事件类型](https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md) + + +### _classmethod_ `new(data)` + +此事件类的工厂函数, 能够通过事件数据选择合适的子类进行序列化 + + +### `normalize_dict(**kwargs)` + +返回可以被json正常反序列化的结构体 + + +## _class_ `UserPermission` + +基类:`str`, `enum.Enum` + + +* **说明** + + +用户权限枚举类 + +> +> * `OWNER`: 群主 + + +> * `ADMINISTRATOR`: 群管理 + + +> * `MEMBER`: 普通群成员 + + +## _class_ `MessageChain` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +Mirai 协议 Messaqge 适配 + +由于Mirai协议的Message实现较为特殊, 故使用MessageChain命名 + + +### `export()` + +导出为可以被正常json序列化的数组 + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +消息事件基类 + + +## _class_ `GroupMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +群消息事件 + + +## _class_ `FriendMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +好友消息事件 + + +## _class_ `TempMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +临时会话消息事件 + + +## _class_ `NoticeEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +通知事件基类 + + +## _class_ `MuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +禁言类事件基类 + + +## _class_ `BotMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被禁言 + + +## _class_ `BotUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被取消禁言 + + +## _class_ `MemberMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被禁言事件(该成员不是Bot) + + +## _class_ `MemberUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被取消禁言事件(该成员不是Bot) + + +## _class_ `BotJoinGroupEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +Bot加入了一个新群 + + +## _class_ `BotLeaveEventActive` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot主动退出一个群 + + +## _class_ `BotLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot被踢出一个群 + + +## _class_ `MemberJoinEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +新人入群的事件 + + +## _class_ `MemberLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员被踢出群(该成员不是Bot) + + +## _class_ `MemberLeaveEventQuit` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员主动离群(该成员不是Bot) + + +## _class_ `FriendRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +好友消息撤回 + + +## _class_ `GroupRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.FriendRecallEvent` + +群消息撤回 + + +## _class_ `GroupStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群变化事件基类 + + +## _class_ `GroupNameChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某个群名改变 + + +## _class_ `GroupEntranceAnnouncementChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某群入群公告改变 + + +## _class_ `GroupMuteAllEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +全员禁言 + + +## _class_ `GroupAllowAnonymousChatEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +匿名聊天 + + +## _class_ `GroupAllowConfessTalkEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +坦白说 + + +## _class_ `GroupAllowMemberInviteEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +允许群员邀请好友加群 + + +## _class_ `MemberStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群成员变化事件基类 + + +## _class_ `MemberCardChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群名片改动 + + +## _class_ `MemberSpecialTitleChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群头衔改动(只有群主有操作限权) + + +## _class_ `BotGroupPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +Bot在群里的权限被改变 + + +## _class_ `MemberPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +成员权限改变的事件(该成员不是Bot) + + +## _class_ `RequestEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +请求事件基类 + + +## _class_ `NewFriendRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +添加好友申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2]`: 响应的操作类型 + + + * `1`: 拒绝添加好友 + + + * `2`: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + + + * `message: str`: 回复的信息 + + + +## _class_ `MemberJoinRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +用户入群申请(Bot需要有管理员权限) + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝(忽略)此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2, 3, 4]`: 响应的操作类型 + + + * `1`: 拒绝入群 + + + * `2`: 忽略请求 + + + * `3`: 拒绝入群并添加黑名单,不再接收该用户的入群申请 + + + * `4`: 忽略入群并添加黑名单,不再接收该用户的入群申请 + + + * `message: str`: 回复的信息 + + + +## _class_ `BotInvitedJoinGroupRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +Bot被邀请入群申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, message='')` + + +* **说明** + + 拒绝这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `message: str`: 邀请消息 + + +# NoneBot.adapters.mirai.event.base 模块 + + +## _class_ `UserPermission` + +基类:`str`, `enum.Enum` + + +* **说明** + + +用户权限枚举类 + +> +> * `OWNER`: 群主 + + +> * `ADMINISTRATOR`: 群管理 + + +> * `MEMBER`: 普通群成员 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +mirai-api-http 协议事件,字段与 mirai-api-http 一致。各事件字段参考 [mirai-api-http 事件类型](https://github.com/project-mirai/mirai-api-http/blob/master/docs/EventType.md) + + +### _classmethod_ `new(data)` + +此事件类的工厂函数, 能够通过事件数据选择合适的子类进行序列化 + + +### `normalize_dict(**kwargs)` + +返回可以被json正常反序列化的结构体 + +# NoneBot.adapters.mirai.event.meta 模块 + + +## _class_ `MetaEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +元事件基类 + + +## _class_ `BotOnlineEvent` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot登录成功 + + +## _class_ `BotOfflineEventActive` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot主动离线 + + +## _class_ `BotOfflineEventForce` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot被挤下线 + + +## _class_ `BotOfflineEventDropped` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot被服务器断开或因网络问题而掉线 + + +## _class_ `BotReloginEvent` + +基类:`nonebot.adapters.mirai.event.meta.MetaEvent` + +Bot主动重新登录 + +# NoneBot.adapters.mirai.event.message 模块 + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +消息事件基类 + + +## _class_ `GroupMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +群消息事件 + + +## _class_ `FriendMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +好友消息事件 + + +## _class_ `TempMessage` + +基类:`nonebot.adapters.mirai.event.message.MessageEvent` + +临时会话消息事件 + +# NoneBot.adapters.mirai.event.notice 模块 + + +## _class_ `NoticeEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +通知事件基类 + + +## _class_ `MuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +禁言类事件基类 + + +## _class_ `BotMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被禁言 + + +## _class_ `BotUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +Bot被取消禁言 + + +## _class_ `MemberMuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被禁言事件(该成员不是Bot) + + +## _class_ `MemberUnmuteEvent` + +基类:`nonebot.adapters.mirai.event.notice.MuteEvent` + +群成员被取消禁言事件(该成员不是Bot) + + +## _class_ `BotJoinGroupEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +Bot加入了一个新群 + + +## _class_ `BotLeaveEventActive` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot主动退出一个群 + + +## _class_ `BotLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.BotJoinGroupEvent` + +Bot被踢出一个群 + + +## _class_ `MemberJoinEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +新人入群的事件 + + +## _class_ `MemberLeaveEventKick` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员被踢出群(该成员不是Bot) + + +## _class_ `MemberLeaveEventQuit` + +基类:`nonebot.adapters.mirai.event.notice.MemberJoinEvent` + +成员主动离群(该成员不是Bot) + + +## _class_ `FriendRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +好友消息撤回 + + +## _class_ `GroupRecallEvent` + +基类:`nonebot.adapters.mirai.event.notice.FriendRecallEvent` + +群消息撤回 + + +## _class_ `GroupStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群变化事件基类 + + +## _class_ `GroupNameChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某个群名改变 + + +## _class_ `GroupEntranceAnnouncementChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +某群入群公告改变 + + +## _class_ `GroupMuteAllEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +全员禁言 + + +## _class_ `GroupAllowAnonymousChatEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +匿名聊天 + + +## _class_ `GroupAllowConfessTalkEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +坦白说 + + +## _class_ `GroupAllowMemberInviteEvent` + +基类:`nonebot.adapters.mirai.event.notice.GroupStateChangeEvent` + +允许群员邀请好友加群 + + +## _class_ `MemberStateChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.NoticeEvent` + +群成员变化事件基类 + + +## _class_ `MemberCardChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群名片改动 + + +## _class_ `MemberSpecialTitleChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +群头衔改动(只有群主有操作限权) + + +## _class_ `BotGroupPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +Bot在群里的权限被改变 + + +## _class_ `MemberPermissionChangeEvent` + +基类:`nonebot.adapters.mirai.event.notice.MemberStateChangeEvent` + +成员权限改变的事件(该成员不是Bot) + +# NoneBot.adapters.mirai.event.request 模块 + + +## _class_ `RequestEvent` + +基类:`nonebot.adapters.mirai.event.base.Event` + +请求事件基类 + + +## _class_ `NewFriendRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +添加好友申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝此人的好友申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2]`: 响应的操作类型 + + + * `1`: 拒绝添加好友 + + + * `2`: 拒绝添加好友并添加黑名单,不再接收该用户的好友申请 + + + * `message: str`: 回复的信息 + + + +## _class_ `MemberJoinRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +用户入群申请(Bot需要有管理员权限) + + +### _async_ `approve(bot)` + + +* **说明** + + 通过此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, operate=1, message='')` + + +* **说明** + + 拒绝(忽略)此人的加群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `operate: Literal[1, 2, 3, 4]`: 响应的操作类型 + + + * `1`: 拒绝入群 + + + * `2`: 忽略请求 + + + * `3`: 拒绝入群并添加黑名单,不再接收该用户的入群申请 + + + * `4`: 忽略入群并添加黑名单,不再接收该用户的入群申请 + + + * `message: str`: 回复的信息 + + + +## _class_ `BotInvitedJoinGroupRequestEvent` + +基类:`nonebot.adapters.mirai.event.request.RequestEvent` + +Bot被邀请入群申请 + + +### _async_ `approve(bot)` + + +* **说明** + + 通过这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + +### _async_ `reject(bot, message='')` + + +* **说明** + + 拒绝这份被邀请入群申请 + + + +* **参数** + + + * `bot: Bot`: 当前的 `Bot` 对象 + + + * `message: str`: 邀请消息 diff --git a/archive/2.0.0a9/api/config.md b/archive/2.0.0a9/api/config.md new file mode 100644 index 00000000..654ea628 --- /dev/null +++ b/archive/2.0.0a9/api/config.md @@ -0,0 +1,285 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.config 模块 + +## 配置 + +NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-dotenv](https://saurabh-kumar.com/python-dotenv/) 来读取配置。 + +配置项需符合特殊格式或 json 序列化格式。详情见 [pydantic Field Type](https://pydantic-docs.helpmanual.io/usage/types/) 文档。 + + +## _class_ `Env` + +基类:`nonebot.config.BaseConfig` + +运行环境配置。大小写不敏感。 + +将会从 `nonebot.init 参数` > `环境变量` > `.env 环境配置文件` 的优先级读取配置。 + + +### `environment` + + +* **类型**: `str` + + +* **默认值**: `"prod"` + + +* **说明** + + 当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。 + + + +## _class_ `Config` + +基类:`nonebot.config.BaseConfig` + +NoneBot 主要配置。大小写不敏感。 + +除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。 +这些配置将会在 json 反序列化后一起带入 `Config` 类中。 + + +### `driver` + + +* **类型**: `str` + + +* **默认值**: `"nonebot.drivers.fastapi"` + + +* **说明** + + NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver` 。 + + + +### `host` + + +* **类型**: `IPvAnyAddress` + + +* **默认值**: `127.0.0.1` + + +* **说明** + + NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。 + + + +### `port` + + +* **类型**: `int` + + +* **默认值**: `8080` + + +* **说明** + + NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。 + + + +### `debug` + + +* **类型**: `bool` + + +* **默认值**: `False` + + +* **说明** + + 是否以调试模式运行 NoneBot。 + + + +### `api_root` + + +* **类型**: `Dict[str, str]` + + +* **默认值**: `{}` + + +* **说明** + + 以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。 + + + +* **示例** + + +```default +API_ROOT={"123456": "http://127.0.0.1:5700"} +``` + + +### `api_timeout` + + +* **类型**: `Optional[float]` + + +* **默认值**: `30.` + + +* **说明** + + API 请求超时时间,单位: 秒。 + + + +### `access_token` + + +* **类型**: `Optional[str]` + + +* **默认值**: `None` + + +* **说明** + + API 请求以及上报所需密钥,在请求头中携带。 + + + +* **示例** + + +```http +POST /cqhttp/ HTTP/1.1 +Authorization: Bearer kSLuTF2GC2Q4q4ugm3 +``` + + +### `secret` + + +* **类型**: `Optional[str]` + + +* **默认值**: `None` + + +* **说明** + + HTTP POST 形式上报所需签名,在请求头中携带。 + + + +* **示例** + + +```http +POST /cqhttp/ HTTP/1.1 +X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 +``` + + +### `superusers` + + +* **类型**: `Set[str]` + + +* **默认值**: `set()` + + +* **说明** + + 机器人超级用户。 + + + +* **示例** + + +```default +SUPERUSERS=["12345789"] +``` + + +### `nickname` + + +* **类型**: `Set[str]` + + +* **默认值**: `set()` + + +* **说明** + + 机器人昵称。 + + + +### `command_start` + + +* **类型**: `Set[str]` + + +* **默认值**: `{"/"}` + + +* **说明** + + 命令的起始标记,用于判断一条消息是不是命令。 + + + +### `command_sep` + + +* **类型**: `Set[str]` + + +* **默认值**: `{"."}` + + +* **说明** + + 命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。 + + + +### `session_expire_timeout` + + +* **类型**: `timedelta` + + +* **默认值**: `timedelta(minutes=2)` + + +* **说明** + + 等待用户回复的超时时间。 + + + +* **示例** + + +```default +SESSION_EXPIRE_TIMEOUT=120 # 单位: 秒 +SESSION_EXPIRE_TIMEOUT=[DD ][HH:MM]SS[.ffffff] +SESSION_EXPIRE_TIMEOUT=P[DD]DT[HH]H[MM]M[SS]S # ISO 8601 +``` diff --git a/archive/2.0.0a9/api/drivers/README.md b/archive/2.0.0a9/api/drivers/README.md new file mode 100644 index 00000000..77485ed2 --- /dev/null +++ b/archive/2.0.0a9/api/drivers/README.md @@ -0,0 +1,318 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.drivers 模块 + +## 后端驱动适配基类 + +各驱动请继承以下基类 + + +## _class_ `Driver` + +基类:`abc.ABC` + +Driver 基类。将后端框架封装,以满足适配器使用。 + + +### `_adapters` + + +* **类型** + + `Dict[str, Type[Bot]]` + + + +* **说明** + + 已注册的适配器列表 + + + +### `_ws_connection_hook` + + +* **类型** + + `Set[T_WebSocketConnectionHook]` + + + +* **说明** + + WebSocket 连接建立时执行的函数 + + + +### `_ws_disconnection_hook` + + +* **类型** + + `Set[T_WebSocketDisconnectionHook]` + + + +* **说明** + + WebSocket 连接断开时执行的函数 + + + +### _abstract_ `__init__(env, config)` + + +* **参数** + + + * `env: Env`: 包含环境信息的 Env 对象 + + + * `config: Config`: 包含配置信息的 Config 对象 + + + +### `env` + + +* **类型** + + `str` + + + +* **说明** + + 环境名称 + + + +### `config` + + +* **类型** + + `Config` + + + +* **说明** + + 配置对象 + + + +### `_clients` + + +* **类型** + + `Dict[str, Bot]` + + + +* **说明** + + 已连接的 Bot + + + +### `register_adapter(name, adapter)` + + +* **说明** + + 注册一个协议适配器 + + + +* **参数** + + + * `name: str`: 适配器名称,用于在连接时进行识别 + + + * `adapter: Type[Bot]`: 适配器 Class + + + +### _abstract property_ `type` + +驱动类型名称 + + +### _abstract property_ `server_app` + +驱动 APP 对象 + + +### _abstract property_ `asgi` + +驱动 ASGI 对象 + + +### _abstract property_ `logger` + +驱动专属 logger 日志记录器 + + +### _property_ `bots` + + +* **类型** + + `Dict[str, Bot]` + + + +* **说明** + + 获取当前所有已连接的 Bot + + + +### _abstract_ `on_startup(func)` + +注册一个在驱动启动时运行的函数 + + +### _abstract_ `on_shutdown(func)` + +注册一个在驱动停止时运行的函数 + + +### `on_bot_connect(func)` + + +* **说明** + + 装饰一个函数使他在 bot 通过 WebSocket 连接成功时执行。 + + + +* **函数参数** + + + * `bot: Bot`: 当前连接上的 Bot 对象 + + + +### `on_bot_disconnect(func)` + + +* **说明** + + 装饰一个函数使他在 bot 通过 WebSocket 连接断开时执行。 + + + +* **函数参数** + + + * `bot: Bot`: 当前连接上的 Bot 对象 + + + +### `_bot_connect(bot)` + +在 WebSocket 连接成功后,调用该函数来注册 bot 对象 + + +### `_bot_disconnect(bot)` + +在 WebSocket 连接断开后,调用该函数来注销 bot 对象 + + +### _abstract_ `run(host=None, port=None, *args, **kwargs)` + + +* **说明** + + 启动驱动框架 + + + +* **参数** + + + * `host: Optional[str]`: 驱动绑定 IP + + + * `post: Optional[int]`: 驱动绑定端口 + + + * `*args` + + + * `**kwargs` + + + +### _abstract async_ `_handle_http()` + +用于处理 HTTP 类型请求的函数 + + +### _abstract async_ `_handle_ws_reverse()` + +用于处理 WebSocket 类型请求的函数 + + +## _class_ `WebSocket` + +基类:`object` + +WebSocket 连接封装,统一接口方便外部调用。 + + +### _abstract_ `__init__(websocket)` + + +* **参数** + + + * `websocket: Any`: WebSocket 连接对象 + + + +### _property_ `websocket` + +WebSocket 连接对象 + + +### _abstract property_ `closed` + + +* **类型** + + `bool` + + + +* **说明** + + 连接是否已经关闭 + + + +### _abstract async_ `accept()` + +接受 WebSocket 连接请求 + + +### _abstract async_ `close(code)` + +关闭 WebSocket 连接请求 + + +### _abstract async_ `receive()` + +接收一条 WebSocket 信息 + + +### _abstract async_ `send(data)` + +发送一条 WebSocket 信息 diff --git a/archive/2.0.0a9/api/drivers/fastapi.md b/archive/2.0.0a9/api/drivers/fastapi.md new file mode 100644 index 00000000..edd8e474 --- /dev/null +++ b/archive/2.0.0a9/api/drivers/fastapi.md @@ -0,0 +1,68 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.drivers.fastapi 模块 + +## FastAPI 驱动适配 + +后端使用方法请参考: [FastAPI 文档](https://fastapi.tiangolo.com/) + + +## _class_ `Driver` + +基类:[`nonebot.drivers.Driver`](README.md#nonebot.drivers.Driver) + +FastAPI 驱动框架 + + +* **上报地址** + + + * `/{adapter name}/`: HTTP POST 上报 + + + * `/{adapter name}/http/`: HTTP POST 上报 + + + * `/{adapter name}/ws`: WebSocket 上报 + + + * `/{adapter name}/ws/`: WebSocket 上报 + + + +### _property_ `type` + +驱动名称: `fastapi` + + +### _property_ `server_app` + +`FastAPI APP` 对象 + + +### _property_ `asgi` + +`FastAPI APP` 对象 + + +### _property_ `logger` + +fastapi 使用的 logger + + +### `on_startup(func)` + +参考文档: [Events](https://fastapi.tiangolo.com/advanced/events/#startup-event) + + +### `on_shutdown(func)` + +参考文档: [Events](https://fastapi.tiangolo.com/advanced/events/#startup-event) + + +### `run(host=None, port=None, *, app=None, **kwargs)` + +使用 `uvicorn` 启动 FastAPI diff --git a/archive/2.0.0a9/api/exception.md b/archive/2.0.0a9/api/exception.md new file mode 100644 index 00000000..817c02a9 --- /dev/null +++ b/archive/2.0.0a9/api/exception.md @@ -0,0 +1,214 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.exception 模块 + +## 异常 + +下列文档中的异常是所有 NoneBot 运行时可能会抛出的。 +这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。 + + +## _exception_ `NoneBotException` + +基类:`Exception` + + +* **说明** + + 所有 NoneBot 发生的异常基类。 + + + +## _exception_ `IgnoredException` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。 + + + +* **参数** + + + * `reason`: 忽略事件的原因 + + + +## _exception_ `ParserExit` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + `shell command` 处理消息失败时返回的异常 + + + +* **参数** + + + * `status` + + + * `message` + + + +## _exception_ `PausedException` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 指示 NoneBot 结束当前 `Handler` 并等待下一条消息后继续下一个 `Handler`。 + 可用于用户输入新信息。 + + + +* **用法** + + 可以在 `Handler` 中通过 `Matcher.pause()` 抛出。 + + + +## _exception_ `RejectedException` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 指示 NoneBot 结束当前 `Handler` 并等待下一条消息后重新运行当前 `Handler`。 + 可用于用户重新输入。 + + + +* **用法** + + 可以在 `Handler` 中通过 `Matcher.reject()` 抛出。 + + + +## _exception_ `FinishedException` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 指示 NoneBot 结束当前 `Handler` 且后续 `Handler` 不再被运行。 + 可用于结束用户会话。 + + + +* **用法** + + 可以在 `Handler` 中通过 `Matcher.finish()` 抛出。 + + + +## _exception_ `StopPropagation` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 指示 NoneBot 终止事件向下层传播。 + + + +* **用法** + + 在 `Matcher.block == True` 时抛出。 + + + +## _exception_ `RequestDenied` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + Bot 连接请求不合法。 + + + +* **参数** + + + * `status_code: int`: HTTP 状态码 + + + * `reason: str`: 拒绝原因 + + + +## _exception_ `AdapterException` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 代表 `Adapter` 抛出的异常,所有的 `Adapter` 都要在内部继承自这个 `Exception` + + + +* **参数** + + + * `adapter_name: str`: 标识 adapter + + + +## _exception_ `NoLogException` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 对当前 `Event` 进行处理但不显示 Log 信息,可在 `get_log_string` 时抛出 + + + +## _exception_ `ApiNotAvailable` + +基类:`nonebot.exception.AdapterException` + + +* **说明** + + 在 API 连接不可用时抛出。 + + + +## _exception_ `NetworkError` + +基类:`nonebot.exception.AdapterException` + + +* **说明** + + 在网络出现问题时抛出,如: API 请求地址不正确, API 请求无返回或返回状态非正常等。 + + + +## _exception_ `ActionFailed` + +基类:`nonebot.exception.AdapterException` + + +* **说明** + + API 请求成功返回数据,但 API 操作失败。 diff --git a/archive/2.0.0a9/api/log.md b/archive/2.0.0a9/api/log.md new file mode 100644 index 00000000..e6096cff --- /dev/null +++ b/archive/2.0.0a9/api/log.md @@ -0,0 +1,42 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.log 模块 + +## 日志 + +NoneBot 使用 [loguru](https://github.com/Delgan/loguru) 来记录日志信息。 + +自定义 logger 请参考 [loguru](https://github.com/Delgan/loguru) 文档。 + + +## `logger` + + +* **说明** + + NoneBot 日志记录器对象。 + + + +* **默认信息** + + + * 格式: `[%(asctime)s %(name)s] %(levelname)s: %(message)s` + + + * 等级: `DEBUG` / `INFO` ,根据 config 配置改变 + + + * 输出: 输出至 stdout + + + +* **用法** + + +```python +from nonebot.log import logger +``` diff --git a/archive/2.0.0a9/api/matcher.md b/archive/2.0.0a9/api/matcher.md new file mode 100644 index 00000000..22eabc3b --- /dev/null +++ b/archive/2.0.0a9/api/matcher.md @@ -0,0 +1,470 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.matcher 模块 + +## 事件响应器 + +该模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行 对话 。 + + +## `matchers` + + +* **类型** + + `Dict[int, List[Type[Matcher]]]` + + + +* **说明** + + 用于存储当前所有的事件响应器 + + + +## _class_ `Matcher` + +基类:`object` + +事件响应器类 + + +### `module` + + +* **类型** + + `Optional[str]` + + + +* **说明** + + 事件响应器所在模块名称 + + + +### `type` + + +* **类型** + + `str` + + + +* **说明** + + 事件响应器类型 + + + +### `rule` + + +* **类型** + + `Rule` + + + +* **说明** + + 事件响应器匹配规则 + + + +### `permission` + + +* **类型** + + `Permission` + + + +* **说明** + + 事件响应器触发权限 + + + +### `priority` + + +* **类型** + + `int` + + + +* **说明** + + 事件响应器优先级 + + + +### `block` + + +* **类型** + + `bool` + + + +* **说明** + + 事件响应器是否阻止事件传播 + + + +### `temp` + + +* **类型** + + `bool` + + + +* **说明** + + 事件响应器是否为临时 + + + +### `expire_time` + + +* **类型** + + `Optional[datetime]` + + + +* **说明** + + 事件响应器过期时间点 + + + +### `_default_state` + + +* **类型** + + `T_State` + + + +* **说明** + + 事件响应器默认状态 + + + +### `_default_state_factory` + + +* **类型** + + `Optional[T_State]` + + + +* **说明** + + 事件响应器默认工厂函数 + + + +### `_default_parser` + + +* **类型** + + `Optional[T_ArgsParser]` + + + +* **说明** + + 事件响应器默认参数解析函数 + + + +### `__init__()` + +实例化 Matcher 以便运行 + + +### `handlers` + + +* **类型** + + `List[T_Handler]` + + + +* **说明** + + 事件响应器拥有的事件处理函数列表 + + + +### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, default_state_factory=None, expire_time=None)` + + +* **说明** + + 创建一个新的事件响应器,并存储至 [matchers](#matchers) + + + +* **参数** + + + * `type_: str`: 事件响应器类型,与 `event.get_type()` 一致时触发,空字符串表示任意 + + + * `rule: Optional[Rule]`: 匹配规则 + + + * `permission: Optional[Permission]`: 权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器,即触发一次后删除 + + + * `priority: int`: 响应优先级 + + + * `block: bool`: 是否阻止事件向更低优先级的响应器传播 + + + * `module: Optional[str]`: 事件响应器所在模块名称 + + + * `default_state: Optional[T_State]`: 默认状态 `state` + + + * `default_state_factory: Optional[T_StateFactory]`: 默认状态 `state` 的工厂函数 + + + * `expire_time: Optional[datetime]`: 事件响应器最终有效时间点,过时即被删除 + + + +* **返回** + + + * `Type[Matcher]`: 新的事件响应器类 + + + +### _async classmethod_ `check_perm(bot, event)` + + +* **说明** + + 检查是否满足触发权限 + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: 上报事件 + + + +* **返回** + + + * `bool`: 是否满足权限 + + + +### _async classmethod_ `check_rule(bot, event, state)` + + +* **说明** + + 检查是否满足匹配规则 + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: 上报事件 + + + * `state: T_State`: 当前状态 + + + +* **返回** + + + * `bool`: 是否满足匹配规则 + + + +### _classmethod_ `args_parser(func)` + + +* **说明** + + 装饰一个函数来更改当前事件响应器的默认参数解析函数 + + + +* **参数** + + + * `func: T_ArgsParser`: 参数解析函数 + + + +### _classmethod_ `handle()` + + +* **说明** + + 装饰一个函数来向事件响应器直接添加一个处理函数 + + + +* **参数** + + + * 无 + + + +### _classmethod_ `receive()` + + +* **说明** + + 装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数 + + + +* **参数** + + + * 无 + + + +### _classmethod_ `got(key, prompt=None, args_parser=None)` + + +* **说明** + + 装饰一个函数来指示 NoneBot 当要获取的 `key` 不存在时接收用户新的一条消息并经过 `ArgsParser` 处理后再运行该函数,如果 `key` 已存在则直接继续运行 + + + +* **参数** + + + * `key: str`: 参数名 + + + * `prompt: Optional[Union[str, Message, MessageSegment]]`: 在参数不存在时向用户发送的消息 + + + * `args_parser: Optional[T_ArgsParser]`: 可选参数解析函数,空则使用默认解析函数 + + + +### _async classmethod_ `send(message, **kwargs)` + + +* **说明** + + 发送一条消息给当前交互用户 + + + +* **参数** + + + * `message: Union[str, Message, MessageSegment]`: 消息内容 + + + * `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api + + + +### _async classmethod_ `finish(message=None, **kwargs)` + + +* **说明** + + 发送一条消息给当前交互用户并结束当前事件响应器 + + + +* **参数** + + + * `message: Union[str, Message, MessageSegment]`: 消息内容 + + + * `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api + + + +### _async classmethod_ `pause(prompt=None, **kwargs)` + + +* **说明** + + 发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数 + + + +* **参数** + + + * `prompt: Union[str, Message, MessageSegment]`: 消息内容 + + + * `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api + + + +### _async classmethod_ `reject(prompt=None, **kwargs)` + + +* **说明** + + 发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后重新运行当前处理函数 + + + +* **参数** + + + * `prompt: Union[str, Message, MessageSegment]`: 消息内容 + + + * `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api diff --git a/archive/2.0.0a9/api/message.md b/archive/2.0.0a9/api/message.md new file mode 100644 index 00000000..5bd6c332 --- /dev/null +++ b/archive/2.0.0a9/api/message.md @@ -0,0 +1,143 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.message 模块 + +## 事件处理 + +NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供了多个插槽以进行事件的预处理等。 + + +## `event_preprocessor(func)` + + +* **说明** + + 事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。 + + + +* **参数** + + 事件预处理函数接收三个参数。 + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: T_State`: 当前 State + + + +## `event_postprocessor(func)` + + +* **说明** + + 事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。 + + + +* **参数** + + 事件后处理函数接收三个参数。 + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: T_State`: 当前事件运行前 State + + + +## `run_preprocessor(func)` + + +* **说明** + + 运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。 + + + +* **参数** + + 运行预处理函数接收四个参数。 + + + * `matcher: Matcher`: 当前要运行的事件响应器 + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: T_State`: 当前 State + + + +## `run_postprocessor(func)` + + +* **说明** + + 运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。 + + + +* **参数** + + 运行后处理函数接收五个参数。 + + + * `matcher: Matcher`: 运行完毕的事件响应器 + + + * `exception: Optional[Exception]`: 事件响应器运行错误(如果存在) + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: T_State`: 当前 State + + + +## _async_ `handle_event(bot, event)` + + +* **说明** + + 处理一个事件。调用该函数以实现分发事件。 + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + +* **示例** + + +```python +import asyncio +asyncio.create_task(handle_event(bot, event)) +``` diff --git a/archive/2.0.0a9/api/nonebot.md b/archive/2.0.0a9/api/nonebot.md new file mode 100644 index 00000000..58f7fbda --- /dev/null +++ b/archive/2.0.0a9/api/nonebot.md @@ -0,0 +1,269 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot 模块 + +## 快捷导入 + +为方便使用,`nonebot` 模块从子模块导入了部分内容 + + +* `on_message` => `nonebot.plugin.on_message` + + +* `on_notice` => `nonebot.plugin.on_notice` + + +* `on_request` => `nonebot.plugin.on_request` + + +* `on_metaevent` => `nonebot.plugin.on_metaevent` + + +* `on_startswith` => `nonebot.plugin.on_startswith` + + +* `on_endswith` => `nonebot.plugin.on_endswith` + + +* `on_keyword` => `nonebot.plugin.on_keyword` + + +* `on_command` => `nonebot.plugin.on_command` + + +* `on_shell_command` => `nonebot.plugin.on_shell_command` + + +* `on_regex` => `nonebot.plugin.on_regex` + + +* `CommandGroup` => `nonebot.plugin.CommandGroup` + + +* `Matchergroup` => `nonebot.plugin.MatcherGroup` + + +* `load_plugin` => `nonebot.plugin.load_plugin` + + +* `load_plugins` => `nonebot.plugin.load_plugins` + + +* `load_builtin_plugins` => `nonebot.plugin.load_builtin_plugins` + + +* `get_plugin` => `nonebot.plugin.get_plugin` + + +* `get_loaded_plugins` => `nonebot.plugin.get_loaded_plugins` + + +* `export` => `nonebot.plugin.export` + + +* `require` => `nonebot.plugin.require` + + +## `get_driver()` + + +* **说明** + + 获取全局 Driver 对象。可用于在计划任务的回调中获取当前 Driver 对象。 + + + +* **返回** + + + * `Driver`: 全局 Driver 对象 + + + +* **异常** + + + * `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用) + + + +* **用法** + + +```python +driver = nonebot.get_driver() +``` + + +## `get_app()` + + +* **说明** + + 获取全局 Driver 对应 Server App 对象。 + + + +* **返回** + + + * `Any`: Server App 对象 + + + +* **异常** + + + * `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用) + + + +* **用法** + + +```python +app = nonebot.get_app() +``` + + +## `get_asgi()` + + +* **说明** + + 获取全局 Driver 对应 Asgi 对象。 + + + +* **返回** + + + * `Any`: Asgi 对象 + + + +* **异常** + + + * `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用) + + + +* **用法** + + +```python +asgi = nonebot.get_asgi() +``` + + +## `get_bots()` + + +* **说明** + + 获取所有通过 ws 连接 NoneBot 的 Bot 对象。 + + + +* **返回** + + + * `Dict[str, Bot]`: 一个以字符串 ID 为键,Bot 对象为值的字典 + + + +* **异常** + + + * `ValueError`: 全局 Driver 对象尚未初始化 (nonebot.init 尚未调用) + + + +* **用法** + + +```python +bots = nonebot.get_bots() +``` + + +## `init(*, _env_file=None, **kwargs)` + + +* **说明** + + 初始化 NoneBot 以及 全局 Driver 对象。 + + NoneBot 将会从 .env 文件中读取环境信息,并使用相应的 env 文件配置。 + + 你也可以传入自定义的 _env_file 来指定 NoneBot 从该文件读取配置。 + + + +* **参数** + + + * `_env_file: Optional[str]`: 配置文件名,默认从 .env.{env_name} 中读取配置 + + + * `**kwargs`: 任意变量,将会存储到 Config 对象里 + + + +* **返回** + + + * `None` + + + +* **用法** + + +```python +nonebot.init(database=Database(...)) +``` + + +## `run(host=None, port=None, *args, **kwargs)` + + +* **说明** + + 启动 NoneBot,即运行全局 Driver 对象。 + + + +* **参数** + + + * `host: Optional[str]`: 主机名/IP,若不传入则使用配置文件中指定的值 + + + * `port: Optional[int]`: 端口,若不传入则使用配置文件中指定的值 + + + * `*args`: 传入 Driver.run 的位置参数 + + + * `**kwargs`: 传入 Driver.run 的命名参数 + + + +* **返回** + + + * `None` + + + +* **用法** + + +```python +nonebot.run(host="127.0.0.1", port=8080) +``` diff --git a/archive/2.0.0a9/api/permission.md b/archive/2.0.0a9/api/permission.md new file mode 100644 index 00000000..1c42b2c8 --- /dev/null +++ b/archive/2.0.0a9/api/permission.md @@ -0,0 +1,63 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.permission 模块 + +## 权限 + +每个 `Matcher` 拥有一个 `Permission` ,其中是 **异步** `PermissionChecker` 的集合,只要有一个 `PermissionChecker` 检查结果为 `True` 时就会继续运行。 + +:::tip 提示 +`PermissionChecker` 既可以是 async function 也可以是 sync function +::: + + +## `MESSAGE` + + +* **说明**: 匹配任意 `message` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 message type 的 Matcher。 + + +## `NOTICE` + + +* **说明**: 匹配任意 `notice` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 notice type 的 Matcher。 + + +## `REQUEST` + + +* **说明**: 匹配任意 `request` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 request type 的 Matcher。 + + +## `METAEVENT` + + +* **说明**: 匹配任意 `meta_event` 类型事件,仅在需要同时捕获不同类型事件时使用。优先使用 meta_event type 的 Matcher。 + + +## `USER(*user, perm=)` + + +* **说明** + + 在白名单内且满足 perm + + + +* **参数** + + + * `*user: str`: 白名单 + + + * `perm: Permission`: 需要同时满足的权限 + + + +## `SUPERUSER` + + +* **说明**: 匹配任意超级用户消息类型事件 diff --git a/archive/2.0.0a9/api/plugin.md b/archive/2.0.0a9/api/plugin.md new file mode 100644 index 00000000..960521da --- /dev/null +++ b/archive/2.0.0a9/api/plugin.md @@ -0,0 +1,1401 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.plugin 模块 + +## 插件 + +为 NoneBot 插件开发提供便携的定义函数。 + + +## `plugins` + + +* **类型** + + `Dict[str, Plugin]` + + + +* **说明** + + 已加载的插件 + + + +## _class_ `Export` + +基类:`dict` + + +* **说明** + + 插件导出内容以使得其他插件可以获得。 + + + +* **示例** + + +```python +nonebot.export().default = "bar" + +@nonebot.export() +def some_function(): + pass + +# this doesn't work before python 3.9 +# use +# export = nonebot.export(); @export.sub +# instead +# See also PEP-614: https://www.python.org/dev/peps/pep-0614/ +@nonebot.export().sub +def something_else(): + pass +``` + + +## _class_ `Plugin` + +基类:`object` + +存储插件信息 + + +### `name` + + +* **类型**: `str` + + +* **说明**: 插件名称,使用 文件/文件夹 名称作为插件名 + + +### `module` + + +* **类型**: `ModuleType` + + +* **说明**: 插件模块对象 + + +### `matcher` + + +* **类型**: `Set[Type[Matcher]]` + + +* **说明**: 插件内定义的 `Matcher` + + +### `export` + + +* **类型**: `Export` + + +* **说明**: 插件内定义的导出内容 + + +## `on(type='', rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个基础事件响应器,可自定义类型。 + + + +* **参数** + + + * `type: str`: 事件响应器类型 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_metaevent(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个元事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_message(rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=True, state=None, state_factory=None)` + + +* **说明** + + 注册一个消息事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_notice(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个通知事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_request(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个请求事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_startswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容开头时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息开头内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_endswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容结尾时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息结尾内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_keyword(keywords, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + + + +* **参数** + + + * `keywords: Set[str]`: 关键词列表 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_command(cmd, rule=None, aliases=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 + + 命令匹配规则参考: [命令形式匹配](rule.html#command-command) + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_shell_command(cmd, rule=None, aliases=None, parser=None, **kwargs)` + + +* **说明** + + 注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 + + 与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。 + + 并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]` 中 + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `parser: Optional[ArgumentParser]`: `nonebot.rule.ArgumentParser` 对象 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_regex(pattern, flags=0, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 + + 命令匹配规则参考: [正则匹配](rule.html#regex-regex-flags-0) + + + +* **参数** + + + * `pattern: str`: 正则表达式 + + + * `flags: Union[int, re.RegexFlag]`: 正则匹配标志 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## _class_ `CommandGroup` + +基类:`object` + +命令组,用于声明一组有相同名称前缀的命令。 + + +### `__init__(cmd, **kwargs)` + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 + + + * `**kwargs`: 其他传递给 `on_command` 的参数默认值,参考 [on_command](#on-command-cmd-rule-none-aliases-none-kwargs) + + + +### `basecmd` + + +* **类型**: `Tuple[str, ...]` + + +* **说明**: 命令前缀 + + +### `base_kwargs` + + +* **类型**: `Dict[str, Any]` + + +* **说明**: 其他传递给 `on_command` 的参数默认值 + + +### `command(cmd, **kwargs)` + + +* **说明** + + 注册一个新的命令。 + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 + + + * `**kwargs`: 其他传递给 `on_command` 的参数,将会覆盖命令组默认值 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `shell_command(cmd, **kwargs)` + + +* **说明** + + 注册一个新的命令。 + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 + + + * `**kwargs`: 其他传递给 `on_command` 的参数,将会覆盖命令组默认值 + + + +* **返回** + + + * `Type[Matcher]` + + + +## _class_ `MatcherGroup` + +基类:`object` + +事件响应器组合,统一管理。为 `Matcher` 创建提供默认属性。 + + +### `__init__(**kwargs)` + + +* **说明** + + 创建一个事件响应器组合,参数为默认值,与 `on` 一致 + + + +### `matchers` + + +* **类型** + + `List[Type[Matcher]]` + + + +* **说明** + + 组内事件响应器列表 + + + +### `base_kwargs` + + +* **类型**: `Dict[str, Any]` + + +* **说明**: 其他传递给 `on` 的参数默认值 + + +### `on(**kwargs)` + + +* **说明** + + 注册一个基础事件响应器,可自定义类型。 + + + +* **参数** + + + * `type: str`: 事件响应器类型 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_metaevent(**kwargs)` + + +* **说明** + + 注册一个元事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_message(**kwargs)` + + +* **说明** + + 注册一个消息事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_notice(**kwargs)` + + +* **说明** + + 注册一个通知事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_request(**kwargs)` + + +* **说明** + + 注册一个请求事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_startswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容开头时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息开头内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_endswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容结尾时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息结尾内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_keyword(keywords, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + + + +* **参数** + + + * `keywords: Set[str]`: 关键词列表 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_command(cmd, rule=None, aliases=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 + + 命令匹配规则参考: [命令形式匹配](rule.html#command-command) + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_shell_command(cmd, rule=None, aliases=None, parser=None, **kwargs)` + + +* **说明** + + +注册一个支持 `shell_like` 解析参数的命令消息事件响应器。 + +与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。 + +并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]` 中 + + +* **参数** + + + +* `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + +* `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + +* `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + +* `parser: Optional[ArgumentParser]`: `nonebot.rule.ArgumentParser` 对象 + + +* `permission: Optional[Permission]`: 事件响应权限 + + +* `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + +* `temp: bool`: 是否为临时事件响应器(仅执行一次) + + +* `priority: int`: 事件响应器优先级 + + +* `block: bool`: 是否阻止事件向更低优先级传递 + + +* `state: Optional[T_State]`: 默认 state + + +* `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + +* **返回** + + + +* `Type[Matcher]` + + +### `on_regex(pattern, flags=0, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 + + 命令匹配规则参考: [正则匹配](rule.html#regex-regex-flags-0) + + + +* **参数** + + + * `pattern: str`: 正则表达式 + + + * `flags: Union[int, re.RegexFlag]`: 正则匹配标志 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `load_plugin(module_path)` + + +* **说明** + + 使用 `importlib` 加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。 + + + +* **参数** + + + * `module_path: str`: 插件名称 `path.to.your.plugin` + + + +* **返回** + + + * `Optional[Plugin]` + + + +## `load_plugins(*plugin_dir)` + + +* **说明** + + 导入目录下多个插件,以 `_` 开头的插件不会被导入! + + + +* **参数** + + + * `*plugin_dir: str`: 插件路径 + + + +* **返回** + + + * `Set[Plugin]` + + + +## `load_builtin_plugins(name='echo')` + + +* **说明** + + 导入 NoneBot 内置插件 + + + +* **返回** + + + * `Plugin` + + + +## `get_plugin(name)` + + +* **说明** + + 获取当前导入的某个插件。 + + + +* **参数** + + + * `name: str`: 插件名,与 `load_plugin` 参数一致。如果为 `load_plugins` 导入的插件,则为文件(夹)名。 + + + +* **返回** + + + * `Optional[Plugin]` + + + +## `get_loaded_plugins()` + + +* **说明** + + 获取当前已导入的所有插件。 + + + +* **返回** + + + * `Set[Plugin]` + + + +## `export()` + + +* **说明** + + 获取插件的导出内容对象 + + + +* **返回** + + + * `Export` + + + +## `require(name)` + + +* **说明** + + 获取一个插件的导出内容 + + + +* **参数** + + + * `name: str`: 插件名,与 `load_plugin` 参数一致。如果为 `load_plugins` 导入的插件,则为文件(夹)名。 + + + +* **返回** + + + * `Optional[Export]` diff --git a/archive/2.0.0a9/api/rule.md b/archive/2.0.0a9/api/rule.md new file mode 100644 index 00000000..5c3dfbed --- /dev/null +++ b/archive/2.0.0a9/api/rule.md @@ -0,0 +1,266 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.rule 模块 + +## 规则 + +每个事件响应器 `Matcher` 拥有一个匹配规则 `Rule` ,其中是 **异步** `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。 + +:::tip 提示 +`RuleChecker` 既可以是 async function 也可以是 sync function,但在最终会被 `nonebot.utils.run_sync` 转换为 async function +::: + + +## _class_ `Rule` + +基类:`object` + + +* **说明** + + `Matcher` 规则类,当事件传递时,在 `Matcher` 运行前进行检查。 + + + +* **示例** + + +```python +Rule(async_function) & sync_function +# 等价于 +from nonebot.utils import run_sync +Rule(async_function, run_sync(sync_function)) +``` + + +### `__init__(*checkers)` + + +* **参数** + + + * `*checkers: Callable[[Bot, Event, T_State], Awaitable[bool]]`: **异步** RuleChecker + + + +### `checkers` + + +* **说明** + + 存储 `RuleChecker` + + + +* **类型** + + + * `Set[Callable[[Bot, Event, T_State], Awaitable[bool]]]` + + + +### _async_ `__call__(bot, event, state)` + + +* **说明** + + 检查是否符合所有规则 + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: T_State`: 当前 State + + + +* **返回** + + + * `bool` + + + +## `startswith(msg)` + + +* **说明** + + 匹配消息开头 + + + +* **参数** + + + * `msg: str`: 消息开头字符串 + + + +## `endswith(msg)` + + +* **说明** + + 匹配消息结尾 + + + +* **参数** + + + * `msg: str`: 消息结尾字符串 + + + +## `keyword(*keywords)` + + +* **说明** + + 匹配消息关键词 + + + +* **参数** + + + * `*keywords: str`: 关键词 + + + +## `command(*cmds)` + + +* **说明** + + 命令形式匹配,根据配置里提供的 `command_start`, `command_sep` 判断消息是否为命令。 + + 可以通过 `state["_prefix"]["command"]` 获取匹配成功的命令(例:`("test",)`),通过 `state["_prefix"]["raw_command"]` 获取匹配成功的原始命令文本(例:`"/test"`)。 + + + +* **参数** + + + * `*cmds: Union[str, Tuple[str, ...]]`: 命令内容 + + + +* **示例** + + 使用默认 `command_start`, `command_sep` 配置 + + 命令 `("test",)` 可以匹配:`/test` 开头的消息 + 命令 `("test", "sub")` 可以匹配”`/test.sub` 开头的消息 + + +:::tip 提示 +命令内容与后续消息间无需空格! +::: + + +## _class_ `ArgumentParser` + +基类:`argparse.ArgumentParser` + + +* **说明** + + `shell_like` 命令参数解析器,解析出错时不会退出程序。 + + + +## `shell_command(*cmds, parser=None)` + + +* **说明** + + 支持 `shell_like` 解析参数的命令形式匹配,根据配置里提供的 `command_start`, `command_sep` 判断消息是否为命令。 + + 可以通过 `state["_prefix"]["command"]` 获取匹配成功的命令(例:`("test",)`),通过 `state["_prefix"]["raw_command"]` 获取匹配成功的原始命令文本(例:`"/test"`)。 + + 可以通过 `state["argv"]` 获取用户输入的原始参数列表 + + 添加 `parser` 参数后, 可以自动处理消息并将结果保存在 `state["args"]` 中。 + + + +* **参数** + + + * `*cmds: Union[str, Tuple[str, ...]]`: 命令内容 + + + * `parser: Optional[ArgumentParser]`: `nonebot.rule.ArgumentParser` 对象 + + + +* **示例** + + 使用默认 `command_start`, `command_sep` 配置,更多示例参考 `argparse` 标准库文档。 + + +```python +from nonebot.rule import ArgumentParser + +parser = ArgumentParser() +parser.add_argument("-a", action="store_true") + +rule = shell_command("ls", parser=parser) +``` + +:::tip 提示 +命令内容与后续消息间无需空格! +::: + + +## `regex(regex, flags=0)` + + +* **说明** + + 根据正则表达式进行匹配。 + + 可以通过 `state["_matched"]` `state["_matched_groups"]` `state["_matched_dict"]` + 获取正则表达式匹配成功的文本。 + + + +* **参数** + + + * `regex: str`: 正则表达式 + + + * `flags: Union[int, re.RegexFlag]`: 正则标志 + + +:::tip 提示 +正则表达式匹配使用 search 而非 match,如需从头匹配请使用 `r"^xxx"` 来确保匹配开头 +::: + + +## `to_me()` + + +* **说明** + + 通过 `event.is_tome()` 判断事件是否与机器人有关 + + + +* **参数** + + + * 无 diff --git a/archive/2.0.0a9/api/typing.md b/archive/2.0.0a9/api/typing.md new file mode 100644 index 00000000..5d1b3d7b --- /dev/null +++ b/archive/2.0.0a9/api/typing.md @@ -0,0 +1,214 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.typing 模块 + +## 类型 + +下面的文档中,「类型」部分使用 Python 的 Type Hint 语法,见 [PEP 484](https://www.python.org/dev/peps/pep-0484/)、[PEP 526](https://www.python.org/dev/peps/pep-0526/) 和 [typing](https://docs.python.org/3/library/typing.html)。 + +除了 Python 内置的类型,下面还出现了如下 NoneBot 自定类型,实际上它们是 Python 内置类型的别名。 + +以下类型均可从 nonebot.typing 模块导入。 + + +## `T_State` + + +* **类型** + + `Dict[Any, Any]` + + + +* **说明** + + 事件处理状态 State 类型 + + + + +## `T_StateFactory` + + +* **类型** + + `Callable[[Bot, Event], Awaitable[T_State]]` + + + +* **说明** + + 事件处理状态 State 类工厂函数 + + + + +## `T_WebSocketConnectionHook` + + +* **类型** + + `Callable[[Bot], Awaitable[None]]` + + + +* **说明** + + WebSocket 连接建立时执行的函数 + + + + +## `T_WebSocketDisconnectionHook` + + +* **类型** + + `Callable[[Bot], Awaitable[None]]` + + + +* **说明** + + WebSocket 连接断开时执行的函数 + + + + +## `T_EventPreProcessor` + + +* **类型** + + `Callable[[Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件预处理函数 EventPreProcessor 类型 + + + + +## `T_EventPostProcessor` + + +* **类型** + + `Callable[[Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件预处理函数 EventPostProcessor 类型 + + + + +## `T_RunPreProcessor` + + +* **类型** + + `Callable[[Matcher, Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件响应器运行前预处理函数 RunPreProcessor 类型 + + + + +## `T_RunPostProcessor` + + +* **类型** + + `Callable[[Matcher, Optional[Exception], Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在) + + + + +## `T_RuleChecker` + + +* **类型** + + `Callable[[Bot, Event, T_State], Union[bool, Awaitable[bool]]]` + + + +* **说明** + + RuleChecker 即判断是否响应事件的处理函数。 + + + + +## `T_PermissionChecker` + + +* **类型** + + `Callable[[Bot, Event], Union[bool, Awaitable[bool]]]` + + + +* **说明** + + RuleChecker 即判断是否响应消息的处理函数。 + + + + +## `T_Handler` + + +* **类型** + + + * `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + Handler 即事件的处理函数。 + + + + +## `T_ArgsParser` + + +* **类型** + + `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + ArgsParser 即消息参数解析函数,在 Matcher.got 获取参数时被运行。 diff --git a/archive/2.0.0a9/api/utils.md b/archive/2.0.0a9/api/utils.md new file mode 100644 index 00000000..ab3ea0c2 --- /dev/null +++ b/archive/2.0.0a9/api/utils.md @@ -0,0 +1,84 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.utils 模块 + + +## `escape_tag(s)` + + +* **说明** + + 用于记录带颜色日志时转义 `` 类型特殊标签 + + + +* **参数** + + + * `s: str`: 需要转义的字符串 + + + +* **返回** + + + * `str` + + + +## `run_sync(func)` + + +* **说明** + + 一个用于包装 sync function 为 async function 的装饰器 + + + +* **参数** + + + * `func: Callable[..., Any]`: 被装饰的同步函数 + + + +* **返回** + + + * `Callable[..., Awaitable[Any]]` + + + +## `logger_wrapper` + + +* **说明** + + +用于打印 adapter 的日志。 + + +* **Log 参数** + + + +* `level: Literal['WARNING', 'DEBUG', 'INFO']`: 日志等级 + + +* `message: str`: 日志信息 + + +* `exception: Optional[Exception]`: 异常信息 + + +## _class_ `DataclassEncoder` + +基类:`json.encoder.JSONEncoder` + + +* **说明** + + 在JSON序列化 `Message` (List[Dataclass]) 时使用的 `JSONEncoder` diff --git a/archive/2.0.0a9/guide/README.md b/archive/2.0.0a9/guide/README.md new file mode 100644 index 00000000..4326ac1b --- /dev/null +++ b/archive/2.0.0a9/guide/README.md @@ -0,0 +1,33 @@ +# 概览 + + + +:::tip 提示 +初次使用时可能会觉得这里的概览过于枯燥,可以先简单略读之后直接前往 [安装](./installation.md) 查看安装方法,并进行后续的基础使用教程。 +::: + +## 简介 + +NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。 + +除了起到解析事件的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制。对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 + +得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制,NoneBot 处理事件的吞吐量有了很大的保障,再配合 WebSocket 通信方式(也是最建议的通信方式),NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。 + +需要注意的是,NoneBot 仅支持 **Python 3.7+** + +## 特色 + +NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**! + +- 提供使用简易的脚手架 +- 提供丰富的官方插件 +- 提供可添加/替换的驱动以及协议选项 +- 基于异步 I/O +- 同时支持 HTTP 和反向 WebSocket 通信方式 +- 支持多个机器人账号负载均衡 +- 提供直观的交互式会话接口 +- 提供可自定义的权限控制机制 +- 多种方式渲染要发送的消息内容,使对话足够自然 diff --git a/archive/2.0.0a9/guide/basic-configuration.md b/archive/2.0.0a9/guide/basic-configuration.md new file mode 100644 index 00000000..84ed8fe0 --- /dev/null +++ b/archive/2.0.0a9/guide/basic-configuration.md @@ -0,0 +1,86 @@ +# 基本配置 + +到目前为止我们还在使用 NoneBot 的默认行为,在开始编写自己的插件之前,我们先尝试在配置文件上动动手脚,让 NoneBot 表现出不同的行为。 + +在上一章节中,我们创建了默认的项目结构,其中 `.env`, `.env.*` 均为项目的配置文件,下面将介绍几种 NoneBot 配置方式。 + +:::danger 警告 +请勿将敏感信息写入配置文件并提交至开源仓库! +::: + +## .env 文件 + +NoneBot 在启动时将会从系统环境变量或者 `.env` 文件中寻找变量 `ENVIRONMENT` (大小写不敏感),默认值为 `prod`。 +这将引导 NoneBot 从系统环境变量或者 `.env.{ENVIRONMENT}` 文件中进一步加载具体配置。 + +`.env` 文件是基础环境配置文件,该文件中的配置项在不同环境下都会被加载,但会被 `.env.{ENVIRONMENT}` 文件中的配置所覆盖。 + +现在,我们在 `.env` 文件中写入当前环境信息: + +```bash +# .env +ENVIRONMENT=dev +CUSTOM_CONFIG=common config # 这个配置项在任何环境中都会被加载 +``` + +如你所想,之后 NoneBot 就会从 `.env.dev` 文件中加载环境变量。 + +## .env.\* 文件 + +NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 进行配置管理,会从 `.env.{ENVIRONMENT}` 文件中获悉环境配置。 + +可以在 NoneBot 初始化时指定加载某个环境配置文件: `nonebot.init(_env_file=".env.dev")`,这将忽略你在 `.env` 中设置的 `ENVIRONMENT` 。 + +:::warning 提示 +由于 `pydantic` 使用 JSON 解析配置项,请确保配置项值为 JSON 格式的数据。如: + +```bash +list=["123456789", "987654321", 1] +test={"hello": "world"} +``` + +如果配置项值解析失败将作为字符串处理。 +::: + +示例及说明: + +```bash +HOST=0.0.0.0 # 配置 NoneBot 监听的 IP/主机名 +PORT=8080 # 配置 NoneBot 监听的端口 +DEBUG=true # 开启 debug 模式 **请勿在生产环境开启** +SUPERUSERS=["123456789", "987654321"] # 配置 NoneBot 超级用户 +NICKNAME=["awesome", "bot"] # 配置机器人的昵称 +COMMAND_START=["/", ""] # 配置命令起始字符 +COMMAND_SEP=["."] # 配置命令分割字符 + +# Custom Configs +CUSTOM_CONFIG1="config in env file" +CUSTOM_CONFIG2= # 留空则从系统环境变量读取,如不存在则为空字符串 +``` + +详细的配置项参考 [Config Reference](../api/config.md) 。 + +## 系统环境变量 + +如果在系统环境变量中定义了配置,则一样会被读取。 + +## bot.py 文件 + +配置项也可以在 NoneBot 初始化时传入。此处可以传入任意合法 Python 变量。当然也可以在初始化完成后修改或新增。 + +示例: + +```python +# bot.py +import nonebot + +nonebot.init(custom_config3="config on init") + +config = nonebot.get_driver().config +config.custom_config3 = "changed after init" +config.custom_config4 = "new config after init" +``` + +## 优先级 + +`bot.py init` > `system env` > `env file` diff --git a/archive/2.0.0a9/guide/cqhttp-guide.md b/archive/2.0.0a9/guide/cqhttp-guide.md new file mode 100644 index 00000000..356fa6c3 --- /dev/null +++ b/archive/2.0.0a9/guide/cqhttp-guide.md @@ -0,0 +1,101 @@ +# CQHTTP 协议使用指南 + +## 配置 CQHTTP 协议端(以 QQ 为例) + +单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 + +QQ 协议端举例: + +- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo)) +- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded) +- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai) +- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api) +- [OICQ-http-api](https://github.com/takayama-lily/onebot) (基于 [OICQ](https://github.com/takayama-lily/oicq)) + +这里以 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) 为例 + +1. 下载 go-cqhttp 对应平台的 release 文件,[点此前往](https://github.com/Mrs4s/go-cqhttp/releases) +2. 运行 exe 文件或者使用 `./go-cqhttp` 启动 +3. 生成默认配置文件并修改默认配置 + +```hjson{2,3,35-36,42} +{ + uin: 机器人QQ号 + password: 机器人密码 + encrypt_password: false + password_encrypted: "" + enable_db: true + access_token: "" + relogin: { + enabled: true + relogin_delay: 3 + max_relogin_times: 0 + } + _rate_limit: { + enabled: false + frequency: 1 + bucket_size: 1 + } + ignore_invalid_cqcode: false + force_fragmented: false + heartbeat_interval: 0 + http_config: { + enabled: false + host: "0.0.0.0" + port: 5700 + timeout: 0 + post_urls: {} + } + ws_config: { + enabled: false + host: "0.0.0.0" + port: 6700 + } + ws_reverse_servers: [ + { + enabled: true + reverse_url: ws://127.0.0.1:8080/cqhttp/ws + reverse_api_url: ws://you_websocket_api.server + reverse_event_url: ws://you_websocket_event.server + reverse_reconnect_interval: 3000 + } + ] + post_message_format: array + use_sso_address: false + debug: false + log_level: "" + web_ui: { + enabled: false + host: 127.0.0.1 + web_ui_port: 9999 + web_input: false + } +} +``` + +其中 `ws://127.0.0.1:8080/cqhttp/ws` 中的 `127.0.0.1` 和 `8080` 应分别对应 nonebot 配置的 HOST 和 PORT。 + +`cqhttp` 是前述 `register_adapter` 时传入的第一个参数,代表设置的 `CQHTTPBot` 适配器的路径,你可以对不同的适配器设置不同路径以作区别。 + +## 历史性的第一次对话 + +一旦新的配置文件正确生效之后,NoneBot 所在的控制台(如果正在运行的话)应该会输出类似下面的内容(两条访问日志): + +```default +09-14 21:31:16 [INFO] uvicorn | ('127.0.0.1', 12345) - "WebSocket /cqhttp/ws" [accepted] +09-14 21:31:16 [INFO] nonebot | WebSocket Connection from CQHTTP Bot 你的QQ号 Accepted! +``` + +这表示 CQHTTP 协议端已经成功地使用 CQHTTP 协议连接上了 NoneBot。 + +现在,尝试向你的机器人账号发送如下内容: + +```default +/echo 你好,世界 +``` + +到这里如果一切 OK,你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅! + + + + diff --git a/archive/2.0.0a9/guide/creating-a-handler.md b/archive/2.0.0a9/guide/creating-a-handler.md new file mode 100644 index 00000000..723aeeff --- /dev/null +++ b/archive/2.0.0a9/guide/creating-a-handler.md @@ -0,0 +1,197 @@ +# 事件处理 + +在上一章中,我们已经注册了事件响应器,现在我们可以正式编写事件处理逻辑了! + +## [事件处理函数](../api/typing.md#handler) + +```python{1,2,8,9} +@weather.handle() +async def handle_first_receive(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 + if args: + state["city"] = args # 如果用户发送了参数则直接赋值 + + +@weather.got("city", prompt="你想查询哪个城市的天气呢?") +async def handle_city(bot: Bot, event: Event, state: T_State): + city = state["city"] + if city not in ["上海", "北京"]: + await weather.reject("你想查询的城市暂不支持,请重新输入!") + city_weather = await get_weather(city) + await weather.finish(city_weather) +``` + +在之前的样例中,我们定义了两个函数 `handle_first_receive`, `handle_city`,他们被事件响应器的装饰器装饰从而成为事件响应器的事件处理函数。 + +:::tip 提示 +在事件响应器中,事件处理函数是**顺序**执行的! +::: + +### 添加一个事件处理函数 + +事件响应器提供了三种装饰事件处理函数的装饰器,分别是: + +1. [handle()](../api/matcher.md#classmethod-handle) +2. [receive()](../api/matcher.md#classmethod-receive) +3. [got(key, prompt, args_parser)](../api/matcher.md#classmethod-got-key-prompt-none-args-parser-none) + +#### handle() + +简单的为事件响应器添加一个事件处理函数,这个函数将会在上一个处理函数正常返回执行完毕后立即执行。 + +#### receive() + +指示 NoneBot 接收一条新的用户消息后继续执行该处理函数。此时函数将会接收到新的消息而非前一条消息,之前相关信息可以存储在 state 中。 + +特别的,当装饰的函数前没有其他事件处理函数,那么 `receive()` 不会接收一条新的消息而是直接使用第一条接收到的消息。 + +#### got(key, prompt, args_parser) + +指示 NoneBot 当 `state` 中不存在 `key` 时向用户发送 `prompt` 等待用户回复并赋值给 `state[key]`。 + +`prompt` 可以为 `str`, `Message`, `MessageSegment`,若为空则不会向用户发送,若不为空则会在 format 之后发送,即 `prompt.format(**state)`,注意对 `{}` 进行转义。示例: + +```python +@matcher.receive() +async def handle(bot: Bot, event: Event, state: T_State): + state["key"] = "hello" + + +@matcher.got("key2", prompt="{key}!") +async def handle2(bot: Bot, event: Event, state: T_State): + pass +``` + +`args_parser` 为参数处理函数,在这里传入一个新的函数以覆盖默认的参数处理。详情参照 [args_parser](#参数处理函数-args-parser) + +特别的,这些装饰器都可以套娃使用: + +```python +@matcher.got("key1") +@matcher.got("key2") +async def handle(bot: Bot, event: Event, state: T_State): + pass +``` + +### 事件处理函数参数 + +事件处理函数类型为: + +- `Callable[[Bot, Event, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]` + +简单说就是:除了 `bot` 参数,其他都是可选的。 + +以下函数都是合法的事件处理函数(仅列举常用的): + +```python +async def handle(bot: Bot, event: Event, state: T_State): + pass + +async def handle(bot: Bot, event: Event, state: T_State, matcher: Matcher): + pass + +async def handle(bot: Bot, event: Event): + pass + +async def handle(bot: Bot, state: T_State): + pass + +async def handle(bot: Bot): + pass +``` + +:::danger 警告 +函数的参数名固定不能修改! +::: + +参数分别为: + +1. [nonebot.adapters.Bot](../api/adapters/#class-bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。 +2. [nonebot.adapters.Event](../api/adapters/#class-event): 即上报事件对象,可以获取到上报的所有信息。 +3. [state](../api/typing.md#t-state): 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如: + +- `state["_current_key"]`: 存储当前 `got` 获取的参数名 +- `state["_prefix"]`, `state["_suffix"]`: 存储当前 TRIE 匹配的前缀/后缀,可以通过该值获取用户命令的原始命令 + +:::tip 提示 +NoneBot 会对不同类型的参数进行不同的操作,详情查看 [事件处理函数重载](../advanced/overloaded-handlers.md) +::: + +### 参数处理函数 args_parser + +在使用 `got` 获取用户输入参数时,需要对用户的消息进行处理以转换为我们所需要的信息。在默认情况下,NoneBot 会把用户的消息字符串原封不动的赋值给 `state[key]` 。可以通过以下两种方式修改默认处理逻辑: + +- `@matcher.args_parser` 装饰器:直接装饰一个函数作为参数处理器 +- `got(key, prompt, args_parser)`:直接把函数作为参数传入 + +参数处理函数类型为:`Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`,即: + +```python +async def parser(bot: Bot, event: Event, state: T_State): + state[state["_current_key"]] = str(event.get_message()) +``` + +特别的,`state["_current_key"]` 中存储了当前获取的参数名 + +### 逻辑控制 + +NoneBot 也为事件处理函数提供了一些便捷的逻辑控制函数: + +#### `matcher.send` + +这个函数用于发送一条消息给当前交互的用户。~~其实这并不是一个逻辑控制函数,只是不知道放在哪里……~~ + +#### `matcher.pause` + +这个函数用于结束当前事件处理函数,强制接收一条新的消息再运行**下一个消息处理函数**。 + +#### `matcher.reject` + +这个函数用于结束当前事件处理函数,强制接收一条新的消息再**再次运行当前消息处理函数**。常用于用户输入信息不符合预期。 + +#### `matcher.finish` + +这个函数用于直接结束当前事件处理。 + +以上三个函数都拥有一个参数 `message` / `prompt`,用于向用户发送一条消息。以及 `**kwargs` 直接传递给 `bot.send` 的额外参数。 + +## 常用事件处理结构 + +```python +matcher = on_command("test") + +# 修改默认参数处理 +@matcher.args_parser +async def parse(bot: Bot, event: Event, state: T_State): + print(state["_current_key"], ":", str(event.get_message())) + state[state["_current_key"]] = str(event.get_message()) + +@matcher.handle() +async def first_receive(bot: Bot, event: Event, state: T_State): + # 获取用户原始命令,如:/test + print(state["_prefix"]["raw_command"]) + # 处理用户输入参数,如:/test arg1 arg2 + raw_args = str(event.get_message()).strip() + if raw_args: + arg_list = raw_args.split() + # 将参数存入state以阻止后续再向用户询问参数 + state["arg1"] = arg_list[0] + + +@matcher.got("arg1", prompt="参数?") +async def arg_handle(bot: Bot, event: Event, state: T_State): + # 在这里对参数进行验证 + if state["arg1"] not in ["allow", "list"]: + await matcher.reject("参数不正确!请重新输入") + # 发送一些信息 + await bot.send(event, "message") + await matcher.send("message") + await matcher.finish("message") +``` diff --git a/archive/2.0.0a9/guide/creating-a-matcher.md b/archive/2.0.0a9/guide/creating-a-matcher.md new file mode 100644 index 00000000..ac74f6c1 --- /dev/null +++ b/archive/2.0.0a9/guide/creating-a-matcher.md @@ -0,0 +1,146 @@ +# 注册事件响应器 + +好了,现在插件已经创建完毕,我们可以开始编写实际代码了,下面将以一个简易单文件天气查询插件为例。 + +在插件目录下 `weather.py` 中添加如下代码: + +```python +from nonebot import on_command +from nonebot.rule import to_me +from nonebot.typing import T_State +from nonebot.adapters import Bot, Event + +weather = on_command("天气", rule=to_me(), priority=5) + + +@weather.handle() +async def handle_first_receive(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 + if args: + state["city"] = args # 如果用户发送了参数则直接赋值 + + +@weather.got("city", prompt="你想查询哪个城市的天气呢?") +async def handle_city(bot: Bot, event: Event, state: T_State): + city = state["city"] + if city not in ["上海", "北京"]: + await weather.reject("你想查询的城市暂不支持,请重新输入!") + city_weather = await get_weather(city) + await weather.finish(city_weather) + + +async def get_weather(city: str): + return f"{city}的天气是..." +``` + +为了简单起见,我们在这里的例子中没有接入真实的天气数据,但要接入也非常简单,你可以使用中国天气网、和风天气等网站提供的 API。 + +接下来我们来说明这段代码是如何工作的。 + +:::tip 提示 +从这里开始,你需要对 Python 的 asyncio 编程有所了解,因为 NoneBot 是完全基于 asyncio 的,具体可以参考 [廖雪峰的 Python 教程](https://www.liaoxuefeng.com/wiki/1016959663602400/1017959540289152) +::: + +## [事件响应器](../api/matcher.md) + +```python{5} +from nonebot import on_command +from nonebot.rule import to_me +from nonebot.permission import Permission + +weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5) +``` + +在上方代码中,我们注册了一个事件响应器 `Matcher`,它由几个部分组成: + +1. `on_command` 注册一个消息类型的命令处理器 +2. `"天气"` 指定 command 参数 - 命令名 +3. `rule` 补充事件响应器的匹配规则 +4. `priority` 事件响应器优先级 +5. `block` 是否阻止事件传递 + +其他详细配置可以参考 API 文档,下面我们详细说明各个部分: + +### 事件响应器类型 type + +事件响应器类型其实就是对应事件的类型 `Event.get_type()` ,NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些其他内置的事件响应器。 + +以下所有类型的事件响应器都是由 `on(type, rule)` 的形式进行了简化封装。 + +- `on("事件类型")`: 基础事件响应器,第一个参数为事件类型,空字符串表示不限 +- `on_metaevent()` ~ `on("meta_event")`: 元事件响应器 +- `on_message()` ~ `on("message")`: 消息事件响应器 +- `on_request()` ~ `on("request")`: 请求事件响应器 +- `on_notice()` ~ `on("notice")`: 通知事件响应器 +- `on_startswith(str)` ~ `on("message", startswith(str))`: 消息开头匹配响应器,参考 [startswith](../api/rule.md#startswith-msg) +- `on_endswith(str)` ~ `on("message", endswith(str))`: 消息结尾匹配响应器,参考 [endswith](../api/rule.md#endswith-msg) +- `on_keyword(set)` ~ `on("message", keyword(str))`: 消息关键词匹配响应器,参考 [keyword](../api/rule.md#keyword-keywords) +- `on_command(str|tuple)` ~ `on("message", command(str|tuple))`: 命令响应器,参考 [command](../api/rule.md#command-cmds) +- `on_regex(pattern_str)` ~ `on("message", regex(pattern_str))`: 正则匹配处理器,参考 [regex](../api/rule.md#regex-regex-flags-0) + +### 匹配规则 rule + +事件响应器的匹配规则即 `Rule`,详细内容在下方介绍。[直达](#自定义-rule) + +### 优先级 priority + +事件响应器的优先级代表事件响应器的执行顺序,同一优先级的事件响应器会 **同时执行!**,优先级数字**越小**越先响应!优先级请从 `1` 开始排序! + +:::tip 提示 +使用 `nonebot-plugin-test` 可以在网页端查看当前所有事件响应器的执行流程,有助理解事件响应流程! + +```bash +nb plugin install nonebot_plugin_test +``` + +::: + +### 阻断 block + +当有任意事件响应器发出了阻止事件传递信号时,该事件将不再会传递给下一优先级,直接结束处理。 + +NoneBot 内置的事件响应器中,所有 `message` 类的事件响应器默认会阻断事件传递,其他则不会。 + +## 自定义 rule + +rule 的出现使得 nonebot 对事件的响应可以非常自由,nonebot 内置了一些规则: + +- [startswith(msg)](../api/rule.md#startswith-msg) +- [endswith(msg)](../api/rule.md#endswith-msg) +- [keyword(\*keywords)](../api/rule.md#keyword-keywords) +- [command(\*cmds)](../api/rule.md#command-cmds) +- [regex(regex, flag)](../api/rule.md#regex-regex-flags-0) + +以上规则都是返回类型为 `Rule` 的函数,`Rule` 由非负个 `RuleChecker` 组成,当所有 `RuleChecker` 返回 `True` 时匹配成功。这些 `Rule`, `RuleChecker` 的形式如下: + +```python +from nonebot.rule import Rule +from nonebot.typing import T_State + +async def async_checker(bot: Bot, event: Event, state: T_State) -> bool: + return True + +def sync_checker(bot: Bot, event: Event, state: T_State) -> bool: + return True + +def check(arg1, args2): + + async def _checker(bot: Bot, event: Event, state: T_State) -> bool: + return bool(arg1 + arg2) + + return Rule(_checker) +``` + +`Rule` 和 `RuleChecker` 之间可以使用 `与 &` 互相组合: + +```python +from nonebot.rule import Rule + +Rule(async_checker1) & sync_checker & async_checker2 +``` + +**_请勿将事件处理的逻辑写入 `rule` 中,这会使得事件处理返回奇怪的响应。_** + +:::danger 警告 +`Rule(*checkers)` 只接受 async function,或使用 `nonebot.utils.run_sync` 自行包裹 sync function。在使用 `与 &` 时,NoneBot 会自动包裹 sync function +::: diff --git a/archive/2.0.0a9/guide/creating-a-plugin.md b/archive/2.0.0a9/guide/creating-a-plugin.md new file mode 100644 index 00000000..5ce12a28 --- /dev/null +++ b/archive/2.0.0a9/guide/creating-a-plugin.md @@ -0,0 +1,119 @@ +# 创建插件 + +如果之前使用 `nb-cli` 生成了项目结构,那我们已经有了一个空的插件目录 `Awesome-Bot/awesome_bot/plugins`,并且它已在 `bot.py` 中被加载,我们现在可以开始创建插件了! + +使用 `nb-cli` 创建包形式插件,或自行创建文件(夹) + +```bash +nb plugin new +``` + +插件通常有两种形式,下面分别介绍 + +## 单文件形式 + +在插件目录下创建名为 `foo.py` 的 Python 文件,暂时留空,此时目录结构如下: + + +:::vue +AweSome-Bot +├── awesome_bot +│ └── plugins +│ └── `foo.py` +├── .env +├── .env.dev +├── .env.prod +├── .gitignore +├── bot.py +├── docker-compose.yml +├── Dockerfile +├── pyproject.toml +└── README.md +::: + + +这个时候它已经可以被称为一个插件了,尽管它还什么都没做。 + +## 包形式(推荐) + +在插件目录下创建文件夹 `foo`,并在该文件夹下创建文件 `__init__.py`,此时目录结构如下: + + +:::vue +AweSome-Bot +├── awesome_bot +│ └── plugins +│ └── `foo` +│ └── `__init__.py` +├── .env +├── .env.dev +├── .env.prod +├── .gitignore +├── bot.py +├── docker-compose.yml +├── Dockerfile +├── pyproject.toml +└── README.md +::: + + +这个时候 `foo` 就是一个合法的 Python 包了,同时也是合法的 NoneBot 插件,插件内容可以在 `__init__.py` 中编写。 + +### 推荐结构(仅供参考) + + +:::vue +foo +├── `__init__.py` +├── `config.py` +├── `data_source.py` +└── `model.py` +::: + + +#### \_\_init\_\_.py + +在该文件中编写各类事件响应及处理逻辑。 + +#### config.py + +在该文件中使用 `pydantic` 定义插件所需要的配置项以及类型。 + +示例: + +```python +from pydantic import BaseSettings + + +class Config(BaseSettings): + + # plugin custom config + plugin_setting: str = "default" + + class Config: + extra = "ignore" +``` + +并在 `__init__.py` 文件中添加以下行 + +```python +import nonebot +from .config import Config + +global_config = nonebot.get_driver().config +plugin_config = Config(**global_config.dict()) +``` + +此时就可以通过 `plugin_config.plugin_setting` 获取到插件所需要的配置项了。 + +#### data_source.py + +在该文件中编写数据获取函数。 + +:::warning 警告 +数据获取应尽量使用**异步**处理!例如使用 [httpx](https://www.python-httpx.org/) 而非 [requests](https://requests.readthedocs.io/en/master/) +::: + +#### model.py + +在该文件中编写数据库模型。 diff --git a/archive/2.0.0a9/guide/creating-a-project.md b/archive/2.0.0a9/guide/creating-a-project.md new file mode 100644 index 00000000..5933b5fa --- /dev/null +++ b/archive/2.0.0a9/guide/creating-a-project.md @@ -0,0 +1,51 @@ +# 创建一个完整的项目 + +上一章中我们已经运行了一个简单的 NoneBot 实例,在这一章,我们将从零开始一个完整的项目。 + +## 目录结构 + +可以使用 `nb-cli` 或者自行创建完整的项目目录: + +```bash +nb create +``` + + +:::vue +AweSome-Bot +├── `awesome_bot` _(**或是 src**)_ +│ └── `plugins` +├── `.env` _(**可选的**)_ +├── `.env.dev` _(**可选的**)_ +├── `.env.prod` _(**可选的**)_ +├── .gitignore +├── `bot.py` +├── docker-compose.yml +├── Dockerfile +├── `pyproject.toml` +└── README.md +::: + + +- `awesome_bot/plugins` 或 `src/plugins`: 用于存放编写的 bot 插件 +- `.env`, `.env.dev`, `.env.prod`: 各环境配置文件 +- `bot.py`: bot 入口文件 +- `pyproject.toml`: 项目依赖管理文件,默认使用 [poetry](https://python-poetry.org/) + +## 启动 Bot + +如果你使用 `nb-cli` + +```bash +nb run [--file=bot.py] [--app=app] +``` + +或者使用 + +```bash +python bot.py +``` + +:::tip 提示 +如果在 bot 入口文件内定义了 asgi server, `nb-cli` 将会为你启动**冷重载模式** +::: diff --git a/archive/2.0.0a9/guide/ding-guide.md b/archive/2.0.0a9/guide/ding-guide.md new file mode 100644 index 00000000..c23c6827 --- /dev/null +++ b/archive/2.0.0a9/guide/ding-guide.md @@ -0,0 +1,119 @@ +# 钉钉机器人使用指南 + +基于企业机器人的outgoing(回调)机制,用户@机器人之后,钉钉会将消息内容POST到开发者的消息接收地址。开发者解析出消息内容、发送者身份,根据企业的业务逻辑,组装响应的消息内容返回,钉钉会将响应内容发送到群里。 + +::: warning 只有企业内部机器人支持接收消息 +普通的机器人尚不支持应答机制,该机制指的是群里成员在聊天@机器人的时候,钉钉回调指定的服务地址,即Outgoing机器人。 +::: + +首先你需要有钉钉机器人的相关概念,请参阅相关文档: + +- [群机器人概述](https://developers.dingtalk.com/document/app/overview-of-group-robots) +- [开发企业内部机器人](https://developers.dingtalk.com/document/app/develop-enterprise-internal-robots) + +## 关于 DingAdapter 的说明 + +你需要显式的注册 ding 这个适配器: + +```python{2,6} +import nonebot +from nonebot.adapters.ding import Bot as DingBot + +nonebot.init() +driver = nonebot.get_driver() +driver.register_adapter("ding", DingBot) +nonebot.load_builtin_plugins() + +if __name__ == "__main__": + nonebot.run() +``` + +注册适配器的目的是将 `/ding` 这个路径挂载到程序上,并且和 DingBot 适配器关联起来。之后钉钉把收到的消息回调到 `http://xx.xxx.xxx.xxx:{port}/ding` 时,Nonebot 才知道要用什么适配器去处理该消息。 + +## 第一个命令 + +因为 Nonebot 可以根据你的命令处理函数的类型注解来选择使用什么 Adapter 进行处理,所以你如果需要使用钉钉相关的功能,你的 handler 中 `bot` 类型的注解需要是 DingBot 及其父类。 + +对于 Event 来说也是如此,Event 也可以根据标注来判断,比如一个 handler 的 event 标注位 `PrivateMessageEvent`,那这个 handler 只会处理私聊消息。 + +举个栗子: + +```python +test = on_command("test", to_me()) + + +@test.handle() +async def test_handler1(bot: DingBot, event: PrivateMessageEvent): + await test.finish("PrivateMessageEvent") + + +@test.handle() +async def test_handler2(bot: DingBot, event: GroupMessageEvent): + await test.finish("GroupMessageEvent") +``` + +这样 Nonebot 就会根据不同的类型注解使用不同的 handler 来处理消息。 + +可以查看 Nonebot 官方的这个例子:,更详细的了解一个 Bot 的结构。 + +## 多种消息格式 + +发送 markdown 消息: + +```python +@markdown.handle() +async def markdown_handler(bot: DingBot): + message = MessageSegment.markdown( + "Hello, This is NoneBot", + "#### NoneBot \n> Nonebot 是一款高性能的 Python 机器人框架\n> ![screenshot](https://v2.nonebot.dev/logo.png)\n> [GitHub 仓库地址](https://github.com/nonebot/nonebot2) \n" + ) + await markdown.finish(message) +``` + +可以按自己的需要发送原生的格式消息(需要使用 `MessageSegment` 包裹,可以很方便的实现 @ 等操作): + +```python +@raw.handle() +async def raw_handler(bot: DingBot, event: MessageEvent): + message = MessageSegment.raw({ + "msgtype": "text", + "text": { + "content": f"@{event.senderId},你好" + }, + }) + message += MessageSegment.atDingtalkIds(event.senderId) + await raw.send(message) +``` + +其他消息格式请查看 [钉钉适配器的 MessageSegment](https://github.com/nonebot/nonebot2/blob/dev/nonebot/adapters/ding/message.py#L8),里面封装了很多有关消息的方法,比如 `code`、`image`、`feedCard` 等。 + +## 创建机器人并连接 + +在钉钉官方文档 [「开发企业内部机器人 -> 步骤一:创建机器人应用」](https://developers.dingtalk.com/document/app/develop-enterprise-internal-robots/title-ufs-4gh-poh) 中有详细介绍,这里就省去创建的步骤,介绍一下如何连接上程序。 + +### 本地开发机器人 + +在本地开发机器人的时候可能没有公网 IP,钉钉官方给我们提供一个 [内网穿透工具](https://developers.dingtalk.com/document/resourcedownload/http-intranet-penetration?pnamespace=app),方便开发测试。 + +::: tip +究其根源这是一个魔改版的 ngrok,钉钉提供了一个服务器。 + +本工具不保证稳定性,仅适用于开发测试阶段,禁止当作公网域名使用。如线上应用使用本工具造成稳定性问题,后果由自己承担。如使用本工具传播违法不良信息,钉钉将追究法律责任。 +::: + +官方文档里已经讲了如何使用。我们再以 Windows(终端使用 Powershell) 为例,来演示一下。 + +1. 将仓库 clone 到本地,打开 `windows_64` 文件夹。 +2. 执行 `.\ding.exe -config="./ding.cfg" -subdomain=rcnb 8080` 就可以将 8080 端口暴露到公网中。 + 你访问 都会映射到 。 + +假设我们的机器人监听的端口是 `2333`,并且已经注册了钉钉适配器。那我们就执行 `.\ding.exe -config="./ding.cfg" -subdomain=rcnb 2333`,然后在机器人的后台设置 POST 的地址:`http://rcnb.vaiwan.com/ding`。 +这样钉钉接收到消息之后就会 POST 消息到 `http://rcnb.vaiwan.com/ding` 上,然后这个服务会把消息再转发到我们本地的开发服务器上。 + +### 生产模式 + +生产模式你的机器需要有一个公网 IP,然后到机器人的后台设置 POST 的地址就好了。 + +## 示例 + +关于钉钉机器人能做啥,你可以查看 `https://github.com/nonebot/nonebot2/blob/dev/tests/test_plugins/test_ding.py`,里面有一些例子。 diff --git a/archive/2.0.0a9/guide/end-or-start.md b/archive/2.0.0a9/guide/end-or-start.md new file mode 100644 index 00000000..9587c4bb --- /dev/null +++ b/archive/2.0.0a9/guide/end-or-start.md @@ -0,0 +1,9 @@ +# 结语 + +至此,相信你已经能够写出一个基础的插件了。这里给出几个小提示: + +- 请千万注意事件处理器的优先级设定 +- 在匹配规则中请勿使用耗时极长的函数 +- 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍) + +如果「指南」还不能满足你,前往 [进阶](../advanced/README.md) 查看更多的功能信息。 diff --git a/archive/2.0.0a9/guide/getting-started.md b/archive/2.0.0a9/guide/getting-started.md new file mode 100644 index 00000000..edb898a3 --- /dev/null +++ b/archive/2.0.0a9/guide/getting-started.md @@ -0,0 +1,87 @@ +# 开始使用 + +一切都安装成功后,你就已经做好了进行简单配置以运行一个最小的 NoneBot 实例的准备。 + +## 最小实例 + +如果你已经按照推荐方式安装了 `nb-cli`,使用脚手架创建一个空项目: + +```bash +nb create +``` + +根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`。 + +如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下(这里以 CQHTTP 适配器为例): + +```python{4,6,7,10} +import nonebot +from nonebot.adapters.cqhttp import Bot as CQHTTPBot + +nonebot.init() +driver = nonebot.get_driver() +driver.register_adapter("cqhttp", CQHTTPBot) +nonebot.load_builtin_plugins() + +if __name__ == "__main__": + nonebot.run() +``` + +## 解读 + +在上方 `bot.py` 中,这几行高亮代码将依次: + +1. 使用默认配置初始化 NoneBot +2. 加载 NoneBot 内置的 CQHTTP 协议适配组件 + `register_adapter` 的第一个参数我们传入了一个字符串,该字符串将会在后文 [配置 CQHTTP 协议端](#配置-cqhttp-协议端-以-qq-为例) 时使用。 +3. 加载 NoneBot 内置的插件 +4. 在地址 `127.0.0.1:8080` 运行 NoneBot + +在命令行使用如下命令即可运行这个 NoneBot 实例: + +```bash +# nb-cli +nb run +# 其他 +python bot.py +``` + +运行后会产生如下日志: + +```plain +09-14 21:02:00 [INFO] nonebot | Succeeded to import "nonebot.plugins.base" +09-14 21:02:00 [INFO] nonebot | Running NoneBot... +09-14 21:02:00 [INFO] uvicorn | Started server process [1234] +09-14 21:02:00 [INFO] uvicorn | Waiting for application startup. +09-14 21:02:00 [INFO] uvicorn | Application startup complete. +09-14 21:02:00 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit) +``` + +## 配置协议端上报 + +在 `bot.py` 文件中使用 `register_adapter` 注册协议适配之后即可配置协议端来完成与 NoneBot 的通信,详细配置方法参考: + +- [配置 CQHTTP](./cqhttp-guide.md) +- [配置钉钉](./ding-guide.md) +- [配置 mirai-api-http](./mirai-guide.md) + +NoneBot 接受的上报地址与 `Driver` 有关,默认使用的 `FastAPI Driver` 所接受的上报地址有: + +- `/{adapter name}/`: HTTP POST 上报 +- `/{adapter name}/http/`: HTTP POST 上报 +- `/{adapter name}/ws`: WebSocket 上报 +- `/{adapter name}/ws/`: WebSocket 上报 + +:::warning 注意 +如果到这一步你没有在 NoneBot 看到连接成功日志,比较常见的出错点包括: + +- NoneBot 监听 `0.0.0.0`,然后在协议端上报配置中填了 `ws://0.0.0.0:8080/***/ws` +- 在 Docker 容器内运行协议端,并通过 `127.0.0.1` 访问宿主机上的 NoneBot +- 想从公网访问,但没有修改云服务商的安全组策略或系统防火墙 +- NoneBot 所监听的端口存在冲突,已被其它程序占用 +- 弄混了 NoneBot 的 `host`、`port` 参数与协议端上报配置中的 `host`、`port` 参数 +- `ws://` 错填为 `http://` +- 协议端或 NoneBot 启动时遭到外星武器干扰 + +请尝试重启协议端 NoneBot、更换端口、修改防火墙、重启系统、仔细阅读前面的文档及提示、更新协议端 和 NoneBot 到最新版本等方式来解决。 +::: diff --git a/archive/2.0.0a9/guide/installation.md b/archive/2.0.0a9/guide/installation.md new file mode 100644 index 00000000..b56da782 --- /dev/null +++ b/archive/2.0.0a9/guide/installation.md @@ -0,0 +1,97 @@ +# 安装 + +## NoneBot + +:::warning 注意 +请确保你的 Python 版本 >= 3.7。 +::: + +:::warning 注意 +请在安装 nonebot2 之前卸载 nonebot 1.x + +```bash +pip uninstall nonebot +``` + +::: + +### 通过脚手架安装(推荐安装方式) + +1. (推荐)使用你喜欢的 Python 环境管理工具(如 `poetry`)创建新的虚拟环境。 +2. 使用 `pip` (或其他包管理工具) 安装 nb-cli,nonebot2 作为其依赖会一起被安装。 + + ```bash + pip install nb-cli + ``` + +3. 点个 star 吧 + + nonebot2: [![nb-cli](https://img.shields.io/github/stars/nonebot/nonebot2?style=social)](https://github.com/nonebot/nonebot2) + + nb-cli: [![nb-cli](https://img.shields.io/github/stars/nonebot/nb-cli?style=social)](https://github.com/nonebot/nb-cli) + +4. 如果有疑问,可以加群交流 (点击链接直达) + + [![QQ Chat](https://img.shields.io/badge/QQ%E7%BE%A4-768887710-orange?style=social)](https://jq.qq.com/?_wv=1027&k=5OFifDh) + + [![Telegram Chat](https://img.shields.io/badge/telegram-cqhttp-blue?style=social)](https://t.me/cqhttp) + +### 不使用脚手架(纯净安装) + +```bash +pip install nonebot2 +# 也可以通过 poetry 安装 +poetry add nonebot2 +``` + +如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 GitHub 仓库安装: + +:::warning 注意 +直接从 Github 仓库中安装意味着你将使用最新提交的代码,它们并没有进行充分的稳定性测试 +在任何情况下请不要将其应用于生产环境! +::: + +```bash +# master分支 +poetry add git+https://github.com/nonebot/nonebot2.git#master +# dev分支 +poetry add git+https://github.com/nonebot/nonebot2.git#dev +``` + +或者在克隆 Git 仓库后手动安装: + +```bash +git clone https://github.com/nonebot/nonebot2.git +cd nonebot2 +poetry install --no-dev # 推荐 +pip install . # 不推荐 +``` + +## 安装插件 + +插件可以通过 `nb-cli` 进行安装,也可以自行安装并加载插件。 + +```bash +# 列出所有的插件 +nb plugin list +# 搜索插件 +nb plugin search xxx +# 安装插件 +nb plugin install xxx +``` + +如果急于上线 Bot 或想要使用现成的插件,以下插件可作为参考: + +### 官方插件 + +~~自用插件~~ ~~确信~~ + +- [NoneBot-Plugin-Docs](https://github.com/nonebot/nonebot2/tree/master/packages/nonebot-plugin-docs) 离线文档插件 +- [NoneBot-Plugin-Test](https://github.com/nonebot/plugin-test) 本地机器人测试前端插件 +- [NoneBot-Plugin-APScheduler](https://github.com/nonebot/plugin-apscheduler) 定时任务插件 +- [NoneBot-Plugin-Sentry](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_sentry) Sentry 在线日志分析插件 +- [NoneBot-Plugin-Status](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_status) 服务器状态查看插件 + +### 其他插件 + +还有更多的插件在 [这里](/plugin-store.md) 等着你发现~ diff --git a/archive/2.0.0a9/guide/loading-a-plugin.md b/archive/2.0.0a9/guide/loading-a-plugin.md new file mode 100644 index 00000000..f026bbe0 --- /dev/null +++ b/archive/2.0.0a9/guide/loading-a-plugin.md @@ -0,0 +1,116 @@ +# 加载插件 + +在 [创建一个完整的项目](creating-a-project) 一章节中,我们已经创建了插件目录 `awesome_bot/plugins`,现在我们在机器人入口文件中加载它。当然,你也可以单独加载一个插件。 + +## 加载内置插件 + +在 `bot.py` 文件中添加以下行: + +```python{5} +import nonebot + +nonebot.init() +# 加载 nonebot 内置插件 +nonebot.load_builtin_plugins() + +app = nonebot.get_asgi() + +if __name__ == "__main__": + nonebot.run() +``` + +这将会加载 nonebot 内置的插件,它包含: + +- 命令 `say`:可由**superuser**使用,可以将消息内容由特殊纯文本转为富文本 +- 命令 `echo`:可由任何人使用,将消息原样返回 + +以上命令均需要指定机器人,即私聊、群聊内@机器人、群聊内称呼机器人昵称。参考 [Rule: to_me](../api/rule.md#to-me) + +## 加载插件目录 + +在 `bot.py` 文件中添加以下行: + +```python{5} +import nonebot + +nonebot.init() +# 加载插件目录,该目录下为各插件,以下划线开头的插件将不会被加载 +nonebot.load_plugins("awesome_bot/plugins") + +app = nonebot.get_asgi() + +if __name__ == "__main__": + nonebot.run() +``` + +:::tip 提示 +加载插件目录时,目录下以 `_` 下划线开头的插件将不会被加载! +::: + +:::warning 提示 +**不能存在相同名称的插件!** +::: + +:::danger 警告 +插件间不应该存在过多的耦合,如果确实需要导入某个插件内的数据,可以参考 [进阶-跨插件访问](../advanced/export-and-require.md) +::: + +## 加载单个插件 + +在 `bot.py` 文件中添加以下行: + +```python{5,7} +import nonebot + +nonebot.init() +# 加载一个 pip 安装的插件 +nonebot.load_plugin("nonebot_plugin_status") +# 加载本地的单独插件 +nonebot.load_plugin("awesome_bot.plugins.xxx") + +app = nonebot.get_asgi() + +if __name__ == "__main__": + nonebot.run() +``` + +## 子插件(嵌套插件) + +在插件中同样可以加载子插件,例如如下插件目录结构: + + +:::vue +foo_plugin +├── `plugins` +│ ├── `sub_plugin1` +│ │ └── \_\_init\_\_.py +│ └── `sub_plugin2.py` +├── `__init__.py` +└── config.py +::: + + +在插件目录下的 `__init__.py` 中添加如下代码: + +```python +from pathlib import Path + +import nonebot + +# store all subplugins +_sub_plugins = set() +# load sub plugins +_sub_plugins |= nonebot.load_plugins( + str((Path(__file__).parent / "plugins").resolve())) +``` + +插件将会被加载并存储于 `_sub_plugins` 中。 + +## 运行结果 + +尝试运行 `nb run` 或者 `python bot.py`,可以看到日志输出了类似如下内容: + +```plain +09-19 21:51:59 [INFO] nonebot | Succeeded to import "nonebot.plugins.base" +09-19 21:51:59 [INFO] nonebot | Succeeded to import "plugin_in_folder" +``` diff --git a/archive/2.0.0a9/guide/mirai-guide.md b/archive/2.0.0a9/guide/mirai-guide.md new file mode 100644 index 00000000..bd11083c --- /dev/null +++ b/archive/2.0.0a9/guide/mirai-guide.md @@ -0,0 +1,195 @@ +# Mirai-API-HTTP 协议使用指南 + +::: warning + +Mirai-API-HTTP 的适配现在仍然处于早期阶段, 可能没有进行过充分的测试 + +请在生产环境中谨慎使用 + +::: + +::: tip + +为了你的使用之旅更加顺畅, 我们建议您在配置之前具有以下的前置知识 + +- 对服务端/客户端(C/S)模型的基本了解 +- 对 Web 服务配置基础的认知 +- 对`YAML`语法的一点点了解 + +::: + +::: danger + +Mirai-API-HTTP 的适配器以 [AGPLv3 许可](https://opensource.org/licenses/AGPL-3.0) 单独开源 + +这意味着在使用该适配器时需要 **以该许可开源您的完整程序代码** + +::: + +**为了便捷起见, 以下内容均以缩写 `MAH` 代替 `mirai-api-http`** + +## 配置 MAH 客户端 + +正如你可能刚刚在[CQHTTP 协议使用指南](./cqhttp-guide.md)中所读到的: + +> 单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 + +这次, 我们将采用在实现上有别于 onebot即 CQHTTP协议的另外一种无头 QQ API 协议, 即 MAH + +为了配置 MAH 端, 我们现在需要移步到[MAH 的项目地址](https://github.com/project-mirai/mirai-api-http), 来看看它是如何配置的 + +根据[项目提供的 README](https://github.com/project-mirai/mirai-api-http/blob/056beedba31d6ad06426997a1d3fde861a7f8ba3/README.md),配置 MAH 大概需要以下几步 + +1. 下载并安装 Java 运行环境, 你可以有以下几种选择: + + - [由 Oracle 提供的 Java 运行环境](https://java.com/zh-CN/download/manual.jsp) **在没有特殊需求的情况下推荐** + - [由 Zulu 编译的 OpenJRE 环境](https://www.azul.com/downloads/zulu-community/?version=java-8-lts&architecture=x86-64-bit&package=jre) + +2. 下载[Mirai Console Loader](https://github.com/iTXTech/mirai-console-loader) + + - 请按照文档 README 中的步骤下载并安装 + +3. 安装 MAH: + + - 在 Mirai Console Loader 目录下执行该指令 + + - ```shell + ./mcl --update-package net.mamoe:mirai-api-http --channel stable --type plugin + ``` + + 注意: 该指令的前缀`./mcl`可能根据操作系统以及使用 java 环境的不同而变化 + +4. 修改配置文件 + + ::: tip + + 在此之前, 你可能需要了解我们为 MAH 设计的两种通信方式 + + - 正向 Websocket + - NoneBot 作为纯粹的客户端,通过 websocket 监听事件下发 + - 优势 + 1. 网络配置简单, 特别是在使用 Docker 等网络隔离的容器时 + 2. 在初步测试中连接性较好 + - 劣势 + 1. 与 NoneBot 本身的架构不同, 可能稳定性较差 + 2. 需要在注册 adapter 时显式指定 qq, 对于需要开源的程序来讲不利 + - POST 消息上报 + - NoneBot 在接受消息上报时作为服务端, 发送消息时作为客户端 + - 优势 + 1. 与 NoneBot 本身架构相符, 性能和稳定性较强 + 2. 无需在任何地方指定 QQ, 即插即用 + - 劣势 + 1. 由于同时作为客户端和服务端, 配置较为复杂 + 2. 在测试中网络连接性较差 (未确认原因) + + ::: + + - 这是当使用正向 Websocket 时的配置举例 + + - MAH 的`setting.yml`文件 + + - ```yaml + # 省略了部分无需修改的部分 + + host: "0.0.0.0" # 监听地址 + port: 8080 # 监听端口 + authKey: 1234567890 # 访问密钥, 最少八位 + enableWebsocket: true # 必须为true + ``` + + - `.env`文件 + + - ```shell + MIRAI_AUTH_KEY=1234567890 + MIRAI_HOST=127.0.0.1 # 当MAH运行在本机时 + MIRAI_PORT=8080 # MAH的监听端口 + ``` + + - `bot.py`文件 + + - ```python + import nonebot + from nonebot.adapters.mirai import WebsocketBot + + nonebot.init() + nonebot.get_driver().register_adapter('mirai-ws', WebsocketBot, qq=12345678) # qq参数需要填在mah中登录的qq + nonebot.load_builtin_plugins() # 加载 nonebot 内置插件 + nonebot.run() + ``` + + - 这是当使用 POST 消息上报时的配置文件 + + - MAH 的`setting.yml`文件 + + - ```yaml + # 省略了部分无需修改的部分 + + host: '0.0.0.0' # 监听地址 + port: 8080 # 监听端口 + authKey: 1234567890 # 访问密钥, 最少八位 + + ## 消息上报 + report: + enable: true # 必须为true + groupMessage: + report: true # 群消息上报 + friendMessage: + report: true # 好友消息上报 + tempMessage: + report: true # 临时会话上报 + eventMessage: + report: true # 事件上报 + destinations: + - 'http://127.0.0.1:2333/mirai/http' #上报地址, 请按照实际情况修改 + # 上报时的额外Header + extraHeaders: {} + ``` + + - `.env`文件 + + - ```shell + HOST=127.0.0.1 # 当MAH运行在本机时 + PORT=2333 + + MIRAI_AUTH_KEY=1234567890 + MIRAI_HOST=127.0.0.1 # 当MAH运行在本机时 + MIRAI_PORT=8080 # MAH的监听端口 + ``` + + - `bot.py`文件 + + - ```python + import nonebot + from nonebot.adapters.mirai import Bot + + nonebot.init() + nonebot.get_driver().register_adapter('mirai', Bot) + nonebot.load_builtin_plugins() # 加载 nonebot 内置插件 + nonebot.run() + ``` + +## 历史性的第一次对话 + +现在, 先启动 NoneBot, 再启动 MAH + +如果你的配置文件一切正常, 你将在控制台看到类似于下列的日志 + +```log +02-01 18:25:12 [INFO] nonebot | NoneBot is initializing... +02-01 18:25:12 [INFO] nonebot | Current Env: prod +02-01 18:25:12 [DEBUG] nonebot | Loaded Config: {'driver': 'nonebot.drivers.fastapi', 'host': IPv4Address('127.0.0.1'), 'port': 8080, 'debug': True, 'api_root': {}, 'api_timeout': 30.0, 'access_token': None, 'secret': None, 'superusers': set(), 'nickname': set(), 'command_start': {'/'}, 'command_sep': {'.'}, 'session_expire_timeout': datetime.timedelta(seconds=120), 'mirai_port': 8080, 'environment': 'prod', 'mirai_auth_key': 12345678, 'mirai_host': '127.0.0.1'} +02-01 18:25:12 [DEBUG] nonebot | Succeeded to load adapter "mirai" +02-01 18:25:12 [INFO] nonebot | Succeeded to import "nonebot.plugins.echo" +02-01 18:25:12 [INFO] nonebot | Running NoneBot... +02-01 18:25:12 [DEBUG] nonebot | Loaded adapters: mirai +02-01 18:25:12 [INFO] uvicorn | Started server process [183155] +02-01 18:25:12 [INFO] uvicorn | Waiting for application startup. +02-01 18:25:12 [INFO] uvicorn | Application startup complete. +02-01 18:25:12 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:2333 (Press CTRL+C to quit) +02-01 18:25:14 [INFO] uvicorn | 127.0.0.1:37794 - "POST /mirai/http HTTP/1.1" 204 +02-01 18:25:14 [DEBUG] nonebot | MIRAI | received message {'type': 'BotOnlineEvent', 'qq': 1234567} +02-01 18:25:14 [INFO] nonebot | MIRAI 1234567 | [BotOnlineEvent]: {'self_id': 1234567, 'type': 'BotOnlineEvent', 'qq': 1234567} +02-01 18:25:14 [DEBUG] nonebot | Checking for matchers in priority 1... +``` + +恭喜你, 你的配置已经成功! diff --git a/archive/2.0.0a9/sidebar.config.json b/archive/2.0.0a9/sidebar.config.json new file mode 100644 index 00000000..5498d089 --- /dev/null +++ b/archive/2.0.0a9/sidebar.config.json @@ -0,0 +1,176 @@ +{ + "sidebar": {}, + "locales": { + "/": { + "label": "简体中文", + "selectText": "Languages", + "editLinkText": "在 GitHub 上编辑此页", + "lastUpdated": "上次更新", + "nav": [ + { + "text": "主页", + "link": "/" + }, + { + "text": "指南", + "link": "/guide/" + }, + { + "text": "进阶", + "link": "/advanced/" + }, + { + "text": "API", + "link": "/api/" + }, + { + "text": "插件广场", + "link": "/plugin-store" + }, + { + "text": "更新日志", + "link": "/changelog" + } + ], + "sidebarDepth": 2, + "sidebar": { + "/guide/": [ + { + "title": "开始", + "collapsable": false, + "sidebar": "auto", + "children": [ + "", + "installation", + "getting-started", + "creating-a-project", + "basic-configuration" + ] + }, + { + "title": "编写插件", + "collapsable": false, + "sidebar": "auto", + "children": [ + "loading-a-plugin", + "creating-a-plugin", + "creating-a-matcher", + "creating-a-handler", + "end-or-start" + ] + }, + { + "title": "协议适配", + "collapsable": false, + "sidebar": "auto", + "children": [ + "cqhttp-guide", + "ding-guide", + "mirai-guide" + ] + } + ], + "/advanced/": [ + { + "title": "进阶", + "collapsable": false, + "sidebar": "auto", + "children": [ + "", + "scheduler", + "permission", + "runtime-hook", + "export-and-require", + "overloaded-handlers" + ] + }, + { + "title": "发布", + "collapsable": false, + "sidebar": "auto", + "children": [ + "publish-plugin" + ] + } + ], + "/api/": [ + { + "title": "NoneBot Api Reference", + "path": "", + "collapsable": false, + "children": [ + { + "title": "nonebot 模块", + "path": "nonebot" + }, + { + "title": "nonebot.config 模块", + "path": "config" + }, + { + "title": "nonebot.plugin 模块", + "path": "plugin" + }, + { + "title": "nonebot.message 模块", + "path": "message" + }, + { + "title": "nonebot.matcher 模块", + "path": "matcher" + }, + { + "title": "nonebot.rule 模块", + "path": "rule" + }, + { + "title": "nonebot.permission 模块", + "path": "permission" + }, + { + "title": "nonebot.log 模块", + "path": "log" + }, + { + "title": "nonebot.utils 模块", + "path": "utils" + }, + { + "title": "nonebot.typing 模块", + "path": "typing" + }, + { + "title": "nonebot.exception 模块", + "path": "exception" + }, + { + "title": "nonebot.drivers 模块", + "path": "drivers/" + }, + { + "title": "nonebot.drivers.fastapi 模块", + "path": "drivers/fastapi" + }, + { + "title": "nonebot.adapters 模块", + "path": "adapters/" + }, + { + "title": "nonebot.adapters.cqhttp 模块", + "path": "adapters/cqhttp" + }, + { + "title": "nonebot.adapters.ding 模块", + "path": "adapters/ding" + }, + { + "title": "nonebot.adapters.mirai 模块", + "path": "adapters/mirai" + } + ] + } + ] + } + } + } +} \ No newline at end of file diff --git a/docs/.vuepress/versions.json b/docs/.vuepress/versions.json index 6ae5e41b..95f6667a 100644 --- a/docs/.vuepress/versions.json +++ b/docs/.vuepress/versions.json @@ -1,4 +1,5 @@ [ + "2.0.0a9", "2.0.0a8.post2", "2.0.0a7" ] \ No newline at end of file