mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-02-20 17:46:51 +08:00
commit
b6bbc7d228
2
.github/FUNDING.yml
vendored
Normal file
2
.github/FUNDING.yml
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
open_collective: nonebot
|
||||
custom: ["https://afdian.net/@nonebot"]
|
7
.github/release-drafter.yml
vendored
7
.github/release-drafter.yml
vendored
@ -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:
|
||||
|
4
LICENSE
4
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.
|
||||
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
54
README.md
54
README.md
@ -39,28 +39,62 @@ _✨ Python 异步机器人框架 ✨_
|
||||
<a href="https://v2.nonebot.dev/guide/installation.html">安装</a>
|
||||
·
|
||||
<a href="https://v2.nonebot.dev/guide/getting-started.html">开始使用</a>
|
||||
·
|
||||
<a href="#插件">文档打不开?</a>
|
||||
</p>
|
||||
|
||||
## 简介
|
||||
|
||||
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)
|
||||
|
||||
## 贡献
|
||||
|
||||
|
@ -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)
|
@ -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")
|
||||
```
|
@ -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]
|
||||
```
|
@ -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 文件,暂时留空,此时目录结构如下:
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::vue
|
||||
AweSome-Bot
|
||||
├── awesome_bot
|
||||
│ └── plugins
|
||||
│ └── `weather.py`
|
||||
├── .env
|
||||
├── .env.dev
|
||||
├── .env.prod
|
||||
├── .gitignore
|
||||
├── bot.py
|
||||
├── docker-compose.yml
|
||||
├── Dockerfile
|
||||
├── pyproject.toml
|
||||
└── README.md
|
||||
:::
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
这个时候它已经可以被称为一个插件了,尽管它还什么都没做。
|
||||
|
||||
### 包形式
|
||||
|
||||
在插件目录下创建文件夹 `weather`,并在该文件夹下创建文件 `__init__.py`,此时目录结构如下:
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::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
|
||||
:::
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
这个时候 `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`,用于向用户发送一条消息。
|
||||
|
||||
## 结语
|
||||
|
||||
至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示:
|
||||
|
||||
- 请千万注意事件处理器的优先级设定
|
||||
- 在匹配规则中请勿使用耗时极长的函数
|
||||
- 同一个用户可以跨群(私聊)继续他的事件处理(除非做出权限限制,将在后续介绍)
|
@ -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
|
||||
---
|
7
archive/2.0.0a7/advanced/README.md
Normal file
7
archive/2.0.0a7/advanced/README.md
Normal file
@ -0,0 +1,7 @@
|
||||
# 深入
|
||||
|
||||
## 它如何工作?
|
||||
|
||||
<!-- TODO: how to work -->
|
||||
|
||||
~~未填坑~~
|
1
archive/2.0.0a7/advanced/export-and-require.md
Normal file
1
archive/2.0.0a7/advanced/export-and-require.md
Normal file
@ -0,0 +1 @@
|
||||
# 跨插件访问
|
1
archive/2.0.0a7/advanced/permission.md
Normal file
1
archive/2.0.0a7/advanced/permission.md
Normal file
@ -0,0 +1 @@
|
||||
# 权限控制
|
1
archive/2.0.0a7/advanced/publish-plugin.md
Normal file
1
archive/2.0.0a7/advanced/publish-plugin.md
Normal file
@ -0,0 +1 @@
|
||||
# 发布插件
|
1
archive/2.0.0a7/advanced/runtime-hook.md
Normal file
1
archive/2.0.0a7/advanced/runtime-hook.md
Normal file
@ -0,0 +1 @@
|
||||
# 运行时插槽
|
1
archive/2.0.0a7/advanced/scheduler.md
Normal file
1
archive/2.0.0a7/advanced/scheduler.md
Normal file
@ -0,0 +1 @@
|
||||
# 定时任务
|
@ -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)
|
@ -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 的实现拼接相邻消息段
|
||||
|
||||
|
||||
|
@ -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 适配。
|
380
archive/2.0.0a7/api/adapters/ding.md
Normal file
380
archive/2.0.0a7/api/adapters/ding.md
Normal file
@ -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 适配。
|
285
archive/2.0.0a7/api/config.md
Normal file
285
archive/2.0.0a7/api/config.md
Normal file
@ -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
|
||||
```
|
@ -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`
|
@ -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`: 错误代码
|
@ -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 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数
|
||||
:::
|
143
archive/2.0.0a7/api/message.md
Normal file
143
archive/2.0.0a7/api/message.md
Normal file
@ -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))
|
||||
```
|
@ -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()`
|
||||
|
||||
|
@ -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]`
|
@ -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 类型,第二个参数为运行时产生的错误(如果存在)
|
||||
|
||||
|
||||
|
@ -54,8 +54,6 @@ sidebarDepth: 0
|
||||
|
||||
## _class_ `DataclassEncoder`
|
||||
|
||||
基类:`json.encoder.JSONEncoder`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
@ -1,33 +1,30 @@
|
||||
# 概览
|
||||
|
||||
:::tip 提示
|
||||
<!-- :::tip 提示
|
||||
如果在阅读本文档时遇到难以理解的词汇,请随时查阅 [术语表](../glossary.md) 或使用 [Google 搜索](https://www.google.com/)。
|
||||
:::
|
||||
::: -->
|
||||
|
||||
:::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+。
|
||||
|
||||
## 它如何工作?
|
||||
|
||||
<!-- TODO: how to work -->
|
||||
|
||||
~~未填坑~~
|
||||
需要注意的是,NoneBot 仅支持 **Python 3.7+**
|
||||
|
||||
## 特色
|
||||
|
||||
- 提供直观的测试前端
|
||||
NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**!
|
||||
|
||||
- 提供使用简易的脚手架
|
||||
- 提供丰富的官方插件
|
||||
- 提供可添加/替换的驱动以及协议选项
|
||||
- 基于异步 I/O
|
||||
- 同时支持 HTTP 和反向 WebSocket 通信方式
|
||||
- 支持多个机器人账号负载均衡
|
159
archive/2.0.0a7/guide/creating-a-handler.md
Normal file
159
archive/2.0.0a7/guide/creating-a-handler.md
Normal file
@ -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")
|
||||
```
|
144
archive/2.0.0a7/guide/creating-a-matcher.md
Normal file
144
archive/2.0.0a7/guide/creating-a-matcher.md
Normal file
@ -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
|
||||
:::
|
119
archive/2.0.0a7/guide/creating-a-plugin.md
Normal file
119
archive/2.0.0a7/guide/creating-a-plugin.md
Normal file
@ -0,0 +1,119 @@
|
||||
# 创建插件
|
||||
|
||||
如果之前使用 `nb-cli` 生成了项目结构,那我们已经有了一个空的插件目录 `Awesome-Bot/awesome_bot/plugins`,并且它已在 `bot.py` 中被加载,我们现在可以开始创建插件了!
|
||||
|
||||
使用 `nb-cli` 创建包形式插件,或自行创建文件(夹)
|
||||
|
||||
```bash
|
||||
nb plugin new
|
||||
```
|
||||
|
||||
插件通常有两种形式,下面分别介绍
|
||||
|
||||
## 单文件形式
|
||||
|
||||
在插件目录下创建名为 `foo.py` 的 Python 文件,暂时留空,此时目录结构如下:
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::vue
|
||||
AweSome-Bot
|
||||
├── awesome_bot
|
||||
│ └── plugins
|
||||
│ └── `foo.py`
|
||||
├── .env
|
||||
├── .env.dev
|
||||
├── .env.prod
|
||||
├── .gitignore
|
||||
├── bot.py
|
||||
├── docker-compose.yml
|
||||
├── Dockerfile
|
||||
├── pyproject.toml
|
||||
└── README.md
|
||||
:::
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
这个时候它已经可以被称为一个插件了,尽管它还什么都没做。
|
||||
|
||||
## 包形式(推荐)
|
||||
|
||||
在插件目录下创建文件夹 `foo`,并在该文件夹下创建文件 `__init__.py`,此时目录结构如下:
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::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
|
||||
:::
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
这个时候 `foo` 就是一个合法的 Python 包了,同时也是合法的 NoneBot 插件,插件内容可以在 `__init__.py` 中编写。
|
||||
|
||||
### 推荐结构(仅供参考)
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::vue
|
||||
foo
|
||||
├── `__init__.py`
|
||||
├── `config.py`
|
||||
├── `data_source.py`
|
||||
└── `model.py`
|
||||
:::
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
#### \_\_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
|
||||
|
||||
在该文件中编写数据库模型。
|
@ -4,16 +4,12 @@
|
||||
|
||||
## 目录结构
|
||||
|
||||
首先,我们可以使用 `nb-cli` 或者自行创建项目目录:
|
||||
首先,我们可以使用 `nb-cli` 或者自行创建完整的项目目录:
|
||||
|
||||
```bash
|
||||
pip install nonebot2[cli]
|
||||
# pip install nb-cli
|
||||
nb create
|
||||
```
|
||||
|
||||
这将创建默认的目录结构
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::vue
|
||||
AweSome-Bot
|
9
archive/2.0.0a7/guide/end-or-start.md
Normal file
9
archive/2.0.0a7/guide/end-or-start.md
Normal file
@ -0,0 +1,9 @@
|
||||
# 结语
|
||||
|
||||
至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示:
|
||||
|
||||
- 请千万注意事件处理器的优先级设定
|
||||
- 在匹配规则中请勿使用耗时极长的函数
|
||||
- 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍)
|
||||
|
||||
如果你还不能满足,前往 [进阶](../advanced/README.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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
87
archive/2.0.0a7/guide/installation.md
Normal file
87
archive/2.0.0a7/guide/installation.md
Normal file
@ -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: [](https://github.com/nonebot/nonebot2)
|
||||
|
||||
nb-cli: [](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) 等着你发现~
|
116
archive/2.0.0a7/guide/loading-a-plugin.md
Normal file
116
archive/2.0.0a7/guide/loading-a-plugin.md
Normal file
@ -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()
|
||||
```
|
||||
|
||||
## 子插件(嵌套插件)
|
||||
|
||||
在插件中同样可以加载子插件,例如如下插件目录结构:
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::vue
|
||||
foo_plugin
|
||||
├── `plugins`
|
||||
│ ├── `sub_plugin1`
|
||||
│ │ └── \_\_init\_\_.py
|
||||
│ └── `sub_plugin2.py`
|
||||
├── `__init__.py`
|
||||
└── config.py
|
||||
:::
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
在插件目录下的 `__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"
|
||||
```
|
@ -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"
|
||||
}
|
||||
]
|
||||
}
|
@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
[
|
||||
"2.0.0a6",
|
||||
"2.0.0a4"
|
||||
"2.0.0a7",
|
||||
"2.0.0a6"
|
||||
]
|
@ -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
|
||||
---
|
||||
|
@ -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)
|
||||
|
@ -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 的实现拼接相邻消息段
|
||||
|
||||
|
||||
|
||||
|
@ -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)`
|
||||
|
380
docs/api/adapters/ding.md
Normal file
380
docs/api/adapters/ding.md
Normal file
@ -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 适配。
|
@ -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)
|
||||
|
@ -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`
|
||||
|
@ -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]`: 错误代码
|
||||
|
@ -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 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数
|
||||
:::
|
||||
|
@ -40,6 +40,9 @@ sidebarDepth: 0
|
||||
* `CommandGroup` => `nonebot.plugin.CommandGroup`
|
||||
|
||||
|
||||
* `Matchergroup` => `nonebot.plugin.MatcherGroup`
|
||||
|
||||
|
||||
* `load_plugin` => `nonebot.plugin.load_plugin`
|
||||
|
||||
|
||||
|
@ -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)`
|
||||
|
||||
|
||||
|
@ -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")
|
||||
```
|
@ -54,8 +54,6 @@ sidebarDepth: 0
|
||||
|
||||
## _class_ `DataclassEncoder`
|
||||
|
||||
基类:`json.encoder.JSONEncoder`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
|
@ -1,27 +1,30 @@
|
||||
# 概览
|
||||
|
||||
:::tip 提示
|
||||
<!-- :::tip 提示
|
||||
如果在阅读本文档时遇到难以理解的词汇,请随时查阅 [术语表](../glossary.md) 或使用 [Google 搜索](https://www.google.com/)。
|
||||
:::
|
||||
::: -->
|
||||
|
||||
:::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 通信方式
|
||||
- 支持多个机器人账号负载均衡
|
||||
|
@ -2,6 +2,12 @@
|
||||
|
||||
如果之前使用 `nb-cli` 生成了项目结构,那我们已经有了一个空的插件目录 `Awesome-Bot/awesome_bot/plugins`,并且它已在 `bot.py` 中被加载,我们现在可以开始创建插件了!
|
||||
|
||||
使用 `nb-cli` 创建包形式插件,或自行创建文件(夹)
|
||||
|
||||
```bash
|
||||
nb plugin new
|
||||
```
|
||||
|
||||
插件通常有两种形式,下面分别介绍
|
||||
|
||||
## 单文件形式
|
||||
|
@ -4,16 +4,12 @@
|
||||
|
||||
## 目录结构
|
||||
|
||||
首先,我们可以使用 `nb-cli` 或者自行创建项目目录:
|
||||
首先,我们可以使用 `nb-cli` 或者自行创建完整的项目目录:
|
||||
|
||||
```bash
|
||||
pip install nonebot2[cli]
|
||||
# pip install nb-cli
|
||||
nb create
|
||||
```
|
||||
|
||||
这将创建默认的目录结构
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
:::vue
|
||||
AweSome-Bot
|
||||
|
@ -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
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
@ -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: [](https://github.com/nonebot/nonebot2)
|
||||
|
||||
nb-cli: [](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
|
||||
```
|
||||
|
||||
[](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]
|
||||
```
|
||||
|
||||
[](https://github.com/nonebot/nonebot-test)
|
||||
|
||||
### CLI
|
||||
|
||||
CLI for nonebot2.
|
||||
|
||||
一个多功能脚手架
|
||||
|
||||
```bash
|
||||
pip install nonebot2[cli]
|
||||
poetry add nonebot2[cli]
|
||||
```
|
||||
|
||||
[](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) 等着你发现~
|
||||
|
@ -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__":
|
||||
|
||||
## 子插件(嵌套插件)
|
||||
|
||||
<!-- TODO: 子插件 -->
|
||||
|
||||
在插件中同样可以加载子插件,例如如下插件目录结构:
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
@ -9,7 +9,6 @@ NoneBot Api Reference
|
||||
- `nonebot.matcher <matcher.html>`_
|
||||
- `nonebot.rule <rule.html>`_
|
||||
- `nonebot.permission <permission.html>`_
|
||||
- `nonebot.sched <sched.html>`_
|
||||
- `nonebot.log <log.html>`_
|
||||
- `nonebot.utils <utils.html>`_
|
||||
- `nonebot.typing <typing.html>`_
|
||||
@ -18,3 +17,4 @@ NoneBot Api Reference
|
||||
- `nonebot.drivers.fastapi <drivers/fastapi.html>`_
|
||||
- `nonebot.adapters <adapters/>`_
|
||||
- `nonebot.adapters.cqhttp <adapters/cqhttp.html>`_
|
||||
- `nonebot.adapters.ding <adapters/ding.html>`_
|
||||
|
@ -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:
|
||||
|
29
docs_build/adapters/ding.rst
Normal file
29
docs_build/adapters/ding.rst
Normal file
@ -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:
|
@ -1,11 +0,0 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
NoneBot.sched 模块
|
||||
===================
|
||||
|
||||
.. automodule:: nonebot.sched
|
||||
:members:
|
||||
:show-inheritance:
|
@ -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:
|
||||
|
@ -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("<y>Scheduler Started</y>")
|
||||
|
||||
|
||||
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
|
||||
|
@ -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"<Event {self.self_id}: {self.name} {self.time}>"
|
||||
|
||||
@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
|
||||
|
@ -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, "<m>CQHTTP</m> | " + 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) 协议鉴权。参考 `鉴权 <https://github.com/howmanybots/onebot/blob/master/v11/specs/communication/authorization.md>`_
|
||||
"""
|
||||
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"<r><bg #f8bbd0>Failed to handle event. Raw: {message}</bg #f8bbd0></r>"
|
||||
)
|
||||
|
||||
@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 <y>{api}</y>")
|
||||
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<type>[a-zA-Z0-9-_.]+)"
|
||||
r"(?P<params>"
|
||||
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
|
||||
|
432
nonebot/adapters/cqhttp/bot.py
Normal file
432
nonebot/adapters/cqhttp/bot.py
Normal file
@ -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) 协议鉴权。参考 `鉴权 <https://github.com/howmanybots/onebot/blob/master/v11/specs/communication/authorization.md>`_
|
||||
"""
|
||||
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"<r><bg #f8bbd0>Failed to handle event. Raw: {message}</bg #f8bbd0></r>"
|
||||
)
|
||||
|
||||
@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 <y>{api}</y>")
|
||||
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)
|
@ -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]:
|
||||
...
|
204
nonebot/adapters/cqhttp/event.py
Normal file
204
nonebot/adapters/cqhttp/event.py
Normal file
@ -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
|
59
nonebot/adapters/cqhttp/exception.py
Normal file
59
nonebot/adapters/cqhttp/exception.py
Normal file
@ -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"<ActionFailed retcode={self.retcode}>"
|
||||
|
||||
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"<NetWorkError message={self.msg}>"
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
|
||||
class ApiNotAvailable(BaseApiNotAvailable, CQHTTPAdapterException):
|
||||
pass
|
231
nonebot/adapters/cqhttp/message.py
Normal file
231
nonebot/adapters/cqhttp/message.py
Normal file
@ -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<type>[a-zA-Z0-9-_.]+)"
|
||||
r"(?P<params>"
|
||||
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)
|
44
nonebot/adapters/cqhttp/utils.py
Normal file
44
nonebot/adapters/cqhttp/utils.py
Normal file
@ -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()
|
17
nonebot/adapters/ding/__init__.py
Normal file
17
nonebot/adapters/ding/__init__.py
Normal file
@ -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)
|
197
nonebot/adapters/ding/bot.py
Normal file
197
nonebot/adapters/ding/bot.py
Normal file
@ -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:
|
||||
"""
|
||||
:说明:
|
||||
|
||||
钉钉协议鉴权。参考 `鉴权 <https://ding-doc.dingtalk.com/doc#/serverapi2/elzz1p>`_
|
||||
"""
|
||||
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"<r><bg #f8bbd0>Failed to handle event. Raw: {message}</bg #f8bbd0></r>"
|
||||
)
|
||||
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 <y>{api}</y>")
|
||||
|
||||
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)
|
196
nonebot/adapters/ding/event.py
Normal file
196
nonebot/adapters/ding/event.py
Normal file
@ -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")
|
76
nonebot/adapters/ding/exception.py
Normal file
76
nonebot/adapters/ding/exception.py
Normal file
@ -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"<ApiError errcode={self.errcode} errmsg={self.errmsg}>"
|
||||
|
||||
|
||||
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"<NetWorkError message={self.msg}>"
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
|
||||
|
||||
class SessionExpired(BaseApiNotAvailable, DingAdapterException):
|
||||
"""
|
||||
:说明:
|
||||
|
||||
发消息的 session 已经过期。
|
||||
"""
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Session Webhook is Expired>"
|
133
nonebot/adapters/ding/message.py
Normal file
133
nonebot/adapters/ding/message.py
Normal file
@ -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)
|
47
nonebot/adapters/ding/model.py
Normal file
47
nonebot/adapters/ding/model.py
Normal file
@ -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
|
3
nonebot/adapters/ding/utils.py
Normal file
3
nonebot/adapters/ding/utils.py
Normal file
@ -0,0 +1,3 @@
|
||||
from nonebot.utils import logger_wrapper
|
||||
|
||||
log = logger_wrapper("DING")
|
@ -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
|
||||
|
@ -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"<g>Loaded adapters: {', '.join(self._adapters)}</g>")
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _handle_http(self):
|
||||
|
@ -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,
|
||||
|
@ -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"<ActionFailed, retcode={self.retcode}>"
|
||||
|
||||
def __str__(self):
|
||||
return self.__repr__()
|
||||
pass
|
||||
|
@ -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"<MatcherGroup from {self.module or 'unknow'}, type={self.type}, "
|
||||
f"priority={self.priority}, temp={self.temp}>")
|
||||
|
||||
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
|
||||
|
@ -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
|
||||
|
@ -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``: 需要同时满足的权限
|
||||
"""
|
||||
|
@ -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]:
|
||||
"""
|
||||
:说明:
|
||||
|
||||
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
|
||||
|
||||
命令匹配规则参考: `命令形式匹配 <rule.html#command-command>`_
|
||||
|
||||
:参数:
|
||||
|
||||
* ``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]:
|
||||
"""
|
||||
:说明:
|
||||
|
||||
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
|
||||
|
||||
命令匹配规则参考: `正则匹配 <rule.html#regex-regex-flags-0>`_
|
||||
|
||||
:参数:
|
||||
|
||||
* ``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]:
|
||||
"""
|
||||
:说明:
|
||||
|
||||
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
|
||||
|
||||
命令匹配规则参考: `命令形式匹配 <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]``
|
||||
"""
|
||||
|
||||
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]:
|
||||
"""
|
||||
:说明:
|
||||
|
||||
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
|
||||
|
||||
命令匹配规则参考: `正则匹配 <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]``
|
||||
"""
|
||||
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)
|
||||
|
@ -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]:
|
||||
...
|
||||
|
@ -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
|
||||
|
@ -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`` 判断消息是否是发送给机器人
|
||||
|
||||
:参数:
|
||||
|
||||
* 无
|
||||
"""
|
||||
|
||||
|
@ -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
|
@ -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:
|
||||
|
@ -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:
|
||||
"""
|
||||
:说明:
|
||||
|
||||
用于记录带颜色日志时转义 ``<tag>`` 类型特殊标签
|
||||
|
||||
:参数:
|
||||
|
||||
* ``s: str``: 需要转义的字符串
|
||||
|
||||
:返回:
|
||||
|
||||
- ``str``
|
||||
"""
|
||||
return re.sub(r"</?((?:[fb]g\s)?[^<>\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"<m>{logger_name}</m> | " + message)
|
||||
|
||||
return log
|
||||
|
@ -11,6 +11,10 @@ sidebar: auto
|
||||
- 修改 cqhttp 检查 reply 时未去除后续 at 以及空格
|
||||
- 添加 get_plugin 获取插件函数
|
||||
- 添加插件 export, require 方法
|
||||
- **移除**内置 apscheduler 定时任务支持
|
||||
- **移除**内置协议适配默认加载
|
||||
- 新增**钉钉**协议适配
|
||||
- 移除原有共享型 `MatcherGroup` 改为默认型 `MatcherGroup`
|
||||
|
||||
## v2.0.0a6
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user