From e53599dc17037b1990a2ad4c03056d4c03141578 Mon Sep 17 00:00:00 2001 From: yanyongyu Date: Wed, 23 Sep 2020 23:01:06 +0800 Subject: [PATCH] :bookmark: pre release 2.0.0a1 --- archive/2.0.0a1/README.md | 15 + archive/2.0.0a1/api/README.md | 31 ++ archive/2.0.0a1/api/config.md | 265 +++++++++++++++++ archive/2.0.0a1/api/exception.md | 156 ++++++++++ archive/2.0.0a1/api/log.md | 55 ++++ archive/2.0.0a1/api/nonebot.md | 208 +++++++++++++ archive/2.0.0a1/api/permission.md | 121 ++++++++ archive/2.0.0a1/api/rule.md | 122 ++++++++ archive/2.0.0a1/api/sched.md | 41 +++ archive/2.0.0a1/api/typing.md | 236 +++++++++++++++ archive/2.0.0a1/api/utils.md | 39 +++ archive/2.0.0a1/guide/README.md | 38 +++ archive/2.0.0a1/guide/basic-configuration.md | 68 +++++ archive/2.0.0a1/guide/creating-a-project.md | 55 ++++ archive/2.0.0a1/guide/getting-started.md | 146 ++++++++++ archive/2.0.0a1/guide/installation.md | 73 +++++ archive/2.0.0a1/guide/writing-a-plugin.md | 290 +++++++++++++++++++ archive/2.0.0a1/sidebar.config.json | 88 ++++++ docs/.vuepress/versions.json | 3 + tests/test_plugins/test_weather.py | 24 ++ 20 files changed, 2074 insertions(+) create mode 100644 archive/2.0.0a1/README.md create mode 100644 archive/2.0.0a1/api/README.md create mode 100644 archive/2.0.0a1/api/config.md create mode 100644 archive/2.0.0a1/api/exception.md create mode 100644 archive/2.0.0a1/api/log.md create mode 100644 archive/2.0.0a1/api/nonebot.md create mode 100644 archive/2.0.0a1/api/permission.md create mode 100644 archive/2.0.0a1/api/rule.md create mode 100644 archive/2.0.0a1/api/sched.md create mode 100644 archive/2.0.0a1/api/typing.md create mode 100644 archive/2.0.0a1/api/utils.md create mode 100644 archive/2.0.0a1/guide/README.md create mode 100644 archive/2.0.0a1/guide/basic-configuration.md create mode 100644 archive/2.0.0a1/guide/creating-a-project.md create mode 100644 archive/2.0.0a1/guide/getting-started.md create mode 100644 archive/2.0.0a1/guide/installation.md create mode 100644 archive/2.0.0a1/guide/writing-a-plugin.md create mode 100644 archive/2.0.0a1/sidebar.config.json create mode 100644 docs/.vuepress/versions.json create mode 100644 tests/test_plugins/test_weather.py diff --git a/archive/2.0.0a1/README.md b/archive/2.0.0a1/README.md new file mode 100644 index 00000000..e568de9f --- /dev/null +++ b/archive/2.0.0a1/README.md @@ -0,0 +1,15 @@ +--- +home: true +heroImage: /logo.png +tagline: An asynchronous QQ bot framework. +actionText: 开始使用 +actionLink: /guide/ +features: + - title: 简洁 + details: 提供极其简洁易懂的 API,使你可以毫无压力地开始验证你的绝佳创意,只需编写最少量的代码,即可实现丰富的功能。 + - title: 易于扩展 + details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。 + - title: 高性能 + details: 采用异步 I/O,利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。 +footer: MIT Licensed | Copyright © 2020 NoneBot Team +--- diff --git a/archive/2.0.0a1/api/README.md b/archive/2.0.0a1/api/README.md new file mode 100644 index 00000000..2fa1066a --- /dev/null +++ b/archive/2.0.0a1/api/README.md @@ -0,0 +1,31 @@ +# NoneBot Api Reference + + +* **模块索引** + + + * [nonebot](nonebot.html) + + + * [nonebot.typing](typing.html) + + + * [nonebot.config](config.html) + + + * [nonebot.sched](sched.html) + + + * [nonebot.log](log.html) + + + * [nonebot.rule](rule.html) + + + * [nonebot.permission](permission.html) + + + * [nonebot.utils](utils.html) + + + * [nonebot.exception](exception.html) diff --git a/archive/2.0.0a1/api/config.md b/archive/2.0.0a1/api/config.md new file mode 100644 index 00000000..fd90f50e --- /dev/null +++ b/archive/2.0.0a1/api/config.md @@ -0,0 +1,265 @@ +--- +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` + +基类:`pydantic.env_settings.BaseSettings` + +运行环境配置。大小写不敏感。 + +将会从 `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[int]` + + +* 默认值: `set()` + + +* 说明: +机器人超级用户。 + + +* 示例: + +```default +SUPER_USERS=[12345789] +``` + + +### `nickname` + + +* 类型: `Union[str, Set[str]]` + + +* 默认值: `""` + + +* 说明: +机器人昵称。 + + +### `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 +``` + + +### `apscheduler_config` + + +* 类型: `dict` + + +* 默认值: `{"apscheduler.timezone": "Asia/Shanghai"}` + + +* 说明: +APScheduler 的配置对象,见 [Configuring the Scheduler](https://apscheduler.readthedocs.io/en/latest/userguide.html#configuring-the-scheduler) diff --git a/archive/2.0.0a1/api/exception.md b/archive/2.0.0a1/api/exception.md new file mode 100644 index 00000000..2c7abad1 --- /dev/null +++ b/archive/2.0.0a1/api/exception.md @@ -0,0 +1,156 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.exception 模块 + +## 异常 + +下列文档中的异常是所有 NoneBot 运行时可能会抛出的。 +这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。 + + +## _exception_ `IgnoredException` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。 + + + +* **参数** + + + * `reason`: 忽略事件的原因 + + + +## _exception_ `PausedException` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 结束当前 `Handler` 并等待下一条消息后继续下一个 `Handler`。 + 可用于用户输入新信息。 + + + +* **用法** + + 可以在 `Handler` 中通过 `Matcher.pause()` 抛出。 + + + +## _exception_ `RejectedException` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 结束当前 `Handler` 并等待下一条消息后重新运行当前 `Handler`。 + 可用于用户重新输入。 + + + +* **用法** + + 可以在 `Handler` 中通过 `Matcher.reject()` 抛出。 + + + +## _exception_ `FinishedException` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 结束当前 `Handler` 且后续 `Handler` 不再被运行。 + 可用于结束用户会话。 + + + +* **用法** + + 可以在 `Handler` 中通过 `Matcher.finish()` 抛出。 + + + +## _exception_ `ExpiredException` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 当前 `Matcher` 已失效。 + + + +* **用法** + + 当 `Matcher` 运行前检查时抛出。 + + + +## _exception_ `StopPropagation` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 终止事件向下层传播。 + + + +* **用法** + + 在 `Matcher.block == True` 时抛出。 + + + +## _exception_ `ApiNotAvailable` + +基类:`Exception` + + +* **说明** + + 在 API 连接不可用时抛出。 + + + +## _exception_ `NetworkError` + +基类:`Exception` + + +* **说明** + + 在网络出现问题时抛出,如: API 请求地址不正确, API 请求无返回或返回状态非正常等。 + + + +## _exception_ `ActionFailed` + +基类:`Exception` + + +* **说明** + + API 请求成功返回数据,但 API 操作失败。 + + + +* **参数** + + + * `retcode`: 错误代码 diff --git a/archive/2.0.0a1/api/log.md b/archive/2.0.0a1/api/log.md new file mode 100644 index 00000000..77ce3609 --- /dev/null +++ b/archive/2.0.0a1/api/log.md @@ -0,0 +1,55 @@ +--- +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 +``` + + +## _class_ `LoguruHandler` + +基类:`logging.Handler` + + +### `emit(record)` + +Do whatever it takes to actually log the specified logging record. + +This version is intended to be implemented by subclasses and so +raises a NotImplementedError. diff --git a/archive/2.0.0a1/api/nonebot.md b/archive/2.0.0a1/api/nonebot.md new file mode 100644 index 00000000..3c278a5c --- /dev/null +++ b/archive/2.0.0a1/api/nonebot.md @@ -0,0 +1,208 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot 模块 + + +## `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.0a1/api/permission.md b/archive/2.0.0a1/api/permission.md new file mode 100644 index 00000000..26d3cd34 --- /dev/null +++ b/archive/2.0.0a1/api/permission.md @@ -0,0 +1,121 @@ +--- +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: int`: 白名单 + + + * `perm: Permission`: 需要同时满足的权限 + + + +## `PRIVATE` + + +* **说明**: 匹配任意私聊消息类型事件 + + +## `PRIVATE_FRIEND` + + +* **说明**: 匹配任意好友私聊消息类型事件 + + +## `PRIVATE_GROUP` + + +* **说明**: 匹配任意群临时私聊消息类型事件 + + +## `PRIVATE_OTHER` + + +* **说明**: 匹配任意其他私聊消息类型事件 + + +## `GROUP` + + +* **说明**: 匹配任意群聊消息类型事件 + + +## `GROUP_MEMBER` + + +* **说明**: 匹配任意群员群聊消息类型事件 + +:::warning 警告 +该权限通过 event.sender 进行判断且不包含管理员以及群主! +::: + + +## `GROUP_ADMIN` + + +* **说明**: 匹配任意群管理员群聊消息类型事件 + + +## `GROUP_OWNER` + + +* **说明**: 匹配任意群主群聊消息类型事件 + + +## `SUPERUSER` + + +* **说明**: 匹配任意超级用户消息类型事件 + + +## `EVERYBODY` + + +* **说明**: 匹配任意消息类型事件 diff --git a/archive/2.0.0a1/api/rule.md b/archive/2.0.0a1/api/rule.md new file mode 100644 index 00000000..269abc57 --- /dev/null +++ b/archive/2.0.0a1/api/rule.md @@ -0,0 +1,122 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.rule 模块 + +## 规则 + +每个 `Matcher` 拥有一个 `Rule` ,其中是 **异步** `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。 + +:::tip 提示 +`RuleChecker` 既可以是 async function 也可以是 sync 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, dict], Awaitable[bool]]`: **异步** RuleChecker + + + +### `checkers` + + +* **说明** + + 存储 `RuleChecker` + + + +* **类型** + + + * `Set[Callable[[Bot, Event, dict], Awaitable[bool]]]` + + + +### _async_ `__call__(bot, event, state)` + + +* **说明** + + 检查是否符合所有规则 + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: dict`: 当前 State + + + +* **返回** + + + * `bool` + + + +## `startswith(msg)` + + +* **说明** + + 匹配消息开头 + + + +* **参数** + + + * `msg: str`: 消息开头字符串 + + + +## `endswith(msg)` + + +* **说明** + + 匹配消息结尾 + + + +* **参数** + + + * `msg: str`: 消息结尾字符串 diff --git a/archive/2.0.0a1/api/sched.md b/archive/2.0.0a1/api/sched.md new file mode 100644 index 00000000..450fd7d0 --- /dev/null +++ b/archive/2.0.0a1/api/sched.md @@ -0,0 +1,41 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.sched 模块 + +## 计划任务 + +计划任务使用第三方库 [APScheduler](https://github.com/agronholm/apscheduler) ,使用文档请参考 [APScheduler使用文档](https://apscheduler.readthedocs.io/en/latest/) 。 + + +## `scheduler` + + +* **类型** + + `Optional[apscheduler.schedulers.asyncio.AsyncIOScheduler]` + + + +* **说明** + + 当可选依赖 `APScheduler` 未安装时,`scheduler` 为 None + + 使用 `pip install nonebot[scheduler]` 安装可选依赖 + + + +* **常用示例** + + +```python +from nonebot import 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") +``` diff --git a/archive/2.0.0a1/api/typing.md b/archive/2.0.0a1/api/typing.md new file mode 100644 index 00000000..f68bdfcb --- /dev/null +++ b/archive/2.0.0a1/api/typing.md @@ -0,0 +1,236 @@ +--- +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 模块导入。 + + +## `Driver` + + +* **类型** + + `BaseDriver` + + + +* **说明** + + 所有 Driver 的基类。 + + + + +## `WebSocket` + + +* **类型** + + `BaseWebSocket` + + + +* **说明** + + 所有 WebSocket 的基类。 + + + + +## `Bot` + + +* **类型** + + `BaseBot` + + + +* **说明** + + 所有 Bot 的基类。 + + + + +## `Event` + + +* **类型** + + `BaseEvent` + + + +* **说明** + + 所有 Event 的基类。 + + + + +## `Message` + + +* **类型** + + `BaseMessage` + + + +* **说明** + + 所有 Message 的基类。 + + + + +## `MessageSegment` + + +* **类型** + + `BaseMessageSegment` + + + +* **说明** + + 所有 MessageSegment 的基类。 + + + + +## `PreProcessor` + + +* **类型** + + `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + 消息预处理函数 PreProcessor 类型 + + + + +## `Matcher` + + +* **类型** + + `Matcher` + + + +* **说明** + + Matcher 即响应事件的处理类。通过 Rule 判断是否响应事件,运行 Handler。 + + + + +## `Rule` + + +* **类型** + + `Rule` + + + +* **说明** + + Rule 即判断是否响应事件的处理类。内部存储 RuleChecker ,返回全为 True 则响应事件。 + + + + +## `RuleChecker` + + +* **类型** + + `Callable[[Bot, Event, dict], Union[bool, Awaitable[bool]]]` + + + +* **说明** + + RuleChecker 即判断是否响应事件的处理函数。 + + + + +## `Permission` + + +* **类型** + + `Permission` + + + +* **说明** + + Permission 即判断是否响应消息的处理类。内部存储 PermissionChecker ,返回只要有一个 True 则响应消息。 + + + + +## `PermissionChecker` + + +* **类型** + + `Callable[[Bot, Event], Union[bool, Awaitable[bool]]]` + + + +* **说明** + + RuleChecker 即判断是否响应消息的处理函数。 + + + + +## `Handler` + + +* **类型** + + `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + Handler 即事件的处理函数。 + + + + +## `ArgsParser` + + +* **类型** + + `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + ArgsParser 即消息参数解析函数,在 Matcher.got 获取参数时被运行。 diff --git a/archive/2.0.0a1/api/utils.md b/archive/2.0.0a1/api/utils.md new file mode 100644 index 00000000..7de3ba3f --- /dev/null +++ b/archive/2.0.0a1/api/utils.md @@ -0,0 +1,39 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.utils 模块 + + +## `run_sync(func)` + + +* **说明** + + 一个用于包装 sync function 为 async function 的装饰器 + + + +* **参数** + + + * `func: Callable[..., Any]`: 被装饰的同步函数 + + + +* **返回** + + + * `Callable[..., Awaitable[Any]]` + + + +## _class_ `DataclassEncoder` + +基类:`json.encoder.JSONEncoder` + + +* **说明** + + 在JSON序列化 `Message` (List[Dataclass]) 时使用的 `JSONEncoder` diff --git a/archive/2.0.0a1/guide/README.md b/archive/2.0.0a1/guide/README.md new file mode 100644 index 00000000..6cf31e90 --- /dev/null +++ b/archive/2.0.0a1/guide/README.md @@ -0,0 +1,38 @@ +# 概览 + +:::tip 提示 +如果在阅读本文档时遇到难以理解的词汇,请随时查阅 [术语表](../glossary.md) 或使用 [Google 搜索](https://www.google.com/)。 +::: + +:::tip 提示 +初次使用时可能会觉得这里的概览过于枯燥,可以先简单略读之后直接前往 [安装](./installation.md) 查看安装方法,并进行后续的基础使用教程。 +::: + +NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的消息进行解析和处理,并以插件化的形式,分发给消息所对应的命令处理器和自然语言处理器,来完成具体的功能。 + +除了起到解析消息的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制,尤其对于命令处理器,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 + +目前 NoneBot2 在 [FastAPI](https://fastapi.tiangolo.com/) 的基础上封装了与 [CQHTTP(OneBot) 协议](http://cqhttp.cc/)插件的网络交互。 + +得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制,NoneBot 处理消息的吞吐量有了很大的保障,再配合 WebSocket 通信方式(也是最建议的通信方式),NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。 + +需要注意的是,NoneBot 仅支持 Python 3.7+ 及 CQHTTP(OneBot) 插件 v11+。 + +## 它如何工作? + +NoneBot 的运行离不开 酷 Q 和 CQHTTP 插件。酷 Q 扮演着「无头 QQ 客户端」的角色,它进行实际的消息、通知、请求的接收和发送,当 酷 Q 收到消息时,它将这个消息包装为一个事件(通知和请求同理),并通过它自己的插件机制将事件传送给 CQHTTP 插件,后者再根据其配置中的 `post_url` 或 `ws_reverse_url` 等项来将事件发送至 NoneBot。 + +在 NoneBot 收到事件前,它底层的 aiocqhttp 实际已经先看到了事件,aiocqhttp 根据事件的类型信息,通知到 NoneBot 的相应函数。特别地,对于消息类型的事件,还将消息内容转换成了 `aiocqhttp.message.Message` 类型,以便处理。 + +NoneBot 的事件处理函数收到通知后,对于不同类型的事件,再做相应的预处理和解析,然后调用对应的插件,并向其提供适合此类事件的会话(Session)对象。NoneBot 插件的编写者要做的,就是利用 Session 对象中提供的数据,在插件的处理函数中实现所需的功能。 + +## 特色 + +- 提供直观的测试前端 +- 提供使用简易的脚手架 +- 基于异步 I/O +- 同时支持 HTTP 和反向 WebSocket 通信方式 +- 支持多个机器人账号负载均衡 +- 提供直观的交互式会话接口 +- 提供可自定义的权限控制机制 +- 多种方式渲染要发送的消息内容,使对话足够自然 diff --git a/archive/2.0.0a1/guide/basic-configuration.md b/archive/2.0.0a1/guide/basic-configuration.md new file mode 100644 index 00000000..e4c4449f --- /dev/null +++ b/archive/2.0.0a1/guide/basic-configuration.md @@ -0,0 +1,68 @@ +# 基本配置 + +到目前为止我们还在使用 NoneBot 的默认行为,在开始编写自己的插件之前,我们先尝试在配置文件上动动手脚,让 NoneBot 表现出不同的行为。 + +在上一章节中,我们创建了默认的项目结构,其中 `.env`, `.env.*` 均为项目的配置文件,下面将介绍几种 NoneBot 配置方式。 + +:::danger 警告 +请勿将敏感信息写入配置文件并提交至开源仓库! +::: + +## .env 文件 + +NoneBot 在启动时将会从系统环境变量或者 `.env` 文件中寻找变量 `ENVIRONMENT` (大小写不敏感),默认值为 `prod`。 +这将引导 NoneBot 从系统环境变量或者 `.env.{ENVIRONMENT}` 文件中进一步加载具体配置。 + +现在,我们在 `.env` 文件中写入当前环境信息 + +```bash +# .env +ENVIRONMENT=dev +``` + +## .env.\* 文件 + +详细配置文件,使用 [pydantic](https://pydantic-docs.helpmanual.io/) 加载配置。在 NoneBot 初始化时可以指定忽略 `.env` 中的环境信息转而加载某个配置文件: `nonebot.init(_env_file=".env.dev")`。 + +:::warning 提示 +由于 `pydantic` 使用 JSON 加载配置项,请确保配置项值为 JSON 能够解析的数据。如果 JSON 解析失败将作为字符串处理。 +::: + +示例及说明: + +```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` > `env file` > `system env` diff --git a/archive/2.0.0a1/guide/creating-a-project.md b/archive/2.0.0a1/guide/creating-a-project.md new file mode 100644 index 00000000..74cdb24a --- /dev/null +++ b/archive/2.0.0a1/guide/creating-a-project.md @@ -0,0 +1,55 @@ +# 创建一个完整的项目 + +上一章中我们已经运行了一个最小的 NoneBot 实例,在这一章,我们将从零开始一个完整的项目。 + +## 目录结构 + +首先,我们可以使用 `nb-cli` 或者自行创建项目目录: + +```bash +pip install nonebot2[cli] +# pip install nb-cli +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.0a1/guide/getting-started.md b/archive/2.0.0a1/guide/getting-started.md new file mode 100644 index 00000000..d52a9396 --- /dev/null +++ b/archive/2.0.0a1/guide/getting-started.md @@ -0,0 +1,146 @@ +# 开始使用 + +一切都安装成功后,你就已经做好了进行简单配置以运行一个最小的 NoneBot 实例的准备。 + +## 最小实例 + +使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下: + +```python{3,4,7} +import nonebot + +nonebot.init() +nonebot.load_builtin_plugins() + +if __name__ == "__main__": + nonebot.run() +``` + +这几行高亮代码将依次: + +1. 使用默认配置初始化 NoneBot 包 +2. 加载 NoneBot 内置的插件 +3. 在地址 `127.0.0.1:8080` 运行 NoneBot + +在命令行使用如下命令即可运行这个 NoneBot 实例: + +```bash +python bot.py +``` + +运行后会产生如下日志: + +```default +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] nonebot | Scheduler Started +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) +``` + +## 配置 QQ 协议端 + +单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 + +目前支持的协议有: + +- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot) + +QQ 协议端举例: + +- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai) +- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded) +- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api) +- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo)) +- [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 文件 +2. 双击 exe 文件或者使用 `./go-cqhttp` 启动 +3. 生成默认配置文件并修改默认配置 + +```json{2,3,30-31} +{ + "uin": 你的QQ号, + "password": "你的密码", + "encrypt_password": false, + "password_encrypted": "", + "enable_db": true, + "access_token": "", + "relogin": { + "enabled": true, + "relogin_delay": 3, + "max_relogin_times": 0 + }, + "ignore_invalid_cqcode": false, + "force_fragmented": true, + "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": "", + "reverse_event_url": "", + "reverse_reconnect_interval": 3000 + } + ], + "post_message_format": "string", + "debug": false, + "log_level": "" +} +``` + +其中 `ws://127.0.0.1:8080/cqhttp/ws` 中的 `127.0.0.1` 和 `8080` 应分别对应 nonebot 配置的 HOST 和 PORT + +## 历史性的第一次对话 + +一旦新的配置文件正确生效之后,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! +``` + +这表示 QQ 协议端已经成功地使用 CQHTTP 协议连接上了 NoneBot。 + +:::warning 注意 +如果到这一步你没有看到上面这样的成功日志,CQHTTP 的日志中在不断地重连或无反应,请注意检查配置中的 IP 和端口是否确实可以访问。比较常见的出错点包括: + +- NoneBot 监听 `0.0.0.0`,然后在 CQHTTP 配置中填了 `ws://0.0.0.0:8080/cqhttp/ws` +- 在 Docker 容器内运行 CQHTTP,并通过 `127.0.0.1` 访问宿主机上的 NoneBot +- 想从公网访问,但没有修改云服务商的安全组策略或系统防火墙 +- NoneBot 所监听的端口存在冲突,已被其它程序占用 +- 弄混了 NoneBot 的 `host`、`port` 参数与 CQHTTP 配置中的 `host`、`port` 参数 +- 使用了 `ws_reverse_api_url` 和 `ws_reverse_event_url` 而非 universal client +- `ws://` 错填为 `http://` +- CQHTTP 或 NoneBot 启动时遭到外星武器干扰 + +请尝试重启 CQHTTP、重启 NoneBot、更换端口、修改防火墙、重启系统、仔细阅读前面的文档及提示、更新 CQHTTP 和 NoneBot 到最新版本等方式来解决。 +::: + +现在,尝试向你的 QQ 机器人账号发送如下内容: + +```default +/say 你好,世界 +``` + +到这里如果一切 OK,你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅! + + + + diff --git a/archive/2.0.0a1/guide/installation.md b/archive/2.0.0a1/guide/installation.md new file mode 100644 index 00000000..06a88598 --- /dev/null +++ b/archive/2.0.0a1/guide/installation.md @@ -0,0 +1,73 @@ +# 安装 + +## NoneBot + +:::warning 注意 +请确保你的 Python 版本 >= 3.7。 +::: + +```bash +pip install nonebot2 +``` + +如果你需要使用最新的(可能尚未发布的)特性,可以克隆 Git 仓库后手动安装: + +```bash +git clone https://github.com/nonebot/nonebot2.git +cd nonebot2 +poetry install --no-dev # 推荐 +pip install . # 不推荐 +``` + +## 额外依赖 + +### APScheduler + +A task scheduling library for Python. + +可用于计划任务,后台执行任务等 + +```bash +pip install nonebot2[scheduler] +poetry add nonebot2[scheduler] +``` + +[View On GitHub](https://github.com/agronholm/apscheduler) + +### NoneBot-Test + +A test frontend for nonebot2. + +通过前端展示 nonebot 已加载的插件以及运行状态,同时可以用于模拟发送事件测试机器人 + +```bash +pip install nonebot2[test] +poetry add nonebot2[test] +``` + +[View On GitHub](https://github.com/nonebot/nonebot-test) + +### CLI + +CLI for nonebot2. + +一个多功能脚手架 + +```bash +pip install nonebot2[cli] +poetry add nonebot2[cli] +``` + +[View On GitHub](https://github.com/yanyongyu/nb-cli) + +### 我全都要 + +```bash +pip install nonebot2[full] +poetry add nonebot2[full] +``` + +```bash +pip install nonebot2[cli,scheduler] +poetry add nonebot2[cli,scheduler] +``` diff --git a/archive/2.0.0a1/guide/writing-a-plugin.md b/archive/2.0.0a1/guide/writing-a-plugin.md new file mode 100644 index 00000000..bd176750 --- /dev/null +++ b/archive/2.0.0a1/guide/writing-a-plugin.md @@ -0,0 +1,290 @@ +# 编写插件 + +本章将以一个天气查询插件为例,教学如何编写自己的命令。 + +## 加载插件 + +在 [创建一个完整的项目](creating-a-project) 一章节中,我们已经创建了插件目录 `awesome_bot/plugins`,现在我们在机器人入口文件中加载它。当然,你也可以单独加载一个插件。 + +:::tip 提示 +加载插件目录时,目录下以 `_` 下划线开头的插件将不会被加载! +::: + +在 `bot.py` 文件中添加以下行: + +```python{5,7} +import nonebot + +nonebot.init() +# 加载单独的一个插件,参数为合法的python包名 +nonebot.load_plugin("nonebot.plugins.base") +# 加载插件目录,该目录下为各插件,以下划线开头的插件将不会被加载 +nonebot.load_plugins("awesome_bot/plugins") + +app = nonebot.get_asgi() + +if __name__ == "__main__": + nonebot.run() +``` + +尝试运行 `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" +``` + +## 创建插件 + +现在我们已经有了一个空的插件目录,我们可以开始创建插件了!插件有两种形式 + +### 单文件形式 + +在插件目录下创建名为 `weather.py` 的 Python 文件,暂时留空,此时目录结构如下: + + +:::vue +AweSome-Bot +├── awesome_bot +│ └── plugins +│ └── `weather.py` +├── .env +├── .env.dev +├── .env.prod +├── .gitignore +├── bot.py +├── docker-compose.yml +├── Dockerfile +├── pyproject.toml +└── README.md +::: + + +这个时候它已经可以被称为一个插件了,尽管它还什么都没做。 + +### 包形式 + +在插件目录下创建文件夹 `weather`,并在该文件夹下创建文件 `__init__.py`,此时目录结构如下: + + +:::vue +AweSome-Bot +├── awesome_bot +│ └── plugins +│ └── `weather` +│ └── `__init__.py` +├── .env +├── .env.dev +├── .env.prod +├── .gitignore +├── bot.py +├── docker-compose.yml +├── Dockerfile +├── pyproject.toml +└── README.md +::: + + +这个时候 `weather` 就是一个合法的 Python 包了,同时也是合法的 NoneBot 插件,插件内容可以在 `__init__.py` 中编写。 + +## 编写真正的内容 + +好了,现在插件已经可以正确加载,我们可以开始编写命令的实际代码了。在 `weather.py` 中添加如下代码: + +```python +from nonebot import on_command +from nonebot.rule import to_me +from nonebot.adapters.cqhttp import Bot, Event + +weather = on_command("天气", rule=to_me(), priority=5) + + +@weather.handle() +async def handle_first_receive(bot: Bot, event: Event, state: dict): + args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 + if args: + state["city"] = args # 如果用户发送了参数则直接赋值 + + +@weather.got("city", prompt="你想查询哪个城市的天气呢?") +async def handle_city(bot: Bot, event: Event, state: dict): + 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{4} +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.type` ,NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些内置的事件响应器。 + +- `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))`: 消息开头匹配处理器 +- `on_endswith(str)` ~ `on("message", endswith(str))`: 消息结尾匹配处理器 +- `on_command(str|tuple)` ~ `on("message", command(str|tuple))`: 命令处理器 +- `on_regax(pattern_str)` ~ `on("message", regax(pattern_str))`: 正则匹配处理器 + +#### 匹配规则 rule + +事件响应器的匹配规则即 `Rule`,由非负个 `RuleChecker` 组成,当所有 `RuleChecker` 返回 `True` 时匹配成功。这些 `RuleChecker` 的形式如下: + +```python +async def check(bot: Bot, event: Event, state: dict) -> bool: + return True + +def check(bot: Bot, event: Event, state: dict) -> bool: + return True +``` + +`Rule` 和 `RuleChecker` 之间可以使用 `与 &` 互相组合: + +```python +from nonebot.rule import Rule + +Rule(async_checker1) & sync_checker & async_checker2 +``` + +:::danger 警告 +`Rule(*checkers)` 只接受 async function,或使用 `nonebot.utils.run_sync` 自行包裹 sync function。在使用 `与 &` 时,NoneBot 会自动包裹 sync function +::: + +#### 优先级 priority + +事件响应器的优先级代表事件响应器的执行顺序,同一优先级的事件响应器会 **同时执行!** + +:::tip 提示 +使用 `nonebot-test` 可以看到当前所有事件响应器的执行流程,有助理解事件响应流程! + +```bash +pip install nonebot2[test] +``` + +::: + +#### 阻断 block + +当有任意事件响应器发出了阻止事件传递信号时,该事件将不再会传递给下一优先级,直接结束处理。 + +NoneBot 内置的事件响应器中,所有 `message` 类的事件响应器默认会阻断事件传递,其他则不会。 + +### 编写事件处理函数 [Handler](../api/typing.md#handler) + +```python{1,2,8,9} +@weather.handle() +async def handle_first_receive(bot: Bot, event: Event, state: dict): + args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 + if args: + state["city"] = args # 如果用户发送了参数则直接赋值 + + +@weather.got("city", prompt="你想查询哪个城市的天气呢?") +async def handle_city(bot: Bot, event: Event, state: dict): + city = state["city"] + if city not in ["上海", "北京"]: + await weather.reject("你想查询的城市暂不支持,请重新输入!") + city_weather = await get_weather(city) + await weather.finish(city_weather) +``` + +在上面的代码中,我们给 `weather` 事件响应器添加了两个事件处理函数:`handle_first_receive`, `handle_city` + +其中有几个要点,我们一一解释: + +#### 添加一个事件处理函数 + +在事件响应器响应事件时,事件处理函数会依次顺序执行,也就是说,与添加顺序一致。 + +我们可以使用 `@matcher.handle()` 装饰器来简单地为该事件响应器添加一个处理函数。 + +同时,NoneBot 内置了几种添加事件处理函数方式以方便处理: + +- `@matcher.receive()`: 指示 NoneBot 接收一条新的用户消息以继续执行后续处理函数。 +- `@matcher.got(key, [prompt="请输入key"], [args_parser=function])`: 指示 NoneBot 当 `state` 中不存在 `key` 时向用户发送 `prompt` 等待用户回复并赋值给 `state[key]` + +这些装饰器可以套娃使用!例如: + +```python +@matcher.got("key1") +@matcher.got("key2") +async def handle(bot: Bot, event: Event, state: dict): + pass +``` + +#### 事件处理函数参数 + +事件处理函数类型为 `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` 。 + +参数分别为: + +1. [nonebot.typing.Bot](../api/typing.md#bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。 +2. [nonebot.typing.Event](../api/typing.md#event): 即上报事件对象,可以获取到上报的所有信息。 +3. `state`: 状态字典,可以存储任意的信息 + +#### 处理事件 + +在事件处理函数中,我们只需要对 `event` 做出相应的处理,存入状态字典 `state` 中,或者向用户发送消息、调用某个机器人 API 等等。 + +在 NoneBot 中,提供了几种特殊的处理函数: + +##### `@matcher.args_parser` + +这是一个装饰器,装饰一个函数来使它成为参数的默认解析函数,当使用 `matcher.got(xxx, [args_parser])` 获取到一条消息时,会运行 `matcher.got` 的 `args_parser` ,如果不存在则运行 `@matcher.args_parser`。 + +##### `matcher.pause` + +这个函数用于结束当前事件处理函数,强制接收一条新的消息再运行**下一个消息处理函数**。 + +##### `matcher.reject` + +这个函数用于结束当前事件处理函数,强制接收一条新的消息再**再次运行当前消息处理函数**。 + +##### `matcher.finish` + +这个函数用于直接结束当前事件处理。 + +以上三个函数都拥有一个参数 `prompt`,用于向用户发送一条消息。 + +## 结语 + +至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示: + +- 请千万注意事件处理器的优先级设定 +- 在匹配规则中请勿使用耗时极长的函数 +- 同一个用户可以跨群(私聊)继续他的事件处理(除非做出权限限制,将在后续介绍) diff --git a/archive/2.0.0a1/sidebar.config.json b/archive/2.0.0a1/sidebar.config.json new file mode 100644 index 00000000..9dd289f1 --- /dev/null +++ b/archive/2.0.0a1/sidebar.config.json @@ -0,0 +1,88 @@ +{ + "locales": { + "/": { + "label": "简体中文", + "selectText": "Languages", + "editLinkText": "在 GitHub 上编辑此页", + "lastUpdated": "上次更新", + "nav": [ + { + "text": "主页", + "link": "/" + }, + { + "text": "指南", + "link": "/guide/" + }, + { + "text": "API", + "link": "/api/" + } + ], + "sidebarDepth": 2, + "sidebar": { + "/guide/": [ + { + "title": "指南", + "path": "", + "collapsable": false, + "sidebar": "auto", + "children": [ + "", + "installation", + "getting-started", + "creating-a-project", + "basic-configuration", + "writing-a-plugin" + ] + } + ], + "/api/": [ + { + "title": "NoneBot Api Reference", + "path": "", + "collapsable": false, + "children": [ + { + "title": "nonebot 模块", + "path": "nonebot" + }, + { + "title": "nonebot.typing 模块", + "path": "typing" + }, + { + "title": "nonebot.config 模块", + "path": "config" + }, + { + "title": "nonebot.sched 模块", + "path": "sched" + }, + { + "title": "nonebot.log 模块", + "path": "log" + }, + { + "title": "nonebot.rule 模块", + "path": "rule" + }, + { + "title": "nonebot.permission 模块", + "path": "permission" + }, + { + "title": "nonebot.utils 模块", + "path": "utils" + }, + { + "title": "nonebot.exception 模块", + "path": "exception" + } + ] + } + ] + } + } + } +} \ No newline at end of file diff --git a/docs/.vuepress/versions.json b/docs/.vuepress/versions.json new file mode 100644 index 00000000..76e10341 --- /dev/null +++ b/docs/.vuepress/versions.json @@ -0,0 +1,3 @@ +[ + "2.0.0a1" +] \ No newline at end of file diff --git a/tests/test_plugins/test_weather.py b/tests/test_plugins/test_weather.py new file mode 100644 index 00000000..26effa5d --- /dev/null +++ b/tests/test_plugins/test_weather.py @@ -0,0 +1,24 @@ +from nonebot import on_command +from nonebot.rule import to_me +from nonebot.typing import Bot, Event + +weather = on_command("天气", rule=to_me(), priority=1) + + +@weather.handle() +async def handle_first_receive(bot: Bot, event: Event, state: dict): + args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 + print(f"==={args}===") + if args: + state["city"] = args # 如果用户发送了参数则直接赋值 + + +@weather.got("city", prompt="你想查询哪个城市的天气呢?") +async def handle_city(bot: Bot, event: Event, state: dict): + city = state["city"] + if city not in ["上海", "北京"]: + await weather.reject("你想查询的城市暂不支持,请重新输入!") + # weather = await get_weather_from_xxx(city) + city_weather = "晴天" + # await bot.send(city_weather) + await weather.finish(city_weather)