diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 00000000..6e9fc665 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,2 @@ +open_collective: nonebot +custom: ["https://afdian.net/@nonebot"] diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml index c77a0550..d8404730 100644 --- a/.github/release-drafter.yml +++ b/.github/release-drafter.yml @@ -1,6 +1,9 @@ name-template: 'v$RESOLVED_VERSION 🌈' tag-template: 'v$RESOLVED_VERSION' categories: + - title: '💥 Breaking Changes' + labels: + - 'Breaking' - title: '🚀 Features' labels: - 'feature' @@ -10,8 +13,8 @@ categories: - 'fix' - 'bugfix' - 'bug' - - title: '🧰 Maintenance' - label: 'chore' + - title: '🍻 Plugin Publish' + label: 'Plugin' change-template: '- $TITLE @$AUTHOR (#$NUMBER)' change-title-escapes: '\<*_&' # You can add # and @ to disable mentions, and add ` to disable code blocks. version-resolver: diff --git a/LICENSE b/LICENSE index 4b707817..0933f08b 100644 --- a/LICENSE +++ b/LICENSE @@ -1,5 +1,5 @@ The MIT License (MIT) -Copyright (c) 2018 Richard Chien +Copyright (c) 2020 NoneBot Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in @@ -16,4 +16,4 @@ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN -CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 999134d8..58ebe0d0 100644 --- a/README.md +++ b/README.md @@ -39,28 +39,62 @@ _✨ Python 异步机器人框架 ✨_ 安装 · 开始使用 + · + 文档打不开?

## 简介 -NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的消息进行解析和处理,并以插件化的形式,分发给消息所对应的命令处理器和自然语言处理器,来完成具体的功能。 +NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。 -除了起到解析消息的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制,尤其对于命令处理器,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 +除了起到解析事件的作用,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 通信,更是有质的飞跃。 -得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制,NoneBot 处理消息的吞吐量有了很大的保障,再配合 WebSocket 通信方式(也是最建议的通信方式),NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。 +## 特色 -需要注意的是,NoneBot 仅支持 Python 3.7+ 及 CQHTTP(OneBot) 插件 v11+。 +NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**! -此外,NoneBot2 还有可配套使用的额外脚手架/框架: +目前 NoneBot2 内置的驱动框架: -- [NB-CLI](https://github.com/nonebot/nb-cli) -- [NoneBot-Test](https://github.com/nonebot/nonebot-test) +- [FastAPI](https://fastapi.tiangolo.com/) -## 文档 +目前 NoneBot2 内置的协议适配: -文档目前尚未完成,「API」部分由 sphinx 自动生成,你可以在 [这里](https://v2.nonebot.dev/) 查看。 +- [CQHTTP(OneBot) 协议](https://github.com/howmanybots/onebot/blob/master/README.md) +- [钉钉](https://ding-doc.dingtalk.com/doc#/serverapi2/krgddi) _开发中_ +- [Telegram](https://core.telegram.org/bots/api) _计划中_ + +## 即刻开始 + +~~完整~~文档可以在 [这里](https://v2.nonebot.dev/) 查看。 + +懒得看文档?下面是快速安装指南:~~这是坏文明~~ + +1. (可选)使用你喜欢的 Python 环境管理工具创建新的虚拟环境。 +2. 使用 `pip` (或其他) 安装 NoneBot 脚手架。 + + ```bash + pip install nb-cli + ``` + +3. 使用脚手架创建项目 + + ```bash + nb create + ``` + +## 插件 + +此外,NoneBot2 还有丰富的官方以及第三方现成的插件供大家使用: + +- [NoneBot-Plugin-Docs](https://github.com/nonebot/nonebot2/tree/master/packages/nonebot-plugin-docs):离线文档至本地使用(别再说文档打不开了!) + + ```bash + nb plugin install nonebot_plugin_docs + ``` + +- 其他插件请查看 [插件商店](https://v2.nonebot.dev/plugin-store.html) ## 贡献 diff --git a/archive/2.0.0a4/api/config.md b/archive/2.0.0a4/api/config.md deleted file mode 100644 index 6943427b..00000000 --- a/archive/2.0.0a4/api/config.md +++ /dev/null @@ -1,265 +0,0 @@ ---- -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` - - -* 类型: `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 -``` - - -### `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.0a4/api/sched.md b/archive/2.0.0a4/api/sched.md deleted file mode 100644 index 450fd7d0..00000000 --- a/archive/2.0.0a4/api/sched.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -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.0a4/guide/installation.md b/archive/2.0.0a4/guide/installation.md deleted file mode 100644 index 4f6e68e1..00000000 --- a/archive/2.0.0a4/guide/installation.md +++ /dev/null @@ -1,76 +0,0 @@ -# 安装 - -## NoneBot - -:::warning 注意 -请确保你的 Python 版本 >= 3.7。 -::: - -请在安装 nonebot2 之前卸载 nonebot 1.x - -```bash -pip uninstall nonebot -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.0a4/guide/writing-a-plugin.md b/archive/2.0.0a4/guide/writing-a-plugin.md deleted file mode 100644 index 42657d9d..00000000 --- a/archive/2.0.0a4/guide/writing-a-plugin.md +++ /dev/null @@ -1,290 +0,0 @@ -# 编写插件 - -本章将以一个天气查询插件为例,教学如何编写自己的命令。 - -## 加载插件 - -在 [创建一个完整的项目](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_regex(pattern_str)` ~ `on("message", regex(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.0a4/README.md b/archive/2.0.0a7/README.md similarity index 89% rename from archive/2.0.0a4/README.md rename to archive/2.0.0a7/README.md index e568de9f..c093eb5c 100644 --- a/archive/2.0.0a4/README.md +++ b/archive/2.0.0a7/README.md @@ -3,7 +3,7 @@ home: true heroImage: /logo.png tagline: An asynchronous QQ bot framework. actionText: 开始使用 -actionLink: /guide/ +actionLink: guide/ features: - title: 简洁 details: 提供极其简洁易懂的 API,使你可以毫无压力地开始验证你的绝佳创意,只需编写最少量的代码,即可实现丰富的功能。 @@ -11,5 +11,5 @@ features: details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。 - title: 高性能 details: 采用异步 I/O,利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。 -footer: MIT Licensed | Copyright © 2020 NoneBot Team +footer: MIT Licensed | Copyright © 2018 - 2020 NoneBot Team --- diff --git a/archive/2.0.0a7/advanced/README.md b/archive/2.0.0a7/advanced/README.md new file mode 100644 index 00000000..92c6af3e --- /dev/null +++ b/archive/2.0.0a7/advanced/README.md @@ -0,0 +1,7 @@ +# 深入 + +## 它如何工作? + + + +~~未填坑~~ diff --git a/archive/2.0.0a7/advanced/export-and-require.md b/archive/2.0.0a7/advanced/export-and-require.md new file mode 100644 index 00000000..832b0e75 --- /dev/null +++ b/archive/2.0.0a7/advanced/export-and-require.md @@ -0,0 +1 @@ +# 跨插件访问 diff --git a/archive/2.0.0a7/advanced/permission.md b/archive/2.0.0a7/advanced/permission.md new file mode 100644 index 00000000..7190bcdd --- /dev/null +++ b/archive/2.0.0a7/advanced/permission.md @@ -0,0 +1 @@ +# 权限控制 diff --git a/archive/2.0.0a7/advanced/publish-plugin.md b/archive/2.0.0a7/advanced/publish-plugin.md new file mode 100644 index 00000000..68e2e6f9 --- /dev/null +++ b/archive/2.0.0a7/advanced/publish-plugin.md @@ -0,0 +1 @@ +# 发布插件 diff --git a/archive/2.0.0a7/advanced/runtime-hook.md b/archive/2.0.0a7/advanced/runtime-hook.md new file mode 100644 index 00000000..58bca681 --- /dev/null +++ b/archive/2.0.0a7/advanced/runtime-hook.md @@ -0,0 +1 @@ +# 运行时插槽 diff --git a/archive/2.0.0a7/advanced/scheduler.md b/archive/2.0.0a7/advanced/scheduler.md new file mode 100644 index 00000000..53e6cedc --- /dev/null +++ b/archive/2.0.0a7/advanced/scheduler.md @@ -0,0 +1 @@ +# 定时任务 diff --git a/archive/2.0.0a4/api/README.md b/archive/2.0.0a7/api/README.md similarity index 87% rename from archive/2.0.0a4/api/README.md rename to archive/2.0.0a7/api/README.md index dcfb548c..243733f8 100644 --- a/archive/2.0.0a4/api/README.md +++ b/archive/2.0.0a7/api/README.md @@ -13,6 +13,9 @@ * [nonebot.plugin](plugin.html) + * [nonebot.message](message.html) + + * [nonebot.matcher](matcher.html) @@ -22,9 +25,6 @@ * [nonebot.permission](permission.html) - * [nonebot.sched](sched.html) - - * [nonebot.log](log.html) @@ -47,3 +47,6 @@ * [nonebot.adapters.cqhttp](adapters/cqhttp.html) + + + * [nonebot.adapters.ding](adapters/ding.html) diff --git a/archive/2.0.0a4/api/adapters/README.md b/archive/2.0.0a7/api/adapters/README.md similarity index 79% rename from archive/2.0.0a4/api/adapters/README.md rename to archive/2.0.0a7/api/adapters/README.md index f3f937ec..1a1dd85b 100644 --- a/archive/2.0.0a4/api/adapters/README.md +++ b/archive/2.0.0a7/api/adapters/README.md @@ -69,6 +69,45 @@ Websocket 连接对象 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)` @@ -108,7 +147,7 @@ Adapter 类型 ```python -await bot.call_api("send_msg", data={"message": "hello world"}) +await bot.call_api("send_msg", message="hello world"}) await bot.send_msg(message="hello world") ``` @@ -137,7 +176,7 @@ await bot.send_msg(message="hello world") ## _class_ `BaseEvent` -基类:`abc.ABC` +基类:`abc.ABC`, `typing.Generic` Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。 @@ -148,7 +187,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **参数** - * `raw_event: dict`: 原始上报消息 + * `raw_event: Union[dict, T]`: 原始上报消息 @@ -270,7 +309,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **参数** - * `message: Union[str, dict, list, MessageSegment, Message]`: 消息内容 + * `message: Union[str, dict, list, BaseModel, MessageSegment, Message]`: 消息内容 @@ -311,7 +350,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **说明** - 缩减消息数组,即拼接相邻纯文本消息段 + 缩减消息数组,即按 MessageSegment 的实现拼接相邻消息段 diff --git a/archive/2.0.0a4/api/adapters/cqhttp.md b/archive/2.0.0a7/api/adapters/cqhttp.md similarity index 74% rename from archive/2.0.0a4/api/adapters/cqhttp.md rename to archive/2.0.0a7/api/adapters/cqhttp.md index 73b4e044..b80d6ad1 100644 --- a/archive/2.0.0a4/api/adapters/cqhttp.md +++ b/archive/2.0.0a7/api/adapters/cqhttp.md @@ -5,29 +5,6 @@ sidebarDepth: 0 # NoneBot.adapters.cqhttp 模块 -## CQHTTP (OneBot) v11 协议适配 - -协议详情请看: [CQHTTP](http://cqhttp.cc/) | [OneBot](https://github.com/howmanybots/onebot) - - -## `log(level, message)` - - -* **说明** - - 用于打印 CQHTTP 日志。 - - - -* **参数** - - - * `level: str`: 日志等级 - - - * `message: str`: 日志信息 - - ## `escape(s, *, escape_comma=True)` @@ -64,9 +41,50 @@ sidebarDepth: 0 -## `_b2s(b)` +## _exception_ `CQHTTPAdapterException` -转换布尔值为字符串。 +基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException) + + +## _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]`: 错误码 + + + +## _exception_ `ApiNotAvailable` + +基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException` ## _async_ `_check_reply(bot, event)` @@ -158,7 +176,7 @@ sidebarDepth: 0 ## _class_ `Bot` -基类:[`nonebot.adapters.BaseBot`](#None) +基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot) CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 @@ -169,6 +187,15 @@ CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 * 返回: `"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)` @@ -261,7 +288,7 @@ CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 ## _class_ `Event` -基类:[`nonebot.adapters.BaseEvent`](#None) +基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent) CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。 @@ -403,13 +430,13 @@ CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) ## _class_ `MessageSegment` -基类:[`nonebot.adapters.BaseMessageSegment`](#None) +基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment) CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 ## _class_ `Message` -基类:[`nonebot.adapters.BaseMessage`](#None) +基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage) CQHTTP 协议 Message 适配。 diff --git a/archive/2.0.0a7/api/adapters/ding.md b/archive/2.0.0a7/api/adapters/ding.md new file mode 100644 index 00000000..0bbdd6d8 --- /dev/null +++ b/archive/2.0.0a7/api/adapters/ding.md @@ -0,0 +1,380 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.ding 模块 + + +## _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_ `ApiNotAvailable` + +基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException` + + +## _exception_ `NetworkError` + +基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 网络错误。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + + +## _exception_ `SessionExpired` + +基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 发消息的 session 已经过期。 + + + +## _class_ `Bot` + +基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot) + +钉钉 协议 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_ `handle_message(body)` + + +* **说明** + + 处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。 + + + +* **参数** + + + * `message: dict`: 收到的上报消息 + + + +### _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 调用失败 + + + +## _class_ `Event` + +基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent) + +钉钉 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。 + + +### _property_ `raw_event` + +原始上报消息 + + +### _property_ `id` + + +* 类型: `Optional[str]` + + +* 说明: 消息 ID + + +### _property_ `name` + + +* 类型: `str` + + +* 说明: 事件名称,由 type.\`detail_type\` 组合而成 + + +### _property_ `self_id` + + +* 类型: `str` + + +* 说明: 机器人自身 ID + + +### _property_ `time` + + +* 类型: `int` + + +* 说明: 消息的时间戳,单位 s + + +### _property_ `type` + + +* 类型: `str` + + +* 说明: 事件类型 + + +### _property_ `detail_type` + + +* 类型: `str` + + +* 说明: 事件详细类型 + + +### _property_ `sub_type` + + +* 类型: `None` + + +* 说明: 钉钉适配器无事件子类型 + + +### _property_ `user_id` + + +* 类型: `Optional[str]` + + +* 说明: 发送者 ID + + +### _property_ `group_id` + + +* 类型: `Optional[str]` + + +* 说明: 事件主体群 ID + + +### _property_ `to_me` + + +* 类型: `Optional[bool]` + + +* 说明: 消息是否与机器人相关 + + +### _property_ `message` + + +* 类型: `Optional[Message]` + + +* 说明: 消息内容 + + +### _property_ `reply` + + +* 类型: `None` + + +* 说明: 回复消息详情 + + +### _property_ `raw_message` + + +* 类型: `Optional[str]` + + +* 说明: 原始消息 + + +### _property_ `plain_text` + + +* 类型: `Optional[str]` + + +* 说明: 纯文本消息内容 + + +### _property_ `sender` + + +* 类型: `Optional[dict]` + + +* 说明: 消息发送者信息 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment) + +钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + + +### _static_ `actionCardSingleMultiBtns(title, text, btns=[], hideAvatar=False, btnOrientation='1')` + + +* **参数** + + + * `btnOrientation`: 0:按钮竖直排列 1:按钮横向排列 + + + * `btns`: [{ "title": title, "actionURL": actionURL }, ...] + + + +### _static_ `feedCard(links=[])` + + +* **参数** + + + * `links`: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...] + + + +### _static_ `empty()` + +不想回复消息到群里 + + +## _class_ `Message` + +基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage) + +钉钉 协议 Message 适配。 diff --git a/archive/2.0.0a7/api/config.md b/archive/2.0.0a7/api/config.md new file mode 100644 index 00000000..f2eaa4d4 --- /dev/null +++ b/archive/2.0.0a7/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` + +基类:`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` + + +* **类型**: `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.0a4/api/drivers/README.md b/archive/2.0.0a7/api/drivers/README.md similarity index 100% rename from archive/2.0.0a4/api/drivers/README.md rename to archive/2.0.0a7/api/drivers/README.md diff --git a/archive/2.0.0a4/api/drivers/fastapi.md b/archive/2.0.0a7/api/drivers/fastapi.md similarity index 67% rename from archive/2.0.0a4/api/drivers/fastapi.md rename to archive/2.0.0a7/api/drivers/fastapi.md index 523b09b2..b4f5c6fb 100644 --- a/archive/2.0.0a4/api/drivers/fastapi.md +++ b/archive/2.0.0a7/api/drivers/fastapi.md @@ -12,22 +12,25 @@ sidebarDepth: 0 ## _class_ `Driver` -基类:[`nonebot.drivers.BaseDriver`](#None) +基类:[`nonebot.drivers.BaseDriver`](README.md#nonebot.drivers.BaseDriver) FastAPI 驱动框架 -### `__init__(env, config)` +* **上报地址** + + + * `/{adapter name}/`: HTTP POST 上报 -* **参数** + * `/{adapter name}/http/`: HTTP POST 上报 - -* `env: Env`: 包含环境信息的 Env 对象 + * `/{adapter name}/ws`: WebSocket 上报 -* `config: Config`: 包含配置信息的 Config 对象 + * `/{adapter name}/ws/`: WebSocket 上报 + ### _property_ `type` @@ -65,29 +68,19 @@ fastapi 使用的 logger 使用 `uvicorn` 启动 FastAPI -### _async_ `_handle_http(adapter, data=Body(Ellipsis), x_self_id=Header(None), x_signature=Header(None), auth=Depends(get_auth_bearer))` +### _async_ `_handle_http(adapter, request, data=Body(Ellipsis))` 用于处理 HTTP 类型请求的函数 -### _async_ `_handle_ws_reverse(adapter, websocket, x_self_id=Header(None), auth=Depends(get_auth_bearer))` +### _async_ `_handle_ws_reverse(adapter, websocket)` 用于处理 WebSocket 类型请求的函数 ## _class_ `WebSocket` -基类:[`nonebot.drivers.BaseWebSocket`](#None) - - -### `__init__(websocket)` - - -* **参数** - - - -* `websocket: Any`: WebSocket 连接对象 +基类:[`nonebot.drivers.BaseWebSocket`](README.md#nonebot.drivers.BaseWebSocket) ### _property_ `closed` diff --git a/archive/2.0.0a4/api/exception.md b/archive/2.0.0a7/api/exception.md similarity index 66% rename from archive/2.0.0a4/api/exception.md rename to archive/2.0.0a7/api/exception.md index 2c7abad1..0c584f75 100644 --- a/archive/2.0.0a4/api/exception.md +++ b/archive/2.0.0a7/api/exception.md @@ -11,11 +11,22 @@ sidebarDepth: 0 这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。 -## _exception_ `IgnoredException` +## _exception_ `NoneBotException` 基类:`Exception` +* **说明** + + 所有 NoneBot 发生的异常基类。 + + + +## _exception_ `IgnoredException` + +基类:`nonebot.exception.NoneBotException` + + * **说明** 指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。 @@ -31,7 +42,7 @@ sidebarDepth: 0 ## _exception_ `PausedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -49,7 +60,7 @@ sidebarDepth: 0 ## _exception_ `RejectedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -67,7 +78,7 @@ sidebarDepth: 0 ## _exception_ `FinishedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -83,26 +94,9 @@ sidebarDepth: 0 -## _exception_ `ExpiredException` - -基类:`Exception` - - -* **说明** - - 指示 NoneBot 当前 `Matcher` 已失效。 - - - -* **用法** - - 当 `Matcher` 运行前检查时抛出。 - - - ## _exception_ `StopPropagation` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -117,9 +111,48 @@ sidebarDepth: 0 +## _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_ `ApiNotAvailable` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** @@ -130,7 +163,7 @@ sidebarDepth: 0 ## _exception_ `NetworkError` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** @@ -141,16 +174,9 @@ sidebarDepth: 0 ## _exception_ `ActionFailed` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** API 请求成功返回数据,但 API 操作失败。 - - - -* **参数** - - - * `retcode`: 错误代码 diff --git a/archive/2.0.0a4/api/log.md b/archive/2.0.0a7/api/log.md similarity index 100% rename from archive/2.0.0a4/api/log.md rename to archive/2.0.0a7/api/log.md diff --git a/archive/2.0.0a4/api/matcher.md b/archive/2.0.0a7/api/matcher.md similarity index 86% rename from archive/2.0.0a4/api/matcher.md rename to archive/2.0.0a7/api/matcher.md index b061cd64..9e72b658 100644 --- a/archive/2.0.0a4/api/matcher.md +++ b/archive/2.0.0a7/api/matcher.md @@ -450,48 +450,3 @@ sidebarDepth: 0 * `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api - - - -## _class_ `MatcherGroup` - -基类:`object` - -事件响应器组合,统一管理。用法同 `Matcher` - - -### `__init__(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` - - -* **说明** - - 创建一个事件响应器组合,参数为默认值,与 `Matcher.new` 一致 - - - -### `matchers` - - -* **类型** - - `List[Type[Matcher]]` - - - -* **说明** - - 组内事件响应器列表 - - - -### `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` - - -* **说明** - - 在组中创建一个新的事件响应器,参数留空则使用组合默认值 - - -:::danger 警告 -如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数 -::: diff --git a/archive/2.0.0a7/api/message.md b/archive/2.0.0a7/api/message.md new file mode 100644 index 00000000..c9d7c158 --- /dev/null +++ b/archive/2.0.0a7/api/message.md @@ -0,0 +1,143 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.message 模块 + +## 事件处理 + +NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供了多个插槽以进行事件的预处理等。 + + +## `event_preprocessor(func)` + + +* **说明** + + 事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。 + + + +* **参数** + + 事件预处理函数接收三个参数。 + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: dict`: 当前 State + + + +## `event_postprocessor(func)` + + +* **说明** + + 事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。 + + + +* **参数** + + 事件后处理函数接收三个参数。 + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: dict`: 当前事件运行前 State + + + +## `run_preprocessor(func)` + + +* **说明** + + 运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。 + + + +* **参数** + + 运行预处理函数接收四个参数。 + + + * `matcher: Matcher`: 当前要运行的事件响应器 + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: dict`: 当前 State + + + +## `run_postprocessor(func)` + + +* **说明** + + 运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。 + + + +* **参数** + + 运行后处理函数接收五个参数。 + + + * `matcher: Matcher`: 运行完毕的事件响应器 + + + * `exception: Optional[Exception]`: 事件响应器运行错误(如果存在) + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + * `state: dict`: 当前 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.0a4/api/nonebot.md b/archive/2.0.0a7/api/nonebot.md similarity index 93% rename from archive/2.0.0a4/api/nonebot.md rename to archive/2.0.0a7/api/nonebot.md index 7c89c882..93ede67e 100644 --- a/archive/2.0.0a4/api/nonebot.md +++ b/archive/2.0.0a7/api/nonebot.md @@ -28,21 +28,21 @@ sidebarDepth: 0 * `on_endswith` => `nonebot.plugin.on_endswith` +* `on_keyword` => `nonebot.plugin.on_keyword` + + * `on_command` => `nonebot.plugin.on_command` * `on_regex` => `nonebot.plugin.on_regex` -* `on_regex` => `nonebot.plugin.on_regex` - - -* `on_regex` => `nonebot.plugin.on_regex` - - * `CommandGroup` => `nonebot.plugin.CommandGroup` +* `MatcherGroup` => `nonebot.plugin.MatcherGroup` + + * `load_plugin` => `nonebot.plugin.load_plugin` @@ -52,9 +52,18 @@ sidebarDepth: 0 * `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()` diff --git a/archive/2.0.0a4/api/permission.md b/archive/2.0.0a7/api/permission.md similarity index 100% rename from archive/2.0.0a4/api/permission.md rename to archive/2.0.0a7/api/permission.md diff --git a/archive/2.0.0a4/api/plugin.md b/archive/2.0.0a7/api/plugin.md similarity index 52% rename from archive/2.0.0a4/api/plugin.md rename to archive/2.0.0a7/api/plugin.md index 42cdf84f..91d7320e 100644 --- a/archive/2.0.0a4/api/plugin.md +++ b/archive/2.0.0a7/api/plugin.md @@ -25,6 +25,38 @@ sidebarDepth: 0 +## _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` @@ -59,6 +91,15 @@ sidebarDepth: 0 * **说明**: 插件内定义的 `Matcher` +### `export` + + +* **类型**: `Export` + + +* **说明**: 插件内定义的导出内容 + + ## `on(type='', rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` @@ -552,6 +593,475 @@ sidebarDepth: 0 +## _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, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_metaevent(**kwargs)` + + +* **说明** + + 注册一个元事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_message(**kwargs)` + + +* **说明** + + 注册一个消息事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_notice(**kwargs)` + + +* **说明** + + 注册一个通知事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_request(**kwargs)` + + +* **说明** + + 注册一个请求事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_startswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容开头时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息开头内容 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_endswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容结尾时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息结尾内容 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_keyword(keywords, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + + + +* **参数** + + + * `keywords: Set[str]`: 关键词列表 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_command(cmd, rule=None, aliases=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 + + 命令匹配规则参考: [命令形式匹配](rule.html#command-command) + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 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, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + ## `load_plugin(module_path)` @@ -614,12 +1124,35 @@ sidebarDepth: 0 +## `get_plugin(name)` + + +* **说明** + + 获取当前导入的某个插件。 + + + +* **参数** + + + * `name: str`: 插件名,与 `load_plugin` 参数一致。如果为 `load_plugins` 导入的插件,则为文件(夹)名。 + + + +* **返回** + + + * `Optional[Plugin]` + + + ## `get_loaded_plugins()` * **说明** - 获取当前已导入的插件。 + 获取当前已导入的所有插件。 @@ -627,3 +1160,42 @@ sidebarDepth: 0 * `Set[Plugin]` + + + +## `export()` + + +* **说明** + + 获取插件的导出内容对象 + + + +* **返回** + + + * `Export` + + + +## `require(name)` + + +* **说明** + + 获取一个插件的导出内容 + + + +* **参数** + + + * `name: str`: 插件名,与 `load_plugin` 参数一致。如果为 `load_plugins` 导入的插件,则为文件(夹)名。 + + + +* **返回** + + + * `Optional[Export]` diff --git a/archive/2.0.0a4/api/rule.md b/archive/2.0.0a7/api/rule.md similarity index 100% rename from archive/2.0.0a4/api/rule.md rename to archive/2.0.0a7/api/rule.md diff --git a/archive/2.0.0a4/api/typing.md b/archive/2.0.0a7/api/typing.md similarity index 77% rename from archive/2.0.0a4/api/typing.md rename to archive/2.0.0a7/api/typing.md index 72d66f23..8f8a2223 100644 --- a/archive/2.0.0a4/api/typing.md +++ b/archive/2.0.0a7/api/typing.md @@ -110,7 +110,7 @@ sidebarDepth: 0 -## `PreProcessor` +## `EventPreProcessor` * **类型** @@ -121,7 +121,55 @@ sidebarDepth: 0 * **说明** - 消息预处理函数 PreProcessor 类型 + 事件预处理函数 EventPreProcessor 类型 + + + + +## `EventPostProcessor` + + +* **类型** + + `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + 事件预处理函数 EventPostProcessor 类型 + + + + +## `RunPreProcessor` + + +* **类型** + + `Callable[[Matcher, Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + 事件响应器运行前预处理函数 RunPreProcessor 类型 + + + + +## `RunPostProcessor` + + +* **类型** + + `Callable[[Matcher, Optional[Exception], Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + 事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在) diff --git a/archive/2.0.0a4/api/utils.md b/archive/2.0.0a7/api/utils.md similarity index 94% rename from archive/2.0.0a4/api/utils.md rename to archive/2.0.0a7/api/utils.md index ed98fab9..52cf5766 100644 --- a/archive/2.0.0a4/api/utils.md +++ b/archive/2.0.0a7/api/utils.md @@ -54,8 +54,6 @@ sidebarDepth: 0 ## _class_ `DataclassEncoder` -基类:`json.encoder.JSONEncoder` - * **说明** diff --git a/archive/2.0.0a4/guide/README.md b/archive/2.0.0a7/guide/README.md similarity index 53% rename from archive/2.0.0a4/guide/README.md rename to archive/2.0.0a7/guide/README.md index 43b7f325..4326ac1b 100644 --- a/archive/2.0.0a4/guide/README.md +++ b/archive/2.0.0a7/guide/README.md @@ -1,33 +1,30 @@ # 概览 -:::tip 提示 + :::tip 提示 初次使用时可能会觉得这里的概览过于枯燥,可以先简单略读之后直接前往 [安装](./installation.md) 查看安装方法,并进行后续的基础使用教程。 ::: -NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的消息进行解析和处理,并以插件化的形式,分发给消息所对应的命令处理器和自然语言处理器,来完成具体的功能。 +## 简介 -除了起到解析消息的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制,尤其对于命令处理器,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 +NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。 -目前 NoneBot2 在 [FastAPI](https://fastapi.tiangolo.com/) 的基础上封装了与 [CQHTTP(OneBot) 协议](http://cqhttp.cc/)插件的网络交互。 +除了起到解析事件的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制。对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 -得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制,NoneBot 处理消息的吞吐量有了很大的保障,再配合 WebSocket 通信方式(也是最建议的通信方式),NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。 +得益于 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 仅支持 **Python 3.7+** ## 特色 -- 提供直观的测试前端 +NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**! + - 提供使用简易的脚手架 +- 提供丰富的官方插件 +- 提供可添加/替换的驱动以及协议选项 - 基于异步 I/O - 同时支持 HTTP 和反向 WebSocket 通信方式 - 支持多个机器人账号负载均衡 diff --git a/archive/2.0.0a4/guide/basic-configuration.md b/archive/2.0.0a7/guide/basic-configuration.md similarity index 100% rename from archive/2.0.0a4/guide/basic-configuration.md rename to archive/2.0.0a7/guide/basic-configuration.md diff --git a/archive/2.0.0a7/guide/creating-a-handler.md b/archive/2.0.0a7/guide/creating-a-handler.md new file mode 100644 index 00000000..ca65b1a6 --- /dev/null +++ b/archive/2.0.0a7/guide/creating-a-handler.md @@ -0,0 +1,159 @@ +# 事件处理 + +在上一章中,我们已经注册了事件响应器,现在我们可以正式编写事件处理逻辑了! + +## [事件处理函数](../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) +``` + +在之前的样例中,我们定义了两个函数 `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: dict): + state["key"] = "hello" + + +@matcher.got("key2", prompt="{key}!") +async def handle2(bot: Bot, event: Event, state: dict): + pass +``` + +`args_parser` 为参数处理函数,在这里传入一个新的函数以覆盖默认的参数处理。详情参照 [args_parser](#参数处理函数-args-parser) + +特别的,这些装饰器都可以套娃使用: + +```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`: 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如: + +- `state["_current_key"]`: 存储当前 `got` 获取的参数名 +- `state["_prefix"]`, `state["_suffix"]`: 存储当前 TRIE 匹配的前缀/后缀,可以通过该值获取用户命令的原始命令 + +### 参数处理函数 args_parser + +在使用 `got` 获取用户输入参数时,需要对用户的消息进行处理以转换为我们所需要的信息。在默认情况下,NoneBot 会把用户的消息字符串原封不动的赋值给 `state[key]` 。可以通过以下两种方式修改默认处理逻辑: + +- `@matcher.args_parser` 装饰器:直接装饰一个函数作为参数处理器 +- `got(key, prompt, args_parser)`:直接把函数作为参数传入 + +参数处理函数类型为:`Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`,即: + +```python +async def parser(bot: Bot, event: Event, state: dict): + state[state["_current_key"]] = str(event.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: dict): + print(state["_current_key"], ":", str(event.message)) + state[state["_current_key"]] = str(event.message) + +@matcher.handle() +async def first_receive(bot: Bot, event: Event, state: dict): + # 获取用户原始命令,如:/test + print(state["_prefix"]["raw_command"]) + # 处理用户输入参数,如:/test arg1 arg2 + raw_args = str(event.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: dict): + # 在这里对参数进行验证 + 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.0a7/guide/creating-a-matcher.md b/archive/2.0.0a7/guide/creating-a-matcher.md new file mode 100644 index 00000000..b603449a --- /dev/null +++ b/archive/2.0.0a7/guide/creating-a-matcher.md @@ -0,0 +1,144 @@ +# 注册事件响应器 + +好了,现在插件已经创建完毕,我们可以开始编写实际代码了,下面将以一个简易单文件天气查询插件为例。 + +在插件目录下 `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(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-test` 可以看到当前所有事件响应器的执行流程,有助理解事件响应流程! + +```bash +pip install nonebot2[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 + +async def async_checker(bot: Bot, event: Event, state: dict) -> bool: + return True + +def sync_checker(bot: Bot, event: Event, state: dict) -> bool: + return True + +def check(arg1, args2): + + async def _checker(bot: Bot, event: Event, state: dict) -> bool: + return bool(arg1 + arg2) + + return Rule(_check) +``` + +`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.0a7/guide/creating-a-plugin.md b/archive/2.0.0a7/guide/creating-a-plugin.md new file mode 100644 index 00000000..0a6678db --- /dev/null +++ b/archive/2.0.0a7/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 BaseSetting + + +class Config(BaseSetting): + + # 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.0a4/guide/creating-a-project.md b/archive/2.0.0a7/guide/creating-a-project.md similarity index 87% rename from archive/2.0.0a4/guide/creating-a-project.md rename to archive/2.0.0a7/guide/creating-a-project.md index 74cdb24a..b8ac3b77 100644 --- a/archive/2.0.0a4/guide/creating-a-project.md +++ b/archive/2.0.0a7/guide/creating-a-project.md @@ -4,16 +4,12 @@ ## 目录结构 -首先,我们可以使用 `nb-cli` 或者自行创建项目目录: +首先,我们可以使用 `nb-cli` 或者自行创建完整的项目目录: ```bash -pip install nonebot2[cli] -# pip install nb-cli nb create ``` -这将创建默认的目录结构 - :::vue AweSome-Bot diff --git a/archive/2.0.0a7/guide/end-or-start.md b/archive/2.0.0a7/guide/end-or-start.md new file mode 100644 index 00000000..11780114 --- /dev/null +++ b/archive/2.0.0a7/guide/end-or-start.md @@ -0,0 +1,9 @@ +# 结语 + +至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示: + +- 请千万注意事件处理器的优先级设定 +- 在匹配规则中请勿使用耗时极长的函数 +- 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍) + +如果你还不能满足,前往 [进阶](../advanced/README.md) 获得更多的功能信息。 diff --git a/archive/2.0.0a4/guide/getting-started.md b/archive/2.0.0a7/guide/getting-started.md similarity index 80% rename from archive/2.0.0a4/guide/getting-started.md rename to archive/2.0.0a7/guide/getting-started.md index 9c358ead..8ed182eb 100644 --- a/archive/2.0.0a4/guide/getting-started.md +++ b/archive/2.0.0a7/guide/getting-started.md @@ -4,38 +4,53 @@ ## 最小实例 -使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下: +如果你已经按照推荐方式安装了 `nb-cli`,使用脚手架创建一个空项目: + +```bash +nb create +``` + +根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`。 + +如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下: ```python{3,4,7} 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() ``` -这几行高亮代码将依次: +## 解读 -1. 使用默认配置初始化 NoneBot 包 +在上方 `bot.py` 中,这几行高亮代码将依次: + +1. 使用默认配置初始化 NoneBot 2. 加载 NoneBot 内置的插件 3. 在地址 `127.0.0.1:8080` 运行 NoneBot 在命令行使用如下命令即可运行这个 NoneBot 实例: ```bash +# nb-cli +nb run +# 其他 python bot.py ``` 运行后会产生如下日志: -```default +```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] 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) ``` @@ -46,23 +61,23 @@ python bot.py 目前支持的协议有: -- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot) +- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot/blob/master/README.md) 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)) +- [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 文件 -2. 双击 exe 文件或者使用 `./go-cqhttp` 启动 +1. 下载 go-cqhttp 对应平台的 release 文件,[点此前往](https://github.com/Mrs4s/go-cqhttp/releases) +2. 运行 exe 文件或者使用 `./go-cqhttp` 启动 3. 生成默认配置文件并修改默认配置 -```json{2,3,30-31} +```json{2,3,35-36,42} { "uin": 你的QQ号, "password": "你的密码", @@ -75,6 +90,11 @@ QQ 协议端举例: "relogin_delay": 3, "max_relogin_times": 0 }, + "_rate_limit": { + "enabled": false, + "frequency": 0, + "bucket_size": 0 + }, "ignore_invalid_cqcode": false, "force_fragmented": true, "heartbeat_interval": 0, @@ -99,9 +119,16 @@ QQ 协议端举例: "reverse_reconnect_interval": 3000 } ], - "post_message_format": "string", + "post_message_format": "array", + "use_sso_address": false, "debug": false, - "log_level": "" + "log_level": "", + "web_ui": { + "enabled": true, + "host": "0.0.0.0", + "web_ui_port": 9999, + "web_input": false + } } ``` diff --git a/archive/2.0.0a7/guide/installation.md b/archive/2.0.0a7/guide/installation.md new file mode 100644 index 00000000..b7259254 --- /dev/null +++ b/archive/2.0.0a7/guide/installation.md @@ -0,0 +1,87 @@ +# 安装 + +## NoneBot + +:::warning 注意 +请确保你的 Python 版本 >= 3.7。 +::: + +:::warning 注意 +请在安装 nonebot2 之前卸载 nonebot 1.x + +```bash +pip uninstall nonebot +``` + +::: + +### 通过脚手架安装(推荐安装方式) + +1. (可选)使用你喜欢的 Python 环境管理工具创建新的虚拟环境。 +2. 使用 `pip` (或其他) 安装 NoneBot 脚手架。 + + ```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) + +### 不使用脚手架(纯净安装) + +```bash +# poetry +poetry add nonebot2 +# pip +pip install nonebot2 +``` + +如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 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.0a7/guide/loading-a-plugin.md b/archive/2.0.0a7/guide/loading-a-plugin.md new file mode 100644 index 00000000..e69c52a8 --- /dev/null +++ b/archive/2.0.0a7/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.0a4/sidebar.config.json b/archive/2.0.0a7/sidebar.config.json similarity index 67% rename from archive/2.0.0a4/sidebar.config.json rename to archive/2.0.0a7/sidebar.config.json index 54e78eaa..d01b84e1 100644 --- a/archive/2.0.0a4/sidebar.config.json +++ b/archive/2.0.0a7/sidebar.config.json @@ -15,6 +15,10 @@ "text": "指南", "link": "/guide/" }, + { + "text": "进阶", + "link": "/advanced/" + }, { "text": "API", "link": "/api/" @@ -22,14 +26,17 @@ { "text": "插件广场", "link": "/plugin-store" + }, + { + "text": "更新日志", + "link": "/changelog" } ], "sidebarDepth": 2, "sidebar": { "/guide/": [ { - "title": "指南", - "path": "", + "title": "开始", "collapsable": false, "sidebar": "auto", "children": [ @@ -37,8 +44,41 @@ "installation", "getting-started", "creating-a-project", - "basic-configuration", - "writing-a-plugin" + "basic-configuration" + ] + }, + { + "title": "编写插件", + "collapsable": false, + "sidebar": "auto", + "children": [ + "loading-a-plugin", + "creating-a-plugin", + "creating-a-matcher", + "creating-a-handler", + "end-or-start" + ] + } + ], + "/advanced/": [ + { + "title": "进阶", + "collapsable": false, + "sidebar": "auto", + "children": [ + "", + "scheduler", + "permission", + "runtime-hook", + "export-and-require" + ] + }, + { + "title": "发布", + "collapsable": false, + "sidebar": "auto", + "children": [ + "publish-plugin" ] } ], @@ -60,6 +100,10 @@ "title": "nonebot.plugin 模块", "path": "plugin" }, + { + "title": "nonebot.message 模块", + "path": "message" + }, { "title": "nonebot.matcher 模块", "path": "matcher" @@ -72,10 +116,6 @@ "title": "nonebot.permission 模块", "path": "permission" }, - { - "title": "nonebot.sched 模块", - "path": "sched" - }, { "title": "nonebot.log 模块", "path": "log" @@ -107,6 +147,10 @@ { "title": "nonebot.adapters.cqhttp 模块", "path": "adapters/cqhttp" + }, + { + "title": "nonebot.adapters.ding 模块", + "path": "adapters/ding" } ] } diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index f7c87283..5d7cf2fb 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -130,9 +130,7 @@ module.exports = context => ({ title: "发布", collapsable: false, sidebar: "auto", - children: [ - "publish-plugin" - ] + children: ["publish-plugin"] } ], "/api/": [ @@ -169,10 +167,6 @@ module.exports = context => ({ title: "nonebot.permission 模块", path: "permission" }, - { - title: "nonebot.sched 模块", - path: "sched" - }, { title: "nonebot.log 模块", path: "log" @@ -204,6 +198,10 @@ module.exports = context => ({ { title: "nonebot.adapters.cqhttp 模块", path: "adapters/cqhttp" + }, + { + title: "nonebot.adapters.ding 模块", + path: "adapters/ding" } ] } diff --git a/docs/.vuepress/versions.json b/docs/.vuepress/versions.json index b2845794..be230268 100644 --- a/docs/.vuepress/versions.json +++ b/docs/.vuepress/versions.json @@ -1,4 +1,4 @@ [ - "2.0.0a6", - "2.0.0a4" + "2.0.0a7", + "2.0.0a6" ] \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index a1607904..c093eb5c 100644 --- a/docs/README.md +++ b/docs/README.md @@ -11,5 +11,5 @@ features: details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。 - title: 高性能 details: 采用异步 I/O,利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。 -footer: MIT Licensed | Copyright © 2020 NoneBot Team +footer: MIT Licensed | Copyright © 2018 - 2020 NoneBot Team --- diff --git a/docs/api/README.md b/docs/api/README.md index 75132b72..243733f8 100644 --- a/docs/api/README.md +++ b/docs/api/README.md @@ -25,9 +25,6 @@ * [nonebot.permission](permission.html) - * [nonebot.sched](sched.html) - - * [nonebot.log](log.html) @@ -50,3 +47,6 @@ * [nonebot.adapters.cqhttp](adapters/cqhttp.html) + + + * [nonebot.adapters.ding](adapters/ding.html) diff --git a/docs/api/adapters/README.md b/docs/api/adapters/README.md index c2d2e399..1a1dd85b 100644 --- a/docs/api/adapters/README.md +++ b/docs/api/adapters/README.md @@ -176,7 +176,7 @@ await bot.send_msg(message="hello world") ## _class_ `BaseEvent` -基类:`abc.ABC` +基类:`abc.ABC`, `typing.Generic` Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。 @@ -187,7 +187,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **参数** - * `raw_event: dict`: 原始上报消息 + * `raw_event: Union[dict, T]`: 原始上报消息 @@ -309,7 +309,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **参数** - * `message: Union[str, dict, list, MessageSegment, Message]`: 消息内容 + * `message: Union[str, dict, list, BaseModel, MessageSegment, Message]`: 消息内容 @@ -350,7 +350,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **说明** - 缩减消息数组,即拼接相邻纯文本消息段 + 缩减消息数组,即按 MessageSegment 的实现拼接相邻消息段 diff --git a/docs/api/adapters/cqhttp.md b/docs/api/adapters/cqhttp.md index aa6ad47f..b80d6ad1 100644 --- a/docs/api/adapters/cqhttp.md +++ b/docs/api/adapters/cqhttp.md @@ -5,29 +5,6 @@ sidebarDepth: 0 # NoneBot.adapters.cqhttp 模块 -## CQHTTP (OneBot) v11 协议适配 - -协议详情请看: [CQHTTP](http://cqhttp.cc/) | [OneBot](https://github.com/howmanybots/onebot) - - -## `log(level, message)` - - -* **说明** - - 用于打印 CQHTTP 日志。 - - - -* **参数** - - - * `level: str`: 日志等级 - - - * `message: str`: 日志信息 - - ## `escape(s, *, escape_comma=True)` @@ -64,9 +41,50 @@ sidebarDepth: 0 -## `_b2s(b)` +## _exception_ `CQHTTPAdapterException` -转换布尔值为字符串。 +基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException) + + +## _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]`: 错误码 + + + +## _exception_ `ApiNotAvailable` + +基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException` ## _async_ `_check_reply(bot, event)` diff --git a/docs/api/adapters/ding.md b/docs/api/adapters/ding.md new file mode 100644 index 00000000..0bbdd6d8 --- /dev/null +++ b/docs/api/adapters/ding.md @@ -0,0 +1,380 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.ding 模块 + + +## _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_ `ApiNotAvailable` + +基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException` + + +## _exception_ `NetworkError` + +基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 网络错误。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + + +## _exception_ `SessionExpired` + +基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 发消息的 session 已经过期。 + + + +## _class_ `Bot` + +基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot) + +钉钉 协议 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_ `handle_message(body)` + + +* **说明** + + 处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。 + + + +* **参数** + + + * `message: dict`: 收到的上报消息 + + + +### _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 调用失败 + + + +## _class_ `Event` + +基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent) + +钉钉 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。 + + +### _property_ `raw_event` + +原始上报消息 + + +### _property_ `id` + + +* 类型: `Optional[str]` + + +* 说明: 消息 ID + + +### _property_ `name` + + +* 类型: `str` + + +* 说明: 事件名称,由 type.\`detail_type\` 组合而成 + + +### _property_ `self_id` + + +* 类型: `str` + + +* 说明: 机器人自身 ID + + +### _property_ `time` + + +* 类型: `int` + + +* 说明: 消息的时间戳,单位 s + + +### _property_ `type` + + +* 类型: `str` + + +* 说明: 事件类型 + + +### _property_ `detail_type` + + +* 类型: `str` + + +* 说明: 事件详细类型 + + +### _property_ `sub_type` + + +* 类型: `None` + + +* 说明: 钉钉适配器无事件子类型 + + +### _property_ `user_id` + + +* 类型: `Optional[str]` + + +* 说明: 发送者 ID + + +### _property_ `group_id` + + +* 类型: `Optional[str]` + + +* 说明: 事件主体群 ID + + +### _property_ `to_me` + + +* 类型: `Optional[bool]` + + +* 说明: 消息是否与机器人相关 + + +### _property_ `message` + + +* 类型: `Optional[Message]` + + +* 说明: 消息内容 + + +### _property_ `reply` + + +* 类型: `None` + + +* 说明: 回复消息详情 + + +### _property_ `raw_message` + + +* 类型: `Optional[str]` + + +* 说明: 原始消息 + + +### _property_ `plain_text` + + +* 类型: `Optional[str]` + + +* 说明: 纯文本消息内容 + + +### _property_ `sender` + + +* 类型: `Optional[dict]` + + +* 说明: 消息发送者信息 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment) + +钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + + +### _static_ `actionCardSingleMultiBtns(title, text, btns=[], hideAvatar=False, btnOrientation='1')` + + +* **参数** + + + * `btnOrientation`: 0:按钮竖直排列 1:按钮横向排列 + + + * `btns`: [{ "title": title, "actionURL": actionURL }, ...] + + + +### _static_ `feedCard(links=[])` + + +* **参数** + + + * `links`: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...] + + + +### _static_ `empty()` + +不想回复消息到群里 + + +## _class_ `Message` + +基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage) + +钉钉 协议 Message 适配。 diff --git a/docs/api/config.md b/docs/api/config.md index 6943427b..f2eaa4d4 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -24,14 +24,16 @@ NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-d ### `environment` -* 类型: `str` +* **类型**: `str` -* 默认值: `"prod"` +* **默认值**: `"prod"` -* 说明: -当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。 +* **说明** + + 当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。 + ## _class_ `Config` @@ -47,69 +49,80 @@ NoneBot 主要配置。大小写不敏感。 ### `driver` -* 类型: `str` +* **类型**: `str` -* 默认值: `"nonebot.drivers.fastapi"` +* **默认值**: `"nonebot.drivers.fastapi"` -* 说明: -NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver` 。 +* **说明** + + NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver` 。 + ### `host` -* 类型: `IPvAnyAddress` +* **类型**: `IPvAnyAddress` -* 默认值: `127.0.0.1` +* **默认值**: `127.0.0.1` -* 说明: -NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。 +* **说明** + + NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。 + ### `port` -* 类型: `int` +* **类型**: `int` -* 默认值: `8080` +* **默认值**: `8080` -* 说明: -NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。 +* **说明** + + NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。 + ### `debug` -* 类型: `bool` +* **类型**: `bool` -* 默认值: `False` +* **默认值**: `False` -* 说明: -是否以调试模式运行 NoneBot。 +* **说明** + + 是否以调试模式运行 NoneBot。 + ### `api_root` -* 类型: `Dict[str, str]` +* **类型**: `Dict[str, str]` -* 默认值: `{}` +* **默认值**: `{}` -* 说明: -以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。 +* **说明** + + 以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。 -* 示例: + +* **示例** + ```default API_ROOT={"123456": "http://127.0.0.1:5700"} @@ -119,30 +132,35 @@ API_ROOT={"123456": "http://127.0.0.1:5700"} ### `api_timeout` -* 类型: `Optional[float]` +* **类型**: `Optional[float]` -* 默认值: `30.` +* **默认值**: `30.` -* 说明: -API 请求超时时间,单位: 秒。 +* **说明** + + API 请求超时时间,单位: 秒。 + ### `access_token` -* 类型: `Optional[str]` +* **类型**: `Optional[str]` -* 默认值: `None` +* **默认值**: `None` -* 说明: -API 请求以及上报所需密钥,在请求头中携带。 +* **说明** + + API 请求以及上报所需密钥,在请求头中携带。 -* 示例: + +* **示例** + ```http POST /cqhttp/ HTTP/1.1 @@ -153,17 +171,20 @@ Authorization: Bearer kSLuTF2GC2Q4q4ugm3 ### `secret` -* 类型: `Optional[str]` +* **类型**: `Optional[str]` -* 默认值: `None` +* **默认值**: `None` -* 说明: -HTTP POST 形式上报所需签名,在请求头中携带。 +* **说明** + + HTTP POST 形式上报所需签名,在请求头中携带。 -* 示例: + +* **示例** + ```http POST /cqhttp/ HTTP/1.1 @@ -174,17 +195,20 @@ X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 ### `superusers` -* 类型: `Set[int]` +* **类型**: `Set[int]` -* 默认值: `set()` +* **默认值**: `set()` -* 说明: -机器人超级用户。 +* **说明** + + 机器人超级用户。 -* 示例: + +* **示例** + ```default SUPER_USERS=[12345789] @@ -194,72 +218,68 @@ SUPER_USERS=[12345789] ### `nickname` -* 类型: `Set[str]` +* **类型**: `Set[str]` -* 默认值: `set()` +* **默认值**: `set()` -* 说明: -机器人昵称。 +* **说明** + + 机器人昵称。 + ### `command_start` -* 类型: `Set[str]` +* **类型**: `Set[str]` -* 默认值: `{"/"}` +* **默认值**: `{"/"}` -* 说明: -命令的起始标记,用于判断一条消息是不是命令。 +* **说明** + + 命令的起始标记,用于判断一条消息是不是命令。 + ### `command_sep` -* 类型: `Set[str]` +* **类型**: `Set[str]` -* 默认值: `{"."}` +* **默认值**: `{"."}` -* 说明: -命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。 +* **说明** + + 命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。 + ### `session_expire_timeout` -* 类型: `timedelta` +* **类型**: `timedelta` -* 默认值: `timedelta(minutes=2)` +* **默认值**: `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/docs/api/drivers/fastapi.md b/docs/api/drivers/fastapi.md index 1f7f96ee..b4f5c6fb 100644 --- a/docs/api/drivers/fastapi.md +++ b/docs/api/drivers/fastapi.md @@ -17,6 +17,22 @@ sidebarDepth: 0 FastAPI 驱动框架 +* **上报地址** + + + * `/{adapter name}/`: HTTP POST 上报 + + + * `/{adapter name}/http/`: HTTP POST 上报 + + + * `/{adapter name}/ws`: WebSocket 上报 + + + * `/{adapter name}/ws/`: WebSocket 上报 + + + ### _property_ `type` 驱动名称: `fastapi` diff --git a/docs/api/exception.md b/docs/api/exception.md index 0a9876a8..0c584f75 100644 --- a/docs/api/exception.md +++ b/docs/api/exception.md @@ -11,11 +11,22 @@ sidebarDepth: 0 这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。 -## _exception_ `IgnoredException` +## _exception_ `NoneBotException` 基类:`Exception` +* **说明** + + 所有 NoneBot 发生的异常基类。 + + + +## _exception_ `IgnoredException` + +基类:`nonebot.exception.NoneBotException` + + * **说明** 指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。 @@ -31,7 +42,7 @@ sidebarDepth: 0 ## _exception_ `PausedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -49,7 +60,7 @@ sidebarDepth: 0 ## _exception_ `RejectedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -67,7 +78,7 @@ sidebarDepth: 0 ## _exception_ `FinishedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -85,7 +96,7 @@ sidebarDepth: 0 ## _exception_ `StopPropagation` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -102,7 +113,7 @@ sidebarDepth: 0 ## _exception_ `RequestDenied` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -121,9 +132,27 @@ sidebarDepth: 0 +## _exception_ `AdapterException` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 代表 `Adapter` 抛出的异常,所有的 `Adapter` 都要在内部继承自这个 `Exception` + + + +* **参数** + + + * `adapter_name: str`: 标识 adapter + + + ## _exception_ `ApiNotAvailable` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** @@ -134,7 +163,7 @@ sidebarDepth: 0 ## _exception_ `NetworkError` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** @@ -145,16 +174,9 @@ sidebarDepth: 0 ## _exception_ `ActionFailed` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** API 请求成功返回数据,但 API 操作失败。 - - - -* **参数** - - - * `retcode: Optional[int]`: 错误代码 diff --git a/docs/api/matcher.md b/docs/api/matcher.md index b061cd64..9e72b658 100644 --- a/docs/api/matcher.md +++ b/docs/api/matcher.md @@ -450,48 +450,3 @@ sidebarDepth: 0 * `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api - - - -## _class_ `MatcherGroup` - -基类:`object` - -事件响应器组合,统一管理。用法同 `Matcher` - - -### `__init__(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` - - -* **说明** - - 创建一个事件响应器组合,参数为默认值,与 `Matcher.new` 一致 - - - -### `matchers` - - -* **类型** - - `List[Type[Matcher]]` - - - -* **说明** - - 组内事件响应器列表 - - - -### `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` - - -* **说明** - - 在组中创建一个新的事件响应器,参数留空则使用组合默认值 - - -:::danger 警告 -如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数 -::: diff --git a/docs/api/nonebot.md b/docs/api/nonebot.md index 68708c95..d2ef4eb4 100644 --- a/docs/api/nonebot.md +++ b/docs/api/nonebot.md @@ -40,6 +40,9 @@ sidebarDepth: 0 * `CommandGroup` => `nonebot.plugin.CommandGroup` +* `Matchergroup` => `nonebot.plugin.MatcherGroup` + + * `load_plugin` => `nonebot.plugin.load_plugin` diff --git a/docs/api/plugin.md b/docs/api/plugin.md index 5f7a7d46..91d7320e 100644 --- a/docs/api/plugin.md +++ b/docs/api/plugin.md @@ -46,10 +46,11 @@ nonebot.export().default = "bar" def some_function(): pass -# this don't work under python 3.9 +# 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 @@ -592,6 +593,475 @@ def something_else(): +## _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, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_metaevent(**kwargs)` + + +* **说明** + + 注册一个元事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_message(**kwargs)` + + +* **说明** + + 注册一个消息事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_notice(**kwargs)` + + +* **说明** + + 注册一个通知事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_request(**kwargs)` + + +* **说明** + + 注册一个请求事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_startswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容开头时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息开头内容 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_endswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容结尾时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息结尾内容 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_keyword(keywords, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + + + +* **参数** + + + * `keywords: Set[str]`: 关键词列表 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_command(cmd, rule=None, aliases=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 + + 命令匹配规则参考: [命令形式匹配](rule.html#command-command) + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 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, RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[dict]`: 默认的 state + + + +* **返回** + + + * `Type[Matcher]` + + + ## `load_plugin(module_path)` diff --git a/docs/api/sched.md b/docs/api/sched.md deleted file mode 100644 index 450fd7d0..00000000 --- a/docs/api/sched.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -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/docs/api/utils.md b/docs/api/utils.md index ed98fab9..52cf5766 100644 --- a/docs/api/utils.md +++ b/docs/api/utils.md @@ -54,8 +54,6 @@ sidebarDepth: 0 ## _class_ `DataclassEncoder` -基类:`json.encoder.JSONEncoder` - * **说明** diff --git a/docs/guide/README.md b/docs/guide/README.md index cacb58ac..4326ac1b 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -1,27 +1,30 @@ # 概览 -:::tip 提示 + :::tip 提示 初次使用时可能会觉得这里的概览过于枯燥,可以先简单略读之后直接前往 [安装](./installation.md) 查看安装方法,并进行后续的基础使用教程。 ::: -NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的消息进行解析和处理,并以插件化的形式,分发给消息所对应的命令处理器和自然语言处理器,来完成具体的功能。 +## 简介 -除了起到解析消息的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制,尤其对于命令处理器,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 +NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。 -目前 NoneBot2 在 [FastAPI](https://fastapi.tiangolo.com/) 的基础上封装了与 [CQHTTP(OneBot) 协议](http://cqhttp.cc/)插件的网络交互。 +除了起到解析事件的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制。对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 -得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制,NoneBot 处理消息的吞吐量有了很大的保障,再配合 WebSocket 通信方式(也是最建议的通信方式),NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。 +得益于 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 仅支持 **Python 3.7+** ## 特色 -- 提供直观的测试前端 +NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**! + - 提供使用简易的脚手架 +- 提供丰富的官方插件 +- 提供可添加/替换的驱动以及协议选项 - 基于异步 I/O - 同时支持 HTTP 和反向 WebSocket 通信方式 - 支持多个机器人账号负载均衡 diff --git a/docs/guide/creating-a-plugin.md b/docs/guide/creating-a-plugin.md index fe52a25d..0a6678db 100644 --- a/docs/guide/creating-a-plugin.md +++ b/docs/guide/creating-a-plugin.md @@ -2,6 +2,12 @@ 如果之前使用 `nb-cli` 生成了项目结构,那我们已经有了一个空的插件目录 `Awesome-Bot/awesome_bot/plugins`,并且它已在 `bot.py` 中被加载,我们现在可以开始创建插件了! +使用 `nb-cli` 创建包形式插件,或自行创建文件(夹) + +```bash +nb plugin new +``` + 插件通常有两种形式,下面分别介绍 ## 单文件形式 diff --git a/docs/guide/creating-a-project.md b/docs/guide/creating-a-project.md index 74cdb24a..b8ac3b77 100644 --- a/docs/guide/creating-a-project.md +++ b/docs/guide/creating-a-project.md @@ -4,16 +4,12 @@ ## 目录结构 -首先,我们可以使用 `nb-cli` 或者自行创建项目目录: +首先,我们可以使用 `nb-cli` 或者自行创建完整的项目目录: ```bash -pip install nonebot2[cli] -# pip install nb-cli nb create ``` -这将创建默认的目录结构 - :::vue AweSome-Bot diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 9c358ead..8ed182eb 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -4,38 +4,53 @@ ## 最小实例 -使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下: +如果你已经按照推荐方式安装了 `nb-cli`,使用脚手架创建一个空项目: + +```bash +nb create +``` + +根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`。 + +如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下: ```python{3,4,7} 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() ``` -这几行高亮代码将依次: +## 解读 -1. 使用默认配置初始化 NoneBot 包 +在上方 `bot.py` 中,这几行高亮代码将依次: + +1. 使用默认配置初始化 NoneBot 2. 加载 NoneBot 内置的插件 3. 在地址 `127.0.0.1:8080` 运行 NoneBot 在命令行使用如下命令即可运行这个 NoneBot 实例: ```bash +# nb-cli +nb run +# 其他 python bot.py ``` 运行后会产生如下日志: -```default +```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] 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) ``` @@ -46,23 +61,23 @@ python bot.py 目前支持的协议有: -- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot) +- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot/blob/master/README.md) 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)) +- [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 文件 -2. 双击 exe 文件或者使用 `./go-cqhttp` 启动 +1. 下载 go-cqhttp 对应平台的 release 文件,[点此前往](https://github.com/Mrs4s/go-cqhttp/releases) +2. 运行 exe 文件或者使用 `./go-cqhttp` 启动 3. 生成默认配置文件并修改默认配置 -```json{2,3,30-31} +```json{2,3,35-36,42} { "uin": 你的QQ号, "password": "你的密码", @@ -75,6 +90,11 @@ QQ 协议端举例: "relogin_delay": 3, "max_relogin_times": 0 }, + "_rate_limit": { + "enabled": false, + "frequency": 0, + "bucket_size": 0 + }, "ignore_invalid_cqcode": false, "force_fragmented": true, "heartbeat_interval": 0, @@ -99,9 +119,16 @@ QQ 协议端举例: "reverse_reconnect_interval": 3000 } ], - "post_message_format": "string", + "post_message_format": "array", + "use_sso_address": false, "debug": false, - "log_level": "" + "log_level": "", + "web_ui": { + "enabled": true, + "host": "0.0.0.0", + "web_ui_port": 9999, + "web_input": false + } } ``` diff --git a/docs/guide/installation.md b/docs/guide/installation.md index 2b54eae1..b7259254 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -6,14 +6,40 @@ 请确保你的 Python 版本 >= 3.7。 ::: +:::warning 注意 请在安装 nonebot2 之前卸载 nonebot 1.x ```bash pip uninstall nonebot +``` + +::: + +### 通过脚手架安装(推荐安装方式) + +1. (可选)使用你喜欢的 Python 环境管理工具创建新的虚拟环境。 +2. 使用 `pip` (或其他) 安装 NoneBot 脚手架。 + + ```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) + +### 不使用脚手架(纯净安装) + +```bash +# poetry +poetry add nonebot2 +# pip pip install nonebot2 ``` -如果你需要使用最新的(可能尚未发布的)特性,可以直接从 GitHub 仓库安装: +如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 GitHub 仓库安装: ```bash # master @@ -31,56 +57,31 @@ poetry install --no-dev # 推荐 pip install . # 不推荐 ``` -## 额外依赖 +## 安装插件 -### APScheduler - -A task scheduling library for Python. - -可用于计划任务,后台执行任务等 +插件可以通过 `nb-cli` 进行安装,也可以自行安装并加载插件。 ```bash -pip install nonebot2[scheduler] -poetry add nonebot2[scheduler] +# 列出所有的插件 +nb plugin list +# 搜索插件 +nb plugin search xxx +# 安装插件 +nb plugin install xxx ``` -[![apscheduler](https://img.shields.io/github/stars/agronholm/apscheduler?style=social)](https://github.com/agronholm/apscheduler) +如果急于上线 Bot 或想要使用现成的插件,以下插件可作为参考: +### 官方插件 -### NoneBot-Test +~~自用插件~~ ~~确信~~ -A test frontend for nonebot2. +- [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) 服务器状态查看插件 -通过前端展示 nonebot 已加载的插件以及运行状态,同时可以用于模拟发送事件测试机器人 +### 其他插件 -```bash -pip install nonebot2[test] -poetry add nonebot2[test] -``` - -[![nonebot-test](https://img.shields.io/github/stars/nonebot/nonebot-test?style=social)](https://github.com/nonebot/nonebot-test) - -### CLI - -CLI for nonebot2. - -一个多功能脚手架 - -```bash -pip install nonebot2[cli] -poetry add nonebot2[cli] -``` - -[![nb-cli](https://img.shields.io/github/stars/nonebot/nb-cli?style=social)](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] -``` +还有更多的插件在 [这里](/plugin-store.md) 等着你发现~ diff --git a/docs/guide/loading-a-plugin.md b/docs/guide/loading-a-plugin.md index 2a3016d5..e69c52a8 100644 --- a/docs/guide/loading-a-plugin.md +++ b/docs/guide/loading-a-plugin.md @@ -11,7 +11,7 @@ import nonebot nonebot.init() # 加载 nonebot 内置插件 -nonebot.load_bulitin_plugins() +nonebot.load_builtin_plugins() app = nonebot.get_asgi() @@ -76,8 +76,6 @@ if __name__ == "__main__": ## 子插件(嵌套插件) - - 在插件中同样可以加载子插件,例如如下插件目录结构: diff --git a/docs_build/README.rst b/docs_build/README.rst index 7721d3d1..95ffcc2d 100644 --- a/docs_build/README.rst +++ b/docs_build/README.rst @@ -9,7 +9,6 @@ NoneBot Api Reference - `nonebot.matcher `_ - `nonebot.rule `_ - `nonebot.permission `_ - - `nonebot.sched `_ - `nonebot.log `_ - `nonebot.utils `_ - `nonebot.typing `_ @@ -18,3 +17,4 @@ NoneBot Api Reference - `nonebot.drivers.fastapi `_ - `nonebot.adapters `_ - `nonebot.adapters.cqhttp `_ + - `nonebot.adapters.ding `_ diff --git a/docs_build/adapters/cqhttp.rst b/docs_build/adapters/cqhttp.rst index 3e63952b..4714296d 100644 --- a/docs_build/adapters/cqhttp.rst +++ b/docs_build/adapters/cqhttp.rst @@ -6,7 +6,28 @@ sidebarDepth: 0 NoneBot.adapters.cqhttp 模块 ============================ -.. automodule:: nonebot.adapters.cqhttp +.. automodule:: nonebot.adapters.cqhttp.utils + :members: + :show-inheritance: + +.. automodule:: nonebot.adapters.cqhttp.exception + :members: + :show-inheritance: + + +.. automodule:: nonebot.adapters.cqhttp.bot + :members: + :private-members: + :show-inheritance: + + +.. automodule:: nonebot.adapters.cqhttp.event + :members: + :private-members: + :show-inheritance: + + +.. automodule:: nonebot.adapters.cqhttp.message :members: :private-members: :show-inheritance: diff --git a/docs_build/adapters/ding.rst b/docs_build/adapters/ding.rst new file mode 100644 index 00000000..cff5979f --- /dev/null +++ b/docs_build/adapters/ding.rst @@ -0,0 +1,29 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +NoneBot.adapters.ding 模块 +============================ + +.. automodule:: nonebot.adapters.ding.exception + :members: + :show-inheritance: + + +.. automodule:: nonebot.adapters.ding.bot + :members: + :private-members: + :show-inheritance: + + +.. automodule:: nonebot.adapters.ding.event + :members: + :private-members: + :show-inheritance: + + +.. automodule:: nonebot.adapters.ding.message + :members: + :private-members: + :show-inheritance: diff --git a/docs_build/sched.rst b/docs_build/sched.rst deleted file mode 100644 index 714be93d..00000000 --- a/docs_build/sched.rst +++ /dev/null @@ -1,11 +0,0 @@ ---- -contentSidebar: true -sidebarDepth: 0 ---- - -NoneBot.sched 模块 -=================== - -.. automodule:: nonebot.sched - :members: - :show-inheritance: diff --git a/docs_build/utils.rst b/docs_build/utils.rst index b7609fdc..5e7acd8d 100644 --- a/docs_build/utils.rst +++ b/docs_build/utils.rst @@ -10,4 +10,5 @@ NoneBot.utils 模块 .. autofunction:: nonebot.utils.escape_tag .. autodecorator:: nonebot.utils.run_sync .. autoclass:: nonebot.utils.DataclassEncoder +.. autodecorator:: nonebot.utils.logger_wrapper :show-inheritance: diff --git a/nonebot/__init__.py b/nonebot/__init__.py index d642ff44..abf1eb58 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -14,6 +14,7 @@ - ``on_command`` => ``nonebot.plugin.on_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`` @@ -135,16 +136,9 @@ def get_bots() -> Union[NoReturn, Dict[str, Bot]]: return driver.bots -from nonebot.sched import scheduler from nonebot.utils import escape_tag from nonebot.config import Env, Config from nonebot.log import logger, default_filter -from nonebot.adapters.cqhttp import Bot as CQBot - -try: - import nonebot_test -except ImportError: - nonebot_test = None def init(*, _env_file: Optional[str] = None, **kwargs): @@ -190,17 +184,6 @@ def init(*, _env_file: Optional[str] = None, **kwargs): importlib.import_module(config.driver), "Driver") _driver = DriverClass(env, config) - # register build-in adapters - _driver.register_adapter("cqhttp", CQBot) - - # load nonebot test frontend if debug - if config.debug and nonebot_test: - logger.debug("Loading nonebot test frontend...") - nonebot_test.init() - - if scheduler: - _driver.on_startup(_start_scheduler) - def run(host: Optional[str] = None, port: Optional[int] = None, @@ -233,14 +216,7 @@ def run(host: Optional[str] = None, get_driver().run(host, port, *args, **kwargs) -async def _start_scheduler(): - if scheduler and not scheduler.running: - scheduler.configure(_driver.config.apscheduler_config) - scheduler.start() - logger.opt(colors=True).info("Scheduler Started") - - -from nonebot.plugin import on_message, on_notice, on_request, on_metaevent, CommandGroup +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 load_plugin, load_plugins, load_builtin_plugins from nonebot.plugin import export, require, get_plugin, get_loaded_plugins diff --git a/nonebot/adapters/__init__.py b/nonebot/adapters/__init__.py index 2ca5505f..692c691f 100644 --- a/nonebot/adapters/__init__.py +++ b/nonebot/adapters/__init__.py @@ -9,9 +9,11 @@ import abc from functools import reduce, partial from dataclasses import dataclass, field +from pydantic import BaseModel + from nonebot.config import Config from nonebot.typing import Driver, Message, WebSocket -from nonebot.typing import Any, Dict, Union, Optional, NoReturn, Callable, Iterable, Awaitable +from nonebot.typing import Any, Dict, Union, Optional, NoReturn, Callable, Iterable, Awaitable, TypeVar, Generic class BaseBot(abc.ABC): @@ -29,6 +31,7 @@ class BaseBot(abc.ABC): websocket: Optional[WebSocket] = None): """ :参数: + * ``driver: Driver``: Driver 对象 * ``connection_type: str``: http 或者 websocket * ``config: Config``: Config 对象 @@ -62,15 +65,22 @@ class BaseBot(abc.ABC): body: Optional[dict]) -> Union[str, NoReturn]: """ :说明: + 检查连接请求是否合法的函数,如果合法则返回当前连接 ``唯一标识符``,通常为机器人 ID;如果不合法则抛出 ``RequestDenied`` 异常。 + :参数: + * ``driver: Driver``: Driver 对象 * ``connection_type: str``: 连接类型 * ``headers: dict``: 请求头 * ``body: Optional[dict]``: 请求数据,WebSocket 连接该部分为空 + :返回: + - ``str``: 连接唯一标识符 + :异常: + - ``RequestDenied``: 请求非法 """ raise NotImplementedError @@ -79,8 +89,11 @@ class BaseBot(abc.ABC): async def handle_message(self, message: dict): """ :说明: + 处理上报消息的函数,转换为 ``Event`` 事件后调用 ``nonebot.message.handle_event`` 进一步处理事件。 + :参数: + * ``message: dict``: 收到的上报消息 """ raise NotImplementedError @@ -89,10 +102,14 @@ class BaseBot(abc.ABC): async def call_api(self, api: str, **data): """ :说明: + 调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用 + :参数: + * ``api: str``: API 名称 * ``**data``: API 数据 + :示例: .. code-block:: python @@ -108,8 +125,11 @@ class BaseBot(abc.ABC): "BaseMessageSegment"], **kwargs): """ :说明: + 调用机器人基础发送消息接口 + :参数: + * ``event: Event``: 上报事件 * ``message: Union[str, Message, MessageSegment]``: 要发送的消息 * ``**kwargs`` @@ -117,15 +137,19 @@ class BaseBot(abc.ABC): raise NotImplementedError -class BaseEvent(abc.ABC): +T = TypeVar("T", bound=BaseModel) + + +class BaseEvent(abc.ABC, Generic[T]): """ Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。 """ - def __init__(self, raw_event: dict): + def __init__(self, raw_event: Union[dict, T]): """ :参数: - * ``raw_event: dict``: 原始上报消息 + + * ``raw_event: Union[dict, T]``: 原始上报消息 """ self._raw_event = raw_event @@ -133,7 +157,7 @@ class BaseEvent(abc.ABC): return f"" @property - def raw_event(self) -> dict: + def raw_event(self) -> Union[dict, T]: """原始上报消息""" return self._raw_event @@ -294,10 +318,19 @@ class BaseMessageSegment(abc.ABC): @abc.abstractmethod def __str__(self): + """该消息段所代表的 str,在命令匹配部分使用""" raise NotImplementedError @abc.abstractmethod def __add__(self, other): + """你需要在这里实现不同消息段的合并: + 比如: + if isinstance(other, str): + ... + elif isinstance(other, MessageSegment): + ... + 注意:不能返回 self,需要返回一个新生成的对象 + """ raise NotImplementedError def __getitem__(self, key): @@ -319,16 +352,17 @@ class BaseMessage(list, abc.ABC): """消息数组""" def __init__(self, - message: Union[str, dict, list, BaseMessageSegment, + message: Union[str, dict, list, BaseModel, BaseMessageSegment, "BaseMessage"] = None, *args, **kwargs): """ :参数: - * ``message: Union[str, dict, list, MessageSegment, Message]``: 消息内容 + + * ``message: Union[str, dict, list, BaseModel, MessageSegment, Message]``: 消息内容 """ super().__init__(*args, **kwargs) - if isinstance(message, (str, dict, list)): + if isinstance(message, (str, dict, list, BaseModel)): self.extend(self._construct(message)) elif isinstance(message, BaseMessage): self.extend(message) @@ -362,15 +396,15 @@ class BaseMessage(list, abc.ABC): def append(self, obj: Union[str, BaseMessageSegment]) -> "BaseMessage": """ :说明: + 添加一个消息段到消息数组末尾 + :参数: + * ``obj: Union[str, MessageSegment]``: 要添加的消息段 """ if isinstance(obj, BaseMessageSegment): - if obj.type == "text" and self and self[-1].type == "text": - self[-1].data["text"] += obj.data["text"] - else: - super().append(obj) + super().append(obj) elif isinstance(obj, str): self.extend(self._construct(obj)) else: @@ -382,8 +416,11 @@ class BaseMessage(list, abc.ABC): Iterable[BaseMessageSegment]]) -> "BaseMessage": """ :说明: + 拼接一个消息数组或多个消息段到消息数组末尾 + :参数: + * ``obj: Union[Message, Iterable[MessageSegment]]``: 要添加的消息数组 """ for segment in obj: @@ -393,13 +430,14 @@ class BaseMessage(list, abc.ABC): def reduce(self) -> None: """ :说明: - 缩减消息数组,即拼接相邻纯文本消息段 + + 缩减消息数组,即按 MessageSegment 的实现拼接相邻消息段 """ index = 0 while index < len(self): if index > 0 and self[ index - 1].type == "text" and self[index].type == "text": - self[index - 1].data["text"] += self[index].data["text"] + self[index - 1] += self[index] del self[index] else: index += 1 @@ -407,11 +445,12 @@ class BaseMessage(list, abc.ABC): def extract_plain_text(self) -> str: """ :说明: + 提取消息内纯文本消息 """ def _concat(x: str, y: BaseMessageSegment) -> str: - return f"{x} {y.data['text']}" if y.type == "text" else x + return f"{x} {y}" if y.type == "text" else x plain_text = reduce(_concat, self, "") return plain_text[1:] if plain_text else plain_text diff --git a/nonebot/adapters/cqhttp/__init__.py b/nonebot/adapters/cqhttp/__init__.py index 714e9f62..14635eda 100644 --- a/nonebot/adapters/cqhttp/__init__.py +++ b/nonebot/adapters/cqhttp/__init__.py @@ -5,913 +5,13 @@ CQHTTP (OneBot) v11 协议适配 协议详情请看: `CQHTTP`_ | `OneBot`_ .. _CQHTTP: - http://cqhttp.cc/ + https://github.com/howmanybots/onebot/blob/master/README.md .. _OneBot: - https://github.com/howmanybots/onebot + https://github.com/howmanybots/onebot/blob/master/README.md """ -import re -import sys -import hmac -import json -import asyncio - -import httpx - -from nonebot.log import logger -from nonebot.config import Config -from nonebot.message import handle_event -from nonebot.typing import overrides, Driver, WebSocket, NoReturn -from nonebot.typing import Any, Dict, Union, Tuple, Iterable, Optional -from nonebot.adapters import BaseBot, BaseEvent, BaseMessage, BaseMessageSegment -from nonebot.exception import NetworkError, ActionFailed, RequestDenied, ApiNotAvailable - - -def log(level: str, message: str): - """ - :说明: - - 用于打印 CQHTTP 日志。 - - :参数: - - * ``level: str``: 日志等级 - * ``message: str``: 日志信息 - """ - return logger.opt(colors=True).log(level, "CQHTTP | " + message) - - -def get_auth_bearer( - access_token: Optional[str] = None) -> Union[Optional[str], NoReturn]: - if not access_token: - return None - scheme, _, param = access_token.partition(" ") - if scheme.lower() not in ["bearer", "token"]: - raise RequestDenied(401, "Not authenticated") - return param - - -def escape(s: str, *, escape_comma: bool = True) -> str: - """ - :说明: - - 对字符串进行 CQ 码转义。 - - :参数: - - * ``s: str``: 需要转义的字符串 - * ``escape_comma: bool``: 是否转义逗号(``,``)。 - """ - s = s.replace("&", "&") \ - .replace("[", "[") \ - .replace("]", "]") - if escape_comma: - s = s.replace(",", ",") - return s - - -def unescape(s: str) -> str: - """ - :说明: - - 对字符串进行 CQ 码去转义。 - - :参数: - - * ``s: str``: 需要转义的字符串 - """ - return s.replace(",", ",") \ - .replace("[", "[") \ - .replace("]", "]") \ - .replace("&", "&") - - -def _b2s(b: Optional[bool]) -> Optional[str]: - """转换布尔值为字符串。""" - return b if b is None else str(b).lower() - - -async def _check_reply(bot: "Bot", event: "Event"): - """ - :说明: - - 检查消息中存在的回复,去除并赋值 ``event.reply``, ``event.to_me`` - - :参数: - - * ``bot: Bot``: Bot 对象 - * ``event: Event``: Event 对象 - """ - if event.type != "message": - return - - try: - index = list(map(lambda x: x.type == "reply", - event.message)).index(True) - except ValueError: - return - msg_seg = event.message[index] - event.reply = await bot.get_msg(message_id=msg_seg.data["id"]) - # ensure string comparation - if str(event.reply["sender"]["user_id"]) == str(event.self_id): - event.to_me = True - del event.message[index] - if len(event.message) > index and event.message[index].type == "at": - del event.message[index] - if len(event.message) > index and event.message[index].type == "text": - event.message[index].data["text"] = event.message[index].data[ - "text"].lstrip() - if not event.message[index].data["text"]: - del event.message[index] - if not event.message: - event.message.append(MessageSegment.text("")) - - -def _check_at_me(bot: "Bot", event: "Event"): - """ - :说明: - - 检查消息开头或结尾是否存在 @机器人,去除并赋值 ``event.to_me`` - - :参数: - - * ``bot: Bot``: Bot 对象 - * ``event: Event``: Event 对象 - """ - if event.type != "message": - return - - if event.detail_type == "private": - event.to_me = True - else: - at_me_seg = MessageSegment.at(event.self_id) - - # check the first segment - if event.message[0] == at_me_seg: - event.to_me = True - del event.message[0] - if event.message and event.message[0].type == "text": - event.message[0].data["text"] = event.message[0].data[ - "text"].lstrip() - if not event.message[0].data["text"]: - del event.message[0] - if event.message and event.message[0] == at_me_seg: - del event.message[0] - if event.message and event.message[0].type == "text": - event.message[0].data["text"] = event.message[0].data[ - "text"].lstrip() - if not event.message[0].data["text"]: - del event.message[0] - - if not event.to_me: - # check the last segment - i = -1 - last_msg_seg = event.message[i] - if last_msg_seg.type == "text" and \ - not last_msg_seg.data["text"].strip() and \ - len(event.message) >= 2: - i -= 1 - last_msg_seg = event.message[i] - - if last_msg_seg == at_me_seg: - event.to_me = True - del event.message[i:] - - if not event.message: - event.message.append(MessageSegment.text("")) - - -def _check_nickname(bot: "Bot", event: "Event"): - """ - :说明: - - 检查消息开头是否存在,去除并赋值 ``event.to_me`` - - :参数: - - * ``bot: Bot``: Bot 对象 - * ``event: Event``: Event 对象 - """ - if event.type != "message": - return - - first_msg_seg = event.message[0] - if first_msg_seg.type != "text": - return - - first_text = first_msg_seg.data["text"] - - nicknames = set(filter(lambda n: n, bot.config.nickname)) - if nicknames: - # check if the user is calling me with my nickname - nickname_regex = "|".join(nicknames) - m = re.search(rf"^({nickname_regex})([\s,,]*|$)", first_text, - re.IGNORECASE) - if m: - nickname = m.group(1) - log("DEBUG", f"User is calling me {nickname}") - event.to_me = True - first_msg_seg.data["text"] = first_text[m.end():] - - -def _handle_api_result( - result: Optional[Dict[str, Any]]) -> Union[Any, NoReturn]: - """ - :说明: - - 处理 API 请求返回值。 - - :参数: - - * ``result: Optional[Dict[str, Any]]``: API 返回数据 - - :返回: - - - ``Any``: API 调用返回数据 - - :异常: - - - ``ActionFailed``: API 调用失败 - """ - if isinstance(result, dict): - if result.get("status") == "failed": - raise ActionFailed(retcode=result.get("retcode")) - return result.get("data") - - -class ResultStore: - _seq = 1 - _futures: Dict[int, asyncio.Future] = {} - - @classmethod - def get_seq(cls) -> int: - s = cls._seq - cls._seq = (cls._seq + 1) % sys.maxsize - return s - - @classmethod - def add_result(cls, result: Dict[str, Any]): - if isinstance(result.get("echo"), dict) and \ - isinstance(result["echo"].get("seq"), int): - future = cls._futures.get(result["echo"]["seq"]) - if future: - future.set_result(result) - - @classmethod - async def fetch(cls, seq: int, timeout: Optional[float]) -> Dict[str, Any]: - future = asyncio.get_event_loop().create_future() - cls._futures[seq] = future - try: - return await asyncio.wait_for(future, timeout) - except asyncio.TimeoutError: - raise NetworkError("WebSocket API call timeout") from None - finally: - del cls._futures[seq] - - -class Bot(BaseBot): - """ - CQHTTP 协议 Bot 适配。继承属性参考 `BaseBot <./#class-basebot>`_ 。 - """ - - def __init__(self, - driver: Driver, - connection_type: str, - config: Config, - self_id: str, - *, - websocket: Optional[WebSocket] = None): - - super().__init__(driver, - connection_type, - config, - self_id, - websocket=websocket) - - @property - @overrides(BaseBot) - def type(self) -> str: - """ - - 返回: ``"cqhttp"`` - """ - return "cqhttp" - - @classmethod - @overrides(BaseBot) - async def check_permission(cls, driver: Driver, connection_type: str, - headers: dict, - body: Optional[dict]) -> Union[str, NoReturn]: - """ - :说明: - CQHTTP (OneBot) 协议鉴权。参考 `鉴权 `_ - """ - x_self_id = headers.get("x-self-id") - x_signature = headers.get("x-signature") - access_token = get_auth_bearer(headers.get("authorization")) - - # 检查连接方式 - if connection_type not in ["http", "websocket"]: - log("WARNING", "Unsupported connection type") - raise RequestDenied(405, "Unsupported connection type") - - # 检查self_id - if not x_self_id: - log("WARNING", "Missing X-Self-ID Header") - raise RequestDenied(400, "Missing X-Self-ID Header") - - # 检查签名 - secret = driver.config.secret - if secret and connection_type == "http": - if not x_signature: - log("WARNING", "Missing Signature Header") - raise RequestDenied(401, "Missing Signature") - sig = hmac.new(secret.encode("utf-8"), - json.dumps(body).encode(), "sha1").hexdigest() - if x_signature != "sha1=" + sig: - log("WARNING", "Signature Header is invalid") - raise RequestDenied(403, "Signature is invalid") - - access_token = driver.config.access_token - if access_token and access_token != access_token: - log( - "WARNING", "Authorization Header is invalid" - if access_token else "Missing Authorization Header") - raise RequestDenied( - 403, "Authorization Header is invalid" - if access_token else "Missing Authorization Header") - return str(x_self_id) - - @overrides(BaseBot) - async def handle_message(self, message: dict): - """ - :说明: - - 调用 `_check_reply <#async-check-reply-bot-event>`_, `_check_at_me <#check-at-me-bot-event>`_, `_check_nickname <#check-nickname-bot-event>`_ 处理事件并转换为 `Event <#class-event>`_ - """ - if not message: - return - - if "post_type" not in message: - ResultStore.add_result(message) - return - - try: - event = Event(message) - - # Check whether user is calling me - await _check_reply(self, event) - _check_at_me(self, event) - _check_nickname(self, event) - - await handle_event(self, event) - except Exception as e: - logger.opt(colors=True, exception=e).error( - f"Failed to handle event. Raw: {message}" - ) - - @overrides(BaseBot) - async def call_api(self, api: str, **data) -> Union[Any, NoReturn]: - """ - :说明: - - 调用 CQHTTP 协议 API - - :参数: - - * ``api: str``: API 名称 - * ``**data: Any``: API 参数 - - :返回: - - - ``Any``: API 调用返回数据 - - :异常: - - - ``NetworkError``: 网络错误 - - ``ActionFailed``: API 调用失败 - """ - if "self_id" in data: - self_id = data.pop("self_id") - if self_id: - bot = self.driver.bots[str(self_id)] - return await bot.call_api(api, **data) - - log("DEBUG", f"Calling API {api}") - if self.connection_type == "websocket": - seq = ResultStore.get_seq() - await self.websocket.send({ - "action": api, - "params": data, - "echo": { - "seq": seq - } - }) - return _handle_api_result(await ResultStore.fetch( - seq, self.config.api_timeout)) - - elif self.connection_type == "http": - api_root = self.config.api_root.get(self.self_id) - if not api_root: - raise ApiNotAvailable - elif not api_root.endswith("/"): - api_root += "/" - - headers = {} - if self.config.access_token is not None: - headers["Authorization"] = "Bearer " + self.config.access_token - - try: - async with httpx.AsyncClient(headers=headers) as client: - response = await client.post( - api_root + api, - json=data, - timeout=self.config.api_timeout) - - if 200 <= response.status_code < 300: - result = response.json() - return _handle_api_result(result) - raise NetworkError(f"HTTP request received unexpected " - f"status code: {response.status_code}") - except httpx.InvalidURL: - raise NetworkError("API root url invalid") - except httpx.HTTPError: - raise NetworkError("HTTP request failed") - - @overrides(BaseBot) - async def send(self, - event: "Event", - message: Union[str, "Message", "MessageSegment"], - at_sender: bool = False, - **kwargs) -> Union[Any, NoReturn]: - """ - :说明: - - 根据 ``event`` 向触发事件的主体发送消息。 - - :参数: - - * ``event: Event``: Event 对象 - * ``message: Union[str, Message, MessageSegment]``: 要发送的消息 - * ``at_sender: bool``: 是否 @ 事件主体 - * ``**kwargs``: 覆盖默认参数 - - :返回: - - - ``Any``: API 调用返回数据 - - :异常: - - - ``ValueError``: 缺少 ``user_id``, ``group_id`` - - ``NetworkError``: 网络错误 - - ``ActionFailed``: API 调用失败 - """ - msg = message if isinstance(message, Message) else Message(message) - - at_sender = at_sender and bool(event.user_id) - - params = {} - if event.user_id: - params["user_id"] = event.user_id - if event.group_id: - params["group_id"] = event.group_id - params.update(kwargs) - - if "message_type" not in params: - if "group_id" in params: - params["message_type"] = "group" - elif "user_id" in params: - params["message_type"] = "private" - else: - raise ValueError("Cannot guess message type to reply!") - - if at_sender and params["message_type"] != "private": - params["message"] = MessageSegment.at(params["user_id"]) + \ - MessageSegment.text(" ") + msg - else: - params["message"] = msg - return await self.send_msg(**params) - - -class Event(BaseEvent): - """ - CQHTTP 协议 Event 适配。继承属性参考 `BaseEvent <./#class-baseevent>`_ 。 - """ - - def __init__(self, raw_event: dict): - if "message" in raw_event: - raw_event["message"] = Message(raw_event["message"]) - - super().__init__(raw_event) - - @property - @overrides(BaseEvent) - def id(self) -> Optional[int]: - """ - - 类型: ``Optional[int]`` - - 说明: 事件/消息 ID - """ - return self._raw_event.get("message_id") or self._raw_event.get("flag") - - @property - @overrides(BaseEvent) - def name(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件名称,由类型与 ``.`` 组合而成 - """ - n = self.type + "." + self.detail_type - if self.sub_type: - n += "." + self.sub_type - return n - - @property - @overrides(BaseEvent) - def self_id(self) -> str: - """ - - 类型: ``str`` - - 说明: 机器人自身 ID - """ - return str(self._raw_event["self_id"]) - - @property - @overrides(BaseEvent) - def time(self) -> int: - """ - - 类型: ``int`` - - 说明: 事件发生时间 - """ - return self._raw_event["time"] - - @property - @overrides(BaseEvent) - def type(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件类型 - """ - return self._raw_event["post_type"] - - @type.setter - @overrides(BaseEvent) - def type(self, value) -> None: - self._raw_event["post_type"] = value - - @property - @overrides(BaseEvent) - def detail_type(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件详细类型 - """ - return self._raw_event[f"{self.type}_type"] - - @detail_type.setter - @overrides(BaseEvent) - def detail_type(self, value) -> None: - self._raw_event[f"{self.type}_type"] = value - - @property - @overrides(BaseEvent) - def sub_type(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 事件子类型 - """ - return self._raw_event.get("sub_type") - - @sub_type.setter - @overrides(BaseEvent) - def sub_type(self, value) -> None: - self._raw_event["sub_type"] = value - - @property - @overrides(BaseEvent) - def user_id(self) -> Optional[int]: - """ - - 类型: ``Optional[int]`` - - 说明: 事件主体 ID - """ - return self._raw_event.get("user_id") - - @user_id.setter - @overrides(BaseEvent) - def user_id(self, value) -> None: - self._raw_event["user_id"] = value - - @property - @overrides(BaseEvent) - def group_id(self) -> Optional[int]: - """ - - 类型: ``Optional[int]`` - - 说明: 事件主体群 ID - """ - return self._raw_event.get("group_id") - - @group_id.setter - @overrides(BaseEvent) - def group_id(self, value) -> None: - self._raw_event["group_id"] = value - - @property - @overrides(BaseEvent) - def to_me(self) -> Optional[bool]: - """ - - 类型: ``Optional[bool]`` - - 说明: 消息是否与机器人相关 - """ - return self._raw_event.get("to_me") - - @to_me.setter - @overrides(BaseEvent) - def to_me(self, value) -> None: - self._raw_event["to_me"] = value - - @property - @overrides(BaseEvent) - def message(self) -> Optional["Message"]: - """ - - 类型: ``Optional[Message]`` - - 说明: 消息内容 - """ - return self._raw_event.get("message") - - @message.setter - @overrides(BaseEvent) - def message(self, value) -> None: - self._raw_event["message"] = value - - @property - @overrides(BaseEvent) - def reply(self) -> Optional[dict]: - """ - - 类型: ``Optional[dict]`` - - 说明: 回复消息详情 - """ - return self._raw_event.get("reply") - - @reply.setter - @overrides(BaseEvent) - def reply(self, value) -> None: - self._raw_event["reply"] = value - - @property - @overrides(BaseEvent) - def raw_message(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 原始消息 - """ - return self._raw_event.get("raw_message") - - @raw_message.setter - @overrides(BaseEvent) - def raw_message(self, value) -> None: - self._raw_event["raw_message"] = value - - @property - @overrides(BaseEvent) - def plain_text(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 纯文本消息内容 - """ - return self.message and self.message.extract_plain_text() - - @property - @overrides(BaseEvent) - def sender(self) -> Optional[dict]: - """ - - 类型: ``Optional[dict]`` - - 说明: 消息发送者信息 - """ - return self._raw_event.get("sender") - - @sender.setter - @overrides(BaseEvent) - def sender(self, value) -> None: - self._raw_event["sender"] = value - - -class MessageSegment(BaseMessageSegment): - """ - CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 - """ - - @overrides(BaseMessageSegment) - def __init__(self, type: str, data: Dict[str, Any]) -> None: - if type == "text": - data["text"] = unescape(data["text"]) - super().__init__(type=type, data=data) - - @overrides(BaseMessageSegment) - def __str__(self): - type_ = self.type - data = self.data.copy() - - # process special types - if type_ == "text": - return escape( - data.get("text", ""), # type: ignore - escape_comma=False) - - params = ",".join( - [f"{k}={escape(str(v))}" for k, v in data.items() if v is not None]) - return f"[CQ:{type_}{',' if params else ''}{params}]" - - @overrides(BaseMessageSegment) - def __add__(self, other) -> "Message": - return Message(self) + other - - @staticmethod - def anonymous(ignore_failure: Optional[bool] = None) -> "MessageSegment": - return MessageSegment("anonymous", {"ignore": _b2s(ignore_failure)}) - - @staticmethod - def at(user_id: Union[int, str]) -> "MessageSegment": - return MessageSegment("at", {"qq": str(user_id)}) - - @staticmethod - def contact_group(group_id: int) -> "MessageSegment": - return MessageSegment("contact", {"type": "group", "id": str(group_id)}) - - @staticmethod - def contact_user(user_id: int) -> "MessageSegment": - return MessageSegment("contact", {"type": "qq", "id": str(user_id)}) - - @staticmethod - def dice() -> "MessageSegment": - return MessageSegment("dice", {}) - - @staticmethod - def face(id_: int) -> "MessageSegment": - return MessageSegment("face", {"id": str(id_)}) - - @staticmethod - def forward(id_: str) -> "MessageSegment": - log("WARNING", "Forward Message only can be received!") - return MessageSegment("forward", {"id": id_}) - - @staticmethod - def image(file: str, - type_: Optional[str] = None, - cache: bool = True, - proxy: bool = True, - timeout: Optional[int] = None) -> "MessageSegment": - return MessageSegment( - "image", { - "file": file, - "type": type_, - "cache": cache, - "proxy": proxy, - "timeout": timeout - }) - - @staticmethod - def json(data: str) -> "MessageSegment": - return MessageSegment("json", {"data": data}) - - @staticmethod - def location(latitude: float, - longitude: float, - title: Optional[str] = None, - content: Optional[str] = None) -> "MessageSegment": - return MessageSegment( - "location", { - "lat": str(latitude), - "lon": str(longitude), - "title": title, - "content": content - }) - - @staticmethod - def music(type_: str, id_: int) -> "MessageSegment": - return MessageSegment("music", {"type": type_, "id": id_}) - - @staticmethod - def music_custom(url: str, - audio: str, - title: str, - content: Optional[str] = None, - img_url: Optional[str] = None) -> "MessageSegment": - return MessageSegment( - "music", { - "type": "custom", - "url": url, - "audio": audio, - "title": title, - "content": content, - "image": img_url - }) - - @staticmethod - def node(id_: int) -> "MessageSegment": - return MessageSegment("node", {"id": str(id_)}) - - @staticmethod - def node_custom(user_id: int, nickname: str, - content: Union[str, "Message"]) -> "MessageSegment": - return MessageSegment("node", { - "user_id": str(user_id), - "nickname": nickname, - "content": content - }) - - @staticmethod - def poke(type_: str, id_: str) -> "MessageSegment": - return MessageSegment("poke", {"type": type_, "id": id_}) - - @staticmethod - def record(file: str, - magic: Optional[bool] = None, - cache: Optional[bool] = None, - proxy: Optional[bool] = None, - timeout: Optional[int] = None) -> "MessageSegment": - return MessageSegment("record", {"file": file, "magic": _b2s(magic)}) - - @staticmethod - def reply(id_: int) -> "MessageSegment": - return MessageSegment("reply", {"id": str(id_)}) - - @staticmethod - def rps() -> "MessageSegment": - return MessageSegment("rps", {}) - - @staticmethod - def shake() -> "MessageSegment": - return MessageSegment("shake", {}) - - @staticmethod - def share(url: str = "", - title: str = "", - content: Optional[str] = None, - img_url: Optional[str] = None) -> "MessageSegment": - return MessageSegment("share", { - "url": url, - "title": title, - "content": content, - "img_url": img_url - }) - - @staticmethod - def text(text: str) -> "MessageSegment": - return MessageSegment("text", {"text": text}) - - @staticmethod - def video(file: str, - cache: Optional[bool] = None, - proxy: Optional[bool] = None, - timeout: Optional[int] = None) -> "MessageSegment": - return MessageSegment("video", { - "file": file, - "cache": cache, - "proxy": proxy, - "timeout": timeout - }) - - @staticmethod - def xml(data: str) -> "MessageSegment": - return MessageSegment("xml", {"data": data}) - - -class Message(BaseMessage): - """ - CQHTTP 协议 Message 适配。 - """ - - @staticmethod - @overrides(BaseMessage) - def _construct(msg: Union[str, dict, list]) -> Iterable[MessageSegment]: - if isinstance(msg, dict): - yield MessageSegment(msg["type"], msg.get("data") or {}) - return - elif isinstance(msg, list): - for seg in msg: - yield MessageSegment(seg["type"], seg.get("data") or {}) - return - - 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", unescape(msg[text_begin:cqcode.pos + - cqcode.start()]) - text_begin = cqcode.pos + cqcode.end() - yield cqcode.group("type"), cqcode.group("params").lstrip(",") - yield "text", unescape(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": data}) - else: - data = { - k: 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 .event import Event +from .message import Message, MessageSegment +from .utils import log, escape, unescape, _b2s +from .bot import Bot, _check_at_me, _check_nickname, _check_reply, _handle_api_result +from .exception import CQHTTPAdapterException, ApiNotAvailable, ActionFailed, NetworkError diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py new file mode 100644 index 00000000..929cd095 --- /dev/null +++ b/nonebot/adapters/cqhttp/bot.py @@ -0,0 +1,432 @@ +import re +import sys +import hmac +import json +import asyncio + +import httpx + +from nonebot.log import logger +from nonebot.config import Config +from nonebot.adapters import BaseBot +from nonebot.message import handle_event +from nonebot.exception import RequestDenied +from nonebot.typing import Any, Dict, Union, Optional +from nonebot.typing import overrides, Driver, WebSocket, NoReturn + +from .event import Event +from .message import Message, MessageSegment +from .exception import NetworkError, ApiNotAvailable, ActionFailed +from .utils import log + + +def get_auth_bearer( + access_token: Optional[str] = None) -> Union[Optional[str], NoReturn]: + if not access_token: + return None + scheme, _, param = access_token.partition(" ") + if scheme.lower() not in ["bearer", "token"]: + raise RequestDenied(401, "Not authenticated") + return param + + +async def _check_reply(bot: "Bot", event: "Event"): + """ + :说明: + + 检查消息中存在的回复,去除并赋值 ``event.reply``, ``event.to_me`` + + :参数: + + * ``bot: Bot``: Bot 对象 + * ``event: Event``: Event 对象 + """ + if event.type != "message": + return + + try: + index = list(map(lambda x: x.type == "reply", + event.message)).index(True) + except ValueError: + return + msg_seg = event.message[index] + event.reply = await bot.get_msg(message_id=msg_seg.data["id"]) + # ensure string comparation + if str(event.reply["sender"]["user_id"]) == str(event.self_id): + event.to_me = True + del event.message[index] + if len(event.message) > index and event.message[index].type == "at": + del event.message[index] + if len(event.message) > index and event.message[index].type == "text": + event.message[index].data["text"] = event.message[index].data[ + "text"].lstrip() + if not event.message[index].data["text"]: + del event.message[index] + if not event.message: + event.message.append(MessageSegment.text("")) + + +def _check_at_me(bot: "Bot", event: "Event"): + """ + :说明: + + 检查消息开头或结尾是否存在 @机器人,去除并赋值 ``event.to_me`` + + :参数: + + * ``bot: Bot``: Bot 对象 + * ``event: Event``: Event 对象 + """ + if event.type != "message": + return + + if event.detail_type == "private": + event.to_me = True + else: + at_me_seg = MessageSegment.at(event.self_id) + + # check the first segment + if event.message[0] == at_me_seg: + event.to_me = True + del event.message[0] + if event.message and event.message[0].type == "text": + event.message[0].data["text"] = event.message[0].data[ + "text"].lstrip() + if not event.message[0].data["text"]: + del event.message[0] + if event.message and event.message[0] == at_me_seg: + del event.message[0] + if event.message and event.message[0].type == "text": + event.message[0].data["text"] = event.message[0].data[ + "text"].lstrip() + if not event.message[0].data["text"]: + del event.message[0] + + if not event.to_me: + # check the last segment + i = -1 + last_msg_seg = event.message[i] + if last_msg_seg.type == "text" and \ + not last_msg_seg.data["text"].strip() and \ + len(event.message) >= 2: + i -= 1 + last_msg_seg = event.message[i] + + if last_msg_seg == at_me_seg: + event.to_me = True + del event.message[i:] + + if not event.message: + event.message.append(MessageSegment.text("")) + + +def _check_nickname(bot: "Bot", event: "Event"): + """ + :说明: + + 检查消息开头是否存在,去除并赋值 ``event.to_me`` + + :参数: + + * ``bot: Bot``: Bot 对象 + * ``event: Event``: Event 对象 + """ + if event.type != "message": + return + + first_msg_seg = event.message[0] + if first_msg_seg.type != "text": + return + + first_text = first_msg_seg.data["text"] + + nicknames = set(filter(lambda n: n, bot.config.nickname)) + if nicknames: + # check if the user is calling me with my nickname + nickname_regex = "|".join(nicknames) + m = re.search(rf"^({nickname_regex})([\s,,]*|$)", first_text, + re.IGNORECASE) + if m: + nickname = m.group(1) + log("DEBUG", f"User is calling me {nickname}") + event.to_me = True + first_msg_seg.data["text"] = first_text[m.end():] + + +def _handle_api_result( + result: Optional[Dict[str, Any]]) -> Union[Any, NoReturn]: + """ + :说明: + + 处理 API 请求返回值。 + + :参数: + + * ``result: Optional[Dict[str, Any]]``: API 返回数据 + + :返回: + + - ``Any``: API 调用返回数据 + + :异常: + + - ``ActionFailed``: API 调用失败 + """ + if isinstance(result, dict): + if result.get("status") == "failed": + raise ActionFailed(retcode=result.get("retcode")) + return result.get("data") + + +class ResultStore: + _seq = 1 + _futures: Dict[int, asyncio.Future] = {} + + @classmethod + def get_seq(cls) -> int: + s = cls._seq + cls._seq = (cls._seq + 1) % sys.maxsize + return s + + @classmethod + def add_result(cls, result: Dict[str, Any]): + if isinstance(result.get("echo"), dict) and \ + isinstance(result["echo"].get("seq"), int): + future = cls._futures.get(result["echo"]["seq"]) + if future: + future.set_result(result) + + @classmethod + async def fetch(cls, seq: int, timeout: Optional[float]) -> Dict[str, Any]: + future = asyncio.get_event_loop().create_future() + cls._futures[seq] = future + try: + return await asyncio.wait_for(future, timeout) + except asyncio.TimeoutError: + raise NetworkError("WebSocket API call timeout") from None + finally: + del cls._futures[seq] + + +class Bot(BaseBot): + """ + CQHTTP 协议 Bot 适配。继承属性参考 `BaseBot <./#class-basebot>`_ 。 + """ + + def __init__(self, + driver: Driver, + connection_type: str, + config: Config, + self_id: str, + *, + websocket: Optional[WebSocket] = None): + + super().__init__(driver, + connection_type, + config, + self_id, + websocket=websocket) + + @property + @overrides(BaseBot) + def type(self) -> str: + """ + - 返回: ``"cqhttp"`` + """ + return "cqhttp" + + @classmethod + @overrides(BaseBot) + async def check_permission(cls, driver: Driver, connection_type: str, + headers: dict, + body: Optional[dict]) -> Union[str, NoReturn]: + """ + :说明: + + CQHTTP (OneBot) 协议鉴权。参考 `鉴权 `_ + """ + x_self_id = headers.get("x-self-id") + x_signature = headers.get("x-signature") + token = get_auth_bearer(headers.get("authorization")) + + # 检查连接方式 + if connection_type not in ["http", "websocket"]: + log("WARNING", "Unsupported connection type") + raise RequestDenied(405, "Unsupported connection type") + + # 检查self_id + if not x_self_id: + log("WARNING", "Missing X-Self-ID Header") + raise RequestDenied(400, "Missing X-Self-ID Header") + + # 检查签名 + secret = driver.config.secret + if secret and connection_type == "http": + if not x_signature: + log("WARNING", "Missing Signature Header") + raise RequestDenied(401, "Missing Signature") + sig = hmac.new(secret.encode("utf-8"), + json.dumps(body).encode(), "sha1").hexdigest() + if x_signature != "sha1=" + sig: + log("WARNING", "Signature Header is invalid") + raise RequestDenied(403, "Signature is invalid") + + access_token = driver.config.access_token + if access_token and access_token != token: + log( + "WARNING", "Authorization Header is invalid" + if token else "Missing Authorization Header") + raise RequestDenied( + 403, "Authorization Header is invalid" + if token else "Missing Authorization Header") + return str(x_self_id) + + @overrides(BaseBot) + async def handle_message(self, message: dict): + """ + :说明: + + 调用 `_check_reply <#async-check-reply-bot-event>`_, `_check_at_me <#check-at-me-bot-event>`_, `_check_nickname <#check-nickname-bot-event>`_ 处理事件并转换为 `Event <#class-event>`_ + """ + if not message: + return + + if "post_type" not in message: + ResultStore.add_result(message) + return + + try: + event = Event(message) + + # Check whether user is calling me + await _check_reply(self, event) + _check_at_me(self, event) + _check_nickname(self, event) + + await handle_event(self, event) + except Exception as e: + logger.opt(colors=True, exception=e).error( + f"Failed to handle event. Raw: {message}" + ) + + @overrides(BaseBot) + async def call_api(self, api: str, **data) -> Union[Any, NoReturn]: + """ + :说明: + + 调用 CQHTTP 协议 API + + :参数: + + * ``api: str``: API 名称 + * ``**data: Any``: API 参数 + + :返回: + + - ``Any``: API 调用返回数据 + + :异常: + + - ``NetworkError``: 网络错误 + - ``ActionFailed``: API 调用失败 + """ + if "self_id" in data: + self_id = data.pop("self_id") + if self_id: + bot = self.driver.bots[str(self_id)] + return await bot.call_api(api, **data) + + log("DEBUG", f"Calling API {api}") + if self.connection_type == "websocket": + seq = ResultStore.get_seq() + await self.websocket.send({ + "action": api, + "params": data, + "echo": { + "seq": seq + } + }) + return _handle_api_result(await ResultStore.fetch( + seq, self.config.api_timeout)) + + elif self.connection_type == "http": + api_root = self.config.api_root.get(self.self_id) + if not api_root: + raise ApiNotAvailable + elif not api_root.endswith("/"): + api_root += "/" + + headers = {} + if self.config.access_token is not None: + headers["Authorization"] = "Bearer " + self.config.access_token + + try: + async with httpx.AsyncClient(headers=headers) as client: + response = await client.post( + api_root + api, + json=data, + timeout=self.config.api_timeout) + + if 200 <= response.status_code < 300: + result = response.json() + return _handle_api_result(result) + raise NetworkError(f"HTTP request received unexpected " + f"status code: {response.status_code}") + except httpx.InvalidURL: + raise NetworkError("API root url invalid") + except httpx.HTTPError: + raise NetworkError("HTTP request failed") + + @overrides(BaseBot) + async def send(self, + event: Event, + message: Union[str, Message, MessageSegment], + at_sender: bool = False, + **kwargs) -> Union[Any, NoReturn]: + """ + :说明: + + 根据 ``event`` 向触发事件的主体发送消息。 + + :参数: + + * ``event: Event``: Event 对象 + * ``message: Union[str, Message, MessageSegment]``: 要发送的消息 + * ``at_sender: bool``: 是否 @ 事件主体 + * ``**kwargs``: 覆盖默认参数 + + :返回: + + - ``Any``: API 调用返回数据 + + :异常: + + - ``ValueError``: 缺少 ``user_id``, ``group_id`` + - ``NetworkError``: 网络错误 + - ``ActionFailed``: API 调用失败 + """ + msg = message if isinstance(message, Message) else Message(message) + + at_sender = at_sender and bool(event.user_id) + + params = {} + if event.user_id: + params["user_id"] = event.user_id + if event.group_id: + params["group_id"] = event.group_id + params.update(kwargs) + + if "message_type" not in params: + if "group_id" in params: + params["message_type"] = "group" + elif "user_id" in params: + params["message_type"] = "private" + else: + raise ValueError("Cannot guess message type to reply!") + + if at_sender and params["message_type"] != "private": + params["message"] = MessageSegment.at(params["user_id"]) + \ + MessageSegment.text(" ") + msg + else: + params["message"] = msg + return await self.send_msg(**params) diff --git a/nonebot/adapters/cqhttp/__init__.pyi b/nonebot/adapters/cqhttp/bot.pyi similarity index 78% rename from nonebot/adapters/cqhttp/__init__.pyi rename to nonebot/adapters/cqhttp/bot.pyi index e5398588..745b4941 100644 --- a/nonebot/adapters/cqhttp/__init__.pyi +++ b/nonebot/adapters/cqhttp/bot.pyi @@ -1,12 +1,11 @@ import asyncio from nonebot.config import Config -from nonebot.adapters import BaseBot, BaseEvent, BaseMessage, BaseMessageSegment -from nonebot.typing import Any, Dict, List, Union, Driver, Optional, NoReturn, WebSocket, Iterable +from nonebot.adapters import BaseBot +from nonebot.typing import Any, Dict, List, Union, Driver, Optional, NoReturn, WebSocket - -def log(level: str, message: str): - ... +from .event import Event +from .message import Message, MessageSegment def get_auth_bearer( @@ -14,27 +13,15 @@ def get_auth_bearer( ... -def escape(s: str, *, escape_comma: bool = ...) -> str: +async def _check_reply(bot: "Bot", event: Event): ... -def unescape(s: str) -> str: +def _check_at_me(bot: "Bot", event: Event): ... -def _b2s(b: Optional[bool]) -> Optional[str]: - ... - - -async def _check_reply(bot: "Bot", event: "Event"): - ... - - -def _check_at_me(bot: "Bot", event: "Event"): - ... - - -def _check_nickname(bot: "Bot", event: "Event"): +def _check_nickname(bot: "Bot", event: Event): ... @@ -86,8 +73,8 @@ class Bot(BaseBot): async def call_api(self, api: str, **data) -> Union[Any, NoReturn]: ... - async def send(self, event: "Event", message: Union[str, "Message", - "MessageSegment"], + async def send(self, event: Event, message: Union[str, Message, + MessageSegment], **kwargs) -> Union[Any, NoReturn]: ... @@ -759,242 +746,3 @@ class Bot(BaseBot): * ``self_id``: 机器人 QQ 号 """ ... - - -class Event(BaseEvent): - - def __init__(self, raw_event: dict): - ... - - @property - def id(self) -> Optional[int]: - ... - - @property - def name(self) -> str: - ... - - @property - def self_id(self) -> str: - ... - - @property - def time(self) -> int: - ... - - @property - def type(self) -> str: - ... - - @type.setter - def type(self, value) -> None: - ... - - @property - def detail_type(self) -> str: - ... - - @detail_type.setter - def detail_type(self, value) -> None: - ... - - @property - def sub_type(self) -> Optional[str]: - ... - - @sub_type.setter - def sub_type(self, value) -> None: - ... - - @property - def user_id(self) -> Optional[int]: - ... - - @user_id.setter - def user_id(self, value) -> None: - ... - - @property - def group_id(self) -> Optional[int]: - ... - - @group_id.setter - def group_id(self, value) -> None: - ... - - @property - def to_me(self) -> Optional[bool]: - ... - - @to_me.setter - def to_me(self, value) -> None: - ... - - @property - def message(self) -> Optional["Message"]: - ... - - @message.setter - def message(self, value) -> None: - ... - - @property - def reply(self) -> Optional[dict]: - ... - - @reply.setter - def reply(self, value) -> None: - ... - - @property - def raw_message(self) -> Optional[str]: - ... - - @raw_message.setter - def raw_message(self, value) -> None: - ... - - @property - def plain_text(self) -> Optional[str]: - ... - - @property - def sender(self) -> Optional[dict]: - ... - - @sender.setter - def sender(self, value) -> None: - ... - - -class MessageSegment(BaseMessageSegment): - - def __init__(self, type: str, data: Dict[str, Any]) -> None: - ... - - def __str__(self): - ... - - def __add__(self, other) -> "Message": - ... - - @staticmethod - def anonymous(ignore_failure: Optional[bool] = ...) -> "MessageSegment": - ... - - @staticmethod - def at(user_id: Union[int, str]) -> "MessageSegment": - ... - - @staticmethod - def contact_group(group_id: int) -> "MessageSegment": - ... - - @staticmethod - def contact_user(user_id: int) -> "MessageSegment": - ... - - @staticmethod - def dice() -> "MessageSegment": - ... - - @staticmethod - def face(id_: int) -> "MessageSegment": - ... - - @staticmethod - def forward(id_: str) -> "MessageSegment": - ... - - @staticmethod - def image(file: str, - type_: Optional[str] = ..., - cache: bool = ..., - proxy: bool = ..., - timeout: Optional[int] = ...) -> "MessageSegment": - ... - - @staticmethod - def json(data: str) -> "MessageSegment": - ... - - @staticmethod - def location(latitude: float, - longitude: float, - title: Optional[str] = ..., - content: Optional[str] = ...) -> "MessageSegment": - ... - - @staticmethod - def music(type_: str, id_: int) -> "MessageSegment": - ... - - @staticmethod - def music_custom(url: str, - audio: str, - title: str, - content: Optional[str] = ..., - img_url: Optional[str] = ...) -> "MessageSegment": - ... - - @staticmethod - def node(id_: int) -> "MessageSegment": - ... - - @staticmethod - def node_custom(user_id: int, nickname: str, - content: Union[str, "Message"]) -> "MessageSegment": - ... - - @staticmethod - def poke(type_: str, id_: str) -> "MessageSegment": - ... - - @staticmethod - def record(file: str, - magic: Optional[bool] = ..., - cache: Optional[bool] = ..., - proxy: Optional[bool] = ..., - timeout: Optional[int] = ...) -> "MessageSegment": - ... - - @staticmethod - def reply(id_: int) -> "MessageSegment": - ... - - @staticmethod - def rps() -> "MessageSegment": - ... - - @staticmethod - def shake() -> "MessageSegment": - ... - - @staticmethod - def share(url: str = ..., - title: str = ..., - content: Optional[str] = ..., - img_url: Optional[str] = ...) -> "MessageSegment": - ... - - @staticmethod - def text(text: str) -> "MessageSegment": - ... - - @staticmethod - def video(file: str, - cache: Optional[bool] = ..., - proxy: Optional[bool] = ..., - timeout: Optional[int] = ...) -> "MessageSegment": - ... - - @staticmethod - def xml(data: str) -> "MessageSegment": - ... - - -class Message(BaseMessage): - - @staticmethod - def _construct(msg: Union[str, dict, list]) -> Iterable[MessageSegment]: - ... diff --git a/nonebot/adapters/cqhttp/event.py b/nonebot/adapters/cqhttp/event.py new file mode 100644 index 00000000..5bc959c9 --- /dev/null +++ b/nonebot/adapters/cqhttp/event.py @@ -0,0 +1,204 @@ +from nonebot.adapters import BaseEvent +from nonebot.typing import Optional, overrides + +from .message import Message + + +class Event(BaseEvent): + """ + CQHTTP 协议 Event 适配。继承属性参考 `BaseEvent <./#class-baseevent>`_ 。 + """ + + def __init__(self, raw_event: dict): + if "message" in raw_event: + raw_event["message"] = Message(raw_event["message"]) + + super().__init__(raw_event) + + @property + @overrides(BaseEvent) + def id(self) -> Optional[int]: + """ + - 类型: ``Optional[int]`` + - 说明: 事件/消息 ID + """ + return self._raw_event.get("message_id") or self._raw_event.get("flag") + + @property + @overrides(BaseEvent) + def name(self) -> str: + """ + - 类型: ``str`` + - 说明: 事件名称,由类型与 ``.`` 组合而成 + """ + n = self.type + "." + self.detail_type + if self.sub_type: + n += "." + self.sub_type + return n + + @property + @overrides(BaseEvent) + def self_id(self) -> str: + """ + - 类型: ``str`` + - 说明: 机器人自身 ID + """ + return str(self._raw_event["self_id"]) + + @property + @overrides(BaseEvent) + def time(self) -> int: + """ + - 类型: ``int`` + - 说明: 事件发生时间 + """ + return self._raw_event["time"] + + @property + @overrides(BaseEvent) + def type(self) -> str: + """ + - 类型: ``str`` + - 说明: 事件类型 + """ + return self._raw_event["post_type"] + + @type.setter + @overrides(BaseEvent) + def type(self, value) -> None: + self._raw_event["post_type"] = value + + @property + @overrides(BaseEvent) + def detail_type(self) -> str: + """ + - 类型: ``str`` + - 说明: 事件详细类型 + """ + return self._raw_event[f"{self.type}_type"] + + @detail_type.setter + @overrides(BaseEvent) + def detail_type(self, value) -> None: + self._raw_event[f"{self.type}_type"] = value + + @property + @overrides(BaseEvent) + def sub_type(self) -> Optional[str]: + """ + - 类型: ``Optional[str]`` + - 说明: 事件子类型 + """ + return self._raw_event.get("sub_type") + + @sub_type.setter + @overrides(BaseEvent) + def sub_type(self, value) -> None: + self._raw_event["sub_type"] = value + + @property + @overrides(BaseEvent) + def user_id(self) -> Optional[int]: + """ + - 类型: ``Optional[int]`` + - 说明: 事件主体 ID + """ + return self._raw_event.get("user_id") + + @user_id.setter + @overrides(BaseEvent) + def user_id(self, value) -> None: + self._raw_event["user_id"] = value + + @property + @overrides(BaseEvent) + def group_id(self) -> Optional[int]: + """ + - 类型: ``Optional[int]`` + - 说明: 事件主体群 ID + """ + return self._raw_event.get("group_id") + + @group_id.setter + @overrides(BaseEvent) + def group_id(self, value) -> None: + self._raw_event["group_id"] = value + + @property + @overrides(BaseEvent) + def to_me(self) -> Optional[bool]: + """ + - 类型: ``Optional[bool]`` + - 说明: 消息是否与机器人相关 + """ + return self._raw_event.get("to_me") + + @to_me.setter + @overrides(BaseEvent) + def to_me(self, value) -> None: + self._raw_event["to_me"] = value + + @property + @overrides(BaseEvent) + def message(self) -> Optional["Message"]: + """ + - 类型: ``Optional[Message]`` + - 说明: 消息内容 + """ + return self._raw_event.get("message") + + @message.setter + @overrides(BaseEvent) + def message(self, value) -> None: + self._raw_event["message"] = value + + @property + @overrides(BaseEvent) + def reply(self) -> Optional[dict]: + """ + - 类型: ``Optional[dict]`` + - 说明: 回复消息详情 + """ + return self._raw_event.get("reply") + + @reply.setter + @overrides(BaseEvent) + def reply(self, value) -> None: + self._raw_event["reply"] = value + + @property + @overrides(BaseEvent) + def raw_message(self) -> Optional[str]: + """ + - 类型: ``Optional[str]`` + - 说明: 原始消息 + """ + return self._raw_event.get("raw_message") + + @raw_message.setter + @overrides(BaseEvent) + def raw_message(self, value) -> None: + self._raw_event["raw_message"] = value + + @property + @overrides(BaseEvent) + def plain_text(self) -> Optional[str]: + """ + - 类型: ``Optional[str]`` + - 说明: 纯文本消息内容 + """ + return self.message and self.message.extract_plain_text() + + @property + @overrides(BaseEvent) + def sender(self) -> Optional[dict]: + """ + - 类型: ``Optional[dict]`` + - 说明: 消息发送者信息 + """ + return self._raw_event.get("sender") + + @sender.setter + @overrides(BaseEvent) + def sender(self, value) -> None: + self._raw_event["sender"] = value diff --git a/nonebot/adapters/cqhttp/exception.py b/nonebot/adapters/cqhttp/exception.py new file mode 100644 index 00000000..2bcc73f4 --- /dev/null +++ b/nonebot/adapters/cqhttp/exception.py @@ -0,0 +1,59 @@ +from nonebot.typing import Optional +from nonebot.exception import (AdapterException, ActionFailed as + BaseActionFailed, NetworkError as + BaseNetworkError, ApiNotAvailable as + BaseApiNotAvailable) + + +class CQHTTPAdapterException(AdapterException): + + def __init__(self): + super().__init__("cqhttp") + + +class ActionFailed(BaseActionFailed, CQHTTPAdapterException): + """ + :说明: + + API 请求返回错误信息。 + + :参数: + + * ``retcode: Optional[int]``: 错误码 + """ + + def __init__(self, retcode: Optional[int] = None): + super().__init__() + self.retcode = retcode + + def __repr__(self): + return f"" + + def __str__(self): + return self.__repr__() + + +class NetworkError(BaseNetworkError, CQHTTPAdapterException): + """ + :说明: + + 网络错误。 + + :参数: + + * ``retcode: Optional[int]``: 错误码 + """ + + def __init__(self, msg: Optional[str] = None): + super().__init__() + self.msg = msg + + def __repr__(self): + return f"" + + def __str__(self): + return self.__repr__() + + +class ApiNotAvailable(BaseApiNotAvailable, CQHTTPAdapterException): + pass diff --git a/nonebot/adapters/cqhttp/message.py b/nonebot/adapters/cqhttp/message.py new file mode 100644 index 00000000..47d21bc8 --- /dev/null +++ b/nonebot/adapters/cqhttp/message.py @@ -0,0 +1,231 @@ +import re + +from nonebot.typing import Any, Dict, Union, Tuple, Iterable, Optional, overrides +from nonebot.adapters import BaseMessage, BaseMessageSegment + +from .utils import log, escape, unescape, _b2s + + +class MessageSegment(BaseMessageSegment): + """ + CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + """ + + @overrides(BaseMessageSegment) + def __init__(self, type: str, data: Dict[str, Any]) -> None: + if type == "text": + data["text"] = unescape(data["text"]) + super().__init__(type=type, data=data) + + @overrides(BaseMessageSegment) + def __str__(self): + type_ = self.type + data = self.data.copy() + + # process special types + if type_ == "text": + return escape( + data.get("text", ""), # type: ignore + escape_comma=False) + + params = ",".join( + [f"{k}={escape(str(v))}" for k, v in data.items() if v is not None]) + return f"[CQ:{type_}{',' if params else ''}{params}]" + + @overrides(BaseMessageSegment) + def __add__(self, other) -> "Message": + return Message(self) + other + + @staticmethod + def anonymous(ignore_failure: Optional[bool] = None) -> "MessageSegment": + return MessageSegment("anonymous", {"ignore": _b2s(ignore_failure)}) + + @staticmethod + def at(user_id: Union[int, str]) -> "MessageSegment": + return MessageSegment("at", {"qq": str(user_id)}) + + @staticmethod + def contact_group(group_id: int) -> "MessageSegment": + return MessageSegment("contact", {"type": "group", "id": str(group_id)}) + + @staticmethod + def contact_user(user_id: int) -> "MessageSegment": + return MessageSegment("contact", {"type": "qq", "id": str(user_id)}) + + @staticmethod + def dice() -> "MessageSegment": + return MessageSegment("dice", {}) + + @staticmethod + def face(id_: int) -> "MessageSegment": + return MessageSegment("face", {"id": str(id_)}) + + @staticmethod + def forward(id_: str) -> "MessageSegment": + log("WARNING", "Forward Message only can be received!") + return MessageSegment("forward", {"id": id_}) + + @staticmethod + def image(file: str, + type_: Optional[str] = None, + cache: bool = True, + proxy: bool = True, + timeout: Optional[int] = None) -> "MessageSegment": + return MessageSegment( + "image", { + "file": file, + "type": type_, + "cache": cache, + "proxy": proxy, + "timeout": timeout + }) + + @staticmethod + def json(data: str) -> "MessageSegment": + return MessageSegment("json", {"data": data}) + + @staticmethod + def location(latitude: float, + longitude: float, + title: Optional[str] = None, + content: Optional[str] = None) -> "MessageSegment": + return MessageSegment( + "location", { + "lat": str(latitude), + "lon": str(longitude), + "title": title, + "content": content + }) + + @staticmethod + def music(type_: str, id_: int) -> "MessageSegment": + return MessageSegment("music", {"type": type_, "id": id_}) + + @staticmethod + def music_custom(url: str, + audio: str, + title: str, + content: Optional[str] = None, + img_url: Optional[str] = None) -> "MessageSegment": + return MessageSegment( + "music", { + "type": "custom", + "url": url, + "audio": audio, + "title": title, + "content": content, + "image": img_url + }) + + @staticmethod + def node(id_: int) -> "MessageSegment": + return MessageSegment("node", {"id": str(id_)}) + + @staticmethod + def node_custom(user_id: int, nickname: str, + content: Union[str, "Message"]) -> "MessageSegment": + return MessageSegment("node", { + "user_id": str(user_id), + "nickname": nickname, + "content": content + }) + + @staticmethod + def poke(type_: str, id_: str) -> "MessageSegment": + return MessageSegment("poke", {"type": type_, "id": id_}) + + @staticmethod + def record(file: str, + magic: Optional[bool] = None, + cache: Optional[bool] = None, + proxy: Optional[bool] = None, + timeout: Optional[int] = None) -> "MessageSegment": + return MessageSegment("record", {"file": file, "magic": _b2s(magic)}) + + @staticmethod + def reply(id_: int) -> "MessageSegment": + return MessageSegment("reply", {"id": str(id_)}) + + @staticmethod + def rps() -> "MessageSegment": + return MessageSegment("rps", {}) + + @staticmethod + def shake() -> "MessageSegment": + return MessageSegment("shake", {}) + + @staticmethod + def share(url: str = "", + title: str = "", + content: Optional[str] = None, + img_url: Optional[str] = None) -> "MessageSegment": + return MessageSegment("share", { + "url": url, + "title": title, + "content": content, + "img_url": img_url + }) + + @staticmethod + def text(text: str) -> "MessageSegment": + return MessageSegment("text", {"text": text}) + + @staticmethod + def video(file: str, + cache: Optional[bool] = None, + proxy: Optional[bool] = None, + timeout: Optional[int] = None) -> "MessageSegment": + return MessageSegment("video", { + "file": file, + "cache": cache, + "proxy": proxy, + "timeout": timeout + }) + + @staticmethod + def xml(data: str) -> "MessageSegment": + return MessageSegment("xml", {"data": data}) + + +class Message(BaseMessage): + """ + CQHTTP 协议 Message 适配。 + """ + + @staticmethod + @overrides(BaseMessage) + def _construct(msg: Union[str, dict, list]) -> Iterable[MessageSegment]: + if isinstance(msg, dict): + yield MessageSegment(msg["type"], msg.get("data") or {}) + return + elif isinstance(msg, list): + for seg in msg: + yield MessageSegment(seg["type"], seg.get("data") or {}) + return + + 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", unescape(msg[text_begin:cqcode.pos + + cqcode.start()]) + text_begin = cqcode.pos + cqcode.end() + yield cqcode.group("type"), cqcode.group("params").lstrip(",") + yield "text", unescape(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": data}) + else: + data = { + k: 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) diff --git a/nonebot/adapters/cqhttp/utils.py b/nonebot/adapters/cqhttp/utils.py new file mode 100644 index 00000000..ecfee872 --- /dev/null +++ b/nonebot/adapters/cqhttp/utils.py @@ -0,0 +1,44 @@ +from nonebot.typing import Optional +from nonebot.utils import logger_wrapper + +log = logger_wrapper("CQHTTP") + + +def escape(s: str, *, escape_comma: bool = True) -> str: + """ + :说明: + + 对字符串进行 CQ 码转义。 + + :参数: + + * ``s: str``: 需要转义的字符串 + * ``escape_comma: bool``: 是否转义逗号(``,``)。 + """ + s = s.replace("&", "&") \ + .replace("[", "[") \ + .replace("]", "]") + if escape_comma: + s = s.replace(",", ",") + return s + + +def unescape(s: str) -> str: + """ + :说明: + + 对字符串进行 CQ 码去转义。 + + :参数: + + * ``s: str``: 需要转义的字符串 + """ + return s.replace(",", ",") \ + .replace("[", "[") \ + .replace("]", "]") \ + .replace("&", "&") + + +def _b2s(b: Optional[bool]) -> Optional[str]: + """转换布尔值为字符串。""" + return b if b is None else str(b).lower() diff --git a/nonebot/adapters/ding/__init__.py b/nonebot/adapters/ding/__init__.py new file mode 100644 index 00000000..4eb33e28 --- /dev/null +++ b/nonebot/adapters/ding/__init__.py @@ -0,0 +1,17 @@ +""" +钉钉群机器人 协议适配 +============================ + +协议详情请看: `钉钉文档`_ + +.. _钉钉文档: + https://ding-doc.dingtalk.com/doc#/serverapi2/krgddi + +""" + +from .utils import log +from .bot import Bot +from .event import Event +from .message import Message, MessageSegment +from .exception import (DingAdapterException, ApiNotAvailable, NetworkError, + ActionFailed, SessionExpired) diff --git a/nonebot/adapters/ding/bot.py b/nonebot/adapters/ding/bot.py new file mode 100644 index 00000000..0f0a10a8 --- /dev/null +++ b/nonebot/adapters/ding/bot.py @@ -0,0 +1,197 @@ +import hmac +import base64 +from datetime import datetime + +import httpx +from nonebot.log import logger +from nonebot.config import Config +from nonebot.adapters import BaseBot +from nonebot.message import handle_event +from nonebot.exception import RequestDenied +from nonebot.typing import Any, Union, Driver, Optional, NoReturn + +from .utils import log +from .event import Event +from .model import MessageModel +from .message import Message, MessageSegment +from .exception import NetworkError, ApiNotAvailable, ActionFailed, SessionExpired + + +class Bot(BaseBot): + """ + 钉钉 协议 Bot 适配。继承属性参考 `BaseBot <./#class-basebot>`_ 。 + """ + + def __init__(self, driver: Driver, connection_type: str, config: Config, + self_id: str, **kwargs): + + super().__init__(driver, connection_type, config, self_id, **kwargs) + + @property + def type(self) -> str: + """ + - 返回: ``"ding"`` + """ + return "ding" + + @classmethod + async def check_permission(cls, driver: Driver, connection_type: str, + headers: dict, body: Optional[dict]) -> str: + """ + :说明: + + 钉钉协议鉴权。参考 `鉴权 `_ + """ + timestamp = headers.get("timestamp") + sign = headers.get("sign") + + # 检查连接方式 + if connection_type not in ["http"]: + raise RequestDenied(405, "Unsupported connection type") + + # 检查 timestamp + if not timestamp: + raise RequestDenied(400, "Missing `timestamp` Header") + + # 检查 sign + secret = driver.config.secret + if secret: + if not sign: + log("WARNING", "Missing Signature Header") + raise RequestDenied(400, "Missing `sign` Header") + string_to_sign = f"{timestamp}\n{secret}" + sig = hmac.new(secret.encode("utf-8"), + string_to_sign.encode("utf-8"), "sha256").digest() + if sign != base64.b64encode(sig).decode("utf-8"): + log("WARNING", "Signature Header is invalid") + raise RequestDenied(403, "Signature is invalid") + else: + log("WARNING", "Ding signature check ignored!") + return body["chatbotUserId"] + + async def handle_message(self, body: dict): + message = MessageModel.parse_obj(body) + if not message: + return + + try: + event = Event(message) + await handle_event(self, event) + except Exception as e: + logger.opt(colors=True, exception=e).error( + f"Failed to handle event. Raw: {message}" + ) + return + + async def call_api(self, + api: str, + event: Optional[Event] = None, + **data) -> Union[Any, NoReturn]: + """ + :说明: + + 调用 钉钉 协议 API + + :参数: + + * ``api: str``: API 名称 + * ``**data: Any``: API 参数 + + :返回: + + - ``Any``: API 调用返回数据 + + :异常: + + - ``NetworkError``: 网络错误 + - ``ActionFailed``: API 调用失败 + """ + if self.connection_type != "http": + log("ERROR", "Only support http connection.") + return + if "self_id" in data: + self_id = data.pop("self_id") + if self_id: + bot = self.driver.bots[str(self_id)] + return await bot.call_api(api, **data) + + log("DEBUG", f"Calling API {api}") + + if api == "send_message": + if event: + # 确保 sessionWebhook 没有过期 + if int(datetime.now().timestamp()) > int( + event.raw_event.sessionWebhookExpiredTime / 1000): + raise SessionExpired + + target = event.raw_event.sessionWebhook + else: + target = None + + if not target: + raise ApiNotAvailable + + headers = {} + segment: MessageSegment = data["message"][0] + try: + async with httpx.AsyncClient(headers=headers) as client: + response = await client.post( + target, + params={"access_token": self.config.access_token}, + json=segment.data, + timeout=self.config.api_timeout) + + if 200 <= response.status_code < 300: + result = response.json() + if isinstance(result, dict): + if result.get("errcode") != 0: + raise ActionFailed(errcode=result.get("errcode"), + errmsg=result.get("errmsg")) + return result + raise NetworkError(f"HTTP request received unexpected " + f"status code: {response.status_code}") + except httpx.InvalidURL: + raise NetworkError("API root url invalid") + except httpx.HTTPError: + raise NetworkError("HTTP request failed") + + async def send(self, + event: Event, + message: Union[str, "Message", "MessageSegment"], + at_sender: bool = False, + **kwargs) -> Union[Any, NoReturn]: + """ + :说明: + + 根据 ``event`` 向触发事件的主体发送消息。 + + :参数: + + * ``event: Event``: Event 对象 + * ``message: Union[str, Message, MessageSegment]``: 要发送的消息 + * ``at_sender: bool``: 是否 @ 事件主体 + * ``**kwargs``: 覆盖默认参数 + + :返回: + + - ``Any``: API 调用返回数据 + + :异常: + + - ``ValueError``: 缺少 ``user_id``, ``group_id`` + - ``NetworkError``: 网络错误 + - ``ActionFailed``: API 调用失败 + """ + msg = message if isinstance(message, Message) else Message(message) + + at_sender = at_sender and bool(event.user_id) + params = {} + params["event"] = event + params.update(kwargs) + + if at_sender and event.detail_type != "private": + params["message"] = f"@{event.user_id} " + msg + else: + params["message"] = msg + + return await self.call_api("send_message", **params) diff --git a/nonebot/adapters/ding/event.py b/nonebot/adapters/ding/event.py new file mode 100644 index 00000000..876ad493 --- /dev/null +++ b/nonebot/adapters/ding/event.py @@ -0,0 +1,196 @@ +from nonebot.adapters import BaseEvent +from nonebot.typing import Union, Optional + +from .message import Message +from .model import MessageModel, ConversationType, TextMessage + + +class Event(BaseEvent): + """ + 钉钉 协议 Event 适配。继承属性参考 `BaseEvent <./#class-baseevent>`_ 。 + """ + + def __init__(self, message: MessageModel): + super().__init__(message) + # 其实目前钉钉机器人只能接收到 text 类型的消息 + self._message = Message(getattr(message, message.msgtype or "text")) + + @property + def raw_event(self) -> MessageModel: + """原始上报消息""" + return self._raw_event + + @property + def id(self) -> Optional[str]: + """ + - 类型: ``Optional[str]`` + - 说明: 消息 ID + """ + return self.raw_event.msgId + + @property + def name(self) -> str: + """ + - 类型: ``str`` + - 说明: 事件名称,由 `type`.`detail_type` 组合而成 + """ + return self.type + "." + self.detail_type + + @property + def self_id(self) -> str: + """ + - 类型: ``str`` + - 说明: 机器人自身 ID + """ + return str(self.raw_event.chatbotUserId) + + @property + def time(self) -> int: + """ + - 类型: ``int`` + - 说明: 消息的时间戳,单位 s + """ + # 单位 ms -> s + return int(self.raw_event.createAt / 1000) + + @property + def type(self) -> str: + """ + - 类型: ``str`` + - 说明: 事件类型 + """ + return "message" + + @type.setter + def type(self, value) -> None: + pass + + @property + def detail_type(self) -> str: + """ + - 类型: ``str`` + - 说明: 事件详细类型 + """ + return self.raw_event.conversationType.name + + @detail_type.setter + def detail_type(self, value) -> None: + if value == "private": + self.raw_event.conversationType = ConversationType.private + if value == "group": + self.raw_event.conversationType = ConversationType.group + + @property + def sub_type(self) -> None: + """ + - 类型: ``None`` + - 说明: 钉钉适配器无事件子类型 + """ + return None + + @sub_type.setter + def sub_type(self, value) -> None: + pass + + @property + def user_id(self) -> Optional[str]: + """ + - 类型: ``Optional[str]`` + - 说明: 发送者 ID + """ + return self.raw_event.senderId + + @user_id.setter + def user_id(self, value) -> None: + self.raw_event.senderId = value + + @property + def group_id(self) -> Optional[str]: + """ + - 类型: ``Optional[str]`` + - 说明: 事件主体群 ID + """ + return self.raw_event.conversationId + + @group_id.setter + def group_id(self, value) -> None: + self.raw_event.conversationId = value + + @property + def to_me(self) -> Optional[bool]: + """ + - 类型: ``Optional[bool]`` + - 说明: 消息是否与机器人相关 + """ + return self.detail_type == "private" or self.raw_event.isInAtList + + @property + def message(self) -> Optional["Message"]: + """ + - 类型: ``Optional[Message]`` + - 说明: 消息内容 + """ + return self._message + + @message.setter + def message(self, value) -> None: + self._message = value + + @property + def reply(self) -> None: + """ + - 类型: ``None`` + - 说明: 回复消息详情 + """ + raise ValueError("暂不支持 reply") + + @property + def raw_message(self) -> Optional[Union[TextMessage]]: + """ + - 类型: ``Optional[str]`` + - 说明: 原始消息 + """ + return getattr(self.raw_event, self.raw_event.msgtype) + + @raw_message.setter + def raw_message(self, value) -> None: + setattr(self.raw_event, self.raw_event.msgtype, value) + + @property + def plain_text(self) -> Optional[str]: + """ + - 类型: ``Optional[str]`` + - 说明: 纯文本消息内容 + """ + return self.message and self.message.extract_plain_text().strip() + + @property + def sender(self) -> Optional[dict]: + """ + - 类型: ``Optional[dict]`` + - 说明: 消息发送者信息 + """ + result = { + # 加密的发送者ID。 + "senderId": self.raw_event.senderId, + # 发送者昵称。 + "senderNick": self.raw_event.senderNick, + # 企业内部群有的发送者当前群的企业 corpId。 + "senderCorpId": self.raw_event.senderCorpId, + # 企业内部群有的发送者在企业内的 userId。 + "senderStaffId": self.raw_event.senderStaffId, + "role": "admin" if self.raw_event.isAdmin else "member" + } + return result + + @sender.setter + def sender(self, value) -> None: + + def set_wrapper(name): + if value.get(name): + setattr(self.raw_event, name, value.get(name)) + + set_wrapper("senderId") + set_wrapper("senderNick") + set_wrapper("senderCorpId") + set_wrapper("senderStaffId") diff --git a/nonebot/adapters/ding/exception.py b/nonebot/adapters/ding/exception.py new file mode 100644 index 00000000..b1d74d14 --- /dev/null +++ b/nonebot/adapters/ding/exception.py @@ -0,0 +1,76 @@ +from nonebot.typing import Optional +from nonebot.exception import (AdapterException, ActionFailed as + BaseActionFailed, ApiNotAvailable as + BaseApiNotAvailable, NetworkError as + BaseNetworkError) + + +class DingAdapterException(AdapterException): + """ + :说明: + + 钉钉 Adapter 错误基类 + """ + + def __init__(self) -> None: + super().__init__("ding") + + +class ActionFailed(BaseActionFailed, DingAdapterException): + """ + :说明: + + API 请求返回错误信息。 + + :参数: + + * ``errcode: Optional[int]``: 错误码 + * ``errmsg: Optional[str]``: 错误信息 + """ + + def __init__(self, + errcode: Optional[int] = None, + errmsg: Optional[str] = None): + super().__init__() + self.errcode = errcode + self.errmsg = errmsg + + def __repr__(self): + return f"" + + +class ApiNotAvailable(BaseApiNotAvailable, DingAdapterException): + pass + + +class NetworkError(BaseNetworkError, DingAdapterException): + """ + :说明: + + 网络错误。 + + :参数: + + * ``retcode: Optional[int]``: 错误码 + """ + + def __init__(self, msg: Optional[str] = None): + super().__init__() + self.msg = msg + + def __repr__(self): + return f"" + + def __str__(self): + return self.__repr__() + + +class SessionExpired(BaseApiNotAvailable, DingAdapterException): + """ + :说明: + + 发消息的 session 已经过期。 + """ + + def __repr__(self) -> str: + return f"" diff --git a/nonebot/adapters/ding/message.py b/nonebot/adapters/ding/message.py new file mode 100644 index 00000000..d8e88314 --- /dev/null +++ b/nonebot/adapters/ding/message.py @@ -0,0 +1,133 @@ +from nonebot.typing import Any, Dict, Union, Iterable +from nonebot.adapters import BaseMessage, BaseMessageSegment +from .utils import log +from .model import TextMessage + + +class MessageSegment(BaseMessageSegment): + """ + 钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + """ + + def __init__(self, type_: str, msg: Dict[str, Any]) -> None: + data = { + "msgtype": type_, + } + if msg: + data.update(msg) + log("DEBUG", f"data {data}") + super().__init__(type=type_, data=data) + + @classmethod + def from_segment(cls, segment: "MessageSegment"): + return MessageSegment(segment.type, segment.data) + + def __str__(self): + log("DEBUG", f"__str__: self.type {self.type} data {self.data}") + if self.type == "text": + return str(self.data["text"]["content"].strip()) + return "" + + def __add__(self, other) -> "Message": + if isinstance(other, str): + if self.type == 'text': + self.data['text']['content'] += other + return MessageSegment.from_segment(self) + return Message(self) + other + + def atMobile(self, mobileNumber): + self.data.setdefault("at", {}) + self.data["at"].setdefault("atMobiles", []) + self.data["at"]["atMobiles"].append(mobileNumber) + + def atAll(self, value): + self.data.setdefault("at", {}) + self.data["at"]["isAtAll"] = value + + @staticmethod + def text(text_: str) -> "MessageSegment": + return MessageSegment("text", {"text": {"content": text_.strip()}}) + + @staticmethod + def markdown(title: str, text: str) -> "MessageSegment": + return MessageSegment("markdown", { + "markdown": { + "title": title, + "text": text, + }, + }) + + @staticmethod + def actionCardSingleBtn(title: str, text: str, btnTitle: str, + btnUrl) -> "MessageSegment": + return MessageSegment( + "actionCard", { + "actionCard": { + "title": title, + "text": text, + "singleTitle": btnTitle, + "singleURL": btnUrl + } + }) + + @staticmethod + def actionCardSingleMultiBtns( + title: str, + text: str, + btns: list = [], + hideAvatar: bool = False, + btnOrientation: str = '1', + ) -> "MessageSegment": + """ + :参数: + + * ``btnOrientation``: 0:按钮竖直排列 1:按钮横向排列 + + * ``btns``: [{ "title": title, "actionURL": actionURL }, ...] + """ + return MessageSegment( + "actionCard", { + "actionCard": { + "title": title, + "text": text, + "hideAvatar": "1" if hideAvatar else "0", + "btnOrientation": btnOrientation, + "btns": btns + } + }) + + @staticmethod + def feedCard(links: list = [],) -> "MessageSegment": + """ + :参数: + + * ``links``: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...] + """ + return MessageSegment("feedCard", {"feedCard": {"links": links}}) + + @staticmethod + def empty() -> "MessageSegment": + """不想回复消息到群里""" + return MessageSegment("empty") + + +class Message(BaseMessage): + """ + 钉钉 协议 Message 适配。 + """ + + @staticmethod + def _construct( + msg: Union[str, dict, list, + TextMessage]) -> Iterable[MessageSegment]: + if isinstance(msg, dict): + yield MessageSegment(msg["type"], msg.get("data") or {}) + return + elif isinstance(msg, list): + for seg in msg: + yield MessageSegment(seg["type"], seg.get("data") or {}) + return + elif isinstance(msg, TextMessage): + yield MessageSegment("text", {"text": msg.dict()}) + elif isinstance(msg, str): + yield MessageSegment.text(msg) diff --git a/nonebot/adapters/ding/model.py b/nonebot/adapters/ding/model.py new file mode 100644 index 00000000..d317ea5b --- /dev/null +++ b/nonebot/adapters/ding/model.py @@ -0,0 +1,47 @@ +from typing import List, Optional +from enum import Enum +from pydantic import BaseModel + + +class Headers(BaseModel): + sign: str + token: str + # ms + timestamp: int + + +class TextMessage(BaseModel): + content: str + + +class AtUsersItem(BaseModel): + dingtalkId: str + staffId: Optional[str] + + +class ConversationType(str, Enum): + private = '1' + group = '2' + + +class MessageModel(BaseModel): + msgtype: str = None + text: Optional[TextMessage] = None + msgId: str + # ms + createAt: int = None + conversationType: ConversationType = None + conversationId: str = None + conversationTitle: str = None + senderId: str = None + senderNick: str = None + senderCorpId: str = None + senderStaffId: str = None + chatbotUserId: str = None + chatbotCorpId: str = None + atUsers: List[AtUsersItem] = None + sessionWebhook: str = None + # ms + sessionWebhookExpiredTime: int = None + isAdmin: bool = None + isInAtList: bool = None diff --git a/nonebot/adapters/ding/utils.py b/nonebot/adapters/ding/utils.py new file mode 100644 index 00000000..eb4145bc --- /dev/null +++ b/nonebot/adapters/ding/utils.py @@ -0,0 +1,3 @@ +from nonebot.utils import logger_wrapper + +log = logger_wrapper("DING") diff --git a/nonebot/config.py b/nonebot/config.py index 252b39ad..756ef945 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -102,9 +102,9 @@ class Env(BaseSettings): environment: str = "prod" """ - - 类型: ``str`` - - 默认值: ``"prod"`` - - 说明: + - **类型**: ``str`` + - **默认值**: ``"prod"`` + :说明: 当前环境名。 NoneBot 将从 ``.env.{environment}`` 文件中加载配置。 """ @@ -122,41 +122,47 @@ class Config(BaseConfig): # nonebot configs driver: str = "nonebot.drivers.fastapi" """ - - 类型: ``str`` - - 默认值: ``"nonebot.drivers.fastapi"`` - - 说明: + - **类型**: ``str`` + - **默认值**: ``"nonebot.drivers.fastapi"`` + :说明: + NoneBot 运行所使用的 ``Driver`` 。继承自 ``nonebot.driver.BaseDriver`` 。 """ host: IPvAnyAddress = IPv4Address("127.0.0.1") # type: ignore """ - - 类型: ``IPvAnyAddress`` - - 默认值: ``127.0.0.1`` - - 说明: + - **类型**: ``IPvAnyAddress`` + - **默认值**: ``127.0.0.1`` + :说明: + NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。 """ port: int = 8080 """ - - 类型: ``int`` - - 默认值: ``8080`` - - 说明: + - **类型**: ``int`` + - **默认值**: ``8080`` + :说明: + NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。 """ debug: bool = False """ - - 类型: ``bool`` - - 默认值: ``False`` - - 说明: + - **类型**: ``bool`` + - **默认值**: ``False`` + :说明: + 是否以调试模式运行 NoneBot。 """ # bot connection configs api_root: Dict[str, str] = {} """ - - 类型: ``Dict[str, str]`` - - 默认值: ``{}`` - - 说明: + - **类型**: ``Dict[str, str]`` + - **默认值**: ``{}`` + :说明: + 以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。 - - 示例: + + :示例: .. code-block:: default @@ -164,18 +170,21 @@ class Config(BaseConfig): """ api_timeout: Optional[float] = 30. """ - - 类型: ``Optional[float]`` - - 默认值: ``30.`` - - 说明: + - **类型**: ``Optional[float]`` + - **默认值**: ``30.`` + :说明: + API 请求超时时间,单位: 秒。 """ access_token: Optional[str] = None """ - - 类型: ``Optional[str]`` - - 默认值: ``None`` - - 说明: + - **类型**: ``Optional[str]`` + - **默认值**: ``None`` + :说明: + API 请求以及上报所需密钥,在请求头中携带。 - - 示例: + + :示例: .. code-block:: http @@ -184,11 +193,13 @@ class Config(BaseConfig): """ secret: Optional[str] = None """ - - 类型: ``Optional[str]`` - - 默认值: ``None`` - - 说明: + - **类型**: ``Optional[str]`` + - **默认值**: ``None`` + :说明: + HTTP POST 形式上报所需签名,在请求头中携带。 - - 示例: + + :示例: .. code-block:: http @@ -199,11 +210,13 @@ class Config(BaseConfig): # bot runtime configs superusers: Set[int] = set() """ - - 类型: ``Set[int]`` - - 默认值: ``set()`` - - 说明: + - **类型**: ``Set[int]`` + - **默认值**: ``set()`` + :说明: + 机器人超级用户。 - - 示例: + + :示例: .. code-block:: default @@ -211,32 +224,37 @@ class Config(BaseConfig): """ nickname: Set[str] = set() """ - - 类型: ``Set[str]`` - - 默认值: ``set()`` - - 说明: + - **类型**: ``Set[str]`` + - **默认值**: ``set()`` + :说明: + 机器人昵称。 """ command_start: Set[str] = {"/"} """ - - 类型: ``Set[str]`` - - 默认值: ``{"/"}`` - - 说明: + - **类型**: ``Set[str]`` + - **默认值**: ``{"/"}`` + :说明: + 命令的起始标记,用于判断一条消息是不是命令。 """ command_sep: Set[str] = {"."} """ - - 类型: ``Set[str]`` - - 默认值: ``{"."}`` - - 说明: + - **类型**: ``Set[str]`` + - **默认值**: ``{"."}`` + :说明: + 命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。 """ session_expire_timeout: timedelta = timedelta(minutes=2) """ - - 类型: ``timedelta`` - - 默认值: ``timedelta(minutes=2)`` - - 说明: + - **类型**: ``timedelta`` + - **默认值**: ``timedelta(minutes=2)`` + :说明: + 等待用户回复的超时时间。 - - 示例: + + :示例: .. code-block:: default @@ -244,16 +262,6 @@ class Config(BaseConfig): 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"} - """ - - 类型: ``dict`` - - 默认值: ``{"apscheduler.timezone": "Asia/Shanghai"}`` - - 说明: - APScheduler 的配置对象,见 `Configuring the Scheduler`_ - - .. _Configuring the Scheduler: - https://apscheduler.readthedocs.io/en/latest/userguide.html#configuring-the-scheduler - """ # custom configs # custom configs can be assigned during nonebot.init diff --git a/nonebot/drivers/__init__.py b/nonebot/drivers/__init__.py index ce6097ff..8227690f 100644 --- a/nonebot/drivers/__init__.py +++ b/nonebot/drivers/__init__.py @@ -51,8 +51,11 @@ class BaseDriver(abc.ABC): def register_adapter(cls, name: str, adapter: Type[Bot]): """ :说明: + 注册一个协议适配器 + :参数: + * ``name: str``: 适配器名称,用于在连接时进行识别 * ``adapter: Type[Bot]``: 适配器 Class """ @@ -110,14 +113,18 @@ class BaseDriver(abc.ABC): **kwargs): """ :说明: + 启动驱动框架 + :参数: + * ``host: Optional[str]``: 驱动绑定 IP * ``post: Optional[int]``: 驱动绑定端口 * ``*args`` * ``**kwargs`` """ - raise NotImplementedError + logger.opt(colors=True).debug( + f"Loaded adapters: {', '.join(self._adapters)}") @abc.abstractmethod async def _handle_http(self): diff --git a/nonebot/drivers/fastapi.py b/nonebot/drivers/fastapi.py index 0828e344..841b82e5 100644 --- a/nonebot/drivers/fastapi.py +++ b/nonebot/drivers/fastapi.py @@ -39,7 +39,16 @@ def get_auth_bearer(access_token: Optional[str] = Header( class Driver(BaseDriver): - """FastAPI 驱动框架""" + """ + FastAPI 驱动框架 + + :上报地址: + + * ``/{adapter name}/``: HTTP POST 上报 + * ``/{adapter name}/http/``: HTTP POST 上报 + * ``/{adapter name}/ws``: WebSocket 上报 + * ``/{adapter name}/ws/``: WebSocket 上报 + """ def __init__(self, env: Env, config: Config): super().__init__(env, config) @@ -98,6 +107,7 @@ class Driver(BaseDriver): app: Optional[str] = None, **kwargs): """使用 ``uvicorn`` 启动 FastAPI""" + super().run(host, port, app, **kwargs) LOGGING_CONFIG = { "version": 1, "disable_existing_loggers": False, diff --git a/nonebot/exception.py b/nonebot/exception.py index f16cbcd0..6a4b65dc 100644 --- a/nonebot/exception.py +++ b/nonebot/exception.py @@ -6,10 +6,17 @@ 这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。 """ -from nonebot.typing import List, Type, Optional + +class NoneBotException(Exception): + """ + :说明: + + 所有 NoneBot 发生的异常基类。 + """ + pass -class IgnoredException(Exception): +class IgnoredException(NoneBotException): """ :说明: @@ -18,7 +25,6 @@ class IgnoredException(Exception): :参数: * ``reason``: 忽略事件的原因 - """ def __init__(self, reason): @@ -31,7 +37,7 @@ class IgnoredException(Exception): return self.__repr__() -class PausedException(Exception): +class PausedException(NoneBotException): """ :说明: @@ -45,7 +51,7 @@ class PausedException(Exception): pass -class RejectedException(Exception): +class RejectedException(NoneBotException): """ :说明: @@ -59,7 +65,7 @@ class RejectedException(Exception): pass -class FinishedException(Exception): +class FinishedException(NoneBotException): """ :说明: @@ -73,7 +79,7 @@ class FinishedException(Exception): pass -class StopPropagation(Exception): +class StopPropagation(NoneBotException): """ :说明: @@ -86,7 +92,7 @@ class StopPropagation(Exception): pass -class RequestDenied(Exception): +class RequestDenied(NoneBotException): """ :说明: @@ -109,7 +115,22 @@ class RequestDenied(Exception): return self.__repr__() -class ApiNotAvailable(Exception): +class AdapterException(NoneBotException): + """ + :说明: + + 代表 ``Adapter`` 抛出的异常,所有的 ``Adapter`` 都要在内部继承自这个 ``Exception`` + + :参数: + + * ``adapter_name: str``: 标识 adapter + """ + + def __init__(self, adapter_name: str) -> None: + self.adapter_name = adapter_name + + +class ApiNotAvailable(AdapterException): """ :说明: @@ -118,7 +139,7 @@ class ApiNotAvailable(Exception): pass -class NetworkError(Exception): +class NetworkError(AdapterException): """ :说明: @@ -127,22 +148,10 @@ class NetworkError(Exception): pass -class ActionFailed(Exception): +class ActionFailed(AdapterException): """ :说明: API 请求成功返回数据,但 API 操作失败。 - - :参数: - - * ``retcode: Optional[int]``: 错误代码 """ - - def __init__(self, retcode: Optional[int]): - self.retcode = retcode - - def __repr__(self): - return f"" - - def __str__(self): - return self.__repr__() + pass diff --git a/nonebot/matcher.py b/nonebot/matcher.py index 92238af9..1c2eabe6 100644 --- a/nonebot/matcher.py +++ b/nonebot/matcher.py @@ -101,8 +101,7 @@ class Matcher(metaclass=MatcherMeta): """ def __init__(self): - """实例化 Matcher 以便运行 - """ + """实例化 Matcher 以便运行""" self.handlers = self.handlers.copy() self.state = self._default_state.copy() @@ -128,8 +127,11 @@ class Matcher(metaclass=MatcherMeta): expire_time: Optional[datetime] = None) -> Type["Matcher"]: """ :说明: + 创建一个新的事件响应器,并存储至 `matchers <#matchers>`_ + :参数: + * ``type_: str``: 事件响应器类型,与 ``event.type`` 一致时触发,空字符串表示任意 * ``rule: Optional[Rule]``: 匹配规则 * ``permission: Optional[Permission]``: 权限 @@ -140,7 +142,9 @@ class Matcher(metaclass=MatcherMeta): * ``module: Optional[str]``: 事件响应器所在模块名称 * ``default_state: Optional[dict]``: 默认状态 ``state`` * ``expire_time: Optional[datetime]``: 事件响应器最终有效时间点,过时即被删除 + :返回: + - ``Type[Matcher]``: 新的事件响应器类 """ @@ -166,11 +170,16 @@ class Matcher(metaclass=MatcherMeta): async def check_perm(cls, bot: Bot, event: Event) -> bool: """ :说明: + 检查是否满足触发权限 + :参数: + * ``bot: Bot``: Bot 对象 * ``event: Event``: 上报事件 + :返回: + - ``bool``: 是否满足权限 """ return await cls.permission(bot, event) @@ -179,12 +188,17 @@ class Matcher(metaclass=MatcherMeta): async def check_rule(cls, bot: Bot, event: Event, state: dict) -> bool: """ :说明: + 检查是否满足匹配规则 + :参数: + * ``bot: Bot``: Bot 对象 * ``event: Event``: 上报事件 * ``state: dict``: 当前状态 + :返回: + - ``bool``: 是否满足匹配规则 """ return (event.type == (cls.type or event.type) and @@ -194,8 +208,11 @@ class Matcher(metaclass=MatcherMeta): def args_parser(cls, func: ArgsParser) -> ArgsParser: """ :说明: + 装饰一个函数来更改当前事件响应器的默认参数解析函数 + :参数: + * ``func: ArgsParser``: 参数解析函数 """ cls._default_parser = func @@ -205,8 +222,11 @@ class Matcher(metaclass=MatcherMeta): def handle(cls) -> Callable[[Handler], Handler]: """ :说明: + 装饰一个函数来向事件响应器直接添加一个处理函数 + :参数: + * 无 """ @@ -220,8 +240,11 @@ class Matcher(metaclass=MatcherMeta): def receive(cls) -> Callable[[Handler], Handler]: """ :说明: + 装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数 + :参数: + * 无 """ @@ -249,8 +272,11 @@ class Matcher(metaclass=MatcherMeta): ) -> Callable[[Handler], Handler]: """ :说明: + 装饰一个函数来指示 NoneBot 当要获取的 ``key`` 不存在时接收用户新的一条消息并经过 ``ArgsParser`` 处理后再运行该函数,如果 ``key`` 已存在则直接继续运行 + :参数: + * ``key: str``: 参数名 * ``prompt: Optional[Union[str, Message, MessageSegment]]``: 在参数不存在时向用户发送的消息 * ``args_parser: Optional[ArgsParser]``: 可选参数解析函数,空则使用默认解析函数 @@ -300,8 +326,11 @@ class Matcher(metaclass=MatcherMeta): async def send(cls, message: Union[str, Message, MessageSegment], **kwargs): """ :说明: + 发送一条消息给当前交互用户 + :参数: + * ``message: Union[str, Message, MessageSegment]``: 消息内容 * ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api """ @@ -316,8 +345,11 @@ class Matcher(metaclass=MatcherMeta): **kwargs) -> NoReturn: """ :说明: + 发送一条消息给当前交互用户并结束当前事件响应器 + :参数: + * ``message: Union[str, Message, MessageSegment]``: 消息内容 * ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api """ @@ -334,8 +366,11 @@ class Matcher(metaclass=MatcherMeta): **kwargs) -> NoReturn: """ :说明: + 发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数 + :参数: + * ``prompt: Union[str, Message, MessageSegment]``: 消息内容 * ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api """ @@ -352,8 +387,11 @@ class Matcher(metaclass=MatcherMeta): **kwargs) -> NoReturn: """ :说明: + 发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后重新运行当前处理函数 + :参数: + * ``prompt: Union[str, Message, MessageSegment]``: 消息内容 * ``**kwargs``: 其他传递给 ``bot.send`` 的参数,请参考对应 adapter 的 bot 对象 api """ @@ -411,199 +449,3 @@ class Matcher(metaclass=MatcherMeta): logger.info(f"Matcher {self} running complete") current_bot.reset(b_t) current_event.reset(e_t) - - -class MatcherGroup: - """事件响应器组合,统一管理。用法同 ``Matcher``""" - - def __init__(self, - type_: str = "", - rule: Optional[Rule] = None, - permission: Optional[Permission] = None, - handlers: Optional[list] = None, - temp: bool = False, - priority: int = 1, - block: bool = False, - *, - module: Optional[str] = None, - default_state: Optional[dict] = None, - expire_time: Optional[datetime] = None): - """ - :说明: - 创建一个事件响应器组合,参数为默认值,与 ``Matcher.new`` 一致 - """ - self.matchers: List[Type[Matcher]] = [] - """ - :类型: ``List[Type[Matcher]]`` - :说明: 组内事件响应器列表 - """ - - self.type = type_ - self.rule = rule or Rule() - self.permission = permission or Permission() - self.handlers = handlers - self.temp = temp - self.priority = priority - self.block = block - self.module = module - self.expire_time = expire_time - - self._default_state = default_state - - self._default_parser: Optional[ArgsParser] = None - - def __repr__(self) -> str: - return ( - f"") - - def __str__(self) -> str: - return self.__repr__() - - def new(self, - type_: str = "", - rule: Optional[Rule] = None, - permission: Optional[Permission] = None, - handlers: Optional[list] = None, - temp: bool = False, - priority: int = 1, - block: bool = False, - *, - module: Optional[str] = None, - default_state: Optional[dict] = None, - expire_time: Optional[datetime] = None) -> Type[Matcher]: - """ - :说明: - 在组中创建一个新的事件响应器,参数留空则使用组合默认值 - - \:\:\:danger 警告 - 如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数 - \:\:\: - """ - matcher = Matcher.new(type_=type_ or self.type, - rule=self.rule & rule, - permission=permission or self.permission, - handlers=handlers or self.handlers, - temp=temp or self.temp, - priority=priority or self.priority, - block=block or self.block, - module=module or self.module, - default_state=default_state or - self._default_state, - expire_time=expire_time or self.expire_time) - self.matchers.append(matcher) - return matcher - - def args_parser(self, func: ArgsParser) -> ArgsParser: - self._default_parser = func - for matcher in self.matchers: - matcher.args_parser(func) - return func - - def handle(self) -> Callable[[Handler], Handler]: - - def _decorator(func: Handler) -> Handler: - self.handlers.append(func) - return func - - return _decorator - - def receive(self) -> Callable[[Handler], Handler]: - - async def _receive(bot: Bot, event: Event, state: dict) -> NoReturn: - raise PausedException - - if self.handlers: - # 已有前置handlers则接受一条新的消息,否则视为接收初始消息 - self.handlers.append(_receive) - - def _decorator(func: Handler) -> Handler: - if not self.handlers or self.handlers[-1] is not func: - self.handlers.append(func) - - return func - - return _decorator - - def got( - self, - key: str, - prompt: Optional[str] = None, - args_parser: Optional[ArgsParser] = None - ) -> Callable[[Handler], Handler]: - - async def _key_getter(bot: Bot, event: Event, state: dict): - state["_current_key"] = key - if key not in state: - if prompt: - await bot.send(event=event, - message=str(prompt).format(state)) - raise PausedException - else: - state["_skip_key"] = True - - async def _key_parser(bot: Bot, event: Event, state: dict): - if key in state and state.get("_skip_key"): - del state["_skip_key"] - return - parser = args_parser or self._default_parser - if parser: - await parser(bot, event, state) - else: - state[state["_current_key"]] = str(event.message) - - self.handlers.append(_key_getter) - self.handlers.append(_key_parser) - - def _decorator(func: Handler) -> Handler: - if not hasattr(self.handlers[-1], "__wrapped__"): - parser = self.handlers.pop() - - @wraps(func) - async def wrapper(bot: Bot, event: Event, state: dict): - await parser(bot, event, state) - await func(bot, event, state) - if "_current_key" in state: - del state["_current_key"] - - self.handlers.append(wrapper) - - return func - - return _decorator - - async def send(self, message: Union[str, Message, MessageSegment], - **kwargs): - bot = current_bot.get() - event = current_event.get() - await bot.send(event=event, message=message, **kwargs) - - async def finish(self, - message: Optional[Union[str, Message, - MessageSegment]] = None, - **kwargs) -> NoReturn: - bot = current_bot.get() - event = current_event.get() - if message: - await bot.send(event=event, message=message, **kwargs) - raise FinishedException - - async def pause(self, - prompt: Optional[Union[str, Message, - MessageSegment]] = None, - **kwargs) -> NoReturn: - bot = current_bot.get() - event = current_event.get() - if prompt: - await bot.send(event=event, message=prompt, **kwargs) - raise PausedException - - async def reject(self, - prompt: Optional[Union[str, Message, - MessageSegment]] = None, - **kwargs) -> NoReturn: - bot = current_bot.get() - event = current_event.get() - if prompt: - await bot.send(event=event, message=prompt, **kwargs) - raise RejectedException diff --git a/nonebot/message.py b/nonebot/message.py index 1b102633..425b476a 100644 --- a/nonebot/message.py +++ b/nonebot/message.py @@ -25,8 +25,11 @@ _run_postprocessors: Set[RunPostProcessor] = set() def event_preprocessor(func: EventPreProcessor) -> EventPreProcessor: """ :说明: + 事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。 + :参数: + 事件预处理函数接收三个参数。 * ``bot: Bot``: Bot 对象 @@ -40,8 +43,11 @@ def event_preprocessor(func: EventPreProcessor) -> EventPreProcessor: def event_postprocessor(func: EventPostProcessor) -> EventPostProcessor: """ :说明: + 事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。 + :参数: + 事件后处理函数接收三个参数。 * ``bot: Bot``: Bot 对象 @@ -55,8 +61,11 @@ def event_postprocessor(func: EventPostProcessor) -> EventPostProcessor: def run_preprocessor(func: RunPreProcessor) -> RunPreProcessor: """ :说明: + 运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。 + :参数: + 运行预处理函数接收四个参数。 * ``matcher: Matcher``: 当前要运行的事件响应器 @@ -71,8 +80,11 @@ def run_preprocessor(func: RunPreProcessor) -> RunPreProcessor: def run_postprocessor(func: RunPostProcessor) -> RunPostProcessor: """ :说明: + 运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。 + :参数: + 运行后处理函数接收五个参数。 * ``matcher: Matcher``: 运行完毕的事件响应器 @@ -176,10 +188,14 @@ async def _run_matcher(Matcher: Type[Matcher], bot: Bot, event: Event, async def handle_event(bot: Bot, event: Event): """ :说明: + 处理一个事件。调用该函数以实现分发事件。 + :参数: + * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 + :示例: .. code-block:: python diff --git a/nonebot/permission.py b/nonebot/permission.py index df6c099b..f4c793b0 100644 --- a/nonebot/permission.py +++ b/nonebot/permission.py @@ -22,24 +22,33 @@ class Permission: Awaitable[bool]]) -> None: """ :参数: + * ``*checkers: Callable[[Bot, Event], Awaitable[bool]]``: **异步** PermissionChecker """ self.checkers = set(checkers) """ :说明: + 存储 ``PermissionChecker`` + :类型: + * ``Set[Callable[[Bot, Event], Awaitable[bool]]]`` """ async def __call__(self, bot: Bot, event: Event) -> bool: """ :说明: + 检查是否满足某个权限 + :参数: + * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 + :返回: + - ``bool`` """ if not self.checkers: @@ -103,8 +112,11 @@ METAEVENT = Permission(_metaevent) def USER(*user: int, perm: Permission = Permission()): """ :说明: + 在白名单内且满足 perm + :参数: + * ``*user: int``: 白名单 * ``perm: Permission``: 需要同时满足的权限 """ diff --git a/nonebot/plugin.py b/nonebot/plugin.py index f063726c..57410566 100644 --- a/nonebot/plugin.py +++ b/nonebot/plugin.py @@ -9,6 +9,7 @@ import re import sys import pkgutil import importlib +from datetime import datetime from dataclasses import dataclass from importlib._bootstrap import _load from contextvars import Context, ContextVar, copy_context @@ -18,7 +19,7 @@ from nonebot.matcher import Matcher from nonebot.permission import Permission from nonebot.typing import Handler, RuleChecker from nonebot.rule import Rule, startswith, endswith, keyword, command, regex -from nonebot.typing import Any, Set, List, Dict, Type, Tuple, Union, Optional, ModuleType +from nonebot.typing import Any, Set, List, Dict, Type, Tuple, Union, Optional, ArgsParser, ModuleType plugins: Dict[str, "Plugin"] = {} """ @@ -33,7 +34,9 @@ _export: ContextVar["Export"] = ContextVar("_export") class Export(dict): """ :说明: + 插件导出内容以使得其他插件可以获得。 + :示例: .. code-block:: python @@ -44,10 +47,11 @@ class Export(dict): def some_function(): pass - # this don't work under python 3.9 + # 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 @@ -107,8 +111,11 @@ def on(type: str = "", state: Optional[dict] = None) -> Type[Matcher]: """ :说明: + 注册一个基础事件响应器,可自定义类型。 + :参数: + * ``type: str``: 事件响应器类型 * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 @@ -117,7 +124,9 @@ def on(type: str = "", * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ matcher = Matcher.new(type, @@ -141,15 +150,20 @@ def on_metaevent(rule: Optional[Union[Rule, RuleChecker]] = None, state: Optional[dict] = None) -> Type[Matcher]: """ :说明: + 注册一个元事件响应器。 + :参数: + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ matcher = Matcher.new("meta_event", @@ -174,8 +188,11 @@ def on_message(rule: Optional[Union[Rule, RuleChecker]] = None, state: Optional[dict] = None) -> Type[Matcher]: """ :说明: + 注册一个消息事件响应器。 + :参数: + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 @@ -183,7 +200,9 @@ def on_message(rule: Optional[Union[Rule, RuleChecker]] = None, * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ matcher = Matcher.new("message", @@ -207,15 +226,20 @@ def on_notice(rule: Optional[Union[Rule, RuleChecker]] = None, state: Optional[dict] = None) -> Type[Matcher]: """ :说明: + 注册一个通知事件响应器。 + :参数: + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ matcher = Matcher.new("notice", @@ -239,15 +263,20 @@ def on_request(rule: Optional[Union[Rule, RuleChecker]] = None, state: Optional[dict] = None) -> Type[Matcher]: """ :说明: + 注册一个请求事件响应器。 + :参数: + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ matcher = Matcher.new("request", @@ -267,8 +296,11 @@ def on_startswith(msg: str, **kwargs) -> Type[Matcher]: """ :说明: + 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。 + :参数: + * ``msg: str``: 指定消息开头内容 * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 @@ -277,7 +309,9 @@ def on_startswith(msg: str, * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ return on_message(startswith(msg) & rule, **kwargs) @@ -288,8 +322,11 @@ def on_endswith(msg: str, **kwargs) -> Type[Matcher]: """ :说明: + 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。 + :参数: + * ``msg: str``: 指定消息结尾内容 * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 @@ -298,7 +335,9 @@ def on_endswith(msg: str, * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ return on_message(endswith(msg) & rule, **kwargs) @@ -309,8 +348,11 @@ def on_keyword(keywords: Set[str], **kwargs) -> Type[Matcher]: """ :说明: + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + :参数: + * ``keywords: Set[str]``: 关键词列表 * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 @@ -319,7 +361,9 @@ def on_keyword(keywords: Set[str], * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ return on_message(keyword(*keywords) & rule, **kwargs) @@ -331,10 +375,13 @@ def on_command(cmd: Union[str, Tuple[str, ...]], **kwargs) -> Type[Matcher]: """ :说明: + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 命令匹配规则参考: `命令形式匹配 `_ + :参数: + * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容 * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名 @@ -344,7 +391,9 @@ def on_command(cmd: Union[str, Tuple[str, ...]], * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ @@ -366,10 +415,13 @@ def on_regex(pattern: str, **kwargs) -> Type[Matcher]: """ :说明: + 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 命令匹配规则参考: `正则匹配 `_ + :参数: + * ``pattern: str``: 正则表达式 * ``flags: Union[int, re.RegexFlag]``: 正则匹配标志 * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 @@ -379,7 +431,9 @@ def on_regex(pattern: str, * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 * ``state: Optional[dict]``: 默认的 state + :返回: + - ``Type[Matcher]`` """ return on_message(regex(pattern, flags) & rule, **kwargs) @@ -391,6 +445,7 @@ class CommandGroup: def __init__(self, cmd: Union[str, Tuple[str, ...]], **kwargs): """ :参数: + * ``cmd: Union[str, Tuple[str, ...]]``: 命令前缀 * ``**kwargs``: 其他传递给 ``on_command`` 的参数默认值,参考 `on_command <#on-command-cmd-rule-none-aliases-none-kwargs>`_ """ @@ -411,11 +466,16 @@ class CommandGroup: **kwargs) -> Type[Matcher]: """ :说明: + 注册一个新的命令。 + :参数: + * ``cmd: Union[str, Tuple[str, ...]]``: 命令前缀 * ``**kwargs``: 其他传递给 ``on_command`` 的参数,将会覆盖命令组默认值 + :返回: + - ``Type[Matcher]`` """ sub_cmd = (cmd,) if isinstance(cmd, str) else cmd @@ -426,13 +486,326 @@ class CommandGroup: return on_command(cmd, **final_kwargs) +class MatcherGroup: + """事件响应器组合,统一管理。为 ``Matcher`` 创建提供默认属性。""" + + def __init__(self, **kwargs): + """ + :说明: + + 创建一个事件响应器组合,参数为默认值,与 ``on`` 一致 + """ + self.matchers: List[Type[Matcher]] = [] + """ + :类型: ``List[Type[Matcher]]`` + :说明: 组内事件响应器列表 + """ + self.base_kwargs: Dict[str, Any] = kwargs + """ + - **类型**: ``Dict[str, Any]`` + - **说明**: 其他传递给 ``on`` 的参数默认值 + """ + + def on(self, **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个基础事件响应器,可自定义类型。 + + :参数: + + * ``type: str``: 事件响应器类型 + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + final_kwargs = self.base_kwargs.copy() + final_kwargs.update(kwargs) + matcher = Matcher.new(**final_kwargs) + self.matchers.append(matcher) + _tmp_matchers.get().add(matcher) + return matcher + + def on_metaevent(self, **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个元事件响应器。 + + :参数: + + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + final_kwargs = self.base_kwargs.copy() + final_kwargs.update(kwargs) + final_kwargs.pop("type", None) + matcher = Matcher.new("meta_event", **final_kwargs) + self.matchers.append(matcher) + _tmp_matchers.get().add(matcher) + return matcher + + def on_message(self, **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个消息事件响应器。 + + :参数: + + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + final_kwargs = self.base_kwargs.copy() + final_kwargs.update(kwargs) + final_kwargs.pop("type", None) + matcher = Matcher.new("message", **final_kwargs) + self.matchers.append(matcher) + _tmp_matchers.get().add(matcher) + return matcher + + def on_notice(self, **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个通知事件响应器。 + + :参数: + + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + final_kwargs = self.base_kwargs.copy() + final_kwargs.update(kwargs) + final_kwargs.pop("type", None) + matcher = Matcher.new("notice", **final_kwargs) + self.matchers.append(matcher) + _tmp_matchers.get().add(matcher) + return matcher + + def on_request(self, **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个请求事件响应器。 + + :参数: + + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + final_kwargs = self.base_kwargs.copy() + final_kwargs.update(kwargs) + final_kwargs.pop("type", None) + matcher = Matcher.new("request", **final_kwargs) + self.matchers.append(matcher) + _tmp_matchers.get().add(matcher) + return matcher + + def on_startswith(self, + msg: str, + rule: Optional[Optional[Union[Rule, RuleChecker]]] = None, + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。 + + :参数: + + * ``msg: str``: 指定消息开头内容 + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + return self.on_message(rule=startswith(msg) & rule, **kwargs) + + def on_endswith(self, + msg: str, + rule: Optional[Optional[Union[Rule, RuleChecker]]] = None, + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。 + + :参数: + + * ``msg: str``: 指定消息结尾内容 + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + return self.on_message(rule=endswith(msg) & rule, **kwargs) + + def on_keyword(self, + keywords: Set[str], + rule: Optional[Union[Rule, RuleChecker]] = None, + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + + :参数: + + * ``keywords: Set[str]``: 关键词列表 + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + return self.on_message(rule=keyword(*keywords) & rule, **kwargs) + + def on_command(self, + cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, RuleChecker]] = None, + aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 + + 命令匹配规则参考: `命令形式匹配 `_ + + :参数: + + * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容 + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + + async def _strip_cmd(bot, event, state: dict): + message = event.message + event.message = message.__class__( + str(message)[len(state["_prefix"]["raw_command"]):].strip()) + + handlers = kwargs.pop("handlers", []) + handlers.insert(0, _strip_cmd) + + commands = set([cmd]) | (aliases or set()) + return self.on_message(rule=command(*commands) & rule, + handlers=handlers, + **kwargs) + + def on_regex(self, + pattern: str, + flags: Union[int, re.RegexFlag] = 0, + rule: Optional[Rule] = None, + **kwargs) -> Type[Matcher]: + """ + :说明: + + 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 + + 命令匹配规则参考: `正则匹配 `_ + + :参数: + + * ``pattern: str``: 正则表达式 + * ``flags: Union[int, re.RegexFlag]``: 正则匹配标志 + * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``permission: Optional[Permission]``: 事件响应权限 + * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``temp: bool``: 是否为临时事件响应器(仅执行一次) + * ``priority: int``: 事件响应器优先级 + * ``block: bool``: 是否阻止事件向更低优先级传递 + * ``state: Optional[dict]``: 默认的 state + + :返回: + + - ``Type[Matcher]`` + """ + return self.on_message(rule=regex(pattern, flags) & rule, **kwargs) + + def load_plugin(module_path: str) -> Optional[Plugin]: """ :说明: + 使用 ``importlib`` 加载单个插件,可以是本地插件或是通过 ``pip`` 安装的插件。 + :参数: + * ``module_path: str``: 插件名称 ``path.to.your.plugin`` + :返回: + - ``Optional[Plugin]`` """ @@ -469,10 +842,15 @@ def load_plugin(module_path: str) -> Optional[Plugin]: def load_plugins(*plugin_dir: str) -> Set[Plugin]: """ :说明: + 导入目录下多个插件,以 ``_`` 开头的插件不会被导入! + :参数: + - ``*plugin_dir: str``: 插件路径 + :返回: + - ``Set[Plugin]`` """ @@ -517,8 +895,11 @@ def load_plugins(*plugin_dir: str) -> Set[Plugin]: def load_builtin_plugins() -> Optional[Plugin]: """ :说明: + 导入 NoneBot 内置插件 + :返回: + - ``Plugin`` """ return load_plugin("nonebot.plugins.base") @@ -527,10 +908,15 @@ def load_builtin_plugins() -> Optional[Plugin]: def get_plugin(name: str) -> Optional[Plugin]: """ :说明: + 获取当前导入的某个插件。 + :参数: + * ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。 + :返回: + - ``Optional[Plugin]`` """ return plugins.get(name) @@ -539,8 +925,11 @@ def get_plugin(name: str) -> Optional[Plugin]: def get_loaded_plugins() -> Set[Plugin]: """ :说明: + 获取当前已导入的所有插件。 + :返回: + - ``Set[Plugin]`` """ return set(plugins.values()) @@ -549,8 +938,11 @@ def get_loaded_plugins() -> Set[Plugin]: def export() -> Export: """ :说明: + 获取插件的导出内容对象 + :返回: + - ``Export`` """ return _export.get() @@ -559,10 +951,15 @@ def export() -> Export: def require(name: str) -> Optional[Export]: """ :说明: + 获取一个插件的导出内容 + :参数: + * ``name: str``: 插件名,与 ``load_plugin`` 参数一致。如果为 ``load_plugins`` 导入的插件,则为文件(夹)名。 + :返回: + - ``Optional[Export]`` """ plugin = get_plugin(name) diff --git a/nonebot/plugin.pyi b/nonebot/plugin.pyi index 37d775d6..607c1d27 100644 --- a/nonebot/plugin.pyi +++ b/nonebot/plugin.pyi @@ -188,13 +188,143 @@ class CommandGroup: def command(self, cmd: Union[str, Tuple[str, ...]], + *, rule: Optional[Union[Rule, RuleChecker]] = ..., aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., permission: Optional[Permission] = ..., - *, handlers: Optional[List[Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., state: Optional[dict] = ...) -> Type[Matcher]: ... + + +class MatcherGroup: + + def __init__(self, + *, + type: str = ..., + rule: Optional[Union[Rule, RuleChecker]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[dict] = ...): + ... + + def on(self, + *, + type: str = ..., + rule: Optional[Union[Rule, RuleChecker]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[dict] = ...) -> Type[Matcher]: + ... + + def on_metaevent(self, + *, + rule: Optional[Union[Rule, RuleChecker]] = None, + handlers: Optional[List[Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = False, + state: Optional[dict] = None) -> Type[Matcher]: + ... + + def on_message(self, + *, + rule: Optional[Union[Rule, RuleChecker]] = None, + permission: Optional[Permission] = None, + handlers: Optional[List[Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = True, + state: Optional[dict] = None) -> Type[Matcher]: + ... + + def on_notice(self, + *, + rule: Optional[Union[Rule, RuleChecker]] = None, + handlers: Optional[List[Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = False, + state: Optional[dict] = None) -> Type[Matcher]: + ... + + def on_request(self, + *, + rule: Optional[Union[Rule, RuleChecker]] = None, + handlers: Optional[List[Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = False, + state: Optional[dict] = None) -> Type[Matcher]: + ... + + def on_startswith(self, + *, + msg: str, + rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[dict] = ...) -> Type[Matcher]: + ... + + def on_endswith(self, + *, + msg: str, + rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[dict] = ...) -> Type[Matcher]: + ... + + def on_keyword(self, + *, + keywords: Set[str], + rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[dict] = ...) -> Type[Matcher]: + ... + + def on_command(self, + *, + cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, RuleChecker]] = ..., + aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[dict] = ...) -> Type[Matcher]: + ... + + def on_regex(self, + *, + pattern: str, + flags: Union[int, re.RegexFlag] = 0, + rule: Optional[Rule] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[dict] = ...) -> Type[Matcher]: + ... diff --git a/nonebot/plugins/base.py b/nonebot/plugins/base.py index 67ed40af..c937f5c0 100644 --- a/nonebot/plugins/base.py +++ b/nonebot/plugins/base.py @@ -14,7 +14,7 @@ async def say_unescape(bot: Bot, event: Event, state: dict): def _unescape(message: Message, segment: MessageSegment): if segment.type == "text": - return message.append(segment.data["text"]) + return message.append(str(segment)) return message.append(segment) message = reduce(_unescape, event.message, Message()) # type: ignore diff --git a/nonebot/rule.py b/nonebot/rule.py index faefbd76..c58d5874 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -24,7 +24,9 @@ from nonebot.typing import Bot, Any, Dict, Event, Union, Tuple, NoReturn, Option class Rule: """ :说明: + ``Matcher`` 规则类,当事件传递时,在 ``Matcher`` 运行前进行检查。 + :示例: .. code-block:: python @@ -41,25 +43,35 @@ class Rule: Awaitable[bool]]) -> None: """ :参数: + * ``*checkers: Callable[[Bot, Event, dict], Awaitable[bool]]``: **异步** RuleChecker + """ self.checkers = set(checkers) """ :说明: + 存储 ``RuleChecker`` + :类型: + * ``Set[Callable[[Bot, Event, dict], Awaitable[bool]]]`` """ async def __call__(self, bot: Bot, event: Event, state: dict) -> bool: """ :说明: + 检查是否符合所有规则 + :参数: + * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 * ``state: dict``: 当前 State + :返回: + - ``bool`` """ results = await asyncio.gather( @@ -118,11 +130,10 @@ class TrieRule: suffix = None message = event.message[0] if message.type == "text": - prefix = cls.prefix.longest_prefix(message.data["text"].lstrip()) + prefix = cls.prefix.longest_prefix(str(message).lstrip()) message_r = event.message[-1] if message_r.type == "text": - suffix = cls.suffix.longest_prefix( - message_r.data["text"].rstrip()[::-1]) + suffix = cls.suffix.longest_prefix(str(message_r).rstrip()[::-1]) state["_prefix"] = { "raw_command": prefix.key, @@ -157,8 +168,11 @@ class TrieRule: def startswith(msg: str) -> Rule: """ :说明: + 匹配消息开头 + :参数: + * ``msg: str``: 消息开头字符串 """ @@ -171,8 +185,11 @@ def startswith(msg: str) -> Rule: def endswith(msg: str) -> Rule: """ :说明: + 匹配消息结尾 + :参数: + * ``msg: str``: 消息结尾字符串 """ @@ -185,8 +202,11 @@ def endswith(msg: str) -> Rule: def keyword(*keywords: str) -> Rule: """ :说明: + 匹配消息关键词 + :参数: + * ``*keywords: str``: 关键词 """ @@ -200,12 +220,17 @@ def keyword(*keywords: str) -> Rule: def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule: """ :说明: + 命令形式匹配,根据配置里提供的 ``command_start``, ``command_sep`` 判断消息是否为命令。 可以通过 ``state["_prefix"]["command"]`` 获取匹配成功的命令(例:``("test",)``),通过 ``state["_prefix"]["raw_command"]`` 获取匹配成功的原始命令文本(例:``"/test"``)。 + :参数: + * ``*cmds: Union[str, Tuple[str, ...]]``: 命令内容 + :示例: + 使用默认 ``command_start``, ``command_sep`` 配置 命令 ``("test",)`` 可以匹配:``/test`` 开头的消息 @@ -240,10 +265,13 @@ def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule: def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: """ :说明: + 根据正则表达式进行匹配。 可以通过 ``state["_matched"]`` 获取正则表达式匹配成功的文本。 + :参数: + * ``regex: str``: 正则表达式 * ``flags: Union[int, re.RegexFlag]``: 正则标志 @@ -269,8 +297,11 @@ def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: def to_me() -> Rule: """ :说明: + 通过 ``event.to_me`` 判断消息是否是发送给机器人 + :参数: + * 无 """ diff --git a/nonebot/sched.py b/nonebot/sched.py deleted file mode 100644 index e47d95b7..00000000 --- a/nonebot/sched.py +++ /dev/null @@ -1,42 +0,0 @@ -""" -计划任务 -======== - -计划任务使用第三方库 `APScheduler`_ ,使用文档请参考 `APScheduler使用文档`_ 。 - -.. _APScheduler: - https://github.com/agronholm/apscheduler -.. _APScheduler使用文档: - https://apscheduler.readthedocs.io/en/latest/ -""" - -try: - from apscheduler.schedulers.asyncio import AsyncIOScheduler -except ImportError: - AsyncIOScheduler = None - -if AsyncIOScheduler: - scheduler = AsyncIOScheduler() - """ - :类型: - ``Optional[apscheduler.schedulers.asyncio.AsyncIOScheduler]`` - :说明: - 当可选依赖 ``APScheduler`` 未安装时,``scheduler`` 为 None - - 使用 ``pip install nonebot[scheduler]`` 安装可选依赖 - - :常用示例: - - .. code-block:: 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") - - """ -else: - scheduler = None diff --git a/nonebot/typing.py b/nonebot/typing.py index 09109b37..21a8b0ee 100644 --- a/nonebot/typing.py +++ b/nonebot/typing.py @@ -21,7 +21,7 @@ from types import ModuleType from typing import NoReturn, TYPE_CHECKING from typing import Any, Set, List, Dict, Type, Tuple, Mapping -from typing import Union, TypeVar, Optional, Iterable, Callable, Awaitable +from typing import Union, TypeVar, Optional, Iterable, Callable, Awaitable, Generic # import some modules needed when checking types if TYPE_CHECKING: diff --git a/nonebot/utils.py b/nonebot/utils.py index db447401..7ef93769 100644 --- a/nonebot/utils.py +++ b/nonebot/utils.py @@ -4,16 +4,22 @@ import asyncio import dataclasses from functools import wraps, partial -from nonebot.typing import Any, Callable, Awaitable, overrides +from nonebot.log import logger +from nonebot.typing import Any, Optional, Callable, Awaitable, overrides def escape_tag(s: str) -> str: """ :说明: + 用于记录带颜色日志时转义 ```` 类型特殊标签 + :参数: + * ``s: str``: 需要转义的字符串 + :返回: + - ``str`` """ return re.sub(r"\s]*)>", r"\\\g<0>", s) @@ -22,10 +28,15 @@ def escape_tag(s: str) -> str: def run_sync(func: Callable[..., Any]) -> Callable[..., Awaitable[Any]]: """ :说明: + 一个用于包装 sync function 为 async function 的装饰器 + :参数: + * ``func: Callable[..., Any]``: 被装饰的同步函数 + :返回: + - ``Callable[..., Awaitable[Any]]`` """ @@ -42,6 +53,7 @@ def run_sync(func: Callable[..., Any]) -> Callable[..., Awaitable[Any]]: class DataclassEncoder(json.JSONEncoder): """ :说明: + 在JSON序列化 ``Message`` (List[Dataclass]) 时使用的 ``JSONEncoder`` """ @@ -50,3 +62,23 @@ class DataclassEncoder(json.JSONEncoder): if dataclasses.is_dataclass(o): return dataclasses.asdict(o) return super().default(o) + + +def logger_wrapper(logger_name: str): + """ + :说明: + + 用于打印 adapter 的日志。 + + :log 参数: + + * ``level: Literal['WARNING', 'DEBUG', 'INFO']``: 日志等级 + * ``message: str``: 日志信息 + * ``exception: Optional[Exception]``: 异常信息 + """ + + def log(level: str, message: str, exception: Optional[Exception] = None): + return logger.opt(colors=True, exception=exception).log( + level, f"{logger_name} | " + message) + + return log diff --git a/pages/changelog.md b/pages/changelog.md index 859be509..2a766f70 100644 --- a/pages/changelog.md +++ b/pages/changelog.md @@ -11,6 +11,10 @@ sidebar: auto - 修改 cqhttp 检查 reply 时未去除后续 at 以及空格 - 添加 get_plugin 获取插件函数 - 添加插件 export, require 方法 +- **移除**内置 apscheduler 定时任务支持 +- **移除**内置协议适配默认加载 +- 新增**钉钉**协议适配 +- 移除原有共享型 `MatcherGroup` 改为默认型 `MatcherGroup` ## v2.0.0a6 diff --git a/poetry.lock b/poetry.lock index a4d8902d..6ac05a37 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,16 +1,3 @@ -[[package]] -name = "aiofiles" -version = "0.5.0" -description = "File support for asyncio." -category = "main" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "alabaster" version = "0.7.12" @@ -24,42 +11,11 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "apscheduler" -version = "3.6.3" -description = "In-process task scheduler with Cron-like capabilities" -category = "main" -optional = true -python-versions = "*" - -[package.dependencies] -pytz = "*" -six = ">=1.4.0" -tzlocal = ">=1.2" - -[package.extras] -asyncio = ["trollius"] -doc = ["sphinx", "sphinx-rtd-theme"] -gevent = ["gevent"] -mongodb = ["pymongo (>=2.8)"] -redis = ["redis (>=3.0)"] -rethinkdb = ["rethinkdb (>=2.4.0)"] -sqlalchemy = ["sqlalchemy (>=0.8)"] -testing = ["pytest", "pytest-cov", "pytest-tornado5", "mock", "pytest-asyncio (<0.6)", "pytest-asyncio"] -tornado = ["tornado (>=4.3)"] -twisted = ["twisted"] -zookeeper = ["kazoo"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "arrow" version = "0.17.0" description = "Better dates & times for Python" -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" @@ -75,7 +31,7 @@ reference = "aliyun" name = "attrs" version = "20.3.0" description = "Classes Without Boilerplate" -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" @@ -110,7 +66,7 @@ reference = "aliyun" name = "bcrypt" version = "3.2.0" description = "Modern password hashing for your software and your servers" -category = "main" +category = "dev" optional = true python-versions = ">=3.6" @@ -131,7 +87,7 @@ reference = "aliyun" name = "binaryornot" version = "0.4.4" description = "Ultra-lightweight pure Python package to check if a file is binary or text." -category = "main" +category = "dev" optional = true python-versions = "*" @@ -147,7 +103,7 @@ reference = "aliyun" name = "cached-property" version = "1.5.2" description = "A decorator for caching properties in classes." -category = "main" +category = "dev" optional = true python-versions = "*" @@ -171,9 +127,9 @@ reference = "aliyun" [[package]] name = "cffi" -version = "1.14.3" +version = "1.14.4" description = "Foreign Function Interface for Python calling C code." -category = "main" +category = "dev" optional = true python-versions = "*" @@ -189,7 +145,7 @@ reference = "aliyun" name = "chardet" version = "3.0.4" description = "Universal encoding detector for Python 2 and 3" -category = "main" +category = "dev" optional = false python-versions = "*" @@ -228,7 +184,7 @@ reference = "aliyun" name = "cookiecutter" version = "1.7.2" description = "A command-line utility that creates projects from project templates, e.g. creating a Python package project from a Python package project template." -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" @@ -252,7 +208,7 @@ reference = "aliyun" name = "cryptography" version = "3.2.1" description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." -category = "main" +category = "dev" optional = true python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*" @@ -276,7 +232,7 @@ reference = "aliyun" name = "distro" version = "1.5.0" description = "Distro - an OS platform information API" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -287,9 +243,9 @@ reference = "aliyun" [[package]] name = "docker" -version = "4.3.1" +version = "4.4.0" description = "A Python library for the Docker Engine API." -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" @@ -313,7 +269,7 @@ reference = "aliyun" name = "docker-compose" version = "1.27.4" description = "Multi-container orchestration for Docker" -category = "main" +category = "dev" optional = true python-versions = ">=3.4" @@ -344,7 +300,7 @@ reference = "aliyun" name = "dockerpty" version = "0.4.1" description = "Python library to use the pseudo-tty of a docker container" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -360,7 +316,7 @@ reference = "aliyun" name = "docopt" version = "0.6.2" description = "Pythonic argument parser, that will make you smile" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -433,7 +389,7 @@ reference = "aliyun" [[package]] name = "httpcore" -version = "0.12.1" +version = "0.12.2" description = "A minimal low-level HTTP client." category = "main" optional = false @@ -518,18 +474,18 @@ reference = "aliyun" [[package]] name = "importlib-metadata" -version = "2.0.0" +version = "3.1.1" description = "Read metadata from Python packages" -category = "main" +category = "dev" optional = true -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" +python-versions = ">=3.6" [package.dependencies] zipp = ">=0.5" [package.extras] -docs = ["sphinx", "rst.linker"] -testing = ["packaging", "pep517", "importlib-resources (>=1.3)"] +docs = ["sphinx", "jaraco.packaging (>=3.2)", "rst.linker (>=1.9)"] +testing = ["pytest (>=3.5,!=3.7.3)", "pytest-checkdocs (>=1.2.3)", "pytest-flake8", "pytest-cov", "jaraco.test (>=3.2.0)", "packaging", "pep517", "pyfakefs", "flufl.flake8", "pytest-black (>=0.3.7)", "pytest-mypy", "importlib-resources (>=1.3)"] [package.source] type = "legacy" @@ -540,7 +496,7 @@ reference = "aliyun" name = "jinja2" version = "2.11.2" description = "A very fast and expressive template engine." -category = "main" +category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" @@ -559,7 +515,7 @@ reference = "aliyun" name = "jinja2-time" version = "0.2.0" description = "Jinja2 Extension for Dates and Times" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -576,7 +532,7 @@ reference = "aliyun" name = "jsonschema" version = "3.2.0" description = "An implementation of JSON Schema validation for Python" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -619,7 +575,7 @@ reference = "aliyun" name = "markupsafe" version = "1.1.1" description = "Safely add untrusted strings to HTML/XML markup." -category = "main" +category = "dev" optional = false python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*" @@ -632,7 +588,7 @@ reference = "aliyun" name = "nb-cli" version = "0.2.0" description = "CLI for nonebot2" -category = "main" +category = "dev" optional = true python-versions = ">=3.7,<4.0" @@ -650,27 +606,9 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "nonebot-test" -version = "0.1.0" -description = "Test frontend for nonebot v2+" -category = "main" -optional = true -python-versions = ">=3.7,<4.0" - -[package.dependencies] -aiofiles = ">=0.5.0,<0.6.0" -nonebot2 = ">=2.0.0-alpha.1,<3.0.0" -python-socketio = ">=4.6.0,<5.0.0" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "packaging" -version = "20.4" +version = "20.7" description = "Core utilities for Python packages" category = "dev" optional = false @@ -678,7 +616,6 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" [package.dependencies] pyparsing = ">=2.0.2" -six = "*" [package.source] type = "legacy" @@ -689,7 +626,7 @@ reference = "aliyun" name = "paramiko" version = "2.7.2" description = "SSH2 protocol library" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -713,7 +650,7 @@ reference = "aliyun" name = "poyo" version = "0.5.0" description = "A lightweight YAML Parser for Python. 🐓" -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" @@ -726,7 +663,7 @@ reference = "aliyun" name = "prompt-toolkit" version = "1.0.14" description = "Library for building powerful interactive command lines in Python" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -743,7 +680,7 @@ reference = "aliyun" name = "pycparser" version = "2.20" description = "C parser in Python" -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" @@ -754,7 +691,7 @@ reference = "aliyun" [[package]] name = "pydantic" -version = "1.7.2" +version = "1.7.3" description = "Data validation and settings management using python 3.6 type hinting" category = "main" optional = false @@ -793,7 +730,7 @@ reference = "aliyun" name = "pyfiglet" version = "0.8.post1" description = "Pure-python FIGlet implementation" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -806,7 +743,7 @@ reference = "aliyun" name = "pygments" version = "2.7.2" description = "Pygments is a syntax highlighting package written in Python." -category = "main" +category = "dev" optional = false python-versions = ">=3.5" @@ -817,8 +754,8 @@ reference = "aliyun" [[package]] name = "pygtrie" -version = "2.3.3" -description = "Trie data structure implementation." +version = "2.4.1" +description = "A pure Python trie data structure implementation." category = "main" optional = false python-versions = "*" @@ -832,7 +769,7 @@ reference = "aliyun" name = "pyinquirer" version = "1.0.3" description = "A Python module for collection of common interactive command line user interfaces, based on Inquirer.js" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -850,7 +787,7 @@ reference = "aliyun" name = "pynacl" version = "1.4.0" description = "Python binding to the Networking and Cryptography (NaCl) library" -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" @@ -884,7 +821,7 @@ reference = "aliyun" name = "pyrsistent" version = "0.17.3" description = "Persistent/Functional/Immutable data structures" -category = "main" +category = "dev" optional = true python-versions = ">=3.5" @@ -897,7 +834,7 @@ reference = "aliyun" name = "python-dateutil" version = "2.8.1" description = "Extensions to the standard Python datetime module" -category = "main" +category = "dev" optional = true python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" @@ -925,31 +862,11 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "python-engineio" -version = "3.13.2" -description = "Engine.IO server" -category = "main" -optional = true -python-versions = "*" - -[package.dependencies] -six = ">=1.9.0" - -[package.extras] -asyncio_client = ["aiohttp (>=3.4)"] -client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "python-slugify" version = "4.0.1" description = "A Python Slugify application that handles Unicode" -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" @@ -964,32 +881,11 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "python-socketio" -version = "4.6.0" -description = "Socket.IO server" -category = "main" -optional = true -python-versions = "*" - -[package.dependencies] -python-engineio = ">=3.13.0" -six = ">=1.9.0" - -[package.extras] -asyncio_client = ["aiohttp (>=3.4)", "websockets (>=7.0)"] -client = ["requests (>=2.21.0)", "websocket-client (>=0.54.0)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pytz" version = "2020.4" description = "World timezone definitions, modern and historical" -category = "main" +category = "dev" optional = false python-versions = "*" @@ -1002,7 +898,7 @@ reference = "aliyun" name = "pywin32" version = "227" description = "Python for Window Extensions" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -1015,7 +911,7 @@ reference = "aliyun" name = "pyyaml" version = "5.3.1" description = "YAML parser and emitter for Python" -category = "main" +category = "dev" optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" @@ -1028,7 +924,7 @@ reference = "aliyun" name = "regex" version = "2020.11.13" description = "Alternative regular expression module, to replace re." -category = "main" +category = "dev" optional = true python-versions = "*" @@ -1041,7 +937,7 @@ reference = "aliyun" name = "requests" version = "2.25.0" description = "Python HTTP for Humans." -category = "main" +category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" @@ -1083,8 +979,8 @@ reference = "aliyun" name = "six" version = "1.15.0" description = "Python 2 and 3 compatibility utilities" -category = "main" -optional = false +category = "dev" +optional = true python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" [package.source] @@ -1297,7 +1193,7 @@ reference = "aliyun" name = "text-unidecode" version = "1.3" description = "The most basic Text::Unidecode port" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -1310,7 +1206,7 @@ reference = "aliyun" name = "texttable" version = "1.6.3" description = "module for creating simple ASCII tables" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -1319,22 +1215,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "tzlocal" -version = "2.1" -description = "tzinfo object for the local timezone" -category = "main" -optional = true -python-versions = "*" - -[package.dependencies] -pytz = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "unify" version = "0.5" @@ -1368,7 +1248,7 @@ reference = "aliyun" name = "urllib3" version = "1.26.2" description = "HTTP library with thread-safe connection pooling, file post, and more." -category = "main" +category = "dev" optional = false python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, <4" @@ -1422,7 +1302,7 @@ reference = "aliyun" name = "wcwidth" version = "0.2.5" description = "Measures the displayed width of unicode strings in a terminal" -category = "main" +category = "dev" optional = true python-versions = "*" @@ -1435,7 +1315,7 @@ reference = "aliyun" name = "websocket-client" version = "0.57.0" description = "WebSocket client for Python. hybi13 is supported." -category = "main" +category = "dev" optional = true python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" @@ -1493,7 +1373,7 @@ reference = "aliyun" name = "zipp" version = "3.4.0" description = "Backport of pathlib-compatible object wrapper for zip files" -category = "main" +category = "dev" optional = true python-versions = ">=3.6" @@ -1506,30 +1386,16 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[extras] -cli = ["nb-cli"] -full = ["nb-cli", "nonebot-test", "apscheduler"] -scheduler = ["apscheduler"] -test = ["nonebot-test"] - [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "1d1ddae66f1495be07658ec5a004c4819445f785317c556030c9edb05612917e" +content-hash = "3dfc8b11cbc775c2dca5409212248615b259863864d8a9db247377e273a5eddd" [metadata.files] -aiofiles = [ - {file = "aiofiles-0.5.0-py3-none-any.whl", hash = "sha256:377fdf7815cc611870c59cbd07b68b180841d2a2b79812d8c218be02448c2acb"}, - {file = "aiofiles-0.5.0.tar.gz", hash = "sha256:98e6bcfd1b50f97db4980e182ddd509b7cc35909e903a8fe50d8849e02d815af"}, -] alabaster = [ {file = "alabaster-0.7.12-py2.py3-none-any.whl", hash = "sha256:446438bdcca0e05bd45ea2de1668c1d9b032e1a9154c2c259092d77031ddd359"}, {file = "alabaster-0.7.12.tar.gz", hash = "sha256:a661d72d58e6ea8a57f7a86e37d86716863ee5e92788398526d58b26a4e4dc02"}, ] -apscheduler = [ - {file = "APScheduler-3.6.3-py2.py3-none-any.whl", hash = "sha256:e8b1ecdb4c7cb2818913f766d5898183c7cb8936680710a4d3a966e02262e526"}, - {file = "APScheduler-3.6.3.tar.gz", hash = "sha256:3bb5229eed6fbbdafc13ce962712ae66e175aa214c69bed35a06bffcf0c5e244"}, -] arrow = [ {file = "arrow-0.17.0-py2.py3-none-any.whl", hash = "sha256:e098abbd9af3665aea81bdd6c869e93af4feb078e98468dd351c383af187aac5"}, {file = "arrow-0.17.0.tar.gz", hash = "sha256:ff08d10cda1d36c68657d6ad20d74fbea493d980f8b2d45344e00d6ed2bf6ed4"}, @@ -1564,42 +1430,40 @@ certifi = [ {file = "certifi-2020.11.8.tar.gz", hash = "sha256:f05def092c44fbf25834a51509ef6e631dc19765ab8a57b4e7ab85531f0a9cf4"}, ] cffi = [ - {file = "cffi-1.14.3-2-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:3eeeb0405fd145e714f7633a5173318bd88d8bbfc3dd0a5751f8c4f70ae629bc"}, - {file = "cffi-1.14.3-2-cp35-cp35m-macosx_10_9_x86_64.whl", hash = "sha256:cb763ceceae04803adcc4e2d80d611ef201c73da32d8f2722e9d0ab0c7f10768"}, - {file = "cffi-1.14.3-2-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:44f60519595eaca110f248e5017363d751b12782a6f2bd6a7041cba275215f5d"}, - {file = "cffi-1.14.3-2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:c53af463f4a40de78c58b8b2710ade243c81cbca641e34debf3396a9640d6ec1"}, - {file = "cffi-1.14.3-2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:33c6cdc071ba5cd6d96769c8969a0531be2d08c2628a0143a10a7dcffa9719ca"}, - {file = "cffi-1.14.3-2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c11579638288e53fc94ad60022ff1b67865363e730ee41ad5e6f0a17188b327a"}, - {file = "cffi-1.14.3-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:3cb3e1b9ec43256c4e0f8d2837267a70b0e1ca8c4f456685508ae6106b1f504c"}, - {file = "cffi-1.14.3-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:f0620511387790860b249b9241c2f13c3a80e21a73e0b861a2df24e9d6f56730"}, - {file = "cffi-1.14.3-cp27-cp27m-win32.whl", hash = "sha256:005f2bfe11b6745d726dbb07ace4d53f057de66e336ff92d61b8c7e9c8f4777d"}, - {file = "cffi-1.14.3-cp27-cp27m-win_amd64.whl", hash = "sha256:2f9674623ca39c9ebe38afa3da402e9326c245f0f5ceff0623dccdac15023e05"}, - {file = "cffi-1.14.3-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:09e96138280241bd355cd585148dec04dbbedb4f46128f340d696eaafc82dd7b"}, - {file = "cffi-1.14.3-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:3363e77a6176afb8823b6e06db78c46dbc4c7813b00a41300a4873b6ba63b171"}, - {file = "cffi-1.14.3-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:0ef488305fdce2580c8b2708f22d7785ae222d9825d3094ab073e22e93dfe51f"}, - {file = "cffi-1.14.3-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:0b1ad452cc824665ddc682400b62c9e4f5b64736a2ba99110712fdee5f2505c4"}, - {file = "cffi-1.14.3-cp35-cp35m-win32.whl", hash = "sha256:85ba797e1de5b48aa5a8427b6ba62cf69607c18c5d4eb747604b7302f1ec382d"}, - {file = "cffi-1.14.3-cp35-cp35m-win_amd64.whl", hash = "sha256:e66399cf0fc07de4dce4f588fc25bfe84a6d1285cc544e67987d22663393926d"}, - {file = "cffi-1.14.3-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:15f351bed09897fbda218e4db5a3d5c06328862f6198d4fb385f3e14e19decb3"}, - {file = "cffi-1.14.3-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:4d7c26bfc1ea9f92084a1d75e11999e97b62d63128bcc90c3624d07813c52808"}, - {file = "cffi-1.14.3-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:23e5d2040367322824605bc29ae8ee9175200b92cb5483ac7d466927a9b3d537"}, - {file = "cffi-1.14.3-cp36-cp36m-win32.whl", hash = "sha256:a624fae282e81ad2e4871bdb767e2c914d0539708c0f078b5b355258293c98b0"}, - {file = "cffi-1.14.3-cp36-cp36m-win_amd64.whl", hash = "sha256:de31b5164d44ef4943db155b3e8e17929707cac1e5bd2f363e67a56e3af4af6e"}, - {file = "cffi-1.14.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:f92cdecb618e5fa4658aeb97d5eb3d2f47aa94ac6477c6daf0f306c5a3b9e6b1"}, - {file = "cffi-1.14.3-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:22399ff4870fb4c7ef19fff6eeb20a8bbf15571913c181c78cb361024d574579"}, - {file = "cffi-1.14.3-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:f4eae045e6ab2bb54ca279733fe4eb85f1effda392666308250714e01907f394"}, - {file = "cffi-1.14.3-cp37-cp37m-win32.whl", hash = "sha256:b0358e6fefc74a16f745afa366acc89f979040e0cbc4eec55ab26ad1f6a9bfbc"}, - {file = "cffi-1.14.3-cp37-cp37m-win_amd64.whl", hash = "sha256:6642f15ad963b5092d65aed022d033c77763515fdc07095208f15d3563003869"}, - {file = "cffi-1.14.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:2791f68edc5749024b4722500e86303a10d342527e1e3bcac47f35fbd25b764e"}, - {file = "cffi-1.14.3-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:529c4ed2e10437c205f38f3691a68be66c39197d01062618c55f74294a4a4828"}, - {file = "cffi-1.14.3-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:8f0f1e499e4000c4c347a124fa6a27d37608ced4fe9f7d45070563b7c4c370c9"}, - {file = "cffi-1.14.3-cp38-cp38-win32.whl", hash = "sha256:3b8eaf915ddc0709779889c472e553f0d3e8b7bdf62dab764c8921b09bf94522"}, - {file = "cffi-1.14.3-cp38-cp38-win_amd64.whl", hash = "sha256:bbd2f4dfee1079f76943767fce837ade3087b578aeb9f69aec7857d5bf25db15"}, - {file = "cffi-1.14.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:cc75f58cdaf043fe6a7a6c04b3b5a0e694c6a9e24050967747251fb80d7bce0d"}, - {file = "cffi-1.14.3-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:bf39a9e19ce7298f1bd6a9758fa99707e9e5b1ebe5e90f2c3913a47bc548747c"}, - {file = "cffi-1.14.3-cp39-cp39-win32.whl", hash = "sha256:d80998ed59176e8cba74028762fbd9b9153b9afc71ea118e63bbf5d4d0f9552b"}, - {file = "cffi-1.14.3-cp39-cp39-win_amd64.whl", hash = "sha256:c150eaa3dadbb2b5339675b88d4573c1be3cb6f2c33a6c83387e10cc0bf05bd3"}, - {file = "cffi-1.14.3.tar.gz", hash = "sha256:f92f789e4f9241cd262ad7a555ca2c648a98178a953af117ef7fad46aa1d5591"}, + {file = "cffi-1.14.4-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:ebb253464a5d0482b191274f1c8bf00e33f7e0b9c66405fbffc61ed2c839c775"}, + {file = "cffi-1.14.4-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:2c24d61263f511551f740d1a065eb0212db1dbbbbd241db758f5244281590c06"}, + {file = "cffi-1.14.4-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:9f7a31251289b2ab6d4012f6e83e58bc3b96bd151f5b5262467f4bb6b34a7c26"}, + {file = "cffi-1.14.4-cp27-cp27m-win32.whl", hash = "sha256:5cf4be6c304ad0b6602f5c4e90e2f59b47653ac1ed9c662ed379fe48a8f26b0c"}, + {file = "cffi-1.14.4-cp27-cp27m-win_amd64.whl", hash = "sha256:f60567825f791c6f8a592f3c6e3bd93dd2934e3f9dac189308426bd76b00ef3b"}, + {file = "cffi-1.14.4-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:c6332685306b6417a91b1ff9fae889b3ba65c2292d64bd9245c093b1b284809d"}, + {file = "cffi-1.14.4-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:d9efd8b7a3ef378dd61a1e77367f1924375befc2eba06168b6ebfa903a5e59ca"}, + {file = "cffi-1.14.4-cp35-cp35m-macosx_10_9_x86_64.whl", hash = "sha256:51a8b381b16ddd370178a65360ebe15fbc1c71cf6f584613a7ea08bfad946698"}, + {file = "cffi-1.14.4-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:1d2c4994f515e5b485fd6d3a73d05526aa0fcf248eb135996b088d25dfa1865b"}, + {file = "cffi-1.14.4-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:af5c59122a011049aad5dd87424b8e65a80e4a6477419c0c1015f73fb5ea0293"}, + {file = "cffi-1.14.4-cp35-cp35m-win32.whl", hash = "sha256:594234691ac0e9b770aee9fcdb8fa02c22e43e5c619456efd0d6c2bf276f3eb2"}, + {file = "cffi-1.14.4-cp35-cp35m-win_amd64.whl", hash = "sha256:64081b3f8f6f3c3de6191ec89d7dc6c86a8a43911f7ecb422c60e90c70be41c7"}, + {file = "cffi-1.14.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:f803eaa94c2fcda012c047e62bc7a51b0bdabda1cad7a92a522694ea2d76e49f"}, + {file = "cffi-1.14.4-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:105abaf8a6075dc96c1fe5ae7aae073f4696f2905fde6aeada4c9d2926752362"}, + {file = "cffi-1.14.4-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:0638c3ae1a0edfb77c6765d487fee624d2b1ee1bdfeffc1f0b58c64d149e7eec"}, + {file = "cffi-1.14.4-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:7c6b1dece89874d9541fc974917b631406233ea0440d0bdfbb8e03bf39a49b3b"}, + {file = "cffi-1.14.4-cp36-cp36m-win32.whl", hash = "sha256:155136b51fd733fa94e1c2ea5211dcd4c8879869008fc811648f16541bf99668"}, + {file = "cffi-1.14.4-cp36-cp36m-win_amd64.whl", hash = "sha256:6bc25fc545a6b3d57b5f8618e59fc13d3a3a68431e8ca5fd4c13241cd70d0009"}, + {file = "cffi-1.14.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a7711edca4dcef1a75257b50a2fbfe92a65187c47dab5a0f1b9b332c5919a3fb"}, + {file = "cffi-1.14.4-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:00e28066507bfc3fe865a31f325c8391a1ac2916219340f87dfad602c3e48e5d"}, + {file = "cffi-1.14.4-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:798caa2a2384b1cbe8a2a139d80734c9db54f9cc155c99d7cc92441a23871c03"}, + {file = "cffi-1.14.4-cp37-cp37m-win32.whl", hash = "sha256:00a1ba5e2e95684448de9b89888ccd02c98d512064b4cb987d48f4b40aa0421e"}, + {file = "cffi-1.14.4-cp37-cp37m-win_amd64.whl", hash = "sha256:9cc46bc107224ff5b6d04369e7c595acb700c3613ad7bcf2e2012f62ece80c35"}, + {file = "cffi-1.14.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:df5169c4396adc04f9b0a05f13c074df878b6052430e03f50e68adf3a57aa28d"}, + {file = "cffi-1.14.4-cp38-cp38-manylinux1_i686.whl", hash = "sha256:9ffb888f19d54a4d4dfd4b3f29bc2c16aa4972f1c2ab9c4ab09b8ab8685b9c2b"}, + {file = "cffi-1.14.4-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:8d6603078baf4e11edc4168a514c5ce5b3ba6e3e9c374298cb88437957960a53"}, + {file = "cffi-1.14.4-cp38-cp38-win32.whl", hash = "sha256:b4e248d1087abf9f4c10f3c398896c87ce82a9856494a7155823eb45a892395d"}, + {file = "cffi-1.14.4-cp38-cp38-win_amd64.whl", hash = "sha256:ec80dc47f54e6e9a78181ce05feb71a0353854cc26999db963695f950b5fb375"}, + {file = "cffi-1.14.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:840793c68105fe031f34d6a086eaea153a0cd5c491cde82a74b420edd0a2b909"}, + {file = "cffi-1.14.4-cp39-cp39-manylinux1_i686.whl", hash = "sha256:b18e0a9ef57d2b41f5c68beefa32317d286c3d6ac0484efd10d6e07491bb95dd"}, + {file = "cffi-1.14.4-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:045d792900a75e8b1e1b0ab6787dd733a8190ffcf80e8c8ceb2fb10a29ff238a"}, + {file = "cffi-1.14.4-cp39-cp39-win32.whl", hash = "sha256:ba4e9e0ae13fc41c6b23299545e5ef73055213e466bd107953e4a013a5ddd7e3"}, + {file = "cffi-1.14.4-cp39-cp39-win_amd64.whl", hash = "sha256:f032b34669220030f905152045dfa27741ce1a6db3324a5bc0b96b6c7420c87b"}, + {file = "cffi-1.14.4.tar.gz", hash = "sha256:1a465cbe98a7fd391d47dce4b8f7e5b921e6cd805ef421d04f5f66ba8f06086c"}, ] chardet = [ {file = "chardet-3.0.4-py2.py3-none-any.whl", hash = "md5:0004b00caff7bb543a1d0d0bd0185a03"}, @@ -1646,8 +1510,8 @@ distro = [ {file = "distro-1.5.0.tar.gz", hash = "sha256:0e58756ae38fbd8fc3020d54badb8eae17c5b9dcbed388b17bb55b8a5928df92"}, ] docker = [ - {file = "docker-4.3.1-py2.py3-none-any.whl", hash = "sha256:13966471e8bc23b36bfb3a6fb4ab75043a5ef1dac86516274777576bed3b9828"}, - {file = "docker-4.3.1.tar.gz", hash = "sha256:bad94b8dd001a8a4af19ce4becc17f41b09f228173ffe6a4e0355389eef142f2"}, + {file = "docker-4.4.0-py2.py3-none-any.whl", hash = "sha256:317e95a48c32de8c1aac92a48066a5b73e218ed096e03758bcdd799a7130a1a1"}, + {file = "docker-4.4.0.tar.gz", hash = "sha256:cffc771d4ea1389fc66bc95cb72d304aa41d1a1563482a9a000fba3a84ed5071"}, ] docker-compose = [ {file = "docker-compose-1.27.4.tar.gz", hash = "sha256:5a5690f24c27d4b43dcbe6b3fae91ba680713208e99ee863352b3bae37bcaa83"}, @@ -1676,8 +1540,8 @@ html2text = [ {file = "html2text-2020.1.16.tar.gz", hash = "sha256:e296318e16b059ddb97f7a8a1d6a5c1d7af4544049a01e261731d2d5cc277bbb"}, ] httpcore = [ - {file = "httpcore-0.12.1-py3-none-any.whl", hash = "sha256:37660b117ba9055e8d5d19c29684d2204bbd3150020dde0ebd2dd2bcf18dfe50"}, - {file = "httpcore-0.12.1.tar.gz", hash = "sha256:3c5fcd97c52c3f6a1e4d939d776458e6177b5c238b825ed51d72840e582573b5"}, + {file = "httpcore-0.12.2-py3-none-any.whl", hash = "sha256:420700af11db658c782f7e8fda34f9dcd95e3ee93944dd97d78cb70247e0cd06"}, + {file = "httpcore-0.12.2.tar.gz", hash = "sha256:dd1d762d4f7c2702149d06be2597c35fb154c5eff9789a8c5823fbcf4d2978d6"}, ] httptools = [ {file = "httptools-0.1.1-cp35-cp35m-macosx_10_13_x86_64.whl", hash = "sha256:a2719e1d7a84bb131c4f1e0cb79705034b48de6ae486eb5297a139d6a3296dce"}, @@ -1706,8 +1570,8 @@ imagesize = [ {file = "imagesize-1.2.0.tar.gz", hash = "sha256:b1f6b5a4eab1f73479a50fb79fcf729514a900c341d8503d62a62dbc4127a2b1"}, ] importlib-metadata = [ - {file = "importlib_metadata-2.0.0-py2.py3-none-any.whl", hash = "sha256:cefa1a2f919b866c5beb7c9f7b0ebb4061f30a8a9bf16d609b000e2dfaceb9c3"}, - {file = "importlib_metadata-2.0.0.tar.gz", hash = "sha256:77a540690e24b0305878c37ffd421785a6f7e53c8b5720d211b211de8d0e95da"}, + {file = "importlib_metadata-3.1.1-py3-none-any.whl", hash = "sha256:6112e21359ef8f344e7178aa5b72dc6e62b38b0d008e6d3cb212c5b84df72013"}, + {file = "importlib_metadata-3.1.1.tar.gz", hash = "sha256:b0c2d3b226157ae4517d9625decf63591461c66b3a808c2666d538946519d170"}, ] jinja2 = [ {file = "Jinja2-2.11.2-py2.py3-none-any.whl", hash = "sha256:f0a4641d3cf955324a89c04f3d94663aa4d638abe8f733ecd3582848e1c37035"}, @@ -1764,13 +1628,9 @@ nb-cli = [ {file = "nb-cli-0.2.0.tar.gz", hash = "sha256:d53ab571beee259af99a8cb4574ef85b6c1d821549f857eb45c83b3cb4f903a4"}, {file = "nb_cli-0.2.0-py3-none-any.whl", hash = "sha256:c0975f18bb19da99278ea60c48b668fc6e5fa371b118e8e86d42e989933186ba"}, ] -nonebot-test = [ - {file = "nonebot-test-0.1.0.tar.gz", hash = "sha256:f83bc095927f55e55cfe61c2ccc388e2536980d6d40412879009a16484487af4"}, - {file = "nonebot_test-0.1.0-py3-none-any.whl", hash = "sha256:3f981ac001f0f6c4f408d561b11fbe337fddc0a0f0d1e7a6602f34305ff82bcd"}, -] packaging = [ - {file = "packaging-20.4-py2.py3-none-any.whl", hash = "sha256:998416ba6962ae7fbd6596850b80e17859a5753ba17c32284f67bfff33784181"}, - {file = "packaging-20.4.tar.gz", hash = "sha256:4357f74f47b9c12db93624a82154e9b120fa8293699949152b22065d556079f8"}, + {file = "packaging-20.7-py2.py3-none-any.whl", hash = "sha256:eb41423378682dadb7166144a4926e443093863024de508ca5c9737d6bc08376"}, + {file = "packaging-20.7.tar.gz", hash = "sha256:05af3bb85d320377db281cf254ab050e1a7ebcbf5410685a9a407e18a1f81236"}, ] paramiko = [ {file = "paramiko-2.7.2-py2.py3-none-any.whl", hash = "sha256:4f3e316fef2ac628b05097a637af35685183111d4bc1b5979bd397c2ab7b5898"}, @@ -1790,28 +1650,28 @@ pycparser = [ {file = "pycparser-2.20.tar.gz", hash = "sha256:2d475327684562c3a96cc71adf7dc8c4f0565175cf86b6d7a404ff4c771f15f0"}, ] pydantic = [ - {file = "pydantic-1.7.2-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:dfaa6ed1d509b5aef4142084206584280bb6e9014f01df931ec6febdad5b200a"}, - {file = "pydantic-1.7.2-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:2182ba2a9290964b278bcc07a8d24207de709125d520efec9ad6fa6f92ee058d"}, - {file = "pydantic-1.7.2-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:0fe8b45d31ae53d74a6aa0bf801587bd49970070eac6a6326f9fa2a302703b8a"}, - {file = "pydantic-1.7.2-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:01f0291f4951580f320f7ae3f2ecaf0044cdebcc9b45c5f882a7e84453362420"}, - {file = "pydantic-1.7.2-cp36-cp36m-win_amd64.whl", hash = "sha256:4ba6b903e1b7bd3eb5df0e78d7364b7e831ed8b4cd781ebc3c4f1077fbcb72a4"}, - {file = "pydantic-1.7.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:b11fc9530bf0698c8014b2bdb3bbc50243e82a7fa2577c8cfba660bcc819e768"}, - {file = "pydantic-1.7.2-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:a3c274c49930dc047a75ecc865e435f3df89715c775db75ddb0186804d9b04d0"}, - {file = "pydantic-1.7.2-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:c68b5edf4da53c98bb1ccb556ae8f655575cb2e676aef066c12b08c724a3f1a1"}, - {file = "pydantic-1.7.2-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:95d4410c4e429480c736bba0db6cce5aaa311304aea685ebcf9ee47571bfd7c8"}, - {file = "pydantic-1.7.2-cp37-cp37m-win_amd64.whl", hash = "sha256:a2fc7bf77ed4a7a961d7684afe177ff59971828141e608f142e4af858e07dddc"}, - {file = "pydantic-1.7.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:b9572c0db13c8658b4a4cb705dcaae6983aeb9842248b36761b3fbc9010b740f"}, - {file = "pydantic-1.7.2-cp38-cp38-manylinux1_i686.whl", hash = "sha256:f83f679e727742b0c465e7ef992d6da4a7e5268b8edd8fdaf5303276374bef52"}, - {file = "pydantic-1.7.2-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:e5fece30e80087d9b7986104e2ac150647ec1658c4789c89893b03b100ca3164"}, - {file = "pydantic-1.7.2-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:ce2d452961352ba229fe1e0b925b41c0c37128f08dddb788d0fd73fd87ea0f66"}, - {file = "pydantic-1.7.2-cp38-cp38-win_amd64.whl", hash = "sha256:fc21a37ff3f545de80b166e1735c4172b41b017948a3fb2d5e2f03c219eac50a"}, - {file = "pydantic-1.7.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c9760d1556ec59ff745f88269a8f357e2b7afc75c556b3a87b8dda5bc62da8ba"}, - {file = "pydantic-1.7.2-cp39-cp39-manylinux1_i686.whl", hash = "sha256:2c1673633ad1eea78b1c5c420a47cd48717d2ef214c8230d96ca2591e9e00958"}, - {file = "pydantic-1.7.2-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:388c0c26c574ff49bad7d0fd6ed82fbccd86a0473fa3900397d3354c533d6ebb"}, - {file = "pydantic-1.7.2-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:ab1d5e4d8de00575957e1c982b951bffaedd3204ddd24694e3baca3332e53a23"}, - {file = "pydantic-1.7.2-cp39-cp39-win_amd64.whl", hash = "sha256:f045cf7afb3352a03bc6cb993578a34560ac24c5d004fa33c76efec6ada1361a"}, - {file = "pydantic-1.7.2-py3-none-any.whl", hash = "sha256:6665f7ab7fbbf4d3c1040925ff4d42d7549a8c15fe041164adfe4fc2134d4cce"}, - {file = "pydantic-1.7.2.tar.gz", hash = "sha256:c8200aecbd1fb914e1bd061d71a4d1d79ecb553165296af0c14989b89e90d09b"}, + {file = "pydantic-1.7.3-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:c59ea046aea25be14dc22d69c97bee629e6d48d2b2ecb724d7fe8806bf5f61cd"}, + {file = "pydantic-1.7.3-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:a4143c8d0c456a093387b96e0f5ee941a950992904d88bc816b4f0e72c9a0009"}, + {file = "pydantic-1.7.3-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:d8df4b9090b595511906fa48deda47af04e7d092318bfb291f4d45dfb6bb2127"}, + {file = "pydantic-1.7.3-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:514b473d264671a5c672dfb28bdfe1bf1afd390f6b206aa2ec9fed7fc592c48e"}, + {file = "pydantic-1.7.3-cp36-cp36m-win_amd64.whl", hash = "sha256:dba5c1f0a3aeea5083e75db9660935da90216f8a81b6d68e67f54e135ed5eb23"}, + {file = "pydantic-1.7.3-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:59e45f3b694b05a69032a0d603c32d453a23f0de80844fb14d55ab0c6c78ff2f"}, + {file = "pydantic-1.7.3-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:5b24e8a572e4b4c18f614004dda8c9f2c07328cb5b6e314d6e1bbd536cb1a6c1"}, + {file = "pydantic-1.7.3-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:b2b054d095b6431cdda2f852a6d2f0fdec77686b305c57961b4c5dd6d863bf3c"}, + {file = "pydantic-1.7.3-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:025bf13ce27990acc059d0c5be46f416fc9b293f45363b3d19855165fee1874f"}, + {file = "pydantic-1.7.3-cp37-cp37m-win_amd64.whl", hash = "sha256:6e3874aa7e8babd37b40c4504e3a94cc2023696ced5a0500949f3347664ff8e2"}, + {file = "pydantic-1.7.3-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:e682f6442ebe4e50cb5e1cfde7dda6766fb586631c3e5569f6aa1951fd1a76ef"}, + {file = "pydantic-1.7.3-cp38-cp38-manylinux1_i686.whl", hash = "sha256:185e18134bec5ef43351149fe34fda4758e53d05bb8ea4d5928f0720997b79ef"}, + {file = "pydantic-1.7.3-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:f5b06f5099e163295b8ff5b1b71132ecf5866cc6e7f586d78d7d3fd6e8084608"}, + {file = "pydantic-1.7.3-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:24ca47365be2a5a3cc3f4a26dcc755bcdc9f0036f55dcedbd55663662ba145ec"}, + {file = "pydantic-1.7.3-cp38-cp38-win_amd64.whl", hash = "sha256:d1fe3f0df8ac0f3a9792666c69a7cd70530f329036426d06b4f899c025aca74e"}, + {file = "pydantic-1.7.3-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:f6864844b039805add62ebe8a8c676286340ba0c6d043ae5dea24114b82a319e"}, + {file = "pydantic-1.7.3-cp39-cp39-manylinux1_i686.whl", hash = "sha256:ecb54491f98544c12c66ff3d15e701612fc388161fd455242447083350904730"}, + {file = "pydantic-1.7.3-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:ffd180ebd5dd2a9ac0da4e8b995c9c99e7c74c31f985ba090ee01d681b1c4b95"}, + {file = "pydantic-1.7.3-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:8d72e814c7821125b16f1553124d12faba88e85405b0864328899aceaad7282b"}, + {file = "pydantic-1.7.3-cp39-cp39-win_amd64.whl", hash = "sha256:475f2fa134cf272d6631072554f845d0630907fce053926ff634cc6bc45bf1af"}, + {file = "pydantic-1.7.3-py3-none-any.whl", hash = "sha256:38be427ea01a78206bcaf9a56f835784afcba9e5b88fbdce33bbbfbcd7841229"}, + {file = "pydantic-1.7.3.tar.gz", hash = "sha256:213125b7e9e64713d16d988d10997dabc6a1f73f3991e1ff8e35ebb1409c7dc9"}, ] pydash = [ {file = "pydash-4.9.0-py2.py3-none-any.whl", hash = "sha256:a743212a586f92980ee093fdec4a984cb97d38fe6d5dadd3c4eb1de57bc5fb4a"}, @@ -1826,7 +1686,7 @@ pygments = [ {file = "Pygments-2.7.2.tar.gz", hash = "sha256:381985fcc551eb9d37c52088a32914e00517e57f4a21609f48141ba08e193fa0"}, ] pygtrie = [ - {file = "pygtrie-2.3.3.tar.gz", hash = "sha256:2204dbd95584f67821da5b3771c4305ac5585552b3230b210f1f05322608db2c"}, + {file = "pygtrie-2.4.1.tar.gz", hash = "sha256:4367b87d92eaf475107421dce0295a9d4d72156702908c96c430a426b654aee7"}, ] pyinquirer = [ {file = "PyInquirer-1.0.3.tar.gz", hash = "sha256:c9a92d68d7727fbd886a7908c08fd9e9773e5dc211bf5cbf836ba90d366dee51"}, @@ -1866,17 +1726,9 @@ python-dotenv = [ {file = "python-dotenv-0.15.0.tar.gz", hash = "sha256:587825ed60b1711daea4832cf37524dfd404325b7db5e25ebe88c495c9f807a0"}, {file = "python_dotenv-0.15.0-py2.py3-none-any.whl", hash = "sha256:0c8d1b80d1a1e91717ea7d526178e3882732420b03f08afea0406db6402e220e"}, ] -python-engineio = [ - {file = "python-engineio-3.13.2.tar.gz", hash = "sha256:36b33c6aa702d9b6a7f527eec6387a2da1a9a24484ec2f086d76576413cef04b"}, - {file = "python_engineio-3.13.2-py2.py3-none-any.whl", hash = "sha256:cfded18156862f94544a9f8ef37f56727df731c8552d7023f5afee8369be2db6"}, -] python-slugify = [ {file = "python-slugify-4.0.1.tar.gz", hash = "sha256:69a517766e00c1268e5bbfc0d010a0a8508de0b18d30ad5a1ff357f8ae724270"}, ] -python-socketio = [ - {file = "python-socketio-4.6.0.tar.gz", hash = "sha256:358d8fbbc029c4538ea25bcaa283e47f375be0017fcba829de8a3a731c9df25a"}, - {file = "python_socketio-4.6.0-py2.py3-none-any.whl", hash = "sha256:d437f797c44b6efba2f201867cf02b8c96b97dff26d4e4281ac08b45817cd522"}, -] pytz = [ {file = "pytz-2020.4-py2.py3-none-any.whl", hash = "sha256:5c55e189b682d420be27c6995ba6edce0c0a77dd67bfbe2ae6607134d5851ffd"}, {file = "pytz-2020.4.tar.gz", hash = "sha256:3e6b7dd2d1e0a59084bcee14a17af60c5c562cdc16d828e8eba2e683d3a7e268"}, @@ -1906,6 +1758,8 @@ pyyaml = [ {file = "PyYAML-5.3.1-cp37-cp37m-win_amd64.whl", hash = "sha256:73f099454b799e05e5ab51423c7bcf361c58d3206fa7b0d555426b1f4d9a3eaf"}, {file = "PyYAML-5.3.1-cp38-cp38-win32.whl", hash = "sha256:06a0d7ba600ce0b2d2fe2e78453a470b5a6e000a985dd4a4e54e436cc36b0e97"}, {file = "PyYAML-5.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:95f71d2af0ff4227885f7a6605c37fd53d3a106fcab511b8860ecca9fcf400ee"}, + {file = "PyYAML-5.3.1-cp39-cp39-win32.whl", hash = "sha256:ad9c67312c84def58f3c04504727ca879cb0013b2517c85a9a253f0cb6380c0a"}, + {file = "PyYAML-5.3.1-cp39-cp39-win_amd64.whl", hash = "sha256:6034f55dab5fea9e53f436aa68fa3ace2634918e8b5994d82f3621c04ff5ed2e"}, {file = "PyYAML-5.3.1.tar.gz", hash = "sha256:b8eac752c5e14d3eca0e6dd9199cd627518cb5ec06add0de9d32baeee6fe645d"}, ] regex = [ @@ -2012,10 +1866,6 @@ texttable = [ {file = "texttable-1.6.3-py2.py3-none-any.whl", hash = "sha256:f802f2ef8459058736264210f716c757cbf85007a30886d8541aa8c3404f1dda"}, {file = "texttable-1.6.3.tar.gz", hash = "sha256:ce0faf21aa77d806bbff22b107cc22cce68dc9438f97a2df32c93e9afa4ce436"}, ] -tzlocal = [ - {file = "tzlocal-2.1-py2.py3-none-any.whl", hash = "sha256:e2cb6c6b5b604af38597403e9852872d7f534962ae2954c7f35efcb1ccacf4a4"}, - {file = "tzlocal-2.1.tar.gz", hash = "sha256:643c97c5294aedc737780a49d9df30889321cbe1204eac2c2ec6134035a92e44"}, -] unify = [ {file = "unify-0.5.tar.gz", hash = "sha256:8ddce812b2457212b7598fe574c9e6eb3ad69710f445391338270c7f8a71723c"}, ] diff --git a/pyproject.toml b/pyproject.toml index c9f38794..d4fc9677 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "nonebot2" -version = "2.0.0-alpha.6" +version = "2.0.0-alpha.7" description = "An asynchronous python bot framework." authors = ["yanyongyu "] license = "MIT" @@ -26,25 +26,19 @@ include = ["nonebot/py.typed"] python = "^3.7" httpx = "^0.16.1" loguru = "^0.5.1" -pygtrie = "^2.3.3" +pygtrie = "^2.4.1" fastapi = "^0.58.1" uvicorn = "^0.11.5" -pydantic = { extras = ["dotenv"], version = "^1.6.1" } -apscheduler = { version = "^3.6.3", optional = true } -nonebot-test = { version = "^0.1.0", optional = true } -nb-cli = { version="^0.2.0", optional = true } +pydantic = { extras = ["dotenv"], version = "^1.7.2" } [tool.poetry.dev-dependencies] yapf = "^0.30.0" -sphinx = "^3.1.1" +sphinx = "^3.3.1" +nb-cli = { version = "^0.2.0", optional = true } +nonebot-plugin-test = { version = "^0.1.0", optional = true } +nonebot-plugin-apscheduler = { version = "^0.1.0", optional = true } sphinx-markdown-builder = { git = "https://github.com/nonebot/sphinx-markdown-builder.git" } -[tool.poetry.extras] -cli = ["nb-cli"] -test = ["nonebot-test"] -scheduler = ["apscheduler"] -full = ["nb-cli", "nonebot-test", "apscheduler"] - [[tool.poetry.source]] name = "aliyun" url = "https://mirrors.aliyun.com/pypi/simple/" diff --git a/tests/bot.py b/tests/bot.py index 68a4e399..6e45e051 100644 --- a/tests/bot.py +++ b/tests/bot.py @@ -4,6 +4,8 @@ import sys 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.log import logger, default_format # test custom log @@ -15,9 +17,14 @@ logger.add("error.log", nonebot.init(custom_config2="config on init") app = nonebot.get_asgi() +driver = nonebot.get_driver() +driver.register_adapter("cqhttp", Bot) +driver.register_adapter("ding", DingBot) # load builtin plugin nonebot.load_builtin_plugins() +nonebot.load_plugin("nonebot_plugin_apscheduler") +nonebot.load_plugin("nonebot_plugin_test") # load local plugins nonebot.load_plugins("test_plugins") @@ -25,7 +32,7 @@ nonebot.load_plugins("test_plugins") print(nonebot.require("test_export")) # modify some config / config depends on loaded configs -config = nonebot.get_driver().config +config = driver.config config.custom_config3 = config.custom_config1 config.custom_config4 = "New custom config" diff --git a/tests/test_plugins/test_group/__init__.py b/tests/test_plugins/test_group/__init__.py index 1f47bd5c..9d1d04a7 100644 --- a/tests/test_plugins/test_group/__init__.py +++ b/tests/test_plugins/test_group/__init__.py @@ -1,6 +1,7 @@ from nonebot.rule import to_me -from nonebot import CommandGroup +from nonebot import CommandGroup, MatcherGroup -test = CommandGroup("test", rule=to_me()) +cmd = CommandGroup("test", rule=to_me()) +match = MatcherGroup(priority=2) -from . import commands +from . import commands, matches diff --git a/tests/test_plugins/test_group/commands.py b/tests/test_plugins/test_group/commands.py index e825329d..52242d32 100644 --- a/tests/test_plugins/test_group/commands.py +++ b/tests/test_plugins/test_group/commands.py @@ -1,9 +1,9 @@ from nonebot.typing import Bot, Event from nonebot.permission import GROUP_OWNER -from . import test +from . import cmd -test_1 = test.command("1", aliases={"test"}, permission=GROUP_OWNER) +test_1 = cmd.command("1", aliases={"test"}, permission=GROUP_OWNER) @test_1.handle() diff --git a/tests/test_plugins/test_group/matches.py b/tests/test_plugins/test_group/matches.py new file mode 100644 index 00000000..8c3c786b --- /dev/null +++ b/tests/test_plugins/test_group/matches.py @@ -0,0 +1,15 @@ +from nonebot.typing import Bot, Event + +from . import match + + +async def heartbeat(bot: Bot, event: Event, state: dict) -> bool: + return event.detail_type == "heartbeat" + + +test = match.on_metaevent(rule=heartbeat) + + +@test.receive() +async def handle_heartbeat(bot: Bot, event: Event, state: dict): + print("[i] Heartbeat") diff --git a/tests/test_plugins/test_permission.py b/tests/test_plugins/test_permission.py index ed03b80f..23d4e0f5 100644 --- a/tests/test_plugins/test_permission.py +++ b/tests/test_plugins/test_permission.py @@ -2,6 +2,7 @@ from nonebot.rule import to_me from nonebot.typing import Event from nonebot.plugin import on_startswith from nonebot.adapters.cqhttp import Bot +from nonebot.adapters.ding import Bot as DingBot, Event as DingEvent from nonebot.permission import GROUP_ADMIN test_command = on_startswith("hello", to_me(), permission=GROUP_ADMIN) @@ -9,4 +10,9 @@ test_command = on_startswith("hello", to_me(), permission=GROUP_ADMIN) @test_command.handle() async def test_handler(bot: Bot, event: Event, state: dict): - await test_command.finish("hello") + await test_command.finish("cqhttp hello") + + +@test_command.handle() +async def test_handler(bot: DingBot, event: DingEvent, state: dict): + await test_command.finish("ding hello")