📝 remove old doc version (#1417)

This commit is contained in:
Ju4tCode 2022-11-24 11:50:20 +08:00 committed by GitHub
parent 1644615462
commit cb83e76e16
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
75 changed files with 0 additions and 10781 deletions

View File

@ -1,49 +0,0 @@
---
sidebar_position: 0
id: index
slug: /
---
# 概览
NoneBot2 是一个现代、跨平台、可扩展的 Python 聊天机器人框架,它基于 Python 的类型注解和异步特性,能够为你的需求实现提供便捷灵活的支持。
需要注意的是NoneBot2 仅支持 **Python 3.8 以上版本**
## 特色
### 异步优先
NoneBot2 基于 Python [asyncio](https://docs.python.org/3/library/asyncio.html) 编写,并在异步机制的基础上进行了一定程度的同步函数兼容。
### 完整的类型注解
NoneBot2 参考 [PEP 484](https://www.python.org/dev/peps/pep-0484/) 等 PEP 完整实现了类型注解,通过 `pyright`/`pylance` 检查。配合编辑器的类型推导功能,能将绝大多数的 Bug 杜绝在编辑器中([编辑器支持](./start/editor-support))。
### 开箱即用
NoneBot2 提供了使用便捷、具有交互式功能的命令行工具--`nb-cli`,使得初次接触 NoneBot2 时更容易上手。详细使用方法请参考各文档章节以及[使用脚手架](./start/nb-cli)。
### 插件系统
插件系统是 NoneBot2 的核心,通过它可以实现机器人的模块化以及功能扩展,便于维护和管理。
### 依赖注入系统
NoneBot2 采用了一套自行定义的依赖注入系统,可以让事件的处理过程更加的简洁、清晰,增加代码的可读性,减少代码冗余。
#### 什么是依赖注入
[**“依赖注入”**](https://zh.m.wikipedia.org/wiki/%E6%8E%A7%E5%88%B6%E5%8F%8D%E8%BD%AC)意思是,在编程中,有一种方法可以让你的代码声明它工作和使用所需要的东西,即**“依赖”**。
系统(在这里是指 NoneBot2将负责做任何需要的事情为你的代码提供这些必要依赖即**“注入”**依赖性)
这在你有以下情形的需求时非常有用:
- 这部分代码拥有共享的逻辑(同样的代码逻辑多次重复)
- 共享数据库以及网络请求连接会话
- 比如 `httpx.AsyncClient`、`aiohttp.ClientSession` 和 `sqlalchemy.Session`
- 用户权限检查以及认证
- 还有更多...
它在完成上述工作的同时,还能尽量减少代码的耦合和重复

View File

@ -1,207 +0,0 @@
---
id: index
sidebar_position: 0
description: 深入了解 NoneBot2 运行机制
slug: /advanced/
options:
menu:
weight: 10
category: advanced
---
# 深入
:::danger 警告
进阶部分尚未更新完成
:::
## 它如何工作?
如同[概览](../README.md)所言:
> NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。
NoneBot2 是一个可以对机器人上报的事件进行处理并完成具体功能的机器人框架,在这里,我们将简要讲述它的工作内容。
**便捷起见,以下内容对 NoneBot2 会被称为 NoneBot与 NoneBot2 交互的机器人实现会被称为协议端**。
在实际应用中NoneBot 会充当一个高性能,轻量级的 Python 微服务框架。协议端可以通过 http、websocket 等方式与之通信,这个通信往往是双向的:一方面,协议端可以上报数据给 NoneBotNoneBot 会处理数据并返回响应给协议端另一方面NoneBot 可以主动推送数据给协议端。而 NoneBot 便是围绕双向通信进行工作的。
在开始工作之前NoneBot 需要进行准备工作:
1. **运行 `nonebot.init` 初始化函数**,它会读取配置文件,并初始化 NoneBot 和后端驱动 `Driver` 对象。
2. **注册协议适配器 `Adapter`**
3. **加载插件**
准备工作完成后NoneBot 会利用 uvicorn 启动,并运行 `on_startup` 钩子函数。
随后,倘若一个协议端与 NoneBot 进行了连接NoneBot 的后端驱动 `Driver` 就会将数据交给 `Adapter`,然后会实例化 `Bot`NoneBot 便会利用 `Bot` 开始工作,它的工作内容分为两个方面:
1. **事件处理**`Bot` 会将协议端上报的数据转化为 `Event`(事件),之后 NoneBot 会根据一套既定流程来处理事件。
2. **调用 `API`**,在**事件处理**的过程中NoneBot 可以通过 `Bot` 调用协议端指定的 `API` 来获取更多数据或者反馈响应给协议端NoneBot 也可以通过调用 `API` 向协议端主动请求数据或者主动推送数据。
在**指南**模块,我们已经叙述了[如何配置 NoneBot](../tutorial/configuration.md)、[如何注册协议适配器](../tutorial/register-adapter.md)以及[如何加载插件](../tutorial/plugin/load-plugin.md),这里便不再赘述。
下面,我们将对**事件处理****调用 API** 进行说明。
## 事件处理
我们可以先看事件处理的流程图:
![handle-event](./images/Handle-Event.png)
在流程图里我们可以看到NoneBot 会有三个阶段来处理事件:
1. **Driver 接收上报数据**
2. **Adapter 处理原始数据**
3. **NoneBot 处理 Event**
我们将顺序说明这三个阶段。其中,会将第三个阶段拆分成**概念解释****处理 Event****特殊异常处理**三个部分来说明。
### Driver 接收上报数据
1. 协议端会通过 websocket 或 http 等方式与 NoneBot 的后端驱动 `Driver` 连接,协议端上报数据后,`Driver` 会将原始数据交给 `Adapter` 处理。
:::warning
连接之前必须要注册 `Adapter`
:::
### Adapter 处理原始数据
1. `Adapter` 检查授权许可,并获取 `self-id` 作为唯一识别 id 。
:::tip
如果协议端通过 websocket 上报数据,这个步骤只会在建立连接时进行,并在之后运行 `on_bot_connect` 钩子函数;通过 http 方式连接时,会在协议端每次上报数据时都进行这个步骤。
:::
:::warning
`self-id` 是帐号的唯一识别 ID ,这意味着不能出现相同的 `self-id`
:::
2. 根据 `self-id` 实例化 `Adapter` 相应的 `Bot`
3. 根据 `Event Model` 将原始数据转化为 NoneBot 可以处理的 `Event` 对象。
:::tip
`Adapter` 在转换数据格式的同时可以进行一系列的特殊操作,例如 OneBot 适配器会对 reply 信息进行提取。
:::
4. `Bot``Event` 交由 NoneBot 进一步处理。
### NoneBot 处理 Event
在讲述这个阶段之前,我们需要先对几个概念进行解释。
#### 概念解释
1. **hook** ,或者说**钩子函数**,它们可以在 NoneBot 处理 `Event` 的不同时刻进行拦截,修改或者扩展,在 NoneBot 中,事件钩子函数分为`事件预处理 hook`、`运行预处理 hook`、`运行后处理 hook` 和`事件后处理 hook`。
:::tip
关于 `hook` 的更多信息,可以查阅[这里](./runtime-hook.md)。
:::
2. **Matcher****matcher**,在**指南**中,我们讲述了[如何注册事件响应器](../tutorial/plugin/create-matcher.md),这里的事件响应器或者说 `Matcher` 并不是一个具体的实例 `instance`,而是一个具有特定属性的类 `class`。只有当 `Matcher` **响应事件**时,才会实例化为具体的 `instance`,也就是 `matcher` 。`matcher` 可以认为是 NoneBot 处理 `Event` 的基本单位,运行 `matcher` 是 NoneBot 工作的主要内容。
3. **handler**,或者说**事件处理函数**,它们可以认为是 NoneBot 处理 `Event` 的最小单位。在不考虑 `hook` 的情况下,**运行 matcher 就是顺序运行 matcher.handlers**,这句话换种表达方式就是,`handler` 只有添加到 `matcher.handlers` 时,才可以参与到 NoneBot 的工作中来。
:::tip
如何让 `handler` 添加到 `matcher.handlers`
一方面,我们可以参照[这里](../tutorial/plugin/create-handler.md)利用装饰器来添加;另一方面,我们在用 `on()` 或者 `on_*()` 注册事件响应器时,可以添加 `handlers=[handler1, handler2, ...]` 这样的关键词参数来添加。
:::
#### 处理 Event
1. **执行事件预处理 hook** NoneBot 接收到 `Event` 后,会传入到 `事件预处理 hook` 中进行处理。
:::warning
需要注意的是,执行多个 `事件预处理 hook` 时并无顺序可言,它们是**并发运行**的。这个原则同样适用于其他的 `hook`
:::
2. **按优先级升序选出同一优先级的 Matcher**NoneBot 提供了一个全局字典 `matchers`,这个字典的 `key` 是优先级 `priority``value` 是一个 `list`,里面存放着同一优先级的 `Matcher`。在注册 `Matcher` 时,它和优先级 `priority` 会添加到里面。
在执行 `事件预处理 hook`NoneBot 会对 `matchers``key` 升序排序并选择出当前最小优先级的 `Matcher`
3. **根据 Matcher 定义的 Rule、Permission 判断是否运行**,在选出 `Matcher`NoneBot 会将 `bot``Event` 传入到 `Matcher.check_rule``Matcher.check_perm` 两个函数中,两个函数分别对 Matcher 定义的 `Rule`、`Permission` 进行 check当 check 通过后,这个 `Matcher` 就会响应事件。当同一个优先级的所有 `Matcher` 均没有响应时NoneBot 会返回到上一个步骤,选择出下一优先级的 `Matcher`
4. **实例化 matcher 并执行运行预处理 hook**,当 `Matcher` 响应事件后,它便会实例化为 `matcher`,并执行 `运行预处理 hook`
5. **顺序运行 matcher 的所有 handlers**`运行预处理 hook` 执行完毕后,便会运行 `matcher`,也就是**顺序运行**它的 `handlers`
:::tip
`matcher` 运行 `handlers` 的顺序是:先运行该 `matcher` 的类 `Matcher` 注册时添加的 `handlers`(如果有的话),再按照装饰器装饰顺序运行装饰的 `handlers`
:::
6. **执行运行后处理 hook**`matcher` 的 `handlers` 运行完毕后,会执行 `运行后处理 hook`
7. **判断是否停止事件传播**NoneBot 会根据当前优先级所有 `matcher``block` 参数或者 `StopPropagation` 异常判断是否停止传播 `Event`如果事件没有停止传播NoneBot 便会返回到第 2 步, 选择出下一优先级的 `Matcher`
8. **执行事件后处理 hook**,在 `Event` 停止传播或执行完所有响应的 `Matcher`NoneBot 会执行 `事件后处理 hook`
`事件后处理 hook` 执行完毕后,当前 `Event` 的处理周期就顺利结束了。
#### 特殊异常处理
在这个阶段NoneBot 规定了几个特殊的异常,当 NoneBot 捕获到它们时,会用特定的行为来处理它们。
1. **IgnoredException**
这个异常可以在 `事件预处理 hook``运行预处理 hook` 抛出。
`事件预处理 hook` 抛出它时NoneBot 会忽略当前的 `Event`,不进行处理。
`运行预处理 hook` 抛出它时NoneBot 会忽略当前的 `matcher`,结束当前 `matcher` 的运行。
:::warning
`hook` 需要抛出这个异常时,要写明原因。
:::
2. **PausedException**
这个异常可以在 `handler` 中由 `Matcher.pause` 抛出。
当 NoneBot 捕获到它时,会停止运行当前 `handler` 并结束当前 `matcher` 的运行,并将后续的 `handler` 交给一个临时 `Matcher` 来响应当前交互用户的下一个消息事件,当临时 `Matcher` 响应时,临时 `Matcher` 会运行后续的 `handler`
3. **RejectedException**
这个异常可以在 `handler` 中由 `Matcher.reject` 抛出。
当 NoneBot 捕获到它时,会停止运行当前 `handler` 并结束当前 `matcher` 的运行,并将当前 handler 和后续 `handler` 交给一个临时 `Matcher` 来响应当前交互用户的下一个消息事件,当临时 `Matcher` 响应时,临时 `Matcher` 会运行当前 `handler` 和后续的 `handler`
4. **FinishedException**
这个异常可以在 `handler` 中由 `Matcher.finish` 抛出。
当 NoneBot 捕获到它时,会停止运行当前 `handler` 并结束当前 `matcher` 的运行。
5. **StopPropagation**
这个异常一般会在执行 `运行后处理 hook` 后抛出。
当 NoneBot 捕获到它时, 会停止传播当前 `Event` ,不再寻找下一优先级的 `Matcher` ,直接执行 `事件后处理 hook`
## 调用 API
NoneBot 可以通过 `bot` 来调用 `API``API` 可以向协议端发送数据,也可以向协议端请求更多的数据。
NoneBot 调用 `API` 会有如下过程:
1. 调用 `calling_api_hook` 预处理钩子。
2. `adapter` 将信息处理为原始数据,并转交 `driver``driver` 交给协议端处理。
3. `driver` 接收协议端的结果,交给`adapter` 处理之后将结果反馈给 NoneBot 。
4. 调用 `called_api_hook` 后处理钩子。
在调用 `API` 时同样规定了特殊的异常,叫做 `MockApiException` 。该异常会由预处理钩子和后处理钩子触发当预处理钩子触发时NoneBot 会跳过之后的调用过程,直接执行后处理钩子。
:::tip
不同 `adapter` 规定了不同的 API对应的 API 列表请参照协议规范。
:::
一般来说,我们可以用 `bot.*` 来调用 `API`\*是 `API``action` 或者 `endpoint`)。
对于发送消息而言,一方面可以调用既有的 `API` ;另一方面 NoneBot 实现了两个便捷方法,`bot.send(event, message, **kwargs)` 方法和可以在 `handler` 中使用的 `Matcher.send(message, **kwargs)` 方法,来向事件主体发送消息。

View File

@ -1,4 +0,0 @@
{
"label": "依赖注入",
"position": 5
}

View File

@ -1,243 +0,0 @@
---
sidebar_position: 1
description: 依赖注入简介
options:
menu:
weight: 60
category: advanced
---
# 简介
受 [FastAPI](https://fastapi.tiangolo.com/tutorial/dependencies/) 启发NoneBot 同样编写了一个简易的依赖注入模块,使得开发者可以通过事件处理函数参数的类型标注来自动注入依赖。
## 什么是依赖注入?
[依赖注入](https://zh.wikipedia.org/wiki/%E4%BE%9D%E8%B5%96%E6%B3%A8%E5%85%A5)
> 在软件工程中,**依赖注入**dependency injection的意思为给予调用方它所需要的事物。 “依赖”是指可被方法调用的事物。依赖注入形式下,调用方不再直接使用“依赖”,取而代之是“注入” 。“注入”是指将“依赖”传递给调用方的过程。在“注入”之后,调用方才会调用该“依赖。 传递依赖给调用方,而不是让让调用方直接获得依赖,这个是该设计的根本需求。
依赖注入往往起到了分离依赖和调用方的作用,这样一方面能让代码更为整洁可读,一方面可以提升代码的复用性。
## 使用依赖注入
以下通过一个简单的例子来说明依赖注入的使用方法:
```python {2,7-8,11}
from nonebot import on_command
from nonebot.params import Depends # 1.引用 Depends
from nonebot.adapters.onebot.v11 import MessageEvent
test = on_command("123")
async def depend(event: MessageEvent): # 2.编写依赖函数
return {"uid": event.get_user_id(), "nickname": event.sender.nickname}
@test.handle()
async def _(x: dict = Depends(depend)): # 3.在事件处理函数里声明依赖项
print(x["uid"], x["nickname"])
```
如注释所言,可以用三步来说明依赖注入的使用过程:
1. 引用 `Depends`
2. 编写依赖函数。依赖函数和普通的事件处理函数并无区别,同样可以接收 `bot`, `event`, `state` 等参数,你可以把它当作一个普通的事件处理函数,但是去除了装饰器(没有使用 `matcher.handle()` 等来装饰),并且可以返回任何类型的值。
在这里我们接受了 `event`,并以 `onebot``MessageEvent` 作为类型标注,返回一个新的字典,包括 `uid``nickname` 两个键值。
3. 在事件处理函数中声明依赖项。依赖项必须要 `Depends` 包裹依赖函数作为默认值。
:::tip
请注意,参数 `x` 的类型标注将会影响到事件处理函数的运行,与类型标注不符的值将会导致事件处理函数被跳过。
:::
:::tip
事实上bot、event、state 它们本身只是依赖注入的一个特例,它们无需声明这是依赖即可注入。
:::
虽然声明依赖项的方式和其他参数如 `bot`, `event` 并无二样,但他的参数有一些限制,必须是**可调用对象**,函数自然是可调用对象,类和生成器也是,我们会在接下来的小节说明。
一般来说,当接收到事件时,`NoneBot2` 会进行以下处理:
1. 准备依赖函数所需要的参数。
2. 调用依赖函数并获得返回值。
3. 将返回值作为事件处理函数中的参数值传入。
## 依赖缓存
在使用 `Depends` 包裹依赖函数时,有一个参数 `use_cache` ,它默认为 `True` ,这个参数会决定 `Nonebot2` 在依赖注入的处理中是否使用缓存。
```python {11}
import random
from nonebot import on_command
from nonebot.params import Depends
test = on_command("123")
async def always_run():
return random.randint(1, 100)
@test.handle()
async def _(x: int = Depends(always_run, use_cache=False)):
print(x)
```
:::tip
缓存是针对单次事件处理来说的,在事件处理中 `Depends` 第一次被调用时,结果存入缓存,在之后都会直接返回缓存中的值,在事件处理结束后缓存就会被清除。
:::
当使用缓存时,依赖注入会这样处理:
1. 查询缓存,如果缓存中有相应的值,则直接返回。
2. 准备依赖函数所需要的参数。
3. 调用依赖函数并获得返回值。
4. 将返回值存入缓存。
5. 将返回值作为事件处理函数中的参数值传入。
## 同步支持
我们在编写依赖函数时,可以简单地用同步函数,`NoneBot2` 的内部流程会进行处理:
```python {2,8-9,12}
from nonebot.log import logger
from nonebot.params import Depends # 1.引用 Depends
from nonebot import on_command, on_message
from nonebot.adapters.onebot.v11 import MessageEvent
test = on_command("123")
def depend(event: MessageEvent): # 2.编写同步依赖函数
return {"uid": event.get_user_id(), "nickname": event.sender.nickname}
@test.handle()
async def _(x: dict = Depends(depend)): # 3.在事件处理函数里声明依赖项
print(x["uid"], x["nickname"])
```
## Class 作为依赖
我们可以看下面的代码段:
```python
class A:
def __init__(self):
pass
a = A()
```
在我们实例化类 `A` 的时候,其实我们就在**调用**它,类本身也是一个**可调用对象**,所以类可以被 `Depends` 包裹成为依赖项。
因此我们对第一节的代码段做一下改造:
```python {2,7-10,13}
from nonebot import on_command
from nonebot.params import Depends # 1.引用 Depends
from nonebot.adapters.onebot.v11 import MessageEvent
test = on_command("123")
class DependClass: # 2.编写依赖类
def __init__(self, event: MessageEvent):
self.uid = event.get_user_id()
self.nickname = event.sender.nickname
@test.handle()
async def _(x: DependClass = Depends(DependClass)): # 3.在事件处理函数里声明依赖项
print(x.uid, x.nickname)
```
依然可以用三步说明如何用类作为依赖项:
1. 引用 `Depends`
2. 编写依赖类。类的 `__init__` 函数可以接收 `bot`, `event`, `state` 等参数,在这里我们接受了 `event`,并以 `onebot``MessageEvent` 作为类型标注。
3. 在事件处理函数中声明依赖项。当用类作为依赖项时,它会是一个对应的实例,在这里 `x` 就是 `DependClass` 实例。
### 另一种依赖项声明方式
当使用类作为依赖项时,`Depends` 的参数可以为空,`NoneBot2` 会根据参数的类型标注进行推断并进行依赖注入。
```python
@test.handle()
async def _(x: DependClass = Depends()): # 在事件处理函数里声明依赖项
print(x.uid, x.nickname)
```
## 生成器作为依赖
:::warning
`yield` 语句只能写一次,否则会引发异常。
如果对此有疑问并想探究原因,可以看 [contextmanager](https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.contextmanager) 和 [asynccontextmanager](https://docs.python.org/zh-cn/3/library/contextlib.html#contextlib.asynccontextmanager) 文档,实际上,`Nonebot2` 的内部就使用了这两个装饰器。
:::
:::tips
生成器是 `Python` 高级特性,如果你对此处文档感到疑惑那说明暂时你还用不上这个功能。
:::
`FastAPI` 一样,`NoneBot2` 的依赖注入支持依赖项在事件处理结束后进行一些额外的工作,比如数据库 session 或者网络 IO 的关闭,互斥锁的解锁等等。
要实现上述功能,我们可以用生成器函数作为依赖项,我们用 `yield` 关键字取代 `return` 关键字,并在 `yield` 之后进行额外的工作。
我们可以看下述代码段, 使用 `httpx.AsyncClient` 异步网络 IO
```python {3,7-10,13}
import httpx
from nonebot import on_command
from nonebot.params import Depends # 1.引用 Depends
test = on_command("123")
async def get_client(): # 2.编写异步生成器函数
async with httpx.AsyncClient() as client:
yield client
print("调用结束")
@test.handle()
async def _(x: httpx.AsyncClient = Depends(get_client)): # 3.在事件处理函数里声明依赖项
resp = await x.get("https://v2.nonebot.dev")
# do something
```
我们用 `yield` 代码段作为生成器函数的“返回”,在事件处理函数里用返回出来的 `client` 做自己需要的工作。在 `NoneBot2` 结束事件处理时,会执行 `yield` 之后的代码。
## 创造可调用对象作为依赖
:::tips
魔法方法 `__call__``Python` 高级特性,如果你对此处文档感到疑惑那说明暂时你还用不上这个功能。
:::
`Python` 的里,类的 `__call__` 方法会让类的实例变成**可调用对象**,我们可以利用这个魔法方法做一个简单的尝试:
```python{3,9-14,16,19}
from typing import Type
from nonebot.log import logger
from nonebot.params import Depends # 1.引用 Depends
from nonebot import on_command
from nonebot.adapters.onebot.v11 import MessageEvent, GroupMessageEvent
test = on_command("123")
class EventChecker: # 2.编写需要的类
def __init__(self, EventClass: Type[MessageEvent]):
self.event_class = EventClass
def __call__(self, event: MessageEvent) -> bool:
return isinstance(event, self.event_class)
checker = EventChecker(GroupMessageEvent) # 3.将类实例化
@test.handle()
async def _(x: bool = Depends(checker)): # 4.在事件处理函数里声明依赖项
if x:
print("这是群聊消息")
else:
print("这不是群聊消息")
```
这是判断 `onebot` 的消息事件是不是群聊消息事件的一个例子,我们可以用四步来说明这个例子:
1. 引用 `Depends`
2. 编写需要的类。类的 `__init__` 函数接收参数 `EventClass`,它将接收事件类本身。类的 `__call__` 函数将接受消息事件对象,并返回一个 `bool` 类型的判定结果。
3. 将类实例化。我们传入群聊消息事件作为参数实例化 `checker`
4. 在事件处理函数里声明依赖项。`NoneBot2` 将会调用 `checker``__call__` 方法,返回给参数 `x` 相应的判断结果。

View File

@ -1,76 +0,0 @@
---
sidebar_position: 2
description: 重载事件处理函数
options:
menu:
weight: 61
category: advanced
---
# 事件处理函数重载
当我们在编写 NoneBot2 应用时,常常会遇到这样一个问题:该怎么让同一类型的不同事件执行不同的响应逻辑?又或者如何让不同的 `bot` 针对同一类型的事件作出不同响应?
针对这个问题, NoneBot2 提供一个便捷而高效的解决方案:事件处理函数重载机制。简单地说,`handler`(事件处理函数)会根据其参数的 `type hints`[PEP484 类型标注](https://www.python.org/dev/peps/pep-0484/))来对相对应的 `bot``event` 进行响应,并且会忽略不符合其参数类型标注的情况。
<!-- 必须要注意的是,该机制利用了 `inspect` 标准库获取到了事件处理函数的 `signature`(签名),进一步获取到参数名称和类型标注。故而,我们在编写 `handler` 时,参数的名称和类型标注必须要符合 `T_Handler` 规定,详情可以参看**指南**中的[事件处理](../../guide/creating-a-handler)。 -->
:::tip 提示
如果想了解更多关于 `inspect` 标准库的信息,可以查看[官方文档](https://docs.python.org/zh-cn/3.9/library/inspect.html)。
:::
下面,我们会以 OneBot 适配器中的群聊消息事件和私聊消息事件为例,对该机制的应用进行简单的介绍。
## 一个例子
首先,我们需要导入需要的方法、类型。
```python
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent, PrivateMessageEvent
```
之后,我们可以注册一个 `Matcher` 来响应消息事件。
```python
matcher = on_command("test_overload")
```
最后,我们编写不同的 `handler` 并编写不同的类型标注来实现事件处理函数重载:
```python
@matcher.handle()
async def _(bot: Bot, event: GroupMessageEvent):
await matcher.send("群聊消息事件响应成功!")
@matcher.handle()
async def _(bot: Bot, event: PrivateMessageEvent):
await matcher.send("私聊消息事件响应成功!")
```
此时,我们可以在群聊或私聊中对我们的机器人发送 `test_overload`,它会在不同的场景做出不同的应答。
这样一个简单的事件处理函数重载就完成了。
## 进阶
事件处理函数重载机制同样支持被 `matcher.got` 等装饰器装饰的函数。例如:
```python
@matcher.got("key1", prompt="群事件提问")
async def _(bot: Bot, event: GroupMessageEvent):
await matcher.send("群聊消息事件响应成功!")
@matcher.got("key2", prompt="私聊事件提问")
async def _(bot: Bot, event: PrivateMessageEvent):
await matcher.send("私聊消息事件响应成功!")
```
只有触发事件符合的函数才会触发装饰器。
:::warning 注意
bot 和 event 参数具有最高的检查优先级,因此,如果参数类型不符合,所有的依赖项 `Depends` 等都不会被执行。
:::

Binary file not shown.

Before

Width:  |  Height:  |  Size: 376 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 128 KiB

View File

@ -1,95 +0,0 @@
---
sidebar_position: 3
description: 自定义事件响应器的响应权限
options:
menu:
weight: 40
category: advanced
---
# 权限控制
**权限控制**是机器人在实际应用中需要解决的重点问题之一NoneBot2 提供了灵活的权限控制机制——`Permission`,接下来我们将简单说明。
## 应用
如同 `Rule` 一样,`Permission` 可以在[定义事件响应器](../tutorial/plugin/create-matcher.md)时添加 `permission` 参数来加以应用,这样 NoneBot2 会在事件响应时检测事件主体的权限。下面我们以 `SUPERUSER` 为例,对该机制的应用做一下介绍。
```python
from nonebot.permission import SUPERUSER
from nonebot import on_command
matcher = on_command("测试超管", permission=SUPERUSER)
@matcher.handle()
async def _():
await matcher.send("超管命令测试成功")
@matcher.got("key1", "超管提问")
async def _():
await matcher.send("超管命令 got 成功")
```
在这段代码中,我们事件响应器指定了 `SUPERUSER` 这样一个权限,那么机器人只会响应超级管理员的 `测试超管` 命令,并且会响应该超级管理员的连续对话。
:::tip 提示
在这里需要强调的是,`Permission` 与 `Rule` 的表现并不相同, `Rule` 只会在初次响应时生效,在余下的对话中并没有限制事件;但是 `Permission` 会持续生效,在连续对话中一直对事件主体加以限制。
:::
## 进阶
`Permission` 除了可以在注册事件响应器时加以应用,还可以在编写事件处理函数 `handler` 时主动调用,我们可以利用这个特性在一个 `handler` 里对不同权限的事件主体进行区别响应,下面我们以 OneBot 适配器中的 `GROUP_ADMIN`(普通管理员非群主)和 `GROUP_OWNER` 为例,说明下怎么进行主动调用。
```python
from nonebot import on_command
from nonebot.adapters.onebot.v11 import Bot, GroupMessageEvent
from nonebot.adapters.onebot.v11 import GROUP_ADMIN, GROUP_OWNER
matcher = on_command("测试权限")
@matcher.handle()
async def _(bot: Bot, event: GroupMessageEvent):
if await GROUP_ADMIN(bot, event):
await matcher.send("管理员测试成功")
elif await GROUP_OWNER(bot, event):
await matcher.send("群主测试成功")
else:
await matcher.send("群员测试成功")
```
在这段代码里,我们并没有对命令的权限指定,这个命令会响应所有在群聊中的 `测试权限` 命令,但是在 `handler` 里,我们对两个 `Permission` 进行主动调用,从而可以对不同的角色进行不同的响应。
## 自定义
如同 `Rule` 一样,`Permission` 也是由非负数个 `PermissionChecker` 组成的,但只需其中一个返回 `True` 时就会匹配成功。下面是自定义 `PermissionChecker``Permission` 的示例:
```python
from nonebot.adapters import Bot, Event
from nonebot.permission import Permission
async def async_checker(bot: Bot, event: Event) -> bool:
return True
def sync_checker(bot: Bot, event: Event) -> bool:
return True
def check(arg1, arg2):
async def _checker(bot: Bot, event: Event) -> bool:
return bool(arg1 + arg2)
return Permission(_checker)
```
`Permission``PermissionChecker` 之间可以使用 `|`(或符号)互相组合:
```python
from nonebot.permission import Permission
Permission(async_checker1) | sync_checker | async_checker2
```
同样地,如果想用 `Permission(*checkers)` 包裹构造 `Permission`,函数必须是异步的;但是在利用 `|`或符号连接构造时NoneBot2 会自动包裹同步函数为异步函数。

View File

@ -1,72 +0,0 @@
---
sidebar_position: 7
description: 发布插件到 NoneBot2 商店
options:
menu:
weight: 80
category: advanced
---
# 发布插件
## 前注
本章节仅包含插件发布流程指导,插件开发请查阅[**创建插件**](../tutorial/plugin/introduction.md)章节与[**Plugin API 文档**](../api/plugin/index.md)。
## 插件发布流程
### 发布到 PyPI
您可以选择自己喜欢的方式将插件发布到 [**PyPI**](https://pypi.org/),如使用 [**setuptools**](https://pypi.org/project/setuptools/) 或 [**Poetry**](https://pypi.org/project/poetry/)。
发布时,请您为自己的插件取一个清晰易懂的名字。通常而言,一款 NoneBot2 插件名称使用 `nonebot-plugin-` 作为前缀(如`nonebot-plugin-foo`),以 `nonebot_plugin_` 作为包名的前缀(如`nonebot_plugin_foo`),这并非强制规范,而是为了防止与其他 PyPI 包产生冲突,所以我们推荐您在没有特殊需求的情况下这样做。
发布后,请确保您的插件已能公开的从 PyPI 访问到,试着检查您的插件在 PyPI 的地址,如 `https://pypi.org/project/<您的 NoneBot2 插件项目名>`
### 托管您的插件源代码
将插件源代码及相关构建文件(如 `pyproject.toml``setup.py` 等与 PyPI 包构建相关的文件)托管在公开代码仓。
请确保您的代码仓库地址能够被正确的访问,检查您的插件在代码仓的地址,如 `https://github.com/<您的 Github 用户名>/<您的插件 Github 项目名>`
### 申请发布到 NoneBot2 插件商店
完成在 PyPI 的插件发布流程与源代码托管流程后,请您前往 [**NoneBot2 商店**](https://v2.nonebot.dev/store.html)页面,切换到**插件**页签,点击**发布插件**按钮。
![插件发布界面](./images/plugin_store_publish.png)
如图所示,在弹出的插件信息提交表单内,填入您所要发布的相应插件信息:
```text
插件名称:您的 NoneBot2 插件名称
插件介绍:为您的插件提供的简短介绍信息
PyPI 项目名:您的插件所在的 PyPI Project 名,如 nonebot-plugin-xxxx
import 包名:您的插件通过 Python 导入时使用的包名,如 nonebot_plugin_xxxx
仓库/主页:您的插件托管地址,如 https://github.com/<您的 Github 用户名>/nonebot-plugin-xxxx
标签:一个或多个可选颜色的 TAG每填写一个点击添加标签若要删除点击标签即可标签长度不超过 10 字符,标签个数不超过 3 个
特定标签内容 Adapter点击 Type 的 Adapter将创建一个 a: 开头的标签,填入内容以指定您插件使用的 adapter
特定标签内容 Topic点击 Type 的 Topic将创建一个 t: 开头的标签,填入内容以指定您插件的主题
```
![插件信息填写](./images/plugin_store_publish_2.png)
完成填写后,请点击**发布**按钮,这将自动在[**NoneBot2**](https://github.com/nonebot/nonebot2)代码仓内创建发布您的插件的对应 Issue。
### 等待插件发布处理
您的插件发布 Issue 创建后,将会经过 _NoneBot2 Publish Bot_ 的检查,以确保插件信息正确无误。
若您的插件发布 Issue 未通过检查,您可以**直接修改** Issue 内容以更新发布请求。_NoneBot2 Publish Bot_ 在您修改 Issue 内容后将会自动重新执行检查。您无需关闭、重新提交发布申请。
之后NoneBot2 的维护者们将会对插件进行进一步的检查,以确保用户能够正常安装并使用该插件。
完成这些步骤后,您的插件将会被合并到 [**NoneBot2 商店**](https://v2.nonebot.dev/store.html),而您也将成为 [**NoneBot2 贡献者**](https://github.com/nonebot/nonebot2/graphs/contributors)中的一员。
## 完成
恭喜您,经过上述的发布流程,您的插件已经成功发布到 NoneBot2 商店了。
此时,您可以在 [**NoneBot2 商店**](https://v2.nonebot.dev/store.html)的插件页签查找到您的插件。同时,欢迎您成为 [**NoneBot2 贡献者**](https://github.com/nonebot/nonebot2/graphs/contributors)
**Congratulations!**

View File

@ -1,75 +0,0 @@
---
sidebar_position: 2
description: 自定义事件响应器的响应规则
options:
menu:
weight: 30
category: advanced
---
# 自定义匹配规则
机器人在实际应用中往往会接收到多种多样的事件类型NoneBot2 提供了可自定义的匹配规则 ── `Rule`。在[定义事件响应器](../tutorial/plugin/create-matcher.md#创建事件响应器)中,已经介绍了多种内置的事件响应器,接下来我们将说明自定义匹配规则的基本用法。
## 创建匹配规则
匹配规则可以是一个 `Rule` 对象,也可以是一个 `RuleChecker` 类型。`Rule` 是多个 `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查通过时匹配成功。`RuleChecker` 是一个返回值为 `Bool` 类型的依赖函数,即,`RuleChecker` 支持依赖注入。
### 创建 `RuleChecker`
```python {1-2}
async def user_checker(event: Event) -> bool:
return event.get_user_id() == "123123"
matcher = on_message(rule=user_checker)
```
在上面的代码中,我们定义了一个函数 `user_checker`,它检查事件的用户 ID 是否等于 `"123123"`。这个函数 `user_checker` 即为一个 `RuleChecker`
### 创建 `Rule`
```python {1-2,4-5,7}
async def user_checker(event: Event) -> bool:
return event.get_user_id() == "123123"
async def message_checker(event: Event) -> bool:
return event.get_plaintext() == "hello"
rule = Rule(user_checker, message_checker)
matcher = on_message(rule=rule)
```
在上面的代码中,我们定义了两个函数 `user_checker``message_checker`,它们检查事件的用户 ID 是否等于 `"123123"`,以及消息的内容是否等于 `"hello"`。随后,我们定义了一个 `Rule` 对象,它包含了这两个函数。
## 注册匹配规则
在[定义事件响应器](../tutorial/plugin/create-matcher.md#创建事件响应器)中,我们已经了解了如何事件响应器的组成。现在,我们仅需要将匹配规则注册到事件响应器中。
```python {4}
async def user_checker(event: Event) -> bool:
return event.get_user_id() == "123123"
matcher = on_message(rule=user_checker)
```
在定义事件响应器的辅助函数中,都有一个 `rule` 参数,用于指定自定义的匹配规则。辅助函数会为你将自定义匹配规则与内置规则组合,并注册到事件响应器中。
## 合并匹配规则
在定义匹配规则时,我们往往希望将规则进行细分,来更好地复用规则。而在使用时,我们需要合并多个规则。除了使用 `Rule` 对象来组合多个 `RuleChecker` 外,我们还可以对 `Rule` 对象进行合并。
```python {4-6}
rule1 = Rule(foo_checker)
rule2 = Rule(bar_checker)
rule = rule1 & rule2
rule = rule1 & bar_checker
rule = foo_checker & rule2
```
同时,你也无需担心合并了一个 `None` 值,`Rule` 会忽略 `None` 值。
```python
assert (rule & None) is rule
```

View File

@ -1,171 +0,0 @@
---
sidebar_position: 4
description: 在 NoneBot2 框架中添加 Hook 函数
options:
menu:
weight: 50
category: advanced
---
# 钩子函数
[钩子编程](https://zh.wikipedia.org/wiki/%E9%92%A9%E5%AD%90%E7%BC%96%E7%A8%8B)
> 钩子编程hooking也称作“挂钩”是计算机程序设计术语指通过拦截软件模块间的函数调用、消息传递、事件传递来修改或扩展操作系统、应用程序或其他软件组件的行为的各种技术。处理被拦截的函数调用、事件、消息的代码被称为钩子hook
在 NoneBot2 中有一系列预定义的钩子函数,分为两类:**全局钩子函数**和**事件钩子函数**,这些钩子函数可以用装饰器的形式来使用。
## 全局钩子函数
全局钩子函数是指 NoneBot2 针对其本身运行过程的钩子函数。
这些钩子函数是由其后端驱动 `Driver` 来运行的,故需要先获得全局 `Driver` 对象:
```python
from nonebot import get_driver
driver=get_driver()
```
共分为六种函数:
### 启动准备
这个钩子函数会在 NoneBot2 启动时运行。
```python
@driver.on_startup
async def do_something():
pass
```
### 终止处理
这个钩子函数会在 NoneBot2 终止时运行。
```python
@driver.on_shutdown
async def do_something():
pass
```
### Bot 连接处理
这个钩子函数会在 `Bot` 通过 websocket 连接到 NoneBot2 时运行。
```python
@driver.on_bot_connect
async def do_something(bot: Bot):
pass
```
### bot 断开处理
这个钩子函数会在 `Bot` 断开与 NoneBot2 的 websocket 连接时运行。
```python
@driver.on_bot_disconnect
async def do_something(bot: Bot):
pass
```
### bot api 调用钩子
这个钩子函数会在 `Bot` 调用 API 时运行。
```python
from nonebot.adapters import Bot
@Bot.on_calling_api
async def handle_api_call(bot: Bot, api: str, data: Dict[str, Any]):
pass
```
### bot api 调用后钩子
这个钩子函数会在 `Bot` 调用 API 后运行。
```python
from nonebot.adapters import Bot
@Bot.on_called_api
async def handle_api_result(bot: Bot, exception: Optional[Exception], api: str, data: Dict[str, Any], result: Any):
pass
```
## 事件钩子函数
这些钩子函数指的是影响 NoneBot2 进行**事件处理**的函数, 这些函数可以认为跟普通的事件处理函数一样,接受相应的参数。
:::tip 提示
关于**事件处理**的流程,可以在[这里](./README.md)查阅。
:::
:::warning
1.在事件处理钩子函数中,与 `matcher` 运行状态相关的函数将不可用,如 `matcher.finish()`
2.如果需要在事件处理钩子函数中打断整个对话的执行,请参考以下范例:
```python
from nonebot.exception import IgnoredException
@event_preprocessor
async def do_something():
raise IgnoredException("reason")
```
:::
共分为四种函数:
### 事件预处理
这个钩子函数会在 `Event` 上报到 NoneBot2 时运行
```python
from nonebot.message import event_preprocessor
@event_preprocessor
async def do_something():
pass
```
### 事件后处理
这个钩子函数会在 NoneBot2 处理 `Event` 后运行
```python
from nonebot.message import event_postprocessor
@event_postprocessor
async def do_something():
pass
```
### 运行预处理
这个钩子函数会在 NoneBot2 运行 `matcher` 前运行。
```python
from nonebot.message import run_preprocessor
@run_preprocessor
async def do_something():
pass
```
### 运行后处理
这个钩子函数会在 NoneBot2 运行 `matcher` 后运行。
```python
from nonebot.message import run_postprocessor
@run_postprocessor
async def do_something():
pass
```

View File

@ -1,147 +0,0 @@
---
sidebar_position: 1
description: 在 NoneBot2 中使用定时任务
options:
menu:
weight: 20
category: advanced
---
# 定时任务
[APScheduler](https://apscheduler.readthedocs.io/en/3.x/) —— Advanced Python Scheduler
> Advanced Python Scheduler (APScheduler) is a Python library that lets you schedule your Python code to be executed later, either just once or periodically. You can add new jobs or remove old ones on the fly as you please. If you store your jobs in a database, they will also survive scheduler restarts and maintain their state. When the scheduler is restarted, it will then run all the jobs it should have run while it was offline.
## 从 NoneBot v1 迁移
`APScheduler` 作为 NoneBot v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。NoneBot2 已将 `APScheduler` 独立为 nonebot_plugin_apscheduler 插件,你可以在[商店](/store)中找到它。
相比于 NoneBot v1NoneBot v2 只需要安装插件并修改 `scheduler` 的导入方式即可完成迁移。
## 安装插件
### 通过 nb-cli
如正在使用 nb-cli 构建项目,你可以从插件市场复制安装命令或手动输入以下命令以添加 nonebot_plugin_apscheduler。
```bash
nb plugin install nonebot_plugin_apscheduler
```
:::tip 提示
nb-cli 默认通过 PyPI 安装,你可以添加命令参数 `-i [mirror]``--index [mirror]` 以使用镜像源安装。
:::
### 通过 Poetry
执行以下命令以添加 nonebot_plugin_apscheduler
```bash
poetry add nonebot-plugin-apscheduler
```
:::tip 提示
由于稍后我们将使用 `nonebot.require()` 方法进行声明依赖,所以无需额外的 `nonebot.load_plugin()`
:::
## 快速上手
1. 在需要设置定时任务的插件中,通过 `nonebot.require` 声明插件依赖
2. 从 nonebot_plugin_apscheduler 导入 `scheduler` 对象
3. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务
将上述步骤归纳为最小实现的代码如下:
```python {3,5}
from nonebot import require
require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler 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")
```
## 分步进行
### 导入 scheduler 对象
为了使插件能够实现定时任务,需要先将 `scheduler` 对象导入插件。
NoneBot2 提供了 `nonebot.require` 方法来实现声明插件依赖,确保 `nonebot_plugin_apscheduler` 插件可以在使用之前被导入。声明完成即可直接通过 import 导入 `scheduler` 对象。
NoneBot2 使用的 `scheduler` 对象为 `AsyncIOScheduler`
```python {3,5}
from nonebot import require
require("nonebot_plugin_apscheduler")
from nonebot_plugin_apscheduler import scheduler
```
### 编写定时任务
由于本部分为标准的通过 `APScheduler` 配置定时任务,有关指南请参阅 [APScheduler 官方文档](https://apscheduler.readthedocs.io/en/3.x/userguide.html#adding-jobs)。
### 配置插件选项
根据项目的 `.env` 文件设置,向 `.env.*``bot.py` 文件添加 nonebot_plugin_apscheduler 的可选配置项
:::warning 注意
`.env.*` 文件的编写应遵循 NoneBot2 对 `.env.*` 文件的编写要求
:::
#### `apscheduler_autostart`
类型:`bool`
默认值:`True`
是否自动启动 `APScheduler`
对于大多数情况,我们需要在 NoneBot2 项目被启动时启动定时任务,则此处设为 `true`
##### 在 `.env` 中添加
```bash
APSCHEDULER_AUTOSTART=true
```
##### 在 `bot.py` 中添加
```python
nonebot.init(apscheduler_autostart=True)
```
#### `apscheduler_config`
类型:`dict`
默认值:`{"apscheduler.timezone": "Asia/Shanghai"}`
`APScheduler` 相关配置。修改/增加其中配置项需要确保 `prefix: apscheduler`
对于 `APScheduler` 的相关配置,请参阅 [scheduler-config](https://apscheduler.readthedocs.io/en/3.x/userguide.html#scheduler-config) 和 [BaseScheduler](https://apscheduler.readthedocs.io/en/3.x/modules/schedulers/base.html#apscheduler.schedulers.base.BaseScheduler)
> 官方文档在绝大多数时候能提供最准确和最具时效性的指南
##### 在 `.env` 中添加
```bash
APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"}
```
##### 在 `bot.py` 中添加
```python
nonebot.init(apscheduler_config={
"apscheduler.timezone": "Asia/Shanghai"
})
```

View File

@ -1,106 +0,0 @@
---
sidebar_position: 1
description: 使用 NoneBug 测试机器人
slug: /advanced/unittest/
options:
menu:
weight: 70
category: advanced
---
import CodeBlock from "@theme/CodeBlock";
# 单元测试
[单元测试](https://zh.wikipedia.org/wiki/%E5%8D%95%E5%85%83%E6%B5%8B%E8%AF%95)
> 在计算机编程中单元测试Unit Testing又称为模块测试是针对程序模块软件设计的最小单位来进行正确性检验的测试工作。
NoneBot2 使用 [Pytest](https://docs.pytest.org) 单元测试框架搭配 [NoneBug](https://github.com/nonebot/nonebug) 插件进行单元测试,通过直接与事件响应器/适配器等交互简化测试流程,更易于编写。
## 安装 NoneBug
安装 NoneBug 时Pytest 会作为依赖被一起安装。
要运行 NoneBug还需要额外安装 Pytest 异步插件 `pytest-asyncio` 或 `anyio`,文档将以 `pytest-asyncio` 为例。
```bash
poetry add nonebug pytest-asyncio --dev
# 也可以通过 pip 安装
pip install nonebug pytest-asyncio
```
:::tip 提示
建议首先阅读 [Pytest 文档](https://docs.pytest.org) 理解相关术语。
:::
## 加载插件
我们可以使用 Pytest **Fixtures** 来加载插件,下面是一个示例:
```python title=conftest.py
from pathlib import Path
from typing import TYPE_CHECKING, Set
import pytest
if TYPE_CHECKING:
from nonebot.plugin import Plugin
@pytest.fixture
def load_plugins(nonebug_init: None) -> Set["Plugin"]:
import nonebot # 这里的导入必须在函数内
# 加载插件
return nonebot.load_plugins("awesome_bot/plugins")
```
此 Fixture 的 [`nonebug_init`](https://github.com/nonebot/nonebug/blob/master/nonebug/fixture.py) 形参也是一个 Fixture用于初始化 NoneBug。
Fixture 名称 `load_plugins` 可以修改为其他名称,文档以 `load_plugins` 为例。需要加载插件时,在测试函数添加形参 `load_plugins` 即可。加载完成后即可使用 `import` 导入事件响应器。
## 测试流程
Pytest 会在函数开始前通过 Fixture `app`(nonebug_app) **初始化 NoneBug** 并返回 `App` 对象。
:::warning 警告
所有从 `nonebot` 导入模块的函数都需要首先初始化 NoneBug App否则会发生不可预料的问题。
在每个测试函数结束时NoneBug 会自动销毁所有与 NoneBot 相关的资源。所有与 NoneBot 相关的 import 应在函数内进行导入。
:::
随后使用 `test_matcher` 等测试方法获取到 `Context` 上下文,通过上下文管理提供的方法(如 `should_call_send` 等)预定义行为。
在上下文管理器关闭时,`Context` 会调用 `run_test` 方法按照预定义行为对事件响应器进行断言(如:断言事件响应和 API 调用等)。
## 测试样例
:::tip 提示
将从 `utils` 导入的 `make_fake_message``make_fake_event` 替换为对应平台的消息/事件类型。
将 `load_example` 替换为加载插件的 Fixture 名称。
:::
使用 NoneBug 的 `test_matcher` 可以模拟出一个事件流程。如下是一个简单的示例:
import WeatherSource from "!!raw-loader!@site/../tests/examples/weather.py";
import WeatherTest from "!!raw-loader!@site/../tests/test_examples/test_weather.py";
<CodeBlock className="language-python" title="test_weather.py">
{WeatherTest}
</CodeBlock>
<details>
<summary>示例插件</summary>
<CodeBlock className="language-python" title="examples/weather.py">
{WeatherSource}
</CodeBlock>
</details>
在测试用例编写完成后 ,可以使用下面的命令运行单元测试。
```bash
pytest test_weather.py
```

View File

@ -1,4 +0,0 @@
{
"label": "单元测试",
"position": 6
}

View File

@ -1,162 +0,0 @@
---
sidebar_position: 4
description: 测试适配器
---
# 测试适配器
通常来说,测试适配器需要测试这三项。
1. 测试连接
2. 测试事件转化
3. 测试 API 调用
## 注册适配器
任何的适配器都需要注册才能起作用。
我们可以使用 Pytest 的 Fixtures在测试开始前初始化 NoneBot 并**注册适配器**。
我们假设适配器为 `nonebot.adapters.test`
```python {20,21} title=conftest.py
from pathlib import Path
import pytest
from nonebug import App
# 如果适配器采用 nonebot.adapters monospace 则需要使用此hook方法正确添加路径
@pytest.fixture
def import_hook():
import nonebot.adapters
nonebot.adapters.__path__.append( # type: ignore
str((Path(__file__).parent.parent / "nonebot" / "adapters").resolve())
)
@pytest.fixture
async def init_adapter(app: App, import_hook):
import nonebot
from nonebot.adapters.test import Adapter
driver = nonebot.get_driver()
driver.register_adapter(Adapter)
```
## 测试连接
任何的适配器的连接方式主要有以下 4 种:
1. 反向 HTTPWebHook
2. 反向 WebSocket
3. ~~正向 HTTP尚未实现~~
4. ~~正向 WebSocket尚未实现~~
NoneBug 的 `test_server` 方法可以供我们测试反向连接方式。
`test_server``get_client` 方法可以获取 HTTP/WebSocket 客户端。
我们假设适配器 HTTP 上报地址为 `/test/http`,反向 WebSocket 地址为 `/test/ws`,上报机器人 ID
使用请求头 `Bot-ID` 来演示如何通过 NoneBug 测试适配器。
```python {8,16,17,19-22,26,34,36-39} title=test_connection.py
from pathlib import Path
import pytest
from nonebug import App
@pytest.mark.asyncio
@pytest.mark.parametrize(
"endpoints", ["/test/http"]
)
async def test_http(app: App, init_adapter, endpoints: str):
import nonebot
async with app.test_server() as ctx:
client = ctx.get_client()
body = {"post_type": "test"}
headers = {"Bot-ID": "test"}
resp = await client.post(endpoints, json=body, headers=headers)
assert resp.status_code == 204 # 检测状态码是否正确
bots = nonebot.get_bots()
assert "test" in bots # 检测是否连接成功
@pytest.mark.asyncio
@pytest.mark.parametrize(
"endpoints", ["/test/ws"]
)
async def test_ws(app: App, init_adapter, endpoints: str):
import nonebot
async with app.test_server() as ctx:
client = ctx.get_client()
headers = {"Bot-ID": "test"}
async with client.websocket_connect(endpoints, headers=headers) as ws:
bots = nonebot.get_bots()
assert "test" in bots # 检测是否连接成功
```
## 测试事件转化
事件转化就是将原始数据反序列化为 `Event` 对象的过程。
测试事件转化就是测试反序列化是否按照预期转化为对应 `Event` 类型。
下面将以 `dict_to_event` 作为反序列化方法,`type` 为 `test` 的事件类型为 `TestEvent` 来演示如何测试事件转化。
```python {8,9} title=test_event.py
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_event(app: App, init_adapter):
from nonebot.adapters.test import Adapter, TestEvent
event = Adapter.dict_to_event({"post_type": "test"}) # 反序列化原始数据
assert isinstance(event, TestEvent) # 断言类型是否与预期一致
```
## 测试 API 调用
将消息序列化为原始数据并由适配器发送到协议端叫做 API 调用。
测试 API 调用就是调用 API 并验证返回与预期返回是否一致。
```python {16-18,23-32} title=test_call_api.py
import asyncio
from pathlib import Path
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_ws(app: App, init_adapter):
import nonebot
async with app.test_server() as ctx:
client = ctx.get_client()
headers = {"Bot-ID": "test"}
async def call_api():
bot = nonebot.get_bot("test")
return await bot.test_api()
async with client.websocket_connect("/test/ws", headers=headers) as ws:
task = asyncio.create_task(call_api())
# received = await ws.receive_text()
# received = await ws.receive_bytes()
received = await ws.receive_json()
assert received == {"action": "test_api"} # 检测调用是否与预期一致
response = {"result": "test"}
# await ws.send_text(...)
# await ws.send_bytes(...)
await ws.send_json(response, mode="bytes")
result = await task
assert result == response # 检测返回是否与预期一致
```

View File

@ -1,122 +0,0 @@
---
sidebar_position: 3
description: 测试事件响应处理
---
# 测试事件响应处理行为
除了 `send`,事件响应器还有其他的操作,我们也需要对它们进行测试,下面我们将定义如下事件响应器操作的预期行为对对应的事件响应器操作进行测试。
## should_finished
定义事件响应器预期结束当前事件的整个处理流程。
适用事件响应器操作:[`finish`](../../tutorial/plugin/matcher-operation.md#finish)。
<!-- markdownlint-disable MD033 -->
<details>
<summary>示例插件</summary>
```python title=example.py
from nonebot import on_message
foo = on_message()
@foo.handle()
async def _():
await foo.finish("test")
```
</details>
```python {13}
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_matcher(app: App, load_plugins):
from awesome_bot.plugins.example import foo
async with app.test_matcher(foo) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_call_send(event, "test", True)
ctx.should_finished()
```
## should_paused
定义事件响应器预期立即结束当前事件处理依赖并等待接收一个新的事件后进入下一个事件处理依赖。
适用事件响应器操作:[`pause`](../../tutorial/plugin/matcher-operation.md#pause)。
<details>
<summary>示例插件</summary>
```python title=example.py
from nonebot import on_message
foo = on_message()
@foo.handle()
async def _():
await foo.pause("test")
```
</details>
```python {13}
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_matcher(app: App, load_plugins):
from awesome_bot.plugins.example import foo
async with app.test_matcher(foo) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_call_send(event, "test", True)
ctx.should_paused()
```
## should_rejected
定义事件响应器预期立即结束当前事件处理依赖并等待接收一个新的事件后再次执行当前事件处理依赖。
适用事件响应器操作:[`reject`](../../tutorial/plugin/matcher-operation.md#reject)
、[`reject_arg`](../../tutorial/plugin/matcher-operation.md#reject_arg)
和 [`reject_receive`](../../tutorial/plugin/matcher-operation.md#reject_receive)。
<details>
<summary>示例插件</summary>
```python title=example.py
from nonebot import on_message
foo = on_message()
@foo.got("key")
async def _():
await foo.reject("test")
```
</details>
```python {13}
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_matcher(app: App, load_plugins):
from awesome_bot.plugins.example import foo
async with app.test_matcher(foo) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_call_send(event, "test", True)
ctx.should_rejected()
```

View File

@ -1,159 +0,0 @@
---
sidebar_position: 2
description: 测试事件响应和 API 调用
---
# 测试事件响应和 API 调用
事件响应器通过 `Rule``Permission` 来判断当前事件是否触发事件响应器,通过 `send` 发送消息或使用 `call_api` 调用平台 API这里我们将对上述行为进行测试。
## 定义预期响应行为
NoneBug 提供了六种定义 `Rule``Permission` 的预期行为的方法来进行测试:
- `should_pass_rule`
- `should_not_pass_rule`
- `should_ignore_rule`
- `should_pass_permission`
- `should_not_pass_permission`
- `should_ignore_permission`
以下为示例代码
<!-- markdownlint-disable MD033 -->
<details>
<summary>示例插件</summary>
```python title=example.py
from nonebot import on_message
async def always_pass():
return True
async def never_pass():
return False
foo = on_message(always_pass)
bar = on_message(never_pass, permission=never_pass)
```
</details>
```python {12,13,19,20,27,28}
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_matcher(app: App, load_plugins):
from awesome_bot.plugins.example import foo, bar
async with app.test_matcher(foo) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_pass_rule()
ctx.should_pass_permission()
async with app.test_matcher(bar) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_not_pass_rule()
ctx.should_not_pass_permission()
# 如需忽略规则/权限不通过
async with app.test_matcher(bar) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_ignore_rule()
ctx.should_ignore_permission()
```
## 定义预期 API 调用行为
在[事件响应器操作](../../tutorial/plugin/matcher-operation.md)和[调用平台 API](../../tutorial/call-api.md) 中,我们已经了解如何向发送消息或调用平台 `API`。接下来对 [`send`](../../tutorial/plugin/matcher-operation.md#send) 和 [`call_api`](../../api/adapters/index.md#Bot-call_api) 进行测试。
### should_call_send
定义事件响应器预期发送消息,包括使用 [`send`](../../tutorial/plugin/matcher-operation.md#send)、[`finish`](../../tutorial/plugin/matcher-operation.md#finish)、[`pause`](../../tutorial/plugin/matcher-operation.md#pause)、[`reject`](../../tutorial/plugin/matcher-operation.md#reject) 以及 [`got`](../../tutorial/plugin/create-handler.md#使用-got-装饰器) 的 prompt 等方法发送的消息。
`should_call_send` 需要提供四个参数:
- `event`:事件对象。
- `message`:预期的消息对象,可以是`str`、[`Message`](../../api/adapters/index.md#Message) 或 [`MessageSegment`](../../api/adapters/index.md#MessageSegment)。
- `result``send` 的返回值,将会返回给插件。
- `**kwargs``send` 方法的额外参数。
<details>
<summary>示例插件</summary>
```python title=example.py
from nonebot import on_message
foo = on_message()
@foo.handle()
async def _():
await foo.send("test")
```
</details>
```python {12}
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_matcher(app: App, load_plugins):
from awesome_bot.plugins.example import foo
async with app.test_matcher(foo) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_call_send(event, "test", True)
```
### should_call_api
定义事件响应器预期调用机器人 API 接口,包括使用 `call_api` 或者直接使用 `bot.some_api` 的方式调用 API。
`should_call_api` 需要提供四个参数:
- `api`API 名称。
- `data`:预期的请求数据。
- `result``call_api` 的返回值,将会返回给插件。
- `**kwargs``call_api` 方法的额外参数。
<details>
<summary>示例插件</summary>
```python
from nonebot import on_message
from nonebot.adapters import Bot
foo = on_message()
@foo.handle()
async def _(bot: Bot):
await bot.example_api(test="test")
```
</details>
```python {12}
import pytest
from nonebug import App
@pytest.mark.asyncio
async def test_matcher(app: App, load_plugins):
from awesome_bot.plugins.example import foo
async with app.test_matcher(foo) as ctx:
bot = ctx.create_bot()
event = make_fake_event()() # 此处替换为平台事件
ctx.receive_event(bot, event)
ctx.should_call_api("example_api", {"test": "test"}, True)
```

View File

@ -1,3 +0,0 @@
{
"position": 15
}

View File

@ -1,619 +0,0 @@
---
sidebar_position: 0
description: nonebot.adapters 模块
---
# nonebot.adapters
本模块定义了协议适配基类,各协议请继承以下基类。
使用 [Driver.register_adapter](../drivers/index.md#Driver-register_adapter) 注册适配器。
## _abstract class_ `Bot(adapter, self_id)` {#Bot}
- **说明**
Bot 基类。
用于处理上报消息,并提供 API 调用接口。
- **参数**
- `adapter` (Adapter): 协议适配器实例
- `self_id` (str): 机器人 ID
### _property_ `config` {#Bot-config}
- **类型:** [Config](../config.md#Config)
- **说明:** 全局 NoneBot 配置
### _property_ `type` {#Bot-type}
- **类型:** str
- **说明:** 协议适配器名称
### _async method_ `call_api(self, api, **data)` {#Bot-call_api}
- **说明**
调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用
- **参数**
- `api` (str): API 名称
- `**data` (Any): API 数据
- **返回**
- Any
- **用法**
```python
await bot.call_api("send_msg", message="hello world")
await bot.send_msg(message="hello world")
```
### _classmethod_ `on_called_api(cls, func)` {#Bot-on_called_api}
- **说明**
调用 api 后处理。
钩子函数参数:
- bot: 当前 bot 对象
- exception: 调用 api 时发生的错误
- api: 调用的 api 名称
- data: api 调用的参数字典
- result: api 调用的返回
- **参数**
- `func` ((Bot, Exception | None, str, dict[str, Any], Any) -> Awaitable[Any])
- **返回**
- (Bot, Exception | None, str, dict[str, Any], Any) -> Awaitable[Any]
### _classmethod_ `on_calling_api(cls, func)` {#Bot-on_calling_api}
- **说明**
调用 api 预处理。
钩子函数参数:
- bot: 当前 bot 对象
- api: 调用的 api 名称
- data: api 调用的参数字典
- **参数**
- `func` ((Bot, str, dict[str, Any]) -> Awaitable[Any])
- **返回**
- (Bot, str, dict[str, Any]) -> Awaitable[Any]
### _abstract async method_ `send(self, event, message, **kwargs)` {#Bot-send}
- **说明**
调用机器人基础发送消息接口
- **参数**
- `event` (Event): 上报事件
- `message` (str | Message | MessageSegment): 要发送的消息
- `**kwargs` (Any): 任意额外参数
- **返回**
- Any
## _abstract class_ `Event(**extra_data)` {#Event}
- **说明**
Event 基类。提供获取关键信息的方法,其余信息可直接获取。
- **参数**
- `**extra_data` (Any)
### _abstract method_ `get_event_description(self)` {#Event-get_event_description}
- **说明**
获取事件描述的方法,通常为事件具体内容。
- **返回**
- str
### _abstract method_ `get_event_name(self)` {#Event-get_event_name}
- **说明**
获取事件名称的方法。
- **返回**
- str
### _method_ `get_log_string(self)` {#Event-get_log_string}
- **说明**
获取事件日志信息的方法。
通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 `NoLogException` 异常。
- **返回**
- str
- **异常**
NoLogException
### _abstract method_ `get_message(self)` {#Event-get_message}
- **说明**
获取事件消息内容的方法。
- **返回**
- Message
### _method_ `get_plaintext(self)` {#Event-get_plaintext}
- **说明**
获取消息纯文本的方法。
通常不需要修改,默认通过 `get_message().extract_plain_text` 获取。
- **返回**
- str
### _abstract method_ `get_session_id(self)` {#Event-get_session_id}
- **说明**
获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。
- **返回**
- str
### _abstract method_ `get_type(self)` {#Event-get_type}
- **说明**
获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。
- **返回**
- str
### _abstract method_ `get_user_id(self)` {#Event-get_user_id}
- **说明**
获取事件主体 id 的方法,通常是用户 id 。
- **返回**
- str
### _abstract method_ `is_tome(self)` {#Event-is_tome}
- **说明**
获取事件是否与机器人有关的方法。
- **返回**
- bool
### _classmethod_ `validate(cls, value)` {#Event-validate}
- **参数**
- `value` (Any)
- **返回**
- E
## _abstract class_ `Adapter(driver, **kwargs)` {#Adapter}
- **说明**
协议适配器基类。
通常,在 Adapter 中编写协议通信相关代码,如: 建立通信连接、处理接收与发送 data 等。
- **参数**
- `driver` (nonebot.internal.driver.driver.Driver): [Driver](../drivers/index.md#Driver) 实例
- `**kwargs` (Any): 其他由 [Driver.register_adapter](../drivers/index.md#Driver-register_adapter) 传入的额外参数
### _property_ `config` {#Adapter-config}
- **类型:** [Config](../config.md#Config)
- **说明:** 全局 NoneBot 配置
### _method_ `bot_connect(self, bot)` {#Adapter-bot_connect}
- **说明**
告知 NoneBot 建立了一个新的 [Bot](#Bot) 连接。
当有新的 [Bot](#Bot) 实例连接建立成功时调用。
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot): [Bot](#Bot) 实例
- **返回**
- None
### _method_ `bot_disconnect(self, bot)` {#Adapter-bot_disconnect}
- **说明**
告知 NoneBot [Bot](#Bot) 连接已断开。
当有 [Bot](#Bot) 实例连接断开时调用。
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot): [Bot](#Bot) 实例
- **返回**
- None
### _abstract classmethod_ `get_name(cls)` {#Adapter-get_name}
- **说明**
当前协议适配器的名称
- **返回**
- str
### _async method_ `request(self, setup)` {#Adapter-request}
- **说明**
进行一个 HTTP 客户端请求
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- nonebot.internal.driver.model.Response
### _method_ `setup_http_server(self, setup)` {#Adapter-setup_http_server}
- **说明**
设置一个 HTTP 服务器路由配置
- **参数**
- `setup` (nonebot.internal.driver.model.HTTPServerSetup)
- **返回**
- Unknown
### _method_ `setup_websocket_server(self, setup)` {#Adapter-setup_websocket_server}
- **说明**
设置一个 WebSocket 服务器路由配置
- **参数**
- `setup` (nonebot.internal.driver.model.WebSocketServerSetup)
- **返回**
- Unknown
### _method_ `websocket(self, setup)` {#Adapter-websocket}
- **说明**
建立一个 WebSocket 客户端连接请求
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- AsyncGenerator[nonebot.internal.driver.model.WebSocket, NoneType]
## _abstract class_ `Message(message=None)` {#Message}
- **说明**
消息数组
- **参数**
- `message` (str | NoneType | Iterable[(~ TMS)] | (~ TMS)): 消息内容
### _method_ `append(self, obj)` {#Message-append}
- **说明**
添加一个消息段到消息数组末尾。
- **参数**
- `obj` (str | (~ TMS)): 要添加的消息段
- **返回**
- (~ TM)
### _method_ `copy(self)` {#Message-copy}
- **返回**
- (~ TM)
### _method_ `count(self, value)` {#Message-count}
- **参数**
- `value` ((~ TMS) | str)
- **返回**
- int
### _method_ `extend(self, obj)` {#Message-extend}
- **说明**
拼接一个消息数组或多个消息段到消息数组末尾。
- **参数**
- `obj` ((~ TM) | Iterable[(~ TMS)]): 要添加的消息数组
- **返回**
- (~ TM)
### _method_ `extract_plain_text(self)` {#Message-extract_plain_text}
- **说明**
提取消息内纯文本消息
- **返回**
- str
### _method_ `get(self, type_, count=None)` {#Message-get}
- **参数**
- `type_` (str)
- `count` (int | None)
- **返回**
- (~ TM)
### _abstract classmethod_ `get_segment_class(cls)` {#Message-get_segment_class}
- **说明**
获取消息段类型
- **返回**
- Type[(~ TMS)]
### _method_ `index(self, value, *args)` {#Message-index}
- **参数**
- `value` ((~ TMS) | str)
- `*args`
- **返回**
- int
### _classmethod_ `template(cls, format_string)` {#Message-template}
- **说明**
创建消息模板。
用法和 `str.format` 大致相同, 但是可以输出消息对象, 并且支持以 `Message` 对象作为消息模板
并且提供了拓展的格式化控制符, 可以用适用于该消息类型的 `MessageSegment` 的工厂方法创建消息
- **参数**
- `format_string` (str | (~ TM)): 格式化模板
- **返回**
- nonebot.internal.adapter.template.MessageTemplate[(~ TM)]: 消息格式化器
## _abstract class_ `MessageSegment(type, data=<factory>)` {#MessageSegment}
- **说明**
消息段基类
- **参数**
- `type` (str)
- `data` (dict[str, Any])
### _method_ `copy(self)` {#MessageSegment-copy}
- **返回**
- (~ T)
### _method_ `get(self, key, default=None)` {#MessageSegment-get}
- **参数**
- `key` (str)
- `default` (Any)
- **返回**
- Unknown
### _abstract classmethod_ `get_message_class(cls)` {#MessageSegment-get_message_class}
- **说明**
获取消息数组类型
- **返回**
- Type[(~ TM)]
### _abstract method_ `is_text(self)` {#MessageSegment-is_text}
- **说明**
当前消息段是否为纯文本
- **返回**
- bool
### _method_ `items(self)` {#MessageSegment-items}
- **返回**
- Unknown
### _method_ `keys(self)` {#MessageSegment-keys}
- **返回**
- Unknown
### _method_ `values(self)` {#MessageSegment-values}
- **返回**
- Unknown
## _class_ `MessageTemplate(template, factory=str)` {#MessageTemplate}
- **说明**
消息模板格式化实现类。
- **参数**
- `template`: 模板
- `factory`: 消息类型工厂,默认为 `str`
### _method_ `add_format_spec(self, spec, name=None)` {#MessageTemplate-add_format_spec}
- **参数**
- `spec` ((~ FormatSpecFunc_T))
- `name` (str | None)
- **返回**
- (~ FormatSpecFunc_T)
### _method_ `format(self, *args, **kwargs)` {#MessageTemplate-format}
- **说明**
根据传入参数和模板生成消息对象
- **参数**
- `*args`
- `**kwargs`
- **返回**
- Unknown
### _method_ `format_field(self, value, format_spec)` {#MessageTemplate-format_field}
- **参数**
- `value` (Any)
- `format_spec` (str)
- **返回**
- Any
### _method_ `format_map(self, mapping)` {#MessageTemplate-format_map}
- **说明**
根据传入字典和模板生成消息对象, 在传入字段名不是有效标识符时有用
- **参数**
- `mapping` (Mapping[str, Any])
- **返回**
- (~ TF)
### _method_ `vformat(self, format_string, args, kwargs)` {#MessageTemplate-vformat}
- **参数**
- `format_string` (str)
- `args` (Sequence[Any])
- `kwargs` (Mapping[str, Any])
- **返回**
- (~ TF)

View File

@ -1,194 +0,0 @@
---
sidebar_position: 1
description: nonebot.config 模块
---
# nonebot.config
本模块定义了 NoneBot 本身运行所需的配置项。
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(_env_file='<object object>', _env_file_encoding=None, _env_nested_delimiter=None, _secrets_dir=None, *, environment='prod', **values)` {#Env}
- **说明**
运行环境配置。大小写不敏感。
将会从 `环境变量` > `.env 环境配置文件` 的优先级读取环境信息。
- **参数**
- `_env_file` (str | os.PathLike | NoneType)
- `_env_file_encoding` (str | None)
- `_env_nested_delimiter` (str | None)
- `_secrets_dir` (str | os.PathLike | NoneType)
- `environment` (str)
- `**values` (Any)
### _class-var_ `environment` {#Env-environment}
- **类型:** str
- **说明**
当前环境名。
NoneBot 将从 `.env.{environment}` 文件中加载配置。
## _class_ `Config(_env_file='<object object>', _env_file_encoding=None, _env_nested_delimiter=None, _secrets_dir=None, *, driver='~fastapi', host=IPv4Address('127.0.0.1'), port=8080, log_level='INFO', api_timeout=30.0, superusers=set(), nickname=set(), command_start={'/'}, command_sep={'.'}, session_expire_timeout=datetime.timedelta(seconds=120), **values)` {#Config}
- **说明**
NoneBot 主要配置。大小写不敏感。
除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。
这些配置将会在 json 反序列化后一起带入 `Config` 类中。
配置方法参考: [配置](https://v2.nonebot.dev/docs/tutorial/configuration)
- **参数**
- `_env_file` (str | os.PathLike | NoneType)
- `_env_file_encoding` (str | None)
- `_env_nested_delimiter` (str | None)
- `_secrets_dir` (str | os.PathLike | NoneType)
- `driver` (str)
- `host` (pydantic.networks.IPvAnyAddress)
- `port` (int)
- `log_level` (int | str)
- `api_timeout` (float)
- `superusers` (set[str])
- `nickname` (set[str])
- `command_start` (set[str])
- `command_sep` (set[str])
- `session_expire_timeout` (datetime.timedelta)
- `**values` (Any)
### _class-var_ `driver` {#Config-driver}
- **类型:** str
- **说明**
NoneBot 运行所使用的 `Driver` 。继承自 [Driver](./drivers/index.md#Driver) 。
配置格式为 `<module>[:<Driver>][+<module>[:<Mixin>]]*`
`~``nonebot.drivers.` 的缩写。
### _class-var_ `host` {#Config-host}
- **类型:** pydantic.networks.IPvAnyAddress
- **说明:** NoneBot [ReverseDriver](./drivers/index.md#ReverseDriver) 服务端监听的 IP/主机名。
### _class-var_ `port` {#Config-port}
- **类型:** int
- **说明:** NoneBot [ReverseDriver](./drivers/index.md#ReverseDriver) 服务端监听的端口。
### _class-var_ `log_level` {#Config-log_level}
- **类型:** int | str
- **说明**
NoneBot 日志输出等级,可以为 `int` 类型等级或等级名称
参考 [`loguru 日志等级`](https://loguru.readthedocs.io/en/stable/api/logger.html#levels)。
:::tip 提示
日志等级名称应为大写,如 `INFO`
:::
- **用法**
```conf
LOG_LEVEL=25
LOG_LEVEL=INFO
```
### _class-var_ `api_timeout` {#Config-api_timeout}
- **类型:** float | None
- **说明:** API 请求超时时间,单位: 秒。
### _class-var_ `superusers` {#Config-superusers}
- **类型:** set[str]
- **说明:** 机器人超级用户。
- **用法**
```conf
SUPERUSERS=["12345789"]
```
### _class-var_ `nickname` {#Config-nickname}
- **类型:** set[str]
- **说明:** 机器人昵称。
### _class-var_ `command_start` {#Config-command_start}
- **类型:** set[str]
- **说明:** 命令的起始标记,用于判断一条消息是不是命令。
- **用法**
```conf
COMMAND_START=["/", ""]
```
### _class-var_ `command_sep` {#Config-command_sep}
- **类型:** set[str]
- **说明:** 命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。
- **用法**
```conf
COMMAND_SEP=["."]
```
### _class-var_ `session_expire_timeout` {#Config-session_expire_timeout}
- **类型:** datetime.timedelta
- **说明:** 等待用户回复的超时时间。
- **用法**
```conf
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
```

View File

@ -1,98 +0,0 @@
---
sidebar_position: 9
description: nonebot.consts 模块
---
# nonebot.consts
本模块包含了 NoneBot 事件处理过程中使用到的常量。
## _var_ `RECEIVE_KEY` {#RECEIVE_KEY}
- **类型:** Literal['_receive_{id}']
- **说明:** `receive` 存储 key
## _var_ `LAST_RECEIVE_KEY` {#LAST_RECEIVE_KEY}
- **类型:** Literal['_last_receive']
- **说明:** `last_receive` 存储 key
## _var_ `ARG_KEY` {#ARG_KEY}
- **类型:** Literal['{key}']
- **说明:** `arg` 存储 key
## _var_ `REJECT_TARGET` {#REJECT_TARGET}
- **类型:** Literal['_current_target']
- **说明:** 当前 `reject` 目标存储 key
## _var_ `REJECT_CACHE_TARGET` {#REJECT_CACHE_TARGET}
- **类型:** Literal['_next_target']
- **说明:** 下一个 `reject` 目标存储 key
## _var_ `PREFIX_KEY` {#PREFIX_KEY}
- **类型:** Literal['_prefix']
- **说明:** 命令前缀存储 key
## _var_ `CMD_KEY` {#CMD_KEY}
- **类型:** Literal['command']
- **说明:** 命令元组存储 key
## _var_ `RAW_CMD_KEY` {#RAW_CMD_KEY}
- **类型:** Literal['raw_command']
- **说明:** 命令文本存储 key
## _var_ `CMD_ARG_KEY` {#CMD_ARG_KEY}
- **类型:** Literal['command_arg']
- **说明:** 命令参数存储 key
## _var_ `CMD_START_KEY` {#CMD_START_KEY}
- **类型:** Literal['command_start']
- **说明:** 命令开头存储 key
## _var_ `SHELL_ARGS` {#SHELL_ARGS}
- **类型:** Literal['_args']
- **说明:** shell 命令 parse 后参数字典存储 key
## _var_ `SHELL_ARGV` {#SHELL_ARGV}
- **类型:** Literal['_argv']
- **说明:** shell 命令原始参数列表存储 key
## _var_ `REGEX_MATCHED` {#REGEX_MATCHED}
- **类型:** Literal['_matched']
- **说明:** 正则匹配结果存储 key
## _var_ `REGEX_GROUP` {#REGEX_GROUP}
- **类型:** Literal['_matched_groups']
- **说明:** 正则匹配 group 元组存储 key
## _var_ `REGEX_DICT` {#REGEX_DICT}
- **类型:** Literal['_matched_dict']
- **说明:** 正则匹配 group 字典存储 key

View File

@ -1,98 +0,0 @@
---
sidebar_position: 0
description: nonebot.dependencies 模块
---
# nonebot.dependencies
本模块模块实现了依赖注入的定义与处理。
## _abstract class_ `Param(default=PydanticUndefined, **kwargs)` {#Param}
- **说明**
依赖注入的基本单元 —— 参数。
继承自 `pydantic.fields.FieldInfo`,用于描述参数信息(不包括参数名)。
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _class_ `Dependent(call, params=<factory>, parameterless=<factory>)` {#Dependent}
- **说明**
依赖注入容器
- **参数**
- `call` ((*Any, \*\*Any) -> (~ R) | (*Any, \*\*Any) -> Awaitable[(~ R)]): 依赖注入的可调用对象,可以是任何 Callable 对象
- `params` (tuple[pydantic.fields.ModelField]): 具名参数列表
- `parameterless` (tuple[[Param](#Param)]): 匿名参数列表
- `pre_checkers`: 依赖注入解析前的参数检查
- `allow_types`: 允许的参数类型
### _async method_ `check(self, **params)` {#Dependent-check}
- **参数**
- `**params` (Any)
- **返回**
- None
### _classmethod_ `parse(cls, *, call, parameterless=None, allow_types)` {#Dependent-parse}
- **参数**
- `call` ((*Any, \*\*Any) -> (~ R) | (*Any, \*\*Any) -> Awaitable[(~ R)])
- `parameterless` (Iterable[Any] | None)
- `allow_types` (Iterable[Type[[Param](#Param)]])
- **返回**
- Dependent[R]
### _staticmethod_ `parse_parameterless(parameterless, allow_types)` {#Dependent-parse_parameterless}
- **参数**
- `parameterless` (tuple[Any, ...])
- `allow_types` (tuple[Type[[Param](#Param)], ...])
- **返回**
- tuple[[Param](#Param), ...]
### _staticmethod_ `parse_params(call, allow_types)` {#Dependent-parse_params}
- **参数**
- `call` ((*Any, \*\*Any) -> (~ R) | (*Any, \*\*Any) -> Awaitable[(~ R)])
- `allow_types` (tuple[Type[[Param](#Param)], ...])
- **返回**
- tuple[pydantic.fields.ModelField]
### _async method_ `solve(self, **params)` {#Dependent-solve}
- **参数**
- `**params` (Any)
- **返回**
- dict[str, Any]

View File

@ -1,48 +0,0 @@
---
sidebar_position: 1
description: nonebot.dependencies.utils 模块
---
# nonebot.dependencies.utils
## _def_ `get_typed_signature(call)` {#get_typed_signature}
- **说明**
获取可调用对象签名
- **参数**
- `call` ((\*Any, \*\*Any) -> Any)
- **返回**
- inspect.Signature
## _def_ `get_typed_annotation(param, globalns)` {#get_typed_annotation}
- **说明**
获取参数的类型注解
- **参数**
- `param` (inspect.Parameter)
- `globalns` (dict[str, Any])
- **返回**
- Any
## _def_ `check_field_type(field, value)` {#check_field_type}
- **参数**
- `field` (pydantic.fields.ModelField)
- `value` ((~ V))
- **返回**
- (~ V)

View File

@ -1,3 +0,0 @@
{
"position": 14
}

View File

@ -1,120 +0,0 @@
---
sidebar_position: 2
description: nonebot.drivers.aiohttp 模块
---
# nonebot.drivers.aiohttp
[AIOHTTP](https://aiohttp.readthedocs.io/en/stable/) 驱动适配器。
```bash
nb driver install aiohttp
# 或者
pip install nonebot2[aiohttp]
```
:::tip 提示
本驱动仅支持客户端连接
:::
## _class_ `Mixin()` {#Mixin}
- **说明**
AIOHTTP Mixin
### _property_ `type` {#Mixin-type}
- **类型:** str
### _async method_ `request(self, setup)` {#Mixin-request}
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- nonebot.internal.driver.model.Response
### _method_ `websocket(self, setup)` {#Mixin-websocket}
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- AsyncGenerator[WebSocket, NoneType]
## _class_ `WebSocket(*, request, session, websocket)` {#WebSocket}
- **说明**
AIOHTTP Websocket Wrapper
- **参数**
- `request` (nonebot.internal.driver.model.Request)
- `session` (aiohttp.client.ClientSession)
- `websocket` (aiohttp.client_ws.ClientWebSocketResponse)
### _async method_ `accept(self)` {#WebSocket-accept}
- **返回**
- Unknown
### _async method_ `close(self, code=1000)` {#WebSocket-close}
- **参数**
- `code` (int)
- **返回**
- Unknown
### _async method_ `receive(self)` {#WebSocket-receive}
- **返回**
- str
### _async method_ `receive_bytes(self)` {#WebSocket-receive_bytes}
- **返回**
- bytes
### _async method_ `receive_text(self)` {#WebSocket-receive_text}
- **返回**
- str
### _async method_ `send_bytes(self, data)` {#WebSocket-send_bytes}
- **参数**
- `data` (bytes)
- **返回**
- None
### _async method_ `send_text(self, data)` {#WebSocket-send_text}
- **参数**
- `data` (str)
- **返回**
- None
## _library-attr_ `Driver`
三方库 API

View File

@ -1,276 +0,0 @@
---
sidebar_position: 1
description: nonebot.drivers.fastapi 模块
---
# nonebot.drivers.fastapi
[FastAPI](https://fastapi.tiangolo.com/) 驱动适配
:::tip 提示
本驱动仅支持服务端连接
:::
## _class_ `Config(_env_file='<object object>', _env_file_encoding=None, _env_nested_delimiter=None, _secrets_dir=None, *, fastapi_openapi_url=None, fastapi_docs_url=None, fastapi_redoc_url=None, fastapi_include_adapter_schema=True, fastapi_reload=False, fastapi_reload_dirs=None, fastapi_reload_delay=0.25, fastapi_reload_includes=None, fastapi_reload_excludes=None)` {#Config}
- **说明**
FastAPI 驱动框架设置,详情参考 FastAPI 文档
- **参数**
- `_env_file` (str | os.PathLike | NoneType)
- `_env_file_encoding` (str | None)
- `_env_nested_delimiter` (str | None)
- `_secrets_dir` (str | os.PathLike | NoneType)
- `fastapi_openapi_url` (str)
- `fastapi_docs_url` (str)
- `fastapi_redoc_url` (str)
- `fastapi_include_adapter_schema` (bool)
- `fastapi_reload` (bool)
- `fastapi_reload_dirs` (list[str])
- `fastapi_reload_delay` (float)
- `fastapi_reload_includes` (list[str])
- `fastapi_reload_excludes` (list[str])
### _class-var_ `fastapi_openapi_url` {#Config-fastapi_openapi_url}
- **类型:** str | None
- **说明:** `openapi.json` 地址,默认为 `None` 即关闭
### _class-var_ `fastapi_docs_url` {#Config-fastapi_docs_url}
- **类型:** str | None
- **说明:** `swagger` 地址,默认为 `None` 即关闭
### _class-var_ `fastapi_redoc_url` {#Config-fastapi_redoc_url}
- **类型:** str | None
- **说明:** `redoc` 地址,默认为 `None` 即关闭
### _class-var_ `fastapi_include_adapter_schema` {#Config-fastapi_include_adapter_schema}
- **类型:** bool
- **说明:** 是否包含适配器路由的 schema默认为 `True`
### _class-var_ `fastapi_reload` {#Config-fastapi_reload}
- **类型:** bool
- **说明:** 开启/关闭冷重载
### _class-var_ `fastapi_reload_dirs` {#Config-fastapi_reload_dirs}
- **类型:** list[str] | None
- **说明:** 重载监控文件夹列表,默认为 uvicorn 默认值
### _class-var_ `fastapi_reload_delay` {#Config-fastapi_reload_delay}
- **类型:** float
- **说明:** 重载延迟,默认为 uvicorn 默认值
### _class-var_ `fastapi_reload_includes` {#Config-fastapi_reload_includes}
- **类型:** list[str] | None
- **说明:** 要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
### _class-var_ `fastapi_reload_excludes` {#Config-fastapi_reload_excludes}
- **类型:** list[str] | None
- **说明:** 不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
## _class_ `Driver(env, config)` {#Driver}
- **说明**
FastAPI 驱动框架。
- **参数**
- `env` ([Env](../config.md#Env))
- `config` ([Config](../config.md#Config))
### _property_ `asgi` {#Driver-asgi}
- **类型:** fastapi.applications.FastAPI
- **说明:** `FastAPI APP` 对象
### _property_ `logger` {#Driver-logger}
- **类型:** logging.Logger
- **说明:** fastapi 使用的 logger
### _property_ `server_app` {#Driver-server_app}
- **类型:** fastapi.applications.FastAPI
- **说明:** `FastAPI APP` 对象
### _property_ `type` {#Driver-type}
- **类型:** str
- **说明:** 驱动名称: `fastapi`
### _method_ `on_shutdown(self, func)` {#Driver-on_shutdown}
- **说明**
参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#shutdown-event>`\_
- **参数**
- `func` (Callable)
- **返回**
- Callable
### _method_ `on_startup(self, func)` {#Driver-on_startup}
- **说明**
参考文档: `Events <https://fastapi.tiangolo.com/advanced/events/#startup-event>`\_
- **参数**
- `func` (Callable)
- **返回**
- Callable
### _method_ `run(self, host=None, port=None, *, app=None, **kwargs)` {#Driver-run}
- **说明**
使用 `uvicorn` 启动 FastAPI
- **参数**
- `host` (str | None)
- `port` (int | None)
- `app` (str | None)
- `**kwargs`
- **返回**
- Unknown
### _method_ `setup_http_server(self, setup)` {#Driver-setup_http_server}
- **参数**
- `setup` (nonebot.internal.driver.model.HTTPServerSetup)
- **返回**
- Unknown
### _method_ `setup_websocket_server(self, setup)` {#Driver-setup_websocket_server}
- **参数**
- `setup` (nonebot.internal.driver.model.WebSocketServerSetup)
- **返回**
- None
## _class_ `FastAPIWebSocket(*, request, websocket)` {#FastAPIWebSocket}
- **说明**
FastAPI WebSocket Wrapper
- **参数**
- `request` (nonebot.internal.driver.model.Request)
- `websocket` (starlette.websockets.WebSocket)
### _property_ `closed` {#FastAPIWebSocket-closed}
- **类型:** bool
### _async method_ `accept(self)` {#FastAPIWebSocket-accept}
- **返回**
- None
### _async method_ `close(self, code=1000, reason='')` {#FastAPIWebSocket-close}
- **参数**
- `code` (int)
- `reason` (str)
- **返回**
- None
### _async method_ `receive(self)` {#FastAPIWebSocket-receive}
- **返回**
- str | bytes
### _async method_ `receive_bytes(self)` {#FastAPIWebSocket-receive_bytes}
- **返回**
- bytes
### _async method_ `receive_text(self)` {#FastAPIWebSocket-receive_text}
- **返回**
- str
### _async method_ `send_bytes(self, data)` {#FastAPIWebSocket-send_bytes}
- **参数**
- `data` (bytes)
- **返回**
- None
### _async method_ `send_text(self, data)` {#FastAPIWebSocket-send_text}
- **参数**
- `data` (str)
- **返回**
- None

View File

@ -1,52 +0,0 @@
---
sidebar_position: 3
description: nonebot.drivers.httpx 模块
---
# nonebot.drivers.httpx
[HTTPX](https://www.python-httpx.org/) 驱动适配
```bash
nb driver install httpx
# 或者
pip install nonebot2[httpx]
```
:::tip 提示
本驱动仅支持客户端 HTTP 连接
:::
## _class_ `Mixin()` {#Mixin}
- **说明**
HTTPX Mixin
### _property_ `type` {#Mixin-type}
- **类型:** str
### _async method_ `request(self, setup)` {#Mixin-request}
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- nonebot.internal.driver.model.Response
### _method_ `websocket(self, setup)` {#Mixin-websocket}
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- AsyncGenerator[nonebot.internal.driver.model.WebSocket, NoneType]
## _library-attr_ `Driver`
三方库 API

View File

@ -1,528 +0,0 @@
---
sidebar_position: 0
description: nonebot.drivers 模块
---
# nonebot.drivers
本模块定义了驱动适配器基类。
各驱动请继承以下基类。
## _abstract class_ `Driver(env, config)` {#Driver}
- **说明**
Driver 基类。
- **参数**
- `env` ([Env](../config.md#Env)): 包含环境信息的 Env 对象
- `config` ([Config](../config.md#Config)): 包含配置信息的 Config 对象
### _property_ `bots` {#Driver-bots}
- **类型:** dict[str, Bot]
- **说明:** 获取当前所有已连接的 Bot
### _abstract property_ `logger` {#Driver-logger}
- **类型:**
- **说明:** 驱动专属 logger 日志记录器
### _abstract property_ `type` {#Driver-type}
- **类型:** str
- **说明:** 驱动类型名称
### _classmethod_ `on_bot_connect(cls, func)` {#Driver-on_bot_connect}
- **说明**
装饰一个函数使他在 bot 连接成功时执行。
钩子函数参数:
- bot: 当前连接上的 Bot 对象
- **参数**
- `func` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any])
- **返回**
- (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
### _classmethod_ `on_bot_disconnect(cls, func)` {#Driver-on_bot_disconnect}
- **说明**
装饰一个函数使他在 bot 连接断开时执行。
钩子函数参数:
- bot: 当前连接上的 Bot 对象
- **参数**
- `func` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any])
- **返回**
- (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
### _abstract method_ `on_shutdown(self, func)` {#Driver-on_shutdown}
- **说明**
注册一个在驱动器停止时执行的函数
- **参数**
- `func` (Callable)
- **返回**
- Callable
### _abstract method_ `on_startup(self, func)` {#Driver-on_startup}
- **说明**
注册一个在驱动器启动时执行的函数
- **参数**
- `func` (Callable)
- **返回**
- Callable
### _method_ `register_adapter(self, adapter, **kwargs)` {#Driver-register_adapter}
- **说明**
注册一个协议适配器
- **参数**
- `adapter` (Type[Adapter]): 适配器类
- `**kwargs`: 其他传递给适配器的参数
- **返回**
- None
### _abstract method_ `run(self, *args, **kwargs)` {#Driver-run}
- **说明**
启动驱动框架
- **参数**
- `*args`
- `**kwargs`
- **返回**
- Unknown
## _class_ `Cookies(cookies=None)` {#Cookies}
- **参数**
- `cookies` (NoneType | Cookies | http.cookiejar.CookieJar | dict[str, str] | list[tuple[str, str]])
### _method_ `clear(self, domain=None, path=None)` {#Cookies-clear}
- **参数**
- `domain` (str | None)
- `path` (str | None)
- **返回**
- None
### _method_ `delete(self, name, domain=None, path=None)` {#Cookies-delete}
- **参数**
- `name` (str)
- `domain` (str | None)
- `path` (str | None)
- **返回**
- None
### _method_ `get(self, name, default=None, domain=None, path=None)` {#Cookies-get}
- **参数**
- `name` (str)
- `default` (str | None)
- `domain` (str | None)
- `path` (str | None)
- **返回**
- str | None
### _method_ `set(self, name, value, domain='', path='/')` {#Cookies-set}
- **参数**
- `name` (str)
- `value` (str)
- `domain` (str)
- `path` (str)
- **返回**
- None
### _method_ `update(self, cookies=None)` {#Cookies-update}
- **参数**
- `cookies` (NoneType | Cookies | http.cookiejar.CookieJar | dict[str, str] | list[tuple[str, str]])
- **返回**
- None
## _class_ `Request(method, url, *, params=None, headers=None, cookies=None, content=None, data=None, json=None, files=None, version=HTTPVersion.H11, timeout=None, proxy=None)` {#Request}
- **参数**
- `method` (str | bytes)
- `url` (URL | str | tuple[bytes, bytes, int | None, bytes])
- `params` (NoneType | str | Mapping[str, str | int | float | list[str | int | float]] | list[tuple[str, str | int | float | list[str | int | float]]])
- `headers` (NoneType | multidict.\_multidict.CIMultiDict[str] | dict[str, str] | list[tuple[str, str]])
- `cookies` (NoneType | Cookies | http.cookiejar.CookieJar | dict[str, str] | list[tuple[str, str]])
- `content` (str | bytes | NoneType)
- `data` (dict | None)
- `json` (Any)
- `files` (dict[str, IO[bytes] | bytes | tuple[str | None, IO[bytes] | bytes] | tuple[str | None, IO[bytes] | bytes, str | None]] | list[tuple[str, IO[bytes] | bytes | tuple[str | None, IO[bytes] | bytes] | tuple[str | None, IO[bytes] | bytes, str | None]]] | NoneType)
- `version` (str | nonebot.internal.driver.model.HTTPVersion)
- `timeout` (float | None)
- `proxy` (str | None)
## _class_ `Response(status_code, *, headers=None, content=None, request=None)` {#Response}
- **参数**
- `status_code` (int)
- `headers` (NoneType | multidict.\_multidict.CIMultiDict[str] | dict[str, str] | list[tuple[str, str]])
- `content` (str | bytes | NoneType)
- `request` (nonebot.internal.driver.model.Request | None)
## _abstract class_ `WebSocket(*, request)` {#WebSocket}
- **参数**
- `request` (nonebot.internal.driver.model.Request)
### _abstract property_ `closed` {#WebSocket-closed}
- **类型:** bool
- **说明:** 连接是否已经关闭
### _abstract async method_ `accept(self)` {#WebSocket-accept}
- **说明**
接受 WebSocket 连接请求
- **返回**
- None
### _abstract async method_ `close(self, code=1000, reason='')` {#WebSocket-close}
- **说明**
关闭 WebSocket 连接请求
- **参数**
- `code` (int)
- `reason` (str)
- **返回**
- None
### _abstract async method_ `receive(self)` {#WebSocket-receive}
- **说明**
接收一条 WebSocket text/bytes 信息
- **返回**
- str | bytes
### _abstract async method_ `receive_bytes(self)` {#WebSocket-receive_bytes}
- **说明**
接收一条 WebSocket binary 信息
- **返回**
- bytes
### _abstract async method_ `receive_text(self)` {#WebSocket-receive_text}
- **说明**
接收一条 WebSocket text 信息
- **返回**
- str
### _async method_ `send(self, data)` {#WebSocket-send}
- **说明**
发送一条 WebSocket text/bytes 信息
- **参数**
- `data` (str | bytes)
- **返回**
- None
### _abstract async method_ `send_bytes(self, data)` {#WebSocket-send_bytes}
- **说明**
发送一条 WebSocket binary 信息
- **参数**
- `data` (bytes)
- **返回**
- None
### _abstract async method_ `send_text(self, data)` {#WebSocket-send_text}
- **说明**
发送一条 WebSocket text 信息
- **参数**
- `data` (str)
- **返回**
- None
## _enum_ `HTTPVersion` {#HTTPVersion}
- **说明**
An enumeration.
- **枚举成员**
- `H10`
- `H11`
- `H2`
## _abstract class_ `ForwardMixin()` {#ForwardMixin}
- **说明**
客户端混入基类。
### _abstract property_ `type` {#ForwardMixin-type}
- **类型:** str
- **说明:** 客户端驱动类型名称
### _abstract async method_ `request(self, setup)` {#ForwardMixin-request}
- **说明**
发送一个 HTTP 请求
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- nonebot.internal.driver.model.Response
### _abstract method_ `websocket(self, setup)` {#ForwardMixin-websocket}
- **说明**
发起一个 WebSocket 连接
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- AsyncGenerator[nonebot.internal.driver.model.WebSocket, NoneType]
## _abstract class_ `ForwardDriver(env, config)` {#ForwardDriver}
- **说明**
客户端基类。将客户端框架封装,以满足适配器使用。
- **参数**
- `env` ([Env](../config.md#Env))
- `config` ([Config](../config.md#Config))
## _abstract class_ `ReverseDriver(env, config)` {#ReverseDriver}
- **说明**
服务端基类。将后端框架封装,以满足适配器使用。
- **参数**
- `env` ([Env](../config.md#Env))
- `config` ([Config](../config.md#Config))
### _abstract property_ `asgi` {#ReverseDriver-asgi}
- **类型:** Any
- **说明:** 驱动 ASGI 对象
### _abstract property_ `server_app` {#ReverseDriver-server_app}
- **类型:** Any
- **说明:** 驱动 APP 对象
### _abstract method_ `setup_http_server(self, setup)` {#ReverseDriver-setup_http_server}
- **说明**
设置一个 HTTP 服务器路由配置
- **参数**
- `setup` (HTTPServerSetup)
- **返回**
- None
### _abstract method_ `setup_websocket_server(self, setup)` {#ReverseDriver-setup_websocket_server}
- **说明**
设置一个 WebSocket 服务器路由配置
- **参数**
- `setup` (WebSocketServerSetup)
- **返回**
- None
## _def_ `combine_driver(driver, *mixins)` {#combine_driver}
- **说明**
将一个驱动器和多个混入类合并。
- **参数**
- `driver` (Type[nonebot.internal.driver.driver.Driver])
- `*mixins` (Type[nonebot.internal.driver.driver.ForwardMixin])
- **返回**
- Type[nonebot.internal.driver.driver.Driver]
## _class_ `HTTPServerSetup(path, method, name, handle_func)` {#HTTPServerSetup}
- **说明**
HTTP 服务器路由配置。
- **参数**
- `path` (yarl.URL)
- `method` (str)
- `name` (str)
- `handle_func` ((nonebot.internal.driver.model.Request) -> Awaitable[nonebot.internal.driver.model.Response])
## _class_ `WebSocketServerSetup(path, name, handle_func)` {#WebSocketServerSetup}
- **说明**
WebSocket 服务器路由配置。
- **参数**
- `path` (yarl.URL)
- `name` (str)
- `handle_func` ((nonebot.internal.driver.model.WebSocket) -> Awaitable[Any])
## _library-attr_ `URL`
三方库 API

View File

@ -1,246 +0,0 @@
---
sidebar_position: 5
description: nonebot.drivers.quart 模块
---
# nonebot.drivers.quart
[Quart](https://pgjones.gitlab.io/quart/index.html) 驱动适配
```bash
nb driver install quart
# 或者
pip install nonebot2[quart]
```
:::tip 提示
本驱动仅支持服务端连接
:::
## _class_ `Config(_env_file='<object object>', _env_file_encoding=None, _env_nested_delimiter=None, _secrets_dir=None, *, quart_reload=False, quart_reload_dirs=None, quart_reload_delay=0.25, quart_reload_includes=None, quart_reload_excludes=None)` {#Config}
- **说明**
Quart 驱动框架设置
- **参数**
- `_env_file` (str | os.PathLike | NoneType)
- `_env_file_encoding` (str | None)
- `_env_nested_delimiter` (str | None)
- `_secrets_dir` (str | os.PathLike | NoneType)
- `quart_reload` (bool)
- `quart_reload_dirs` (list[str])
- `quart_reload_delay` (float)
- `quart_reload_includes` (list[str])
- `quart_reload_excludes` (list[str])
### _class-var_ `quart_reload` {#Config-quart_reload}
- **类型:** bool
- **说明:** 开启/关闭冷重载
### _class-var_ `quart_reload_dirs` {#Config-quart_reload_dirs}
- **类型:** list[str] | None
- **说明:** 重载监控文件夹列表,默认为 uvicorn 默认值
### _class-var_ `quart_reload_delay` {#Config-quart_reload_delay}
- **类型:** float
- **说明:** 重载延迟,默认为 uvicorn 默认值
### _class-var_ `quart_reload_includes` {#Config-quart_reload_includes}
- **类型:** list[str] | None
- **说明:** 要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
### _class-var_ `quart_reload_excludes` {#Config-quart_reload_excludes}
- **类型:** list[str] | None
- **说明:** 不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
## _class_ `Driver(env, config)` {#Driver}
- **说明**
Quart 驱动框架
- **参数**
- `env` ([Env](../config.md#Env))
- `config` ([Config](../config.md#Config))
### _property_ `asgi` {#Driver-asgi}
- **类型:**
- **说明:** `Quart` 对象
### _property_ `logger` {#Driver-logger}
- **类型:**
- **说明:** Quart 使用的 logger
### _property_ `server_app` {#Driver-server_app}
- **类型:** quart.app.Quart
- **说明:** `Quart` 对象
### _property_ `type` {#Driver-type}
- **类型:** str
- **说明:** 驱动名称: `quart`
### _method_ `on_shutdown(self, func)` {#Driver-on_shutdown}
- **说明**
参考文档: [`Startup and Shutdown`](https://pgjones.gitlab.io/quart/how_to_guides/startup_shutdown.html)
- **参数**
- `func` ((~ \_AsyncCallable))
- **返回**
- (~ \_AsyncCallable)
### _method_ `on_startup(self, func)` {#Driver-on_startup}
- **说明**
参考文档: [`Startup and Shutdown`](https://pgjones.gitlab.io/quart/how_to_guides/startup_shutdown.html)
- **参数**
- `func` ((~ \_AsyncCallable))
- **返回**
- (~ \_AsyncCallable)
### _method_ `run(self, host=None, port=None, *, app=None, **kwargs)` {#Driver-run}
- **说明**
使用 `uvicorn` 启动 Quart
- **参数**
- `host` (str | None)
- `port` (int | None)
- `app` (str | None)
- `**kwargs`
- **返回**
- Unknown
### _method_ `setup_http_server(self, setup)` {#Driver-setup_http_server}
- **参数**
- `setup` (nonebot.internal.driver.model.HTTPServerSetup)
- **返回**
- Unknown
### _method_ `setup_websocket_server(self, setup)` {#Driver-setup_websocket_server}
- **参数**
- `setup` (nonebot.internal.driver.model.WebSocketServerSetup)
- **返回**
- None
## _class_ `WebSocket(*, request, websocket)` {#WebSocket}
- **说明**
Quart WebSocket Wrapper
- **参数**
- `request` (nonebot.internal.driver.model.Request)
- `websocket` (quart.wrappers.websocket.Websocket)
### _async method_ `accept(self)` {#WebSocket-accept}
- **返回**
- Unknown
### _async method_ `close(self, code=1000, reason='')` {#WebSocket-close}
- **参数**
- `code` (int)
- `reason` (str)
- **返回**
- Unknown
### _async method_ `receive(self)` {#WebSocket-receive}
- **返回**
- str | bytes
### _async method_ `receive_bytes(self)` {#WebSocket-receive_bytes}
- **返回**
- bytes
### _async method_ `receive_text(self)` {#WebSocket-receive_text}
- **返回**
- str
### _async method_ `send_bytes(self, data)` {#WebSocket-send_bytes}
- **参数**
- `data` (bytes)
- **返回**
- Unknown
### _async method_ `send_text(self, data)` {#WebSocket-send_text}
- **参数**
- `data` (str)
- **返回**
- Unknown

View File

@ -1,134 +0,0 @@
---
sidebar_position: 4
description: nonebot.drivers.websockets 模块
---
# nonebot.drivers.websockets
[websockets](https://websockets.readthedocs.io/) 驱动适配
```bash
nb driver install websockets
# 或者
pip install nonebot2[websockets]
```
:::tip 提示
本驱动仅支持客户端 WebSocket 连接
:::
## _def_ `catch_closed(func)` {#catch_closed}
- **参数**
- `func`
- **返回**
- Unknown
## _class_ `Mixin()` {#Mixin}
- **说明**
Websockets Mixin
### _property_ `type` {#Mixin-type}
- **类型:** str
### _async method_ `request(self, setup)` {#Mixin-request}
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- nonebot.internal.driver.model.Response
### _method_ `websocket(self, setup)` {#Mixin-websocket}
- **参数**
- `setup` (nonebot.internal.driver.model.Request)
- **返回**
- AsyncGenerator[WebSocket, NoneType]
## _class_ `WebSocket(*, request, websocket)` {#WebSocket}
- **说明**
Websockets WebSocket Wrapper
- **参数**
- `request` (nonebot.internal.driver.model.Request)
- `websocket` (websockets.legacy.client.WebSocketClientProtocol)
### _property_ `closed` {#WebSocket-closed}
- **类型:** bool
### _async method_ `accept(self)` {#WebSocket-accept}
- **返回**
- Unknown
### _async method_ `close(self, code=1000, reason='')` {#WebSocket-close}
- **参数**
- `code` (int)
- `reason` (str)
- **返回**
- Unknown
### _async method_ `receive(self)` {#WebSocket-receive}
- **返回**
- str | bytes
### _async method_ `receive_bytes(self)` {#WebSocket-receive_bytes}
- **返回**
- bytes
### _async method_ `receive_text(self)` {#WebSocket-receive_text}
- **返回**
- str
### _async method_ `send_bytes(self, data)` {#WebSocket-send_bytes}
- **参数**
- `data` (bytes)
- **返回**
- None
### _async method_ `send_text(self, data)` {#WebSocket-send_text}
- **参数**
- `data` (str)
- **返回**
- None
## _library-attr_ `Driver`
三方库 API

View File

@ -1,260 +0,0 @@
---
sidebar_position: 10
description: nonebot.exception 模块
---
# nonebot.exception
本模块包含了所有 NoneBot 运行时可能会抛出的异常。
这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。
```bash
NoneBotException
├── ParserExit
├── ProcessException
| ├── IgnoredException
| ├── SkippedException
| | └── TypeMisMatch
| ├── MockApiException
| └── StopPropagation
├── MatcherException
| ├── PausedException
| ├── RejectedException
| └── FinishedException
├── AdapterException
| ├── NoLogException
| ├── ApiNotAvailable
| ├── NetworkError
| └── ActionFailed
└── DriverException
└── WebSocketClosed
```
## _class_ `NoneBotException()` {#NoneBotException}
- **说明**
所有 NoneBot 发生的异常基类。
## _class_ `ParserExit(status=0, message=None)` {#ParserExit}
- **说明**
[shell_command](./rule.md#shell_command) 处理消息失败时返回的异常
- **参数**
- `status` (int)
- `message` (str | None)
## _class_ `ProcessException()` {#ProcessException}
- **说明**
事件处理过程中发生的异常基类。
## _class_ `IgnoredException(reason)` {#IgnoredException}
- **说明**
指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。
- **参数**
- `reason` (Any): 忽略事件的原因
## _class_ `SkippedException()` {#SkippedException}
- **说明**
指示 NoneBot 立即结束当前 `Dependent` 的运行。
例如,可以在 `Handler` 中通过 [Matcher.skip](./matcher.md#Matcher-skip) 抛出。
- **用法**
```python
def always_skip():
Matcher.skip()
@matcher.handle()
async def handler(dependency = Depends(always_skip)):
# never run
```
## _class_ `TypeMisMatch(param, value)` {#TypeMisMatch}
- **说明**
当前 `Handler` 的参数类型不匹配。
- **参数**
- `param` (pydantic.fields.ModelField)
- `value` (Any)
## _class_ `MockApiException(result)` {#MockApiException}
- **说明**
指示 NoneBot 阻止本次 API 调用或修改本次调用返回值,并返回自定义内容。可由 api hook 抛出。
- **参数**
- `result` (Any): 返回的内容
## _class_ `StopPropagation()` {#StopPropagation}
- **说明**
指示 NoneBot 终止事件向下层传播。
在 {ref}`nonebot.matcher.Matcher.block` 为 `True`
或使用 [Matcher.stop_propagation](./matcher.md#Matcher-stop_propagation) 方法时抛出。
- **用法**
```python
matcher = on_notice(block=True)
# 或者
@matcher.handle()
async def handler(matcher: Matcher):
matcher.stop_propagation()
```
## _class_ `MatcherException()` {#MatcherException}
- **说明**
所有 Matcher 发生的异常基类。
## _class_ `PausedException()` {#PausedException}
- **说明**
指示 NoneBot 结束当前 `Handler` 并等待下一条消息后继续下一个 `Handler`。可用于用户输入新信息。
可以在 `Handler` 中通过 [Matcher.pause](./matcher.md#Matcher-pause) 抛出。
- **用法**
```python
@matcher.handle()
async def handler():
await matcher.pause("some message")
```
## _class_ `RejectedException()` {#RejectedException}
- **说明**
指示 NoneBot 结束当前 `Handler` 并等待下一条消息后重新运行当前 `Handler`。可用于用户重新输入。
可以在 `Handler` 中通过 [Matcher.reject](./matcher.md#Matcher-reject) 抛出。
- **用法**
```python
@matcher.handle()
async def handler():
await matcher.reject("some message")
```
## _class_ `FinishedException()` {#FinishedException}
- **说明**
指示 NoneBot 结束当前 `Handler` 且后续 `Handler` 不再被运行。可用于结束用户会话。
可以在 `Handler` 中通过 [Matcher.finish](./matcher.md#Matcher-finish) 抛出。
- **用法**
```python
@matcher.handle()
async def handler():
await matcher.finish("some message")
```
## _class_ `AdapterException(adapter_name, *args)` {#AdapterException}
- **说明**
代表 `Adapter` 抛出的异常,所有的 `Adapter` 都要在内部继承自这个 `Exception`
- **参数**
- `adapter_name` (str): 标识 adapter
- `*args` (object)
## _class_ `NoLogException(adapter_name, *args)` {#NoLogException}
- **说明**
指示 NoneBot 对当前 `Event` 进行处理但不显示 Log 信息。
可在 [Event.get_log_string](./adapters/index.md#Event-get_log_string) 时抛出
- **参数**
- `adapter_name` (str)
- `*args` (object)
## _class_ `ApiNotAvailable(adapter_name, *args)` {#ApiNotAvailable}
- **说明**
在 API 连接不可用时抛出。
- **参数**
- `adapter_name` (str)
- `*args` (object)
## _class_ `NetworkError(adapter_name, *args)` {#NetworkError}
- **说明**
在网络出现问题时抛出,如: API 请求地址不正确, API 请求无返回或返回状态非正常等。
- **参数**
- `adapter_name` (str)
- `*args` (object)
## _class_ `ActionFailed(adapter_name, *args)` {#ActionFailed}
- **说明**
API 请求成功返回数据,但 API 操作失败。
- **参数**
- `adapter_name` (str)
- `*args` (object)
## _class_ `DriverException()` {#DriverException}
- **说明**
`Driver` 抛出的异常基类
## _class_ `WebSocketClosed(code, reason=None)` {#WebSocketClosed}
- **说明**
WebSocket 连接已关闭
- **参数**
- `code` (int)
- `reason` (str | None)

View File

@ -1,207 +0,0 @@
---
sidebar_position: 0
description: nonebot 模块
---
# nonebot
本模块主要定义了 NoneBot 启动所需函数,供 bot 入口文件调用。
## 快捷导入
为方便使用,本模块从子模块导入了部分内容,以下内容可以直接通过本模块导入:
- `on` => [`on`](./plugin/on.md#on)
- `on_metaevent` => [`on_metaevent`](./plugin/on.md#on_metaevent)
- `on_message` => [`on_message`](./plugin/on.md#on_message)
- `on_notice` => [`on_notice`](./plugin/on.md#on_notice)
- `on_request` => [`on_request`](./plugin/on.md#on_request)
- `on_startswith` => [`on_startswith`](./plugin/on.md#on_startswith)
- `on_endswith` => [`on_endswith`](./plugin/on.md#on_endswith)
- `on_fullmatch` => [`on_fullmatch`](./plugin/on.md#on_fullmatch)
- `on_keyword` => [`on_keyword`](./plugin/on.md#on_keyword)
- `on_command` => [`on_command`](./plugin/on.md#on_command)
- `on_shell_command` => [`on_shell_command`](./plugin/on.md#on_shell_command)
- `on_regex` => [`on_regex`](./plugin/on.md#on_regex)
- `on_type` => [`on_type`](./plugin/on.md#on_type)
- `CommandGroup` => [`CommandGroup`](./plugin/on.md#CommandGroup)
- `Matchergroup` => [`MatcherGroup`](./plugin/on.md#MatcherGroup)
- `load_plugin` => [`load_plugin`](./plugin/load.md#load_plugin)
- `load_plugins` => [`load_plugins`](./plugin/load.md#load_plugins)
- `load_all_plugins` => [`load_all_plugins`](./plugin/load.md#load_all_plugins)
- `load_from_json` => [`load_from_json`](./plugin/load.md#load_from_json)
- `load_from_toml` => [`load_from_toml`](./plugin/load.md#load_from_toml)
- `load_builtin_plugin` => [`load_builtin_plugin`](./plugin/load.md#load_builtin_plugin)
- `load_builtin_plugins` => [`load_builtin_plugins`](./plugin/load.md#load_builtin_plugins)
- `get_plugin` => [`get_plugin`](./plugin/index.md#get_plugin)
- `get_plugin_by_module_name` => [`get_plugin_by_module_name`](./plugin/index.md#get_plugin_by_module_name)
- `get_loaded_plugins` => [`get_loaded_plugins`](./plugin/index.md#get_loaded_plugins)
- `get_available_plugin_names` => [`get_available_plugin_names`](./plugin/index.md#get_available_plugin_names)
- `require` => [`require`](./plugin/load.md#require)
## _def_ `get_driver()` {#get_driver}
- **说明**
获取全局 [Driver](./drivers/index.md#Driver) 实例。
可用于在计划任务的回调等情形中获取当前 [Driver](./drivers/index.md#Driver) 实例。
- **返回**
- nonebot.internal.driver.driver.Driver: 全局 [Driver](./drivers/index.md#Driver) 对象
- **异常**
- `ValueError`: 全局 [Driver](./drivers/index.md#Driver) 对象尚未初始化 ([nonebot.init](#init) 尚未调用)
- **用法**
```python
driver = nonebot.get_driver()
```
## _def_ `get_app()` {#get_app}
- **说明**
获取全局 [ReverseDriver](./drivers/index.md#ReverseDriver) 对应的 Server App 对象。
- **返回**
- Any: Server App 对象
- **异常**
- `AssertionError`: 全局 Driver 对象不是 [ReverseDriver](./drivers/index.md#ReverseDriver) 类型
- `ValueError`: 全局 [Driver](./drivers/index.md#Driver) 对象尚未初始化 ([nonebot.init](#init) 尚未调用)
- **用法**
```python
app = nonebot.get_app()
```
## _def_ `get_asgi()` {#get_asgi}
- **说明**
获取全局 [ReverseDriver](./drivers/index.md#ReverseDriver) 对应 [ASGI](https://asgi.readthedocs.io/) 对象。
- **返回**
- Any: ASGI 对象
- **异常**
- `AssertionError`: 全局 Driver 对象不是 [ReverseDriver](./drivers/index.md#ReverseDriver) 类型
- `ValueError`: 全局 [Driver](./drivers/index.md#Driver) 对象尚未初始化 ([nonebot.init](#init) 尚未调用)
- **用法**
```python
asgi = nonebot.get_asgi()
```
## _def_ `get_bot(self_id=None)` {#get_bot}
- **说明**
获取一个连接到 NoneBot 的 [Bot](./adapters/index.md#Bot) 对象。
当提供 `self_id` 时,此函数是 `get_bots()[self_id]` 的简写;
当不提供时,返回一个 [Bot](./adapters/index.md#Bot)。
- **参数**
- `self_id` (str | None): 用来识别 [Bot](./adapters/index.md#Bot) 的 {ref}`nonebot.adapters.Bot.self_id` 属性
- **返回**
- nonebot.internal.adapter.bot.Bot: [Bot](./adapters/index.md#Bot) 对象
- **异常**
- `KeyError`: 对应 self_id 的 Bot 不存在
- `ValueError`: 没有传入 self_id 且没有 Bot 可用
- `ValueError`: 全局 [Driver](./drivers/index.md#Driver) 对象尚未初始化 ([nonebot.init](#init) 尚未调用)
- **用法**
```python
assert nonebot.get_bot("12345") == nonebot.get_bots()["12345"]
another_unspecified_bot = nonebot.get_bot()
```
## _def_ `get_bots()` {#get_bots}
- **说明**
获取所有连接到 NoneBot 的 [Bot](./adapters/index.md#Bot) 对象。
- **返回**
- dict[str, nonebot.internal.adapter.bot.Bot]: 一个以 {ref}`nonebot.adapters.Bot.self_id` 为键,[Bot](./adapters/index.md#Bot) 对象为值的字典
- **异常**
- `ValueError`: 全局 [Driver](./drivers/index.md#Driver) 对象尚未初始化 ([nonebot.init](#init) 尚未调用)
- **用法**
```python
bots = nonebot.get_bots()
```
## _def_ `init(*, _env_file=None, **kwargs)` {#init}
- **说明**
初始化 NoneBot 以及 全局 [Driver](./drivers/index.md#Driver) 对象。
NoneBot 将会从 .env 文件中读取环境信息,并使用相应的 env 文件配置。
也可以传入自定义的 `_env_file` 来指定 NoneBot 从该文件读取配置。
- **参数**
- `_env_file` (str | None): 配置文件名,默认从 `.env.{env_name}` 中读取配置
- `**kwargs` (Any): 任意变量,将会存储到 {ref}`nonebot.drivers.Driver.config` 对象里
- **返回**
- None
- **用法**
```python
nonebot.init(database=Database(...))
```
## _def_ `run(*args, **kwargs)` {#run}
- **说明**
启动 NoneBot即运行全局 [Driver](./drivers/index.md#Driver) 对象。
- **参数**
- `*args` (Any): 传入 [Driver.run](./drivers/index.md#Driver-run) 的位置参数
- `**kwargs` (Any): 传入 [Driver.run](./drivers/index.md#Driver-run) 的命名参数
- **返回**
- None
- **用法**
```python
nonebot.run(host="127.0.0.1", port=8080)
```

View File

@ -1,75 +0,0 @@
---
sidebar_position: 7
description: nonebot.log 模块
---
# nonebot.log
本模块定义了 NoneBot 的日志记录 Logger。
NoneBot 使用 [`loguru`][loguru] 来记录日志信息。
自定义 logger 请参考 [自定义日志](https://v2.nonebot.dev/docs/tutorial/custom-logger)
以及 [`loguru`][loguru] 文档。
[loguru]: https://github.com/Delgan/loguru
## _var_ `logger` {#logger}
- **类型:** Logger
- **说明**
NoneBot 日志记录器对象。
默认信息:
- 格式: `[%(asctime)s %(name)s] %(levelname)s: %(message)s`
- 等级: `INFO` ,根据 `config.log_level` 配置改变
- 输出: 输出至 stdout
- **用法**
```python
from nonebot.log import logger
```
## _var_ `default_format` {#default_format}
- **类型:** str
- **说明:** 默认日志格式
## _class_ `LoguruHandler(level=0)` {#LoguruHandler}
- **说明**
logging 与 loguru 之间的桥梁,将 logging 的日志转发到 loguru。
- **参数**
- `level`
### _method_ `emit(self, record)` {#LoguruHandler-emit}
- **参数**
- `record` (logging.LogRecord)
- **返回**
- Unknown
## _def_ `default_filter(record)` {#default_filter}
- **说明**
默认的日志过滤器,根据 `config.log_level` 配置改变日志等级。
- **参数**
- `record` (Record)
- **返回**
- Unknown

View File

@ -1,481 +0,0 @@
---
sidebar_position: 3
description: nonebot.matcher 模块
---
# nonebot.matcher
本模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行对话。
## _class_ `Matcher()` {#Matcher}
- **说明**
事件响应器类
### _classmethod_ `append_handler(cls, handler, parameterless=None)` {#Matcher-append_handler}
- **参数**
- `handler` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any])
- `parameterless` (Iterable[Any] | None)
- **返回**
- [Dependent](./dependencies/index.md#Dependent)[typing.Any]
### _async classmethod_ `check_perm(cls, bot, event, stack=None, dependency_cache=None)` {#Matcher-check_perm}
- **说明**
检查是否满足触发权限
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot): Bot 对象
- `event` (nonebot.internal.adapter.event.Event): 上报事件
- `stack` (contextlib.AsyncExitStack | None): 异步上下文栈
- `dependency_cache` (dict[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any], Task[Any]] | None): 依赖缓存
- **返回**
- bool: 是否满足权限
### _async classmethod_ `check_rule(cls, bot, event, state, stack=None, dependency_cache=None)` {#Matcher-check_rule}
- **说明**
检查是否满足匹配规则
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot): Bot 对象
- `event` (nonebot.internal.adapter.event.Event): 上报事件
- `state` (dict[Any, Any]): 当前状态
- `stack` (contextlib.AsyncExitStack | None): 异步上下文栈
- `dependency_cache` (dict[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any], Task[Any]] | None): 依赖缓存
- **返回**
- bool: 是否满足匹配规则
### _async classmethod_ `finish(cls, message=None, **kwargs)` {#Matcher-finish}
- **说明**
发送一条消息给当前交互用户并结束当前事件响应器
- **参数**
- `message` (str | nonebot.internal.adapter.message.Message | nonebot.internal.adapter.message.MessageSegment | nonebot.internal.adapter.template.MessageTemplate | NoneType): 消息内容
- `**kwargs`: [Bot.send](./adapters/index.md#Bot-send) 的参数,请参考对应 adapter 的 bot 对象 api
- **返回**
- NoReturn
### _method_ `get_arg(self, key, default=None)` {#Matcher-get_arg}
- **说明**
获取一个 `got` 消息
如果没有找到对应的消息,返回 `default`
- **参数**
- `key` (str)
- `default` ((~ T) | None)
- **返回**
- nonebot.internal.adapter.message.Message | (~ T) | NoneType
### _method_ `get_last_receive(self, default=None)` {#Matcher-get_last_receive}
- **说明**
获取最近一次 `receive` 事件
如果没有事件,返回 `default`
- **参数**
- `default` ((~ T) | None)
- **返回**
- nonebot.internal.adapter.event.Event | (~ T) | NoneType
### _method_ `get_receive(self, id, default=None)` {#Matcher-get_receive}
- **说明**
获取一个 `receive` 事件
如果没有找到对应的事件,返回 `default`
- **参数**
- `id` (str)
- `default` ((~ T) | None)
- **返回**
- nonebot.internal.adapter.event.Event | (~ T) | NoneType
### _method_ `get_target(self, default=None)` {#Matcher-get_target}
- **参数**
- `default` ((~ T) | None)
- **返回**
- str | (~ T) | NoneType
### _classmethod_ `got(cls, key, prompt=None, parameterless=None)` {#Matcher-got}
- **说明**
装饰一个函数来指示 NoneBot 获取一个参数 `key`
当要获取的 `key` 不存在时接收用户新的一条消息再运行该函数,如果 `key` 已存在则直接继续运行
- **参数**
- `key` (str): 参数名
- `prompt` (str | nonebot.internal.adapter.message.Message | nonebot.internal.adapter.message.MessageSegment | nonebot.internal.adapter.template.MessageTemplate | NoneType): 在参数不存在时向用户发送的消息
- `parameterless` (Iterable[Any] | None): 非参数类型依赖列表
- **返回**
- ((\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]) -> (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
### _classmethod_ `handle(cls, parameterless=None)` {#Matcher-handle}
- **说明**
装饰一个函数来向事件响应器直接添加一个处理函数
- **参数**
- `parameterless` (Iterable[Any] | None): 非参数类型依赖列表
- **返回**
- ((\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]) -> (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
### _classmethod_ `new(cls, type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, plugin=None, module=None, expire_time=None, default_state=None, default_type_updater=None, default_permission_updater=None)` {#Matcher-new}
- **说明**
创建一个新的事件响应器,并存储至 `matchers <#matchers>`\_
- **参数**
- `type_` (str): 事件响应器类型,与 `event.get_type()` 一致时触发,空字符串表示任意
- `rule` (nonebot.internal.rule.Rule | None): 匹配规则
- `permission` (nonebot.internal.permission.Permission | None): 权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](./dependencies/index.md#Dependent)[Any]] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器,即触发一次后删除
- `priority` (int): 响应优先级
- `block` (bool): 是否阻止事件向更低优先级的响应器传播
- `plugin` (Plugin | None): 事件响应器所在插件
- `module` (module | None): 事件响应器所在模块
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `default_state` (dict[Any, Any] | None): 默认状态 `state`
- `default_type_updater` ((*Any, \*\*Any) -> str | (*Any, \*\*Any) -> Awaitable[str] | [Dependent](./dependencies/index.md#Dependent)[str] | NoneType)
- `default_permission_updater` ((*Any, \*\*Any) -> Permission | (*Any, \*\*Any) -> Awaitable[Permission] | [Dependent](./dependencies/index.md#Dependent)[nonebot.internal.permission.Permission] | NoneType)
- **返回**
- Type[Matcher]: 新的事件响应器类
### _async classmethod_ `pause(cls, prompt=None, **kwargs)` {#Matcher-pause}
- **说明**
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
- **参数**
- `prompt` (str | nonebot.internal.adapter.message.Message | nonebot.internal.adapter.message.MessageSegment | nonebot.internal.adapter.template.MessageTemplate | NoneType): 消息内容
- `**kwargs`: [Bot.send](./adapters/index.md#Bot-send) 的参数,请参考对应 adapter 的 bot 对象 api
- **返回**
- NoReturn
### _classmethod_ `permission_updater(cls, func)` {#Matcher-permission_updater}
- **说明**
装饰一个函数来更改当前事件响应器的默认会话权限更新函数
- **参数**
- `func` ((*Any, \*\*Any) -> Permission | (*Any, \*\*Any) -> Awaitable[Permission]): 会话权限更新函数
- **返回**
- (\*Any, \*\*Any) -> Permission | (\*Any, \*\*Any) -> Awaitable[Permission]
### _classmethod_ `receive(cls, id='', parameterless=None)` {#Matcher-receive}
- **说明**
装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
- **参数**
- `id` (str): 消息 ID
- `parameterless` (Iterable[Any] | None): 非参数类型依赖列表
- **返回**
- ((\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]) -> (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
### _async classmethod_ `reject(cls, prompt=None, **kwargs)` {#Matcher-reject}
- **说明**
最近使用 `got` / `receive` 接收的消息不符合预期,
发送一条消息给当前交互用户并将当前事件处理流程中断在当前位置,在接收用户新的一个事件后从头开始执行当前处理函数
- **参数**
- `prompt` (str | nonebot.internal.adapter.message.Message | nonebot.internal.adapter.message.MessageSegment | nonebot.internal.adapter.template.MessageTemplate | NoneType): 消息内容
- `**kwargs`: [Bot.send](./adapters/index.md#Bot-send) 的参数,请参考对应 adapter 的 bot 对象 api
- **返回**
- NoReturn
### _async classmethod_ `reject_arg(cls, key, prompt=None, **kwargs)` {#Matcher-reject_arg}
- **说明**
最近使用 `got` 接收的消息不符合预期,
发送一条消息给当前交互用户并将当前事件处理流程中断在当前位置,在接收用户新的一条消息后从头开始执行当前处理函数
- **参数**
- `key` (str): 参数名
- `prompt` (str | nonebot.internal.adapter.message.Message | nonebot.internal.adapter.message.MessageSegment | nonebot.internal.adapter.template.MessageTemplate | NoneType): 消息内容
- `**kwargs`: [Bot.send](./adapters/index.md#Bot-send) 的参数,请参考对应 adapter 的 bot 对象 api
- **返回**
- NoReturn
### _async classmethod_ `reject_receive(cls, id='', prompt=None, **kwargs)` {#Matcher-reject_receive}
- **说明**
最近使用 `receive` 接收的消息不符合预期,
发送一条消息给当前交互用户并将当前事件处理流程中断在当前位置,在接收用户新的一个事件后从头开始执行当前处理函数
- **参数**
- `id` (str): 消息 id
- `prompt` (str | nonebot.internal.adapter.message.Message | nonebot.internal.adapter.message.MessageSegment | nonebot.internal.adapter.template.MessageTemplate | NoneType): 消息内容
- `**kwargs`: [Bot.send](./adapters/index.md#Bot-send) 的参数,请参考对应 adapter 的 bot 对象 api
- **返回**
- NoReturn
### _async method_ `resolve_reject(self)` {#Matcher-resolve_reject}
- **返回**
- Unknown
### _async method_ `run(self, bot, event, state, stack=None, dependency_cache=None)` {#Matcher-run}
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot)
- `event` (nonebot.internal.adapter.event.Event)
- `state` (dict[Any, Any])
- `stack` (contextlib.AsyncExitStack | None)
- `dependency_cache` (dict[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any], Task[Any]] | None)
- **返回**
- Unknown
### _async classmethod_ `send(cls, message, **kwargs)` {#Matcher-send}
- **说明**
发送一条消息给当前交互用户
- **参数**
- `message` (str | nonebot.internal.adapter.message.Message | nonebot.internal.adapter.message.MessageSegment | nonebot.internal.adapter.template.MessageTemplate): 消息内容
- `**kwargs` (Any): [Bot.send](./adapters/index.md#Bot-send) 的参数,请参考对应 adapter 的 bot 对象 api
- **返回**
- Any
### _method_ `set_arg(self, key, message)` {#Matcher-set_arg}
- **说明**
设置一个 `got` 消息
- **参数**
- `key` (str)
- `message` (nonebot.internal.adapter.message.Message)
- **返回**
- None
### _method_ `set_receive(self, id, event)` {#Matcher-set_receive}
- **说明**
设置一个 `receive` 事件
- **参数**
- `id` (str)
- `event` (nonebot.internal.adapter.event.Event)
- **返回**
- None
### _method_ `set_target(self, target, cache=True)` {#Matcher-set_target}
- **参数**
- `target` (str)
- `cache` (bool)
- **返回**
- None
### _async method_ `simple_run(self, bot, event, state, stack=None, dependency_cache=None)` {#Matcher-simple_run}
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot)
- `event` (nonebot.internal.adapter.event.Event)
- `state` (dict[Any, Any])
- `stack` (contextlib.AsyncExitStack | None)
- `dependency_cache` (dict[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any], Task[Any]] | None)
- **返回**
- Unknown
### _classmethod_ `skip(cls)` {#Matcher-skip}
- **说明**
跳过当前事件处理函数,继续下一个处理函数
通常在事件处理函数的依赖中使用。
- **返回**
- NoReturn
### _method_ `stop_propagation(self)` {#Matcher-stop_propagation}
- **说明**
阻止事件传播
- **返回**
- Unknown
### _classmethod_ `type_updater(cls, func)` {#Matcher-type_updater}
- **说明**
装饰一个函数来更改当前事件响应器的默认响应事件类型更新函数
- **参数**
- `func` ((*Any, \*\*Any) -> str | (*Any, \*\*Any) -> Awaitable[str]): 响应事件类型更新函数
- **返回**
- (\*Any, \*\*Any) -> str | (\*Any, \*\*Any) -> Awaitable[str]
### _async method_ `update_permission(self, bot, event)` {#Matcher-update_permission}
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot)
- `event` (nonebot.internal.adapter.event.Event)
- **返回**
- nonebot.internal.permission.Permission
### _async method_ `update_type(self, bot, event)` {#Matcher-update_type}
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot)
- `event` (nonebot.internal.adapter.event.Event)
- **返回**
- str

View File

@ -1,89 +0,0 @@
---
sidebar_position: 2
description: nonebot.message 模块
---
# nonebot.message
本模块定义了事件处理主要流程。
NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供了多个插槽以进行事件的预处理等。
## _def_ `event_preprocessor(func)` {#event_preprocessor}
- **说明**
事件预处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之前执行。
- **参数**
- `func` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any])
- **返回**
- (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
## _def_ `event_postprocessor(func)` {#event_postprocessor}
- **说明**
事件后处理。装饰一个函数,使它在每次接收到事件并分发给各响应器之后执行。
- **参数**
- `func` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any])
- **返回**
- (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
## _def_ `run_preprocessor(func)` {#run_preprocessor}
- **说明**
运行预处理。装饰一个函数,使它在每次事件响应器运行前执行。
- **参数**
- `func` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any])
- **返回**
- (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
## _def_ `run_postprocessor(func)` {#run_postprocessor}
- **说明**
运行后处理。装饰一个函数,使它在每次事件响应器运行后执行。
- **参数**
- `func` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any])
- **返回**
- (\*Any, \*\*Any) -> Any | (\*Any, \*\*Any) -> Awaitable[Any]
## _async def_ `handle_event(bot, event)` {#handle_event}
- **说明**
处理一个事件。调用该函数以实现分发事件。
- **参数**
- `bot` (Bot): Bot 对象
- `event` (Event): Event 对象
- **返回**
- None
- **用法**
```python
import asyncio
asyncio.create_task(handle_event(bot, event))
```

View File

@ -1,338 +0,0 @@
---
sidebar_position: 4
description: nonebot.params 模块
---
# nonebot.params
本模块定义了依赖注入的各类参数。
## _def_ `Arg(key=None)` {#Arg}
- **说明**
`got` 的 Arg 参数消息
- **参数**
- `key` (str | None)
- **返回**
- Any
## _def_ `ArgStr(key=None)` {#ArgStr}
- **说明**
`got` 的 Arg 参数消息文本
- **参数**
- `key` (str | None)
- **返回**
- str
## _def_ `Depends(dependency=None, *, use_cache=True)` {#Depends}
- **说明**
子依赖装饰器
- **参数**
- `dependency` ((*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | NoneType): 依赖函数。默认为参数的类型注释。
- `use_cache` (bool): 是否使用缓存。默认为 `True`
- **返回**
- Any
- **用法**
```python
def depend_func() -> Any:
return ...
def depend_gen_func():
try:
yield ...
finally:
...
async def handler(param_name: Any = Depends(depend_func), gen: Any = Depends(depend_gen_func)):
...
```
## _class_ `ArgParam(default=PydanticUndefined, **kwargs)` {#ArgParam}
- **说明**
`got` 的 Arg 参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _class_ `BotParam(default=PydanticUndefined, **kwargs)` {#BotParam}
- **说明**
[Bot](./adapters/index.md#Bot) 参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _class_ `EventParam(default=PydanticUndefined, **kwargs)` {#EventParam}
- **说明**
[Event](./adapters/index.md#Event) 参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _class_ `StateParam(default=PydanticUndefined, **kwargs)` {#StateParam}
- **说明**
事件处理状态参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _class_ `DependParam(default=PydanticUndefined, **kwargs)` {#DependParam}
- **说明**
子依赖参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _def_ `ArgPlainText(key=None)` {#ArgPlainText}
- **说明**
`got` 的 Arg 参数消息纯文本
- **参数**
- `key` (str | None)
- **返回**
- str
## _class_ `DefaultParam(default=PydanticUndefined, **kwargs)` {#DefaultParam}
- **说明**
默认值参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _class_ `MatcherParam(default=PydanticUndefined, **kwargs)` {#MatcherParam}
- **说明**
事件响应器实例参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _class_ `ExceptionParam(default=PydanticUndefined, **kwargs)` {#ExceptionParam}
- **说明**
`run_postprocessor` 的异常参数
- **参数**
- `default` (Any)
- `**kwargs` (Any)
## _def_ `EventType()` {#EventType}
- **说明**
[Event](./adapters/index.md#Event) 类型参数
- **返回**
- str
## _def_ `EventMessage()` {#EventMessage}
- **说明**
[Event](./adapters/index.md#Event) 消息参数
- **返回**
- Any
## _def_ `EventPlainText()` {#EventPlainText}
- **说明**
[Event](./adapters/index.md#Event) 纯文本消息参数
- **返回**
- str
## _def_ `EventToMe()` {#EventToMe}
- **说明**
[Event](./adapters/index.md#Event) `to_me` 参数
- **返回**
- bool
## _def_ `Command()` {#Command}
- **说明**
消息命令元组
- **返回**
- tuple[str, ...]
## _def_ `RawCommand()` {#RawCommand}
- **说明**
消息命令文本
- **返回**
- str
## _def_ `CommandArg()` {#CommandArg}
- **说明**
消息命令参数
- **返回**
- Any
## _def_ `CommandStart()` {#CommandStart}
- **说明**
消息命令开头
- **返回**
- str
## _def_ `ShellCommandArgs()` {#ShellCommandArgs}
- **说明**
shell 命令解析后的参数字典
- **返回**
- Any
## _def_ `ShellCommandArgv()` {#ShellCommandArgv}
- **说明**
shell 命令原始参数列表
- **返回**
- Any
## _def_ `RegexMatched()` {#RegexMatched}
- **说明**
正则匹配结果
- **返回**
- str
## _def_ `RegexGroup()` {#RegexGroup}
- **说明**
正则匹配结果 group 元组
- **返回**
- tuple[Any, ...]
## _def_ `RegexDict()` {#RegexDict}
- **说明**
正则匹配结果 group 字典
- **返回**
- dict[str, Any]
## _def_ `Received(id=None, default=None)` {#Received}
- **说明**
`receive` 事件参数
- **参数**
- `id` (str | None)
- `default` (Any)
- **返回**
- Any
## _def_ `LastReceived(default=None)` {#LastReceived}
- **说明**
`last_receive` 事件参数
- **参数**
- `default` (Any)
- **返回**
- Any

View File

@ -1,157 +0,0 @@
---
sidebar_position: 6
description: nonebot.permission 模块
---
# nonebot.permission
本模块是 {ref}`nonebot.matcher.Matcher.permission` 的类型定义。
每个 [Matcher](./matcher.md#Matcher) 拥有一个 [Permission](#Permission)
其中是 `PermissionChecker` 的集合,只要有一个 `PermissionChecker` 检查结果为 `True` 时就会继续运行。
## _var_ `MESSAGE` {#MESSAGE}
- **类型:** nonebot.internal.permission.Permission
- **说明**
匹配任意 `message` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 message type 的 Matcher。
## _var_ `NOTICE` {#NOTICE}
- **类型:** nonebot.internal.permission.Permission
- **说明**
匹配任意 `notice` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 notice type 的 Matcher。
## _var_ `REQUEST` {#REQUEST}
- **类型:** nonebot.internal.permission.Permission
- **说明**
匹配任意 `request` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 request type 的 Matcher。
## _var_ `METAEVENT` {#METAEVENT}
- **类型:** nonebot.internal.permission.Permission
- **说明**
匹配任意 `meta_event` 类型事件
仅在需要同时捕获不同类型事件时使用,优先使用 meta_event type 的 Matcher。
## _var_ `SUPERUSER` {#SUPERUSER}
- **类型:** nonebot.internal.permission.Permission
- **说明:** 匹配任意超级用户事件
## _def_ `USER(*users, perm=None)` {#USER}
- **说明**
匹配当前事件属于指定会话
- **参数**
- `*users` (str)
- `perm` (nonebot.internal.permission.Permission | None): 需要同时满足的权限
- `user`: 会话白名单
- **返回**
- Unknown
## _class_ `User(users, perm=None)` {#User}
- **说明**
检查当前事件是否属于指定会话
- **参数**
- `users` (tuple[str, ...]): 会话 ID 元组
- `perm` (nonebot.internal.permission.Permission | None): 需同时满足的权限
## _class_ `Permission(*checkers)` {#Permission}
- **说明**
[Matcher](./matcher.md#Matcher) 权限类。
当事件传递时,在 [Matcher](./matcher.md#Matcher) 运行前进行检查。
- **参数**
- `*checkers` ((*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | [Dependent](./dependencies/index.md#Dependent)[bool]): PermissionChecker
- **用法**
```python
Permission(async_function) | sync_function
# 等价于
Permission(async_function, sync_function)
```
### _async method_ `__call__(self, bot, event, stack=None, dependency_cache=None)` {#Permission-**call**}
- **说明**
检查是否满足某个权限
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot): Bot 对象
- `event` (nonebot.internal.adapter.event.Event): Event 对象
- `stack` (contextlib.AsyncExitStack | None): 异步上下文栈
- `dependency_cache` (dict[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any], Task[Any]] | None): 依赖缓存
- **返回**
- bool
## _class_ `Message()` {#Message}
- **说明**
检查是否为消息事件
## _class_ `Notice()` {#Notice}
- **说明**
检查是否为通知事件
## _class_ `Request()` {#Request}
- **说明**
检查是否为请求事件
## _class_ `MetaEvent()` {#MetaEvent}
- **说明**
检查是否为元事件
## _class_ `SuperUser()` {#SuperUser}
- **说明**
检查当前事件是否是消息事件且属于超级管理员

View File

@ -1,3 +0,0 @@
{
"position": 12
}

View File

@ -1,89 +0,0 @@
---
sidebar_position: 0
description: nonebot.plugin 模块
---
# nonebot.plugin
本模块为 NoneBot 插件开发提供便携的定义函数。
## 快捷导入
为方便使用,本模块从子模块导入了部分内容,以下内容可以直接通过本模块导入:
- `on` => [`on`](./on.md#on)
- `on_metaevent` => [`on_metaevent`](./on.md#on_metaevent)
- `on_message` => [`on_message`](./on.md#on_message)
- `on_notice` => [`on_notice`](./on.md#on_notice)
- `on_request` => [`on_request`](./on.md#on_request)
- `on_startswith` => [`on_startswith`](./on.md#on_startswith)
- `on_endswith` => [`on_endswith`](./on.md#on_endswith)
- `on_fullmatch` => [`on_fullmatch`](./on.md#on_fullmatch)
- `on_keyword` => [`on_keyword`](./on.md#on_keyword)
- `on_command` => [`on_command`](./on.md#on_command)
- `on_shell_command` => [`on_shell_command`](./on.md#on_shell_command)
- `on_regex` => [`on_regex`](./on.md#on_regex)
- `on_type` => [`on_type`](./on.md#on_type)
- `CommandGroup` => [`CommandGroup`](./on.md#CommandGroup)
- `Matchergroup` => [`MatcherGroup`](./on.md#MatcherGroup)
- `load_plugin` => [`load_plugin`](./load.md#load_plugin)
- `load_plugins` => [`load_plugins`](./load.md#load_plugins)
- `load_all_plugins` => [`load_all_plugins`](./load.md#load_all_plugins)
- `load_from_json` => [`load_from_json`](./load.md#load_from_json)
- `load_from_toml` => [`load_from_toml`](./load.md#load_from_toml)
- `load_builtin_plugin` => [`load_builtin_plugin`](./load.md#load_builtin_plugin)
- `load_builtin_plugins` => [`load_builtin_plugins`](./load.md#load_builtin_plugins)
- `require` => [`require`](./load.md#require)
- `PluginMetadata` => [`PluginMetadata`](./plugin.md#PluginMetadata)
## _def_ `get_plugin(name)` {#get_plugin}
- **说明**
获取已经导入的某个插件。
如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。
- **参数**
- `name` (str): 插件名,即 [Plugin.name](./plugin.md#Plugin-name)。
- **返回**
- Plugin | None
## _def_ `get_plugin_by_module_name(module_name)` {#get_plugin_by_module_name}
- **说明**
通过模块名获取已经导入的某个插件。
如果提供的模块名为某个插件的子模块,同样会返回该插件。
- **参数**
- `module_name` (str): 模块名,即 [Plugin.module_name](./plugin.md#Plugin-module_name)。
- **返回**
- Plugin | None
## _def_ `get_loaded_plugins()` {#get_loaded_plugins}
- **说明**
获取当前已导入的所有插件。
- **返回**
- set[Plugin]
## _def_ `get_available_plugin_names()` {#get_available_plugin_names}
- **说明**
获取当前所有可用的插件名(包含尚未加载的插件)。
- **返回**
- set[str]

View File

@ -1,157 +0,0 @@
---
sidebar_position: 1
description: nonebot.plugin.load 模块
---
# nonebot.plugin.load
本模块定义插件加载接口。
## _def_ `load_plugin(module_path)` {#load_plugin}
- **说明**
加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。
- **参数**
- `module_path` (str | pathlib.Path): 插件名称 `path.to.your.plugin` 或插件路径 `pathlib.Path(path/to/your/plugin)`
- **返回**
- [Plugin](./plugin.md#Plugin) | None
## _def_ `load_plugins(*plugin_dir)` {#load_plugins}
- **说明**
导入文件夹下多个插件,以 `_` 开头的插件不会被导入!
- **参数**
- `*plugin_dir` (str): 文件夹路径
- **返回**
- set[[Plugin](./plugin.md#Plugin)]
## _def_ `load_all_plugins(module_path, plugin_dir)` {#load_all_plugins}
- **说明**
导入指定列表中的插件以及指定目录下多个插件,以 `_` 开头的插件不会被导入!
- **参数**
- `module_path` (Iterable[str]): 指定插件集合
- `plugin_dir` (Iterable[str]): 指定文件夹路径集合
- **返回**
- set[[Plugin](./plugin.md#Plugin)]
## _def_ `load_from_json(file_path, encoding='utf-8')` {#load_from_json}
- **说明**
导入指定 json 文件中的 `plugins` 以及 `plugin_dirs` 下多个插件,以 `_` 开头的插件不会被导入!
- **参数**
- `file_path` (str): 指定 json 文件路径
- `encoding` (str): 指定 json 文件编码
- **返回**
- set[[Plugin](./plugin.md#Plugin)]
- **用法**
```json title=plugins.json
{
"plugins": ["some_plugin"],
"plugin_dirs": ["some_dir"]
}
```
```python
nonebot.load_from_json("plugins.json")
```
## _def_ `load_from_toml(file_path, encoding='utf-8')` {#load_from_toml}
- **说明**
导入指定 toml 文件 `[tool.nonebot]` 中的 `plugins` 以及 `plugin_dirs` 下多个插件,以 `_` 开头的插件不会被导入!
- **参数**
- `file_path` (str): 指定 toml 文件路径
- `encoding` (str): 指定 toml 文件编码
- **返回**
- set[[Plugin](./plugin.md#Plugin)]
- **用法**
```toml title=pyproject.toml
[tool.nonebot]
plugins = ["some_plugin"]
plugin_dirs = ["some_dir"]
```
```python
nonebot.load_from_toml("pyproject.toml")
```
## _def_ `load_builtin_plugin(name)` {#load_builtin_plugin}
- **说明**
导入 NoneBot 内置插件。
- **参数**
- `name` (str): 插件名称
- **返回**
- [Plugin](./plugin.md#Plugin) | None
## _def_ `load_builtin_plugins(*plugins)` {#load_builtin_plugins}
- **说明**
导入多个 NoneBot 内置插件。
- **参数**
- `*plugins` (str): 插件名称列表
- **返回**
- set[[Plugin](./plugin.md#Plugin)]
## _def_ `require(name)` {#require}
- **说明**
获取一个插件的导出内容。
如果为 `load_plugins` 文件夹导入的插件,则为文件(夹)名。
- **参数**
- `name` (str): 插件名,即 [Plugin.name](./plugin.md#Plugin-name)。
- **返回**
- module
- **异常**
- `RuntimeError`: 插件无法加载

View File

@ -1,122 +0,0 @@
---
sidebar_position: 5
description: nonebot.plugin.manager 模块
---
# nonebot.plugin.manager
本模块实现插件加载流程。
参考: [import hooks](https://docs.python.org/3/reference/import.html#import-hooks), [PEP302](https://www.python.org/dev/peps/pep-0302/)
## _class_ `PluginManager(plugins=None, search_path=None)` {#PluginManager}
- **说明**
插件管理器。
- **参数**
- `plugins` (Iterable[str] | None): 独立插件模块名集合。
- `search_path` (Iterable[str] | None): 插件搜索路径(文件夹)。
### _property_ `available_plugins` {#PluginManager-available_plugins}
- **类型:** set[str]
- **说明:** 返回当前插件管理器中可用的插件名称。
### _property_ `searched_plugins` {#PluginManager-searched_plugins}
- **类型:** set[str]
- **说明:** 返回已搜索到的插件名称。
### _property_ `third_party_plugins` {#PluginManager-third_party_plugins}
- **类型:** set[str]
- **说明:** 返回所有独立插件名称。
### _method_ `load_all_plugins(self)` {#PluginManager-load_all_plugins}
- **说明**
加载所有可用插件。
- **返回**
- set[[Plugin](./plugin.md#Plugin)]
### _method_ `load_plugin(self, name)` {#PluginManager-load_plugin}
- **说明**
加载指定插件。
对于独立插件,可以使用完整插件模块名或者插件名称。
- **参数**
- `name` (str): 插件名称。
- **返回**
- [Plugin](./plugin.md#Plugin) | None
### _method_ `prepare_plugins(self)` {#PluginManager-prepare_plugins}
- **说明**
搜索插件并缓存插件名称。
- **返回**
- set[str]
## _class_ `PluginFinder()` {#PluginFinder}
### _method_ `find_spec(self, fullname, path, target=None)` {#PluginFinder-find_spec}
- **参数**
- `fullname` (str)
- `path` (Sequence[bytes | str] | None)
- `target` (module | None)
- **返回**
- Unknown
## _class_ `PluginLoader(manager, fullname, path)` {#PluginLoader}
- **参数**
- `manager` ([PluginManager](#PluginManager))
- `fullname` (str)
- `path`
### _method_ `create_module(self, spec)` {#PluginLoader-create_module}
- **参数**
- `spec`
- **返回**
- module | None
### _method_ `exec_module(self, module)` {#PluginLoader-exec_module}
- **参数**
- `module` (module)
- **返回**
- None

View File

@ -1,914 +0,0 @@
---
sidebar_position: 2
description: nonebot.plugin.on 模块
---
# nonebot.plugin.on
本模块定义事件响应器便携定义函数。
## _def_ `on(type='', rule=..., permission=..., *, handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on}
- **说明**
注册一个基础事件响应器,可自定义类型。
- **参数**
- `type` (str): 事件响应器类型
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_metaevent(rule=..., *, handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_metaevent}
- **说明**
注册一个元事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_message(rule=..., permission=..., *, handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_message}
- **说明**
注册一个消息事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_notice(rule=..., *, handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_notice}
- **说明**
注册一个通知事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_request(rule=..., *, handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_request}
- **说明**
注册一个请求事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_startswith(msg, rule=..., ignorecase=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_startswith}
- **说明**
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息开头内容
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `ignorecase` (bool): 是否忽略大小写
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_endswith(msg, rule=..., ignorecase=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_endswith}
- **说明**
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息结尾内容
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `ignorecase` (bool): 是否忽略大小写
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_fullmatch(msg, rule=..., ignorecase=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_fullmatch}
- **说明**
注册一个消息事件响应器,并且当消息的**文本部分**与指定内容完全一致时响应。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息全匹配内容
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `ignorecase` (bool): 是否忽略大小写
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_keyword(keywords, rule=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_keyword}
- **说明**
注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。
- **参数**
- `keywords` (set[str]): 关键词列表
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_command(cmd, rule=..., aliases=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_command}
- **说明**
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
命令匹配规则参考: `命令形式匹配 <rule.md#command-command>`\_
- **参数**
- `cmd` (str | tuple[str, ...]): 指定命令内容
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `aliases` (set[str | tuple[str, ...]] | None): 命令别名
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_shell_command(cmd, rule=..., aliases=..., parser=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_shell_command}
- **说明**
注册一个支持 `shell_like` 解析参数的命令消息事件响应器。
与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。
并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]`
- **参数**
- `cmd` (str | tuple[str, ...]): 指定命令内容
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `aliases` (set[str | tuple[str, ...]] | None): 命令别名
- `parser` ([ArgumentParser](../rule.md#ArgumentParser) | None): `nonebot.rule.ArgumentParser` 对象
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_regex(pattern, flags=..., rule=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_regex}
- **说明**
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
命令匹配规则参考: `正则匹配 <rule.md#regex-regex-flags-0>`\_
- **参数**
- `pattern` (str): 正则表达式
- `flags` (int | re.RegexFlag): 正则匹配标志
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _def_ `on_type(types, rule=..., *, permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#on_type}
- **说明**
注册一个事件响应器,并且当事件为指定类型时响应。
- **参数**
- `types` (Type[nonebot.internal.adapter.event.Event] | tuple[Type[nonebot.internal.adapter.event.Event]]): 事件类型
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _class_ `CommandGroup(cmd, *, rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#CommandGroup}
- **参数**
- `cmd` (str | tuple[str, ...])
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType)
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType)
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None)
- `temp` (bool)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType)
- `priority` (int)
- `block` (bool)
- `state` (dict[Any, Any] | None)
### _method_ `command(self, cmd, *, rule=..., aliases=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#CommandGroup-command}
- **说明**
注册一个新的命令。新参数将会覆盖命令组默认值
- **参数**
- `cmd` (str | tuple[str, ...]): 指定命令内容
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `aliases` (set[str | tuple[str, ...]] | None): 命令别名
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `shell_command(self, cmd, *, rule=..., aliases=..., parser=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#CommandGroup-shell_command}
- **说明**
注册一个新的 `shell_like` 命令。新参数将会覆盖命令组默认值
- **参数**
- `cmd` (str | tuple[str, ...]): 指定命令内容
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `aliases` (set[str | tuple[str, ...]] | None): 命令别名
- `parser` ([ArgumentParser](../rule.md#ArgumentParser) | None): `nonebot.rule.ArgumentParser` 对象
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
## _class_ `MatcherGroup(*, type=..., rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup}
- **参数**
- `type` (str)
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType)
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType)
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None)
- `temp` (bool)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType)
- `priority` (int)
- `block` (bool)
- `state` (dict[Any, Any] | None)
### _method_ `on(self, *, type=..., rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on}
- **说明**
注册一个基础事件响应器,可自定义类型。
- **参数**
- `type` (str): 事件响应器类型
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_command(self, cmd, aliases=..., *, rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_command}
- **说明**
注册一个消息事件响应器,并且当消息以指定命令开头时响应。
命令匹配规则参考: `命令形式匹配 <rule.md#command-command>`\_
- **参数**
- `cmd` (str | tuple[str, ...]): 指定命令内容
- `aliases` (set[str | tuple[str, ...]] | None): 命令别名
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_endswith(self, msg, *, ignorecase=..., rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_endswith}
- **说明**
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容结尾时响应。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息结尾内容
- `ignorecase` (bool): 是否忽略大小写
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_fullmatch(self, msg, *, ignorecase=..., rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_fullmatch}
- **说明**
注册一个消息事件响应器,并且当消息的**文本部分**与指定内容完全一致时响应。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息全匹配内容
- `ignorecase` (bool): 是否忽略大小写
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_keyword(self, keywords, *, rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_keyword}
- **说明**
注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。
- **参数**
- `keywords` (set[str]): 关键词列表
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_message(self, *, rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_message}
- **说明**
注册一个消息事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_metaevent(self, *, rule=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_metaevent}
- **说明**
注册一个元事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_notice(self, *, rule=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_notice}
- **说明**
注册一个通知事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_regex(self, pattern, flags=..., *, rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_regex}
- **说明**
注册一个消息事件响应器,并且当消息匹配正则表达式时响应。
命令匹配规则参考: `正则匹配 <rule.md#regex-regex-flags-0>`\_
- **参数**
- `pattern` (str): 正则表达式
- `flags` (int | re.RegexFlag): 正则匹配标志
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_request(self, *, rule=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_request}
- **说明**
注册一个请求事件响应器。
- **参数**
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_shell_command(self, cmd, aliases=..., parser=..., *, rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_shell_command}
- **说明**
注册一个支持 `shell_like` 解析参数的命令消息事件响应器。
与普通的 `on_command` 不同的是,在添加 `parser` 参数时, 响应器会自动处理消息。
并将用户输入的原始参数列表保存在 `state["argv"]`, `parser` 处理的参数保存在 `state["args"]`
- **参数**
- `cmd` (str | tuple[str, ...]): 指定命令内容
- `aliases` (set[str | tuple[str, ...]] | None): 命令别名
- `parser` ([ArgumentParser](../rule.md#ArgumentParser) | None): `nonebot.rule.ArgumentParser` 对象
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_startswith(self, msg, *, ignorecase=..., rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_startswith}
- **说明**
注册一个消息事件响应器,并且当消息的**文本部分**以指定内容开头时响应。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息开头内容
- `ignorecase` (bool): 是否忽略大小写
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]
### _method_ `on_type(self, types, *, rule=..., permission=..., handlers=..., temp=..., expire_time=..., priority=..., block=..., state=...)` {#MatcherGroup-on_type}
- **说明**
注册一个事件响应器,并且当事件为指定类型时响应。
- **参数**
- `types` (Type[nonebot.internal.adapter.event.Event] | tuple[Type[nonebot.internal.adapter.event.Event]]): 事件类型
- `rule` (nonebot.internal.rule.Rule | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应规则
- `permission` (nonebot.internal.permission.Permission | (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | NoneType): 事件响应权限
- `handlers` (list[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any] | [Dependent](../dependencies/index.md#Dependent)] | None): 事件处理函数列表
- `temp` (bool): 是否为临时事件响应器(仅执行一次)
- `expire_time` (datetime.datetime | datetime.timedelta | NoneType): 事件响应器最终有效时间点,过时即被删除
- `priority` (int): 事件响应器优先级
- `block` (bool): 是否阻止事件向更低优先级传递
- `state` (dict[Any, Any] | None): 默认 state
- **返回**
- Type[nonebot.internal.matcher.Matcher]

View File

@ -1,116 +0,0 @@
---
sidebar_position: 3
description: nonebot.plugin.plugin 模块
---
# nonebot.plugin.plugin
本模块定义插件对象。
## _class_ `PluginMetadata(name, description, usage, config=None, extra=<factory>)` {#PluginMetadata}
- **说明**
插件元信息,由插件编写者提供
- **参数**
- `name` (str)
- `description` (str)
- `usage` (str)
- `config` (Type[pydantic.main.BaseModel] | None)
- `extra` (dict[Any, Any])
### _class-var_ `config` {#PluginMetadata-config}
- **类型:** Type[pydantic.main.BaseModel] | None
- **说明:** 插件配置项
### _instance-var_ `name` {#PluginMetadata-name}
- **类型:** str
- **说明:** 插件可阅读名称
### _instance-var_ `description` {#PluginMetadata-description}
- **类型:** str
- **说明:** 插件功能介绍
### _instance-var_ `usage` {#PluginMetadata-usage}
- **类型:** str
- **说明:** 插件使用方法
## _class_ `Plugin(name, module, module_name, manager, matcher=<factory>, parent_plugin=None, sub_plugins=<factory>, metadata=None)` {#Plugin}
- **说明**
存储插件信息
- **参数**
- `name` (str)
- `module` (module)
- `module_name` (str)
- `manager` (PluginManager)
- `matcher` (set[Type[nonebot.internal.matcher.Matcher]])
- `parent_plugin` (Plugin | None)
- `sub_plugins` (set[Plugin])
- `metadata` ([PluginMetadata](#PluginMetadata) | None)
### _class-var_ `parent_plugin` {#Plugin-parent_plugin}
- **类型:** Plugin | None
- **说明:** 父插件
### _instance-var_ `name` {#Plugin-name}
- **类型:** str
- **说明:** 插件索引标识NoneBot 使用 文件/文件夹 名称作为标识符
### _instance-var_ `module` {#Plugin-module}
- **类型:** module
- **说明:** 插件模块对象
### _instance-var_ `module_name` {#Plugin-module_name}
- **类型:** str
- **说明:** 点分割模块路径
### _instance-var_ `manager` {#Plugin-manager}
- **类型:** PluginManager
- **说明:** 导入该插件的插件管理器
### _instance-var_ `matcher` {#Plugin-matcher}
- **类型:** set[Type[nonebot.internal.matcher.Matcher]]
- **说明:** 插件内定义的 `Matcher`
### _instance-var_ `sub_plugins` {#Plugin-sub_plugins}
- **类型:** set[Plugin]
- **说明:** 子插件集合

View File

@ -1,396 +0,0 @@
---
sidebar_position: 5
description: nonebot.rule 模块
---
# nonebot.rule
本模块是 {ref}`nonebot.matcher.Matcher.rule` 的类型定义。
每个事件响应器 [Matcher](./matcher.md#Matcher) 拥有一个匹配规则 [Rule](#Rule)
其中是 `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。
## _class_ `Rule(*checkers)` {#Rule}
- **说明**
[Matcher](./matcher.md#Matcher) 规则类。
当事件传递时,在 [Matcher](./matcher.md#Matcher) 运行前进行检查。
- **参数**
- `*checkers` ((*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool] | [Dependent](./dependencies/index.md#Dependent)[bool])
- **用法**
```python
Rule(async_function) & sync_function
# 等价于
Rule(async_function, sync_function)
```
### _async method_ `__call__(self, bot, event, state, stack=None, dependency_cache=None)` {#Rule-**call**}
- **说明**
检查是否符合所有规则
- **参数**
- `bot` (nonebot.internal.adapter.bot.Bot): Bot 对象
- `event` (nonebot.internal.adapter.event.Event): Event 对象
- `state` (dict[Any, Any]): 当前 State
- `stack` (contextlib.AsyncExitStack | None): 异步上下文栈
- `dependency_cache` (dict[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any], Task[Any]] | None): 依赖缓存
- **返回**
- bool
## _class_ `CMD_RESULT()` {#CMD_RESULT}
## _class_ `TRIE_VALUE(command_start, command)` {#TRIE_VALUE}
- **说明**
TRIE_VALUE(command_start, command)
- **参数**
- `command_start` (str)
- `command` (tuple[str, ...])
## _class_ `StartswithRule(msg, ignorecase=False)` {#StartswithRule}
- **说明**
检查消息纯文本是否以指定字符串开头。
- **参数**
- `msg` (tuple[str, ...]): 指定消息开头字符串元组
- `ignorecase` (bool): 是否忽略大小写
## _def_ `startswith(msg, ignorecase=False)` {#startswith}
- **说明**
匹配消息纯文本开头。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息开头字符串元组
- `ignorecase` (bool): 是否忽略大小写
- **返回**
- nonebot.internal.rule.Rule
## _class_ `EndswithRule(msg, ignorecase=False)` {#EndswithRule}
- **说明**
检查消息纯文本是否以指定字符串结尾。
- **参数**
- `msg` (tuple[str, ...]): 指定消息结尾字符串元组
- `ignorecase` (bool): 是否忽略大小写
## _def_ `endswith(msg, ignorecase=False)` {#endswith}
- **说明**
匹配消息纯文本结尾。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息开头字符串元组
- `ignorecase` (bool): 是否忽略大小写
- **返回**
- nonebot.internal.rule.Rule
## _class_ `FullmatchRule(msg, ignorecase=False)` {#FullmatchRule}
- **说明**
检查消息纯文本是否与指定字符串全匹配。
- **参数**
- `msg` (tuple[str, ...]): 指定消息全匹配字符串元组
- `ignorecase` (bool): 是否忽略大小写
## _def_ `fullmatch(msg, ignorecase=False)` {#fullmatch}
- **说明**
完全匹配消息。
- **参数**
- `msg` (str | tuple[str, ...]): 指定消息全匹配字符串元组
- `ignorecase` (bool): 是否忽略大小写
- **返回**
- nonebot.internal.rule.Rule
## _class_ `KeywordsRule(*keywords)` {#KeywordsRule}
- **说明**
检查消息纯文本是否包含指定关键字。
- **参数**
- `*keywords` (str): 指定关键字元组
## _def_ `keyword(*keywords)` {#keyword}
- **说明**
匹配消息纯文本关键词。
- **参数**
- `*keywords` (str): 指定关键字元组
- **返回**
- nonebot.internal.rule.Rule
## _class_ `CommandRule(cmds)` {#CommandRule}
- **说明**
检查消息是否为指定命令。
- **参数**
- `cmds` (list[tuple[str, ...]]): 指定命令元组列表
## _def_ `command(*cmds)` {#command}
- **说明**
匹配消息命令。
根据配置里提供的 [`command_start`](./config.md#Config-command_start),
[`command_sep`](./config.md#Config-command_sep) 判断消息是否为命令。
可以通过 [Command](./params.md#Command) 获取匹配成功的命令(例: `("test",)`
通过 [RawCommand](./params.md#RawCommand) 获取匹配成功的原始命令文本(例: `"/test"`
通过 [CommandArg](./params.md#CommandArg) 获取匹配成功的命令参数。
- **参数**
- `*cmds` (str | tuple[str, ...]): 命令文本或命令元组
- **返回**
- nonebot.internal.rule.Rule
- **用法**
使用默认 `command_start`, `command_sep` 配置
命令 `("test",)` 可以匹配: `/test` 开头的消息
命令 `("test", "sub")` 可以匹配: `/test.sub` 开头的消息
:::tip 提示
命令内容与后续消息间无需空格!
:::
## _class_ `ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True, allow_abbrev=True, exit_on_error=True)` {#ArgumentParser}
- **说明**
`shell_like` 命令参数解析器,解析出错时不会退出程序。
- **参数**
- `prog`
- `usage`
- `description`
- `epilog`
- `parents`
- `formatter_class`
- `prefix_chars`
- `fromfile_prefix_chars`
- `argument_default`
- `conflict_handler`
- `add_help`
- `allow_abbrev`
- `exit_on_error`
- **用法**
用法与 `argparse.ArgumentParser` 相同,
参考文档: [argparse](https://docs.python.org/3/library/argparse.html)
## _class_ `ShellCommandRule(cmds, parser)` {#ShellCommandRule}
- **说明**
检查消息是否为指定 shell 命令。
- **参数**
- `cmds` (list[tuple[str, ...]]): 指定命令元组列表
- `parser` ([ArgumentParser](#ArgumentParser) | None): 可选参数解析器
## _def_ `shell_command(*cmds, parser=None)` {#shell_command}
- **说明**
匹配 `shell_like` 形式的消息命令。
根据配置里提供的 [`command_start`](./config.md#Config-command_start),
[`command_sep`](./config.md#Config-command_sep) 判断消息是否为命令。
可以通过 [Command](./params.md#Command) 获取匹配成功的命令(例: `("test",)`
通过 [RawCommand](./params.md#RawCommand) 获取匹配成功的原始命令文本(例: `"/test"`
通过 [ShellCommandArgv](./params.md#ShellCommandArgv) 获取解析前的参数列表(例: `["arg", "-h"]`
通过 [ShellCommandArgs](./params.md#ShellCommandArgs) 获取解析后的参数字典(例: `{"arg": "arg", "h": True}`)。
:::warning 警告
如果参数解析失败,则通过 [ShellCommandArgs](./params.md#ShellCommandArgs)
获取的将是 [ParserExit](./exception.md#ParserExit) 异常。
:::
- **参数**
- `*cmds` (str | tuple[str, ...]): 命令文本或命令元组
- `parser` ([ArgumentParser](#ArgumentParser) | None): [ArgumentParser](#ArgumentParser) 对象
- **返回**
- nonebot.internal.rule.Rule
- **用法**
使用默认 `command_start`, `command_sep` 配置,更多示例参考 `argparse` 标准库文档。
```python
from nonebot.rule import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-a", action="store_true")
rule = shell_command("ls", parser=parser)
```
:::tip 提示
命令内容与后续消息间无需空格!
:::
## _class_ `RegexRule(regex, flags=0)` {#RegexRule}
- **说明**
检查消息字符串是否符合指定正则表达式。
- **参数**
- `regex` (str): 正则表达式
- `flags` (int): 正则表达式标记
## _def_ `regex(regex, flags=0)` {#regex}
- **说明**
匹配符合正则表达式的消息字符串。
可以通过 [RegexMatched](./params.md#RegexMatched) 获取匹配成功的字符串,
通过 [RegexGroup](./params.md#RegexGroup) 获取匹配成功的 group 元组,
通过 [RegexDict](./params.md#RegexDict) 获取匹配成功的 group 字典。
- **参数**
- `regex` (str): 正则表达式
flags: 正则表达式标记
:::tip 提示
正则表达式匹配使用 search 而非 match如需从头匹配请使用 `r"^xxx"` 来确保匹配开头
:::
:::tip 提示
正则表达式匹配使用 `EventMessage``str` 字符串,而非 `EventMessage``PlainText` 纯文本字符串
:::
- `flags` (int | re.RegexFlag)
- **返回**
- nonebot.internal.rule.Rule
## _class_ `ToMeRule()` {#ToMeRule}
- **说明**
检查事件是否与机器人有关。
## _def_ `to_me()` {#to_me}
- **说明**
匹配与机器人有关的事件。
- **返回**
- nonebot.internal.rule.Rule
## _class_ `IsTypeRule(*types)` {#IsTypeRule}
- **说明**
检查事件类型是否为指定类型。
- **参数**
- `*types` (Type[nonebot.internal.adapter.event.Event])
## _def_ `is_type(*types)` {#is_type}
- **说明**
匹配事件类型。
- **参数**
- `*types` (Type[nonebot.internal.adapter.event.Event]): 事件类型
- **返回**
- nonebot.internal.rule.Rule

View File

@ -1,219 +0,0 @@
---
sidebar_position: 11
description: nonebot.typing 模块
---
# nonebot.typing
本模块定义了 NoneBot 模块中共享的一些类型。
下面的文档中,「类型」部分使用 Python 的 Type Hint 语法,
参考 [`PEP 484`](https://www.python.org/dev/peps/pep-0484/),
[`PEP 526`](https://www.python.org/dev/peps/pep-0526/) 和
[`typing`](https://docs.python.org/3/library/typing.html)。
除了 Python 内置的类型,下面还出现了如下 NoneBot 自定类型,实际上它们是 Python 内置类型的别名。
## _var_ `T_State` {#T_State}
- **类型:** dict[Any, Any]
- **说明:** 事件处理状态 State 类型
## _var_ `T_BotConnectionHook` {#T_BotConnectionHook}
- **类型:** (*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any]
- **说明**
Bot 连接建立时钩子函数
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_BotDisconnectionHook` {#T_BotDisconnectionHook}
- **类型:** (*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any]
- **说明**
Bot 连接断开时钩子函数
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_CallingAPIHook` {#T_CallingAPIHook}
- **类型:** (Bot, str, dict[str, Any]) -> Awaitable[Any]
- **说明:** `bot.call_api` 钩子函数
## _var_ `T_CalledAPIHook` {#T_CalledAPIHook}
- **类型:** (Bot, Exception | None, str, dict[str, Any], Any) -> Awaitable[Any]
- **说明:** `bot.call_api` 后执行的函数,参数分别为 bot, exception, api, data, result
## _var_ `T_EventPreProcessor` {#T_EventPreProcessor}
- **类型:** (*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any]
- **说明**
事件预处理函数 EventPreProcessor 类型
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_EventPostProcessor` {#T_EventPostProcessor}
- **类型:** (*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any]
- **说明**
事件预处理函数 EventPostProcessor 类型
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_RunPreProcessor` {#T_RunPreProcessor}
- **类型:** (*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any]
- **说明**
事件响应器运行前预处理函数 RunPreProcessor 类型
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_RunPostProcessor` {#T_RunPostProcessor}
- **类型:** (*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any]
- **说明**
事件响应器运行后后处理函数 RunPostProcessor 类型
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- ExceptionParam: 异常对象(可能为 None
- DefaultParam: 带有默认值的参数
## _var_ `T_RuleChecker` {#T_RuleChecker}
- **类型:** (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool]
- **说明**
RuleChecker 即判断是否响应事件的处理函数。
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_PermissionChecker` {#T_PermissionChecker}
- **类型:** (*Any, \*\*Any) -> bool | (*Any, \*\*Any) -> Awaitable[bool]
- **说明**
PermissionChecker 即判断事件是否满足权限的处理函数。
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_Handler` {#T_Handler}
- **类型:** (*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any]
- **说明:** Handler 处理函数。
## _var_ `T_TypeUpdater` {#T_TypeUpdater}
- **类型:** (*Any, \*\*Any) -> str | (*Any, \*\*Any) -> Awaitable[str]
- **说明**
TypeUpdater 在 Matcher.pause, Matcher.reject 时被运行,用于更新响应的事件类型。默认会更新为 `message`
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_PermissionUpdater` {#T_PermissionUpdater}
- **类型:** (*Any, \*\*Any) -> Permission | (*Any, \*\*Any) -> Awaitable[Permission]
- **说明**
PermissionUpdater 在 Matcher.pause, Matcher.reject 时被运行,用于更新会话对象权限。默认会更新为当前事件的触发对象。
依赖参数:
- DependParam: 子依赖参数
- BotParam: Bot 对象
- EventParam: Event 对象
- StateParam: State 对象
- MatcherParam: Matcher 对象
- DefaultParam: 带有默认值的参数
## _var_ `T_DependencyCache` {#T_DependencyCache}
- **类型:** dict[(*Any, \*\*Any) -> Any | (*Any, \*\*Any) -> Awaitable[Any], Task[Any]]
- **说明:** 依赖缓存, 用于存储依赖函数的返回值
## _def_ `overrides(InterfaceClass)` {#overrides}
- **说明**
标记一个方法为父类 interface 的 implement
- **参数**
- `InterfaceClass` (object)
- **返回**
- ((~ T_Wrapped)) -> (~ T_Wrapped)

View File

@ -1,217 +0,0 @@
---
sidebar_position: 8
description: nonebot.utils 模块
---
# nonebot.utils
本模块包含了 NoneBot 的一些工具函数
## _def_ `escape_tag(s)` {#escape_tag}
- **说明**
用于记录带颜色日志时转义 `<tag>` 类型特殊标签
参考: [loguru color 标签](https://loguru.readthedocs.io/en/stable/api/logger.html#color)
- **参数**
- `s` (str): 需要转义的字符串
- **返回**
- str
## _def_ `generic_check_issubclass(cls, class_or_tuple)` {#generic_check_issubclass}
- **说明**
检查 cls 是否是 class_or_tuple 中的一个类型子类。
特别的,如果 cls 是 `typing.Union``types.UnionType` 类型,
则会检查其中的类型是否是 class_or_tuple 中的一个类型子类。None 会被忽略)
- **参数**
- `class_or_tuple` (Type[Any] | tuple[Type[Any], ...])
- **返回**
- bool
## _def_ `is_coroutine_callable(call)` {#is_coroutine_callable}
- **说明**
检查 call 是否是一个 callable 协程函数
- **参数**
- `call` ((\*Any, \*\*Any) -> Any)
- **返回**
- bool
## _def_ `is_gen_callable(call)` {#is_gen_callable}
- **说明**
检查 call 是否是一个生成器函数
- **参数**
- `call` ((\*Any, \*\*Any) -> Any)
- **返回**
- bool
## _def_ `is_async_gen_callable(call)` {#is_async_gen_callable}
- **说明**
检查 call 是否是一个异步生成器函数
- **参数**
- `call` ((\*Any, \*\*Any) -> Any)
- **返回**
- bool
## _def_ `run_sync(call)` {#run_sync}
- **说明**
一个用于包装 sync function 为 async function 的装饰器
- **参数**
- `call` (((~ P)) -> (~ R)): 被装饰的同步函数
- **返回**
- ((~ P)) -> Coroutine[NoneType, NoneType, (~ R)]
## _def_ `run_sync_ctx_manager(cm)` {#run_sync_ctx_manager}
- **说明**
一个用于包装 sync context manager 为 async context manager 的执行函数
- **参数**
- `cm` (ContextManager[(~ T)])
- **返回**
- AsyncGenerator[(~ T), NoneType]
## _async def_ `run_coro_with_catch(coro, exc, return_on_err=None)` {#run_coro_with_catch}
- **重载**
**1.** `(coro, exc)`
- **参数**
- `coro` (Coroutine[Any, Any, (~ T)])
- `exc` (tuple[Type[Exception], ...])
- **返回**
- (~ T) | None
**2.** `(coro, exc, return_on_err)`
- **参数**
- `coro` (Coroutine[Any, Any, (~ T)])
- `exc` (tuple[Type[Exception], ...])
- `return_on_err` ((~ R))
- **返回**
- (~ T) | (~ R)
## _def_ `get_name(obj)` {#get_name}
- **说明**
获取对象的名称
- **参数**
- `obj` (Any)
- **返回**
- str
## _def_ `path_to_module_name(path)` {#path_to_module_name}
- **参数**
- `path` (pathlib.Path)
- **返回**
- str
## _class_ `DataclassEncoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)` {#DataclassEncoder}
- **说明**
在 JSON 序列化 {re}`nonebot.adapters._message.Message` (List[Dataclass]) 时使用的 `JSONEncoder`
- **参数**
- `skipkeys`
- `ensure_ascii`
- `check_circular`
- `allow_nan`
- `sort_keys`
- `indent`
- `separators`
- `default`
### _method_ `default(self, o)` {#DataclassEncoder-default}
- **参数**
- `o`
- **返回**
- Unknown
## _def_ `logger_wrapper(logger_name)` {#logger_wrapper}
- **说明**
用于打印 adapter 的日志。
- **参数**
- `logger_name` (str): adapter 的名称
- **返回**
- Unknown: 日志记录函数
- level: 日志等级
- message: 日志信息
- exception: 异常信息

View File

@ -1,33 +0,0 @@
---
sidebar_position: 80
description: 编辑器支持
---
# 编辑器支持
框架基于 [PEP484](https://www.python.org/dev/peps/pep-0484/)、[PEP 561](https://www.python.org/dev/peps/pep-0517/)、[PEP8](https://www.python.org/dev/peps/pep-0008/) 等规范进行开发并且是 **Fully Typed**。框架使用 `pyright``pylance`)工具进行类型检查,确保代码可以被编辑器正确解析。
## 编辑器推荐配置
### Visual Studio Code
在 Visual Studio Code 中,可以使用 `pylance` Language Server 并启用 `Type Checking` 以达到最佳开发体验。
`.vscode` 文件夹中对应文件添加以下配置并在 VSCode 插件面板安装推荐插件:
```json title=extensions.json
{
"recommendations": ["ms-python.python", "ms-python.vscode-pylance"]
}
```
```json title=settings.json
{
"python.languageServer": "Pylance",
"python.analysis.typeCheckingMode": "basic"
}
```
### 其他
欢迎提交 Pull Request 添加其他编辑器配置推荐。点击左下角 `Edit this page` 前往编辑。

View File

@ -1,45 +0,0 @@
---
sidebar_position: 2
description: 通过脚手架或 pip 安装适配器
---
import Asciinema from "@site/src/components/Asciinema";
# 安装协议适配器
## 查看
前往[商店](/store)即可查看所有协议适配器。
或者使用 nb-cli 命令行查看:
```bash
nb adapter list
```
## 安装
前往[商店](/store)点击复制 nb-cli 安装命令至命令行执行即可安装。
或者自行输入命令安装:
```bash
nb adapter install <adapter-name>
```
或者使用交互模式安装:
```bash
nb adapter install
```
也可以使用 pip 安装
```bash
pip install <adapter-name>
```
<Asciinema
url="https://asciinema.org/a/464727.cast"
options={{ theme: "monokai", poster: "npt:2.0" }}
/>

View File

@ -1,47 +0,0 @@
---
sidebar_position: 1
description: 通过脚手架或 pip 安装驱动器
---
import Asciinema from "@site/src/components/Asciinema";
# 安装驱动器
NoneBot 在默认安装情况下内置了 `fastapi` 服务端驱动器,其他驱动器如 `httpx`、`aiohttp` 则需要额外安装。
## 查看
前往[商店](/store)即可查看所有驱动器。
或者使用 nb-cli 命令行查看:
```bash
nb driver list
```
## 安装
前往[商店](/store)点击复制 nb-cli 安装命令至命令行执行即可安装。
或者自行输入命令安装:
```bash
nb driver install <driver-name>
```
或者使用交互模式安装:
```bash
nb driver install
```
也可以使用 pip 安装
```bash
pip install <driver-name>
```
<Asciinema
url="https://asciinema.org/a/464686.cast"
options={{ theme: "monokai", poster: "npt:2.8" }}
/>

View File

@ -1,45 +0,0 @@
---
sidebar_position: 3
description: 通过脚手架或 pip 安装插件
---
import Asciinema from "@site/src/components/Asciinema";
# 安装第三方插件
## 查看
前往[商店](/store)即可查看所有发布的插件。
或者使用 nb-cli 命令行查看:
```bash
nb plugin list
```
## 安装
前往[商店](/store)点击复制 nb-cli 安装命令至命令行执行即可安装。
或者自行输入命令安装:
```bash
nb plugin install <plugin-name>
```
或者使用交互模式安装:
```bash
nb plugin install
```
也可以使用 pip 安装
```bash
pip install <plugin-name>
```
<Asciinema
url="https://asciinema.org/a/464735.cast"
options={{ theme: "monokai", poster: "npt:4.3" }}
/>

View File

@ -1,80 +0,0 @@
---
sidebar_position: 0
description: 通过脚手架、PyPI 或 GitHub 安装 NoneBot2
options:
menu:
weight: 10
category: guide
---
import Asciinema from "@site/src/components/Asciinema";
# 安装 NoneBot2
:::warning 注意
请确保你的 Python 版本 >= 3.8。
:::
:::warning 注意
请在安装 NoneBot v2 之前卸载 NoneBot v1
```bash
pip uninstall nonebot
```
:::
## 通过脚手架安装(推荐)
1. (可选)使用你喜欢的 Python 环境管理工具(如 Poetry、venv、Conda 等)创建新的虚拟环境
2. 使用 pip 或其他包管理工具安装 nb-cliNoneBot2 会作为其依赖被一起安装
```bash
pip install nb-cli
```
<Asciinema
url="https://asciinema.org/a/464654.cast"
options={{ theme: "monokai", poster: "npt:2.8" }}
/>
:::important 提示
nb-cli 的使用方法详见[使用脚手架](./nb-cli.md)
:::
## 不使用脚手架(纯净安装)
如果你不想使用脚手架,可以直接安装 NoneBot2并自行完成开发配置。
```bash
pip install nonebot2
# 也可以通过 Poetry 安装
poetry add nonebot2
```
## 从 GitHub 安装
如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 GitHub 仓库安装:
:::warning 注意
直接从 GitHub 仓库中安装意味着你将使用最新提交的代码,它们并没有进行充分的稳定性测试
在任何情况下请不要将其应用于生产环境!
:::
```bash title="Install From GitHub"
# 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 . # 不推荐
```

View File

@ -1,84 +0,0 @@
---
sidebar_position: 90
description: 使用 nb-cli 帮助开发
options:
menu:
weight: 11
category: guide
---
# 使用脚手架
## 安装
```bash
pip install nb-cli
```
## 初次使用
在安装完成之后,即可在命令行使用 nb-cli 的命令 `nb` 进行开发:
```bash
# 直接使用 nb 命令
nb
# 或使用 Python 执行 module
python -m nb_cli
```
:::warning 注意
通常情况下,你可以直接在命令行使用 `nb` 命令,但如果命令行出现 `Command not found` 错误,这是由于环境变量 `PATH` 没有正确配置或未配置导致的,可以使用第二种方式代替。
:::
## 使用方式
nb-cli 具有两种使用方式:
1. 命令行指令
查看帮助信息:
```bash
$ nb --help
Usage: nb [OPTIONS] COMMAND [ARGS]...
Options:
-V, --version Show the version and exit.
--help Show this message and exit.
...
```
查看子命令帮助:
```bash
$ nb plugin --help
Usage: nb plugin [OPTIONS] COMMAND [ARGS]...
Manage Bot Plugin.
Options:
--help Show this message and exit.
...
```
2. 交互式选择(支持鼠标)
交互式选择菜单:
```bash
$ nb
Welcome to NoneBot CLI!
[?] What do you want to do? (Use ↑ and ↓ to choose, Enter to submit)
...
```
交互式子命令菜单:
```bash
$ nb plugin
[?] What do you want to do? (Use ↑ and ↓ to choose, Enter to submit)
...
```

View File

@ -1,28 +0,0 @@
---
sidebar-position: 100
description: 如何获取帮助
---
# 遇到问题
如果在安装或者开发过程中遇到了任何问题,可以通过以下方式解决:
1. 点击下方链接前往 GitHub前往 Issues 页面,在 `New Issue` Template 中选择 `Question`
NoneBot2[![NoneBot2](https://img.shields.io/github/stars/nonebot/nonebot2?style=social)](https://github.com/nonebot/nonebot2)
2. 通过 QQ 群(点击下方链接直达)
[![QQ Chat Group](https://img.shields.io/badge/QQ%E7%BE%A4-768887710-orange?style=social)](https://jq.qq.com/?_wv=1027&k=5OFifDh)
3. 通过 QQ 频道
[![QQ Channel](https://img.shields.io/badge/QQ%E9%A2%91%E9%81%93-NoneBot-orange?style=social)](https://qun.qq.com/qqweb/qunpro/share?_wv=3&_wwv=128&appChannel=share&inviteCode=7b4a3&appChannel=share&businessType=9&from=246610&biz=ka)
4. 通过 Telegram 群(点击下方链接直达)
[![Telegram Chat](https://img.shields.io/badge/telegram-cqhttp-blue?style=social)](https://t.me/cqhttp)
5. 通过 Discord 服务器(点击下方链接直达)
[![Discord Server](https://discordapp.com/api/guilds/847819937858584596/widget.png?style=shield)](https://discord.gg/VKtE6Gdc4h)

View File

@ -1,42 +0,0 @@
---
sidebar_position: 10
description: 扩展自定义服务端 API
---
# 添加自定义 API
由于 NoneBot2 可以使用 `ReverseDriver` (即服务端框架)来进行驱动,因此可以将 NoneBot2 来作为一个服务端程序来提供 API 接口等功能。
在扩展 API 之前,你首先需要确保 NoneBot2 使用的是 `ReverseDriver`,详情可以参考 [选择驱动器](./choose-driver.md)。下面我们以 FastAPI 驱动器为例,来演示如何添加自定义 API。
## 获取 APP 实例
在定义 API 接口之前,需要先获取到驱动器框架的 APP 实例。
```python {4}
import nonebot
from fastapi import FastAPI
app: FastAPI = nonebot.get_app()
@app.get("/api")
async def custom_api():
return {"message": "Hello, world!"}
```
## 添加接口
在获取到当前驱动器的 APP 实例后,即可以直接使用驱动器框架提供的方法来添加 API 接口。
在下面的代码中,我们添加了一个 `GET` 类型的 `/api` 接口,具体方法参考 [FastAPI 文档](https://fastapi.tiangolo.com/)。
```python {6-8}
import nonebot
from fastapi import FastAPI
app: FastAPI = nonebot.get_app()
@app.get("/api")
async def custom_api():
return {"message": "Hello, world!"}
```

View File

@ -1,29 +0,0 @@
---
sidebar_position: 8
description: 调用机器人平台 API完成更多的功能
options:
menu:
weight: 29
category: guide
---
# 调用平台 API
在使用机器人功能时,除了发送消息以外,还可能需要调用机器人平台的 API 来完成更多的功能。
NoneBot 提供了两种方式来调用机器人平台 API两种方式都需要首先获得 Bot 实例,然后调用相应的方法。
例如,如果需要调用机器人平台的 `get_user_info` API可以这样做
```python
from nonebot import get_bot
bot = get_bot("bot_id")
result = await bot.get_user_info(user_id=12345678)
await bot.call_api("get_user_info", user_id=12345678)
```
:::tip 提示
API 由平台提供,请参考平台文档。
:::

View File

@ -1,262 +0,0 @@
---
sidebar_position: 5
description: 各驱动器的功能与区别
options:
menu:
weight: 22
category: guide
---
# 选择驱动器
:::warning 注意
驱动器的选择通常与你所使用的协议适配器相关,如果你不知道该选择哪个驱动器,可以先阅读你想要使用的协议适配器文档说明。
:::
:::tip 提示
如何**安装**驱动器请参考[安装驱动器](../start/install-driver.mdx)。
如何**使用**驱动器请参考[配置](./configuration.md#driver)。
:::
## 驱动器的类型
驱动器的类型有两种:
- `ForwardDriver`:即客户端类型驱动器,多用于使用 HTTP 轮询WebSocket 连接服务器的情形。
- `ReverseDriver`:即服务端类型驱动器,多用于使用 WebHook 情形。
其中 `ReverseDriver` 可以配合 `ForwardDriver` 一起使用,即可以同时使用客户端功能和服务端功能。
## 驱动器的功能
在 NoneBot 中,驱动器主要负责数据的收发,不对数据进行处理。通常,驱动器会实现以下功能:
### ForwardDriver
1. 异步发送 HTTP 请求,自定义 `HTTP Method`、`URL`、`Header`、`Body`、`Cookie`、`Proxy`、`Timeout` 等。
2. 异步建立 WebSocket 连接上下文,自定义 `WebSocket URL`、`Header`、`Cookie`、`Proxy`、`Timeout` 等。
### ReverseDriver
1. 协议适配器自定义 HTTP 上报地址以及对上报数据处理的回调函数。
2. 协议适配器自定义 WebSocket 连接请求地址以及对 WebSocket 请求处理的回调函数。
3. 用户可以将 Driver 作为服务端使用,自行添加任何服务端相关功能。
## 内置驱动器
### FastAPI默认
类型:`ReverseDriver`
> FastAPI is a modern, fast (high-performance), web framework for building APIs with Python 3.6+ based on standard Python type hints.
FastAPI 是一个易上手、高性能的异步 Web 框架,具有极佳的编写体验,可以挂载其他 ASGI、WSGI 应用。
FastAPI[文档](https://fastapi.tiangolo.com/)、[仓库](https://github.com/tiangolo/fastapi)
驱动器:[API](../api/drivers/fastapi.md)、[源码](https://github.com/nonebot/nonebot2/blob/master/nonebot/drivers/fastapi.py)
```env
DRIVER=~fastapi
```
#### FastAPI 配置项
##### `fastapi_openapi_url`
类型:`Optional[str]`
默认值:`None`
说明:`FastAPI` 提供的 `OpenAPI` JSON 定义地址,如果为 `None`,则不提供 `OpenAPI` JSON 定义。
##### `fastapi_docs_url`
类型:`Optional[str]`
默认值:`None`
说明:`FastAPI` 提供的 `Swagger` 文档地址,如果为 `None`,则不提供 `Swagger` 文档。
##### `fastapi_redoc_url`
类型:`Optional[str]`
默认值:`None`
说明:`FastAPI` 提供的 `ReDoc` 文档地址,如果为 `None`,则不提供 `ReDoc` 文档。
##### `fastapi_include_adapter_schema`
类型:`bool`
默认值:`True`
说明:`FastAPI` 提供的 `OpenAPI` JSON 定义中是否包含适配器路由的 `Schema`
##### `fastapi_reload`
类型:`bool`
默认值:`False`
说明:是否开启 `uvicorn``reload` 功能,需要提供 asgi 应用路径。
```python title=bot.py
app = nonebot.get_asgi()
nonebot.run(app="bot:app")
```
:::warning 警告
在 Windows 平台上开启该功能有可能会造成预料之外的影响!
`Python>=3.8` 环境下开启该功能后,在 uvicorn 运行时FastAPI 提供的 ASGI 底层,即 reload 功能的实际来源asyncio 使用的事件循环会被 uvicorn 从默认的 `ProactorEventLoop` 强制切换到 `SelectorEventLoop`
> 相关信息参考 [uvicorn#529](https://github.com/encode/uvicorn/issues/529)[uvicorn#1070](https://github.com/encode/uvicorn/pull/1070)[uvicorn#1257](https://github.com/encode/uvicorn/pull/1257)
后者(`SelectorEventLoop`)在 Windows 平台的可使用性不如前者(`ProactorEventLoop`),包括但不限于
1. 不支持创建子进程
2. 最多只支持 512 个套接字
3. ...
> 具体信息参考 [Python 文档](https://docs.python.org/zh-cn/3/library/asyncio-platforms.html#windows)
所以,一些使用了 asyncio 的库因此可能无法正常工作,如:
1. [playwright](https://playwright.dev/python/docs/intro#incompatible-with-selectoreventloop-of-asyncio-on-windows)
如果在开启该功能后,原本**正常运行**的代码报错,且打印的异常堆栈信息和 asyncio 有关(异常一般为 `NotImplementedError`
你可能就需要考虑相关库对事件循环的支持,以及是否启用该功能
:::
##### `fastapi_reload_dirs`
类型:`Optional[List[str]]`
默认值:`None`
说明:重载监控文件夹列表,默认为 uvicorn 默认值
##### `fastapi_reload_delay`
类型:`Optional[float]`
默认值:`None`
说明:重载延迟,默认为 uvicorn 默认值
##### `fastapi_reload_includes`
类型:`Optional[List[str]]`
默认值:`None`
说明:要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
##### `fastapi_reload_excludes`
类型:`Optional[List[str]]`
默认值:`None`
说明:不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
### Quart
类型:`ReverseDriver`
> Quart is an asyncio reimplementation of the popular Flask microframework API.
Quart 是一个类 Flask 的异步版本,拥有与 Flask 非常相似的接口和使用方法。
Quart[文档](https://pgjones.gitlab.io/quart/)、[仓库](https://gitlab.com/pgjones/quart)
驱动器:[API](../api/drivers/quart.md)、[源码](https://github.com/nonebot/nonebot2/blob/master/nonebot/drivers/quart.py)
```env
DRIVER=~quart
```
#### Quart 配置项
##### `quart_reload`
类型:`bool`
默认值:`False`
说明:是否开启 `uvicorn``reload` 功能,需要提供 asgi 应用路径。
```python title=bot.py
app = nonebot.get_asgi()
nonebot.run(app="bot:app")
```
##### `quart_reload_dirs`
类型:`Optional[List[str]]`
默认值:`None`
说明:重载监控文件夹列表,默认为 uvicorn 默认值
##### `quart_reload_delay`
类型:`Optional[float]`
默认值:`None`
说明:重载延迟,默认为 uvicorn 默认值
##### `quart_reload_includes`
类型:`Optional[List[str]]`
默认值:`None`
说明:要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
##### `quart_reload_excludes`
类型:`Optional[List[str]]`
默认值:`None`
说明:不要监听的文件列表,支持 glob pattern默认为 uvicorn 默认值
### HTTPX
类型:`ForwardDriver`
:::warning 注意
本驱动器仅支持 HTTP 请求,不支持 WebSocket 请求。
:::
> HTTPX is a fully featured HTTP client for Python 3, which provides sync and async APIs, and support for both HTTP/1.1 and HTTP/2.
HTTPX[文档](https://www.python-httpx.org/)、[仓库](https://github.com/encode/httpx/)
驱动器:[API](../api/drivers/httpx.md)、[源码](https://github.com/nonebot/nonebot2/blob/master/nonebot/drivers/httpx.py)
```env
DRIVER=~httpx
```
:::important 注意
本驱动器支持 `Mixin`
:::
### websockets
类型:`ForwardDriver`
:::warning 注意
本驱动器仅支持 WebSocket 请求,不支持 HTTP 请求。
:::
> websockets is a library for building WebSocket servers and clients in Python with a focus on correctness, simplicity, robustness, and performance.
websockets[文档](https://websockets.readthedocs.io/en/stable/)、[仓库](https://github.com/aaugustin/websockets)
驱动器:[API](../api/drivers/websockets.md)、[源码](https://github.com/nonebot/nonebot2/blob/master/nonebot/drivers/websockets.py)
```env
DRIVER=~websockets
```
:::important 注意
本驱动器支持 `Mixin`
:::
### AIOHTTP
类型:`ForwardDriver`
> Asynchronous HTTP Client/Server for asyncio and Python.
AIOHTTP[文档](https://docs.aiohttp.org/en/stable/)、[仓库](https://github.com/aio-libs/aiohttp)
驱动器:[API](../api/drivers/aiohttp.md)、[源码](https://github.com/nonebot/nonebot2/blob/master/nonebot/drivers/aiohttp.py)
```env
DRIVER=~aiohttp
```
:::important 注意
本驱动器支持 `Mixin`
:::

View File

@ -1,240 +0,0 @@
---
sidebar_position: 1
description: 项目配置方式与配置项
options:
menu:
weight: 21
category: guide
---
# 配置
在上一章节中,我们创建了默认的项目结构,其中 `.env``.env.*` 均为项目的配置文件,下面将介绍几种 NoneBot 配置方式以及配置项。
:::danger 警告
请勿将敏感信息写入配置文件并提交至开源仓库!
:::
## 配置方式
### .env 文件
NoneBot 在启动时将会从系统环境变量或者 `.env` 文件中寻找变量 `ENVIRONMENT`(大小写不敏感),默认值为 `prod`
这将引导 NoneBot 从系统环境变量或者 `.env.{ENVIRONMENT}` 文件中进一步加载具体配置。
`.env` 文件是基础环境配置文件,该文件中的配置项在不同环境下都会被加载,但会被 `.env.{ENVIRONMENT}` 文件中的配置所覆盖。
NoneBot 使用 [Pydantic](https://pydantic-docs.helpmanual.io/) 进行配置处理,并对 Pydantic 的行为做出了更改,详见下方说明。
现在,我们在 `.env` 文件中写入当前环境信息:
```bash
# .env
ENVIRONMENT=dev
CUSTOM_CONFIG=common config # 这个配置项在任何环境中都会被加载
```
如你所想,之后 NoneBot 就会从 `.env.dev` 文件中加载环境变量。
:::important 参考文档
`.env` 相关文件的加载使用 `dotenv` 语法,请参考 [`dotenv` 文档](https://saurabh-kumar.com/python-dotenv/)
:::
:::warning 提示
由于 Pydantic 使用 JSON 解析配置项,请确保配置项值为 JSON 格式的数据。如:
```bash
list=["123456789", "987654321", 1]
test={"hello": "world"}
```
如果配置项值解析失败将作为**字符串**处理。
特别的,如果配置项**为空**,则会从**系统环境变量**中获取值,如果不存在则为空字符串。
:::
### .env.\* 文件
NoneBot 默认会从 `.env.{ENVIRONMENT}` 文件加载配置,但是可以在 NoneBot 初始化时指定加载某个环境配置文件:`nonebot.init(_env_file=".env.dev")`,这将忽略你在 `.env` 中设置的 `ENVIRONMENT`
配置语法与 `.env` 文件相同。
示例及说明:
```bash
HOST=0.0.0.0 # 配置 NoneBot2 监听的 IP/主机名
PORT=8080 # 配置 NoneBot2 监听的端口
SUPERUSERS=["123456789", "987654321"] # 配置 NoneBot 超级用户
NICKNAME=["awesome", "bot"] # 配置机器人的昵称
COMMAND_START=["/", ""] # 配置命令起始字符
COMMAND_SEP=["."] # 配置命令分割字符
# Custom Configs
CUSTOM_CONFIG1="config in env file"
CUSTOM_CONFIG2= # 留空则从系统环境变量读取,如不存在则为空字符串
```
详细的配置项可以参考[配置项](#详细配置项)。
### 系统环境变量
如果在系统环境变量中定义了配置,则一样会被读取。
### bot.py 文件
配置项也可以在 NoneBot 初始化时传入。此处可以传入任意合法 Python 变量。当然也可以在初始化完成后修改或新增。
示例:
```python
# bot.py
import nonebot
nonebot.init(custom_config3="config on init")
config = nonebot.get_driver().config
config.custom_config3 = "changed after init"
config.custom_config4 = "new config after init"
```
## 配置优先级
`bot.py` 文件(`nonebot.init`> 系统环境变量 > `.env`、`.env.*` 文件
## 读取配置项
配置项可以通过三种类型的对象获取:`driver`、`adapter`、`bot`。
```python
import nonebot
# driver
nonebot.get_driver().config.custom_config
# bot
nonebot.get_bot().config.custom_config
# adapter
nonebot.get_driver()._adapters["adapter_name"].config.custom_config
```
## 详细配置项
配置项的 API 文档可以前往 [Class Config](../api/config.md#class-config) 查看。
### Driver
- **类型**: `str`
- **默认值**: `"~fastapi"`
NoneBot2 运行所使用的驱动器。主要分为 `ForwardDriver`、`ReverseDriver` 即客户端和服务端两类。
配置格式采用特殊语法:`<module>[:<Driver>][+<module>[:<Mixin>]]*`
其中 `<module>` 为驱动器模块名,可以使用 `~` 作为 `nonebot.drivers.` 的简写;`<Driver>` 为驱动器类名,默认为 `Driver``<Mixin>` 为驱动器混入的类名,默认为 `Mixin`
NoneBot2 内置了几个常用驱动器,包括了各类常用功能,常见驱动器配置如下:
```env
DRIVER=~fastapi
DRIVER=~httpx+~websockets
DRIVER=~fastapi+~httpx+~websockets
DRIVER=~fastapi+~aiohttp
```
各驱动器的功能与区别请参考[选择驱动器](./choose-driver.md)。
### Host
- **类型**: `IPvAnyAddress`
- **默认值**: `127.0.0.1`
使用 `ReversedDriver`NoneBot2 监听的 IP/主机名。
```env
HOST=127.0.0.1
```
### Port
- **类型**: `int`
- **默认值**: `8080`
使用 `ReversedDriver`NoneBot2 监听的端口。
```env
PORT=8080
```
### Log Level
- **类型**: `int | str`
- **默认值**: `INFO`
NoneBot2 日志输出等级,可以为 `int` 类型等级或等级名称
参考 [`loguru 日志等级`](https://loguru.readthedocs.io/en/stable/api/logger.html#levels)。
```env
LOG_LEVEL=INFO
```
:::tip 提示
日志等级名称应为大写,如 `INFO`
:::
### API Timeout
- **类型**: `Optional[float]`
- **默认值**: `30.0`
API 请求超时时间,单位为秒。
```env
API_TIMEOUT=30.0
```
### SuperUsers
- **类型**: `Set[str]`
- **默认值**: `set()`
机器人超级用户,可以使用权限 [`SUPERUSER`](../api/permission.md#SUPERUSER)。
```env
SUPERUSERS=["1234567890"]
```
### Nickname
- **类型**: `Set[str]`
- **默认值**: `set()`
机器人昵称,通常协议适配器会根据用户是否 @user 或者是否以机器人昵称开头来判断是否是向机器人发送的消息。
```env
NICKNAME=["bot"]
```
### Command Start 和 Command Separator
- **类型**: `Set[str]`
- **默认值**:
- Command Start: `{"/"}`
- Command Separator: `{"."}`
命令消息的起始符和分隔符。用于 [`command`](../api/rule.md#command) 规则。
```env
COMMAND_START={"/", "!"}
COMMAND_SEP={".", "/"}
```
### Session Expire Timeout
- **类型**: `timedelta`
- **默认值**: `timedelta(minutes=2)`
用户会话超时时间,配置格式参考 [Datetime Types](https://pydantic-docs.helpmanual.io/usage/types/#datetime-types)。
```env
SESSION_EXPIRE_TIMEOUT=120
```

View File

@ -1,79 +0,0 @@
---
sidebar_position: 0
description: 创建并运行项目
options:
menu:
weight: 20
category: guide
---
import Asciinema from "@site/src/components/Asciinema";
# 创建项目
可以使用 `nb-cli` 或者自行创建完整的项目目录:
```bash
nb create
```
<Asciinema
url="https://asciinema.org/a/464654.cast"
options={{ theme: "monokai", startAt: 4.5, poster: "npt:6.5" }}
/>
## 目录结构
```tree title=Project
📦 AweSome-Bot
├── 📂 awesome_bot # 或是 src
│ └── 📜 plugins
├── 📜 .env # 可选的
├── 📜 .env.dev # 可选的
├── 📜 .env.prod # 可选的
├── 📜 .gitignore
├── 📜 bot.py
├── 📜 docker-compose.yml
├── 📜 Dockerfile
├── 📜 pyproject.toml
└── 📜 README.md
```
- `awesome_bot/plugins` 或 `src/plugins`: 用于存放编写的 bot 插件
- `.env`、`.env.dev`、`.env.prod`: 各环境配置文件
- `bot.py`: bot 入口文件
- `pyproject.toml`: 项目插件配置文件
- `Dockerfile`、`docker-compose.yml`: Docker 镜像配置文件
## 启动 Bot
:::warning 提示
如果您使用如 `VSCode` / `PyCharm` 等 IDE 启动 nonebot请检查 IDE 当前工作空间目录是否与当前侧边栏打开目录一致。
> 注意: 在二者不一致的环境下可能导致 nonebot 读取配置文件和插件等不符合预期
:::
1. 通过 nb-cli
```bash
nb run [--file=bot.py] [--app=app]
```
其中 `--file` 参数可以指定 bot 入口文件,默认为 `bot.py``--app` 参数可以指定 asgi server默认为 `app`。
<Asciinema
url="https://asciinema.org/a/464654.cast"
options={{ theme: "monokai", startAt: 15.3, poster: "npt:20.3" }}
/>
2. 直接通过 Python 启动
```bash
python bot.py
```
:::tip 提示
如果在 bot 入口文件内定义了 asgi servernb-cli 将会为你启动**冷重载模式**(当文件发生变动时自动重启 NoneBot2 实例)
:::

View File

@ -1,59 +0,0 @@
---
sidebar_position: 100
description: 修改日志级别与输出
---
# 自定义日志
NoneBot 使用 [Loguru](https://loguru.readthedocs.io/) 进行日志记录,并提供了一些内置的格式和过滤器等。
## 默认日志
NoneBot 启动时会添加一个默认的日志 handler。此 handler 将会将日志输出到 **stdout**,并且根据配置的日志级别进行过滤。
[默认格式](../api/log.md#default_format)):
```python
default_format: str = (
"<g>{time:MM-DD HH:mm:ss}</g> "
"[<lvl>{level}</lvl>] "
"<c><u>{name}</u></c> | "
"{message}"
)
from nonebot.log import default_format
```
[默认过滤器](../api/log.md#default_filter):
```python
from nonebot.log import default_filter
```
## 转移 logging 日志
NoneBot 提供了一个 logging handler 用于将日志输出转移至 loguru 处理。将 logging 的默认 handler 替换为 `LoguruHandler` 即可。
```python
from nonebot.log import LoguruHandler
```
## 自定义日志记录
如果需要移除 NoneBot 的默认日志 handler可以在 `nonebot.init` 之前进行如下操作:
```python
from nonebot.log import logger, logger_id
logger.remove(logger_id)
```
如果需要添加自定义的日志 handler可以在 `nonebot.init` 之前添加 handler参考 [loguru 文档](https://loguru.readthedocs.io/)。
示例:
```python
from nonebot.log import logger, default_format
logger.add("error.log", level="ERROR", format=default_format, rotation="1 week")
```

View File

@ -1,318 +0,0 @@
---
sidebar_position: 11
description: 部署你的机器人
---
# 部署
在编写完成后,你需要部署你的机器人来使得用户能够使用它。通常,会将机器人部署在服务器上,来保证服务持久运行。
在开发时机器人运行的环境称为开发环境,而在部署后机器人运行的环境称为生产环境。与开发环境不同的是,在生产环境中,开发者通常不能随意地修改/添加/删除代码,开启或停止服务。
## 部署前准备
在生产环境中,为确保机器人能够正常运行,你需要固定你的依赖库版本。下面提供了几种常见的文件格式与生成方式:
- `poetry.lock`
[poetry](https://python-poetry.org/) 依赖管理工具使用的 lock 文件,通常会在安装依赖时自动生成,或者使用 `poetry lock` 来生成。
- `pdm.lock`
[pdm](https://pdm.fming.dev/) 依赖管理工具使用的 lock 文件,通常会在安装依赖时自动生成,或者使用 `pdm lock` 来生成。
- `Pipfile.lock`
[Pipenv](https://pipenv.pypa.io/en/latest/) 依赖管理工具使用的 lock 文件,通常会在安装依赖时自动生成,或者使用 `pipenv lock` 来生成。
- `requirements.txt`
如果你未使用任何依赖管理工具,你可以使用 `pip freeze` 来生成这个文件。
## 使用 Docker 部署(推荐)
请自行参考 [Docker 官方文档](https://docs.docker.com/engine/install/) 安装 Docker。
在生产环境安装 [docker-compose](https://docs.docker.com/compose/) 工具以便部署机器人。
### 编译镜像与部署配置
在项目目录下添加以下两个文件(以 poetry 和 FastAPI 驱动器为例):
```dockerfile title=Dockerfile
FROM python:3.9 as requirements-stage
WORKDIR /tmp
COPY ./pyproject.toml ./poetry.lock* /tmp/
RUN curl -sSL https://install.python-poetry.org -o install-poetry.py
RUN python install-poetry.py --yes
ENV PATH="${PATH}:/root/.local/bin"
RUN poetry export -f requirements.txt --output requirements.txt --without-hashes
FROM tiangolo/uvicorn-gunicorn-fastapi:python3.9
WORKDIR /app
COPY --from=requirements-stage /tmp/requirements.txt /app/requirements.txt
RUN pip install --no-cache-dir --upgrade -r requirements.txt
RUN rm requirements.txt
COPY ./ /app/
```
```yaml title=docker-compose.yml
version: "3"
services:
nonebot:
build: .
ports:
- "8080:8080" # 映射端口到宿主机 宿主机端口:容器端口
env_file:
- ".env.prod" # fastapi 使用的环境变量文件
environment:
- ENVIRONMENT=prod
- APP_MODULE=bot:app
- MAX_WORKERS=1
network_mode: bridge
```
配置完成后即可使用 `docker-compose up -d` 命令来启动机器人并在后台运行。
### CI/CD
配合 GitHub Actions 可以完成 CI/CD在 GitHub 上发布 Release 时自动部署至生产环境。
在 [Docker Hub](https://hub.docker.com/) 上创建仓库,并将下方 workflow 文件中高亮行中的仓库名称替换为你的仓库名称。
前往项目仓库的 `Settings` > `Secrets` > `actions` 栏目 `New Repository Secret` 添加部署所需的密钥:
- `DOCKERHUB_USERNAME`: 你的 Docker Hub 用户名
- `DOCKERHUB_PASSWORD`: 你的 Docker Hub PAT[创建方法](https://docs.docker.com/docker-hub/access-tokens/)
- `DEPLOY_HOST`: 部署服务器的 SSH 地址
- `DEPLOY_USER`: 部署服务器用户名
- `DEPLOY_KEY`: 部署服务器私钥 ([创建方法](https://github.com/appleboy/ssh-action#setting-up-a-ssh-key))
- `DEPLOY_PATH`: 部署服务器上的项目路径
将以下文件添加至项目下的 `.github/workflows/` 目录下:
```yaml title=.github/workflows/build.yml {30}
name: Docker Hub Release
on:
push:
tags:
- "v*"
jobs:
docker:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup Docker
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_PASSWORD }}
- name: Generate Tags
uses: docker/metadata-action@v3
id: metadata
with:
images: |
{organization}/{repository}
tags: |
type=semver,pattern={{version}}
type=sha
- name: Build and Publish
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: ${{ steps.metadata.outputs.tags }}
labels: ${{ steps.metadata.outputs.labels }}
```
```yaml title=.github/workflows/deploy.yml
name: Deploy
on:
workflow_run:
workflows:
- Docker Hub Release
types:
- completed
jobs:
deploy:
runs-on: ubuntu-latest
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- name: start deployment
uses: bobheadxi/deployments@v1
id: deployment
with:
step: start
token: ${{ secrets.GITHUB_TOKEN }}
env: official-bot
- name: remote ssh command
uses: appleboy/ssh-action@master
env:
DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }}
with:
host: ${{ secrets.DEPLOY_HOST }}
username: ${{ secrets.DEPLOY_USER }}
key: ${{ secrets.DEPLOY_KEY }}
envs: DEPLOY_PATH
script: |
cd $DEPLOY_PATH
docker-compose down
docker-compose pull
docker-compose up -d
- name: update deployment status
uses: bobheadxi/deployments@v0.6.2
if: always()
with:
step: finish
token: ${{ secrets.GITHUB_TOKEN }}
status: ${{ job.status }}
deployment_id: ${{ steps.deployment.outputs.deployment_id }}
```
将上一部分的 `docker-compose.yml` 文件以及 `.env.prod` 配置文件添加至 `DEPLOY_PATH` 目录下,并修改 `docker-compose.yml` 文件中的镜像配置,替换为 Docker Hub 的仓库名称。
```diff
- build: .
+ image: {organization}/{repository}:latest
```
## 使用 Supervisor 部署
参考:[Uvicorn - Supervisor](https://www.uvicorn.org/deployment/#supervisor)
```ini
[supervisord]
[fcgi-program:nonebot]
socket=tcp://localhost:8080
command=python3 -m uvicorn --fd 0 bot:app
directory=/path/to/bot
autorestart=true
startsecs=10
startretries=3
numprocs=1
process_name=%(program_name)s-%(process_num)d
stdout_logfile=/path/to/log/nonebot.out.log
stdout_logfile_maxbytes=2MB
```
:::warning 警告
请配合虚拟环境使用,如 venv 等,请勿直接在 Linux 服务器系统环境中安装。
:::
## 使用 PM2 部署
:::tip 提示
在阅读这一节的过程中, 你总是可以参照 [PM2 官方文档](https://pm2.keymetrics.io/docs/usage/quick-start/) 来得到更多的信息
:::
### 安装 PM2
需要有 NodeJS 10+环境来运行 PM2, ~~(什么 NTR)~~
然后通过以下命令安装即可:
```shell
npm install -g pm2
```
在安装完成后, 执行以下指令, 如果得到类似的输出则说明你安装成功了 PM2:
```shell
$ pm2 -V
5.2.0
```
### 在后台运行进程
:::tip 提示
以下步骤要求您在您 Bot 的工作目录下执行
如果您使用了虚拟环境, 请确保 Bot 启动命令能在虚拟环境中正常执行
换言之, Bot 程序需要在当前终端环境下正常运行
:::
#### 启动 Bot 进程
```shell
$ pm2 start "python -m nb_cli run" # 或者直接 nb run 也行
[PM2] Starting /usr/bin/bash in fork_mode (1 instance)
[PM2] Done.
┌─────┬────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id │ name │ namespace │ version │ mode │ pid │ uptime │ ↺ │ status │ cpu │ mem │ user │ watching │
├─────┼────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0 │ nb run │ default │ N/A │ fork │ 93061 │ 0s │ 0 │ online │ 0% │ 8.3mb │ mix │ disabled │
└─────┴────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘
```
此时 Bot 进程就在后台运行了, 注意到表格第一列的 ID, 它可以用来查看和控制进程的状态
#### 常用命令
更具体的用法请移步 PM2 官方文档, ~~如果想要详细示例建议直接上手试试~~
其中命令中的所有`<id>`应该替换为上文启动进程后返回的 ID
- 查看最近 150 行日志
- `pm2 log <id> --lines 150`
- 实时监控所有进程日志
- `pm2 monit`
- 展示当前 PM2 管理的所有进程
- `pm2 ls`
- 停止某个进程
- `pm2 stop <id>`
- 删除某个进程
- `pm2 del <id>`
- 重启某个进程
- `pm2 restart <id>`
- 保存当前进程列表
- `pm2 save`
- 恢复保存的进程列表
- `pm2 resurrect`
- 设置开机自动启动进程列表
- `pm2 startup`
- 需要执行过 `pm2 save`
如果不是 root 用户执行, 则需要手动添加指令返回的环境变量

View File

@ -1,5 +0,0 @@
{
"position": 7,
"label": "插件",
"collapsible": false
}

View File

@ -1,37 +0,0 @@
---
sidebar_position: 2
description: 规范定义插件配置项
---
# 定义插件配置
通常,插件可以从配置文件中读取自己的配置项,但是由于额外的全局配置项没有预先定义的问题,导致开发时编辑器无法提示字段与类型,以及运行时没有对配置项直接进行检查。那么就需要一种方式来规范定义插件配置项。
## 定义配置模型
在 NoneBot2 中,我们使用强大高效的 [Pydantic](https://pydantic-docs.helpmanual.io/) 来定义配置模型,这个模型可以被用于配置的读取和类型检查等。例如,我们可以定义一个配置模型包含一个 string 类型的配置项:
```python title=config.py {3,4}
from pydantic import BaseModel, Extra
class Config(BaseModel, extra=Extra.ignore):
token: str
```
:::important 参考
更多丰富的模型定义方法(默认值、自定义 validator 等),请参考 [Pydantic](https://pydantic-docs.helpmanual.io/) 文档。
:::
## 读取配置
定义完成配置模型后,我们可以在插件加载时获取全局配置,导入插件自身的配置模型:
```python title=__init__.py {5}
from nonebot import get_driver
from .config import Config
plugin_config = Config.parse_obj(get_driver().config)
```
至此,插件已经成功读取了自身所需的配置项,并且具有字段和类型提示,也可以对配置进行运行时修改。

View File

@ -1,473 +0,0 @@
---
sidebar_position: 4
description: 定义事件处理流程,完成事件响应
options:
menu:
weight: 27
category: guide
---
# 定义事件处理流程
在上一章节中,我们已经定义了事件响应器,在这一章中,我们将会为事件响应器填充处理流程。
## 添加一个处理依赖
在事件响应器中,事件处理流程由一个或多个处理依赖组成,每个处理依赖都是一个 `Dependent`,详情可以参考[进阶 - 依赖注入](../../advanced/di/dependency-injection.md)。下面介绍如何添加一个处理依赖。
### 使用 `handle` 装饰器
```python {3-5}
matcher = on_message()
@matcher.handle()
async def handle_func():
# do something here
```
如上方示例所示,我们使用 `matcher` 响应器的 `handle` 装饰器装饰了一个函数 `handle_func` 。`handle_func` 函数会被自动转换为 `Dependent` 对象,并被添加到 `matcher` 的事件处理流程中。
`handle_func` 函数中,我们可以编写任何事件响应逻辑,如:操作数据库,发送消息等。上下文信息可以通过依赖注入的方式获取,参考:[获取上下文信息](#获取上下文信息)。发送消息可以通过[事件响应器操作](./matcher-operation.md)或者直接调用 Bot 的方法( API 等,由协议适配器决定)。
:::warning 注意
`handle_func` 函数虽然会被装饰器自动转换为 `Dependent` 对象,但 `handle_func` 仍然为原本的函数,因此 `handle_func` 函数可以进行复用。如:
```python
matcher1 = on_message()
matcher2 = on_message()
@matcher1.handle()
@matcher2.handle()
async def handle_func():
# do something here
```
:::
### 使用 `receive` 装饰器
```python {3-5}
matcher = on_message()
@matcher.receive("id")
async def handle_func(e: Event = Received("id")):
# do something here
```
`receive` 装饰器与 `handle` 装饰器一样,可以装饰一个函数添加到事件响应器的事件处理流程中。但与 `handle` 装饰器不同的是,`receive` 装饰器会中断当前事件处理流程,等待接收一个新的事件,就像是会话状态等待用户一个新的事件。可以接收的新的事件类型取决于事件响应器的 [`type`](./create-matcher.md#事件响应器类型-type) 更新值以及 [`permission`](./create-matcher.md#事件触发权限-permission) 更新值,可以通过自定义更新方法来控制会话响应(如进行非消息交互、多人会话、跨群会话等)。
`receive` 装饰器接受一个可选参数 `id`,用于标识当前需要接收的事件,如果不指定,则默认为空 `""`
`handle_func` 函数中,可以通过依赖注入的方式来获取接收到的事件,参考:[`Received`](#received)、[`LastReceived`](#lastreceived)。
:::important 提示
`receive` 装饰器可以和自身与 `got` 装饰器嵌套使用
:::
:::warning 注意
如果存在多个 `receive` 装饰器,则必须指定不相同的多个 `id`;否则相同的 `id` 将会被跳过接收。
```python
matcher = on_message()
@matcher.receive("id1")
@matcher.receive("id2")
async def handle_func():
# do something here
```
:::
### 使用 `got` 装饰器
```python {3-5}
matcher = on_message()
@matcher.got("key", prompt="Key?")
async def handle_func(key: Message = Arg()):
# do something here
```
`got` 装饰器与 `receive` 装饰器一样,会中断当前事件处理流程,等待接收一个新的事件。但与 `receive` 装饰器不同的是,`got` 装饰器用于接收一条消息,并且可以控制是否向用户发送询问 `prompt` 等,更贴近于对话形式会话。
`got` 装饰器接受一个参数 `key` 和一个可选参数 `prompt`,当 `key` 不存在时,会向用户发送 `prompt` 消息,并等待用户回复。
`handle_func` 函数中,可以通过依赖注入的方式来获取接收到的消息,参考:[`Arg`](#arg)、[`ArgStr`](#argstr)、[`ArgPlainText`](#argplaintext)。
:::important 提示
`got` 装饰器可以和自身与 `receive` 装饰器嵌套使用
:::
### 直接添加
```python {2}
matcher = on_message(
handlers=[handle_func, or_dependent]
)
```
:::warning 注意
通过该方法添加的处理依赖将会处于整个事件处理流程的最前,因此,如果再使用 `handle` 等装饰器,则会在其之后。
:::
## 事件处理流程
在一个事件响应器中,事件被添加的处理依赖依次执行,直到所有处理依赖都执行完毕,或者遇到了某个处理依赖需要更多的事件来进行下一步的处理。在下一个事件到来并符合响应要求时,继续执行。更多有关 NoneBot 事件分发与处理流程的详细信息,请参考[进阶 - 深入](../../advanced/README.md)。
## 获取上下文信息
在事件处理流程中,事件响应器具有自己独立的上下文,例如:当前的事件、机器人等信息,可以通过依赖注入的方式来获取。
### Bot
获取当前事件的 Bot 对象。
```python {7-9}
from typing import Union
from nonebot.adapters import Bot
from nonebot.adapters.ding import Bot as DingBot
from nonebot.adapters.onebot.v11 import Bot as OneBotV11Bot
async def _(foo: Bot): ...
async def _(foo: Union[DingBot, OneBotV11Bot]): ...
async def _(bot): ... # 兼容性处理
```
### Event
获取当前事件。
```python {6-8}
from typing import Union
from nonebot.adapters import Event
from nonebot.adapters.onebot.v11 import PrivateMessageEvent, GroupMessageEvent
async def _(foo: Event): ...
async def _(foo: Union[PrivateMessageEvent, GroupMessageEvent]): ...
async def _(event): ... # 兼容性处理
```
### EventType
获取当前事件的类型。
```python {3}
from nonebot.params import EventType
async def _(foo: str = EventType()): ...
```
### EventMessage
获取当前事件的消息。
```python {4}
from nonebot.adapters import Message
from nonebot.params import EventMessage
async def _(foo: Message = EventMessage()): ...
```
### EventPlainText
获取当前事件的消息纯文本部分。
```python {3}
from nonebot.params import EventPlainText
async def _(foo: str = EventPlainText()): ...
```
### EventToMe
获取当前事件是否与机器人相关。
```python {3}
from nonebot.params import EventToMe
async def _(foo: bool = EventToMe()): ...
```
### State
获取当前事件处理上下文状态State 为一个字典,用户可以向 State 中添加数据来保存状态等操作。(请注意不要随意覆盖 State 中 NoneBot 的数据)
```python {4}
from nonebot.typing import T_State
async def _(foo: T_State): ...
```
### Command
获取当前命令型消息的元组形式命令名。
```python {7}
from nonebot import on_command
from nonebot.params import Command
matcher = on_command("cmd")
@matcher.handle()
async def _(foo: Tuple[str, ...] = Command()): ...
```
:::tip 提示
命令详情只能在首次接收到命令型消息时获取,如果在事件处理后续流程中获取,则会获取到不同的值。
:::
### RawCommand
获取当前命令型消息的文本形式命令名。
```python {7}
from nonebot import on_command
from nonebot.params import RawCommand
matcher = on_command("cmd")
@matcher.handle()
async def _(foo: str = RawCommand()): ...
```
:::tip 提示
命令详情只能在首次接收到命令型消息时获取,如果在事件处理后续流程中获取,则会获取到不同的值。
:::
### CommandArg
获取命令型消息命令后跟随的参数。
```python {8}
from nonebot import on_command
from nonebot.adapters import Message
from nonebot.params import CommandArg
matcher = on_command("cmd")
@matcher.handle()
async def _(foo: Message = CommandArg()): ...
```
:::tip 提示
命令详情只能在首次接收到命令型消息时获取,如果在事件处理后续流程中获取,则会获取到不同的值。
:::
### CommandStart
获取命令型消息命令前缀。
```python {8}
from nonebot import on_command
from nonebot.adapters import Message
from nonebot.params import CommandStart
matcher = on_command("cmd")
@matcher.handle()
async def _(foo: str = CommandStart()): ...
```
:::tip 提示
命令详情只能在首次接收到命令型消息时获取,如果在事件处理后续流程中获取,则会获取到不同的值。
:::
### ShellCommandArgs
获取 shell 命令解析后的参数,支持 MessageSegment 富文本(如:图片)。
:::tip 提示
如果参数解析失败,则为 [`ParserExit`](../../api/exception.md#ParserExit) 异常,并携带错误码与错误信息。
由于 `ArgumentParser` 在解析到 `--help` 参数时也会抛出异常,这种情况下错误码为 `0` 且错误信息即为帮助信息。
:::
```python {8,12}
from nonebot import on_shell_command
from nonebot.params import ShellCommandArgs
from nonebot.rule import Namespace, ArgumentParser
parser = ArgumentParser("demo")
# parser.add_argument ...
matcher = on_shell_command("cmd", parser)
# 解析失败
@matcher.handle()
async def _(foo: ParserExit = ShellCommandArgs()):
if foo.status == 0:
foo.message # help message
else:
foo.message # error message
# 解析成功
@matcher.handle()
async def _(foo: Namespace = ShellCommandArgs()): ...
```
### ShellCommandArgv
获取 shell 命令解析前的参数列表,支持 MessageSegment 富文本(如:图片)。
```python {7}
from nonebot import on_shell_command
from nonebot.params import ShellCommandArgs
matcher = on_shell_command("cmd")
@matcher.handle()
async def _(foo: List[Union[str, MessageSegment]] = ShellCommandArgv()): ...
```
### RegexMatched
获取正则匹配结果。
```python {7}
from nonebot import on_regex
from nonebot.params import RegexMatched
matcher = on_regex("regex")
@matcher.handle()
async def _(foo: str = RegexMatched()): ...
```
### RegexGroup
获取正则匹配结果的 group 元组。
```python {7}
from nonebot import on_regex
from nonebot.params import RegexGroup
matcher = on_regex("regex")
@matcher.handle()
async def _(foo: Tuple[Any, ...] = RegexGroup()): ...
```
### RegexDict
获取正则匹配结果的 group 字典。
```python {7}
from nonebot import on_regex
from nonebot.params import RegexDict
matcher = on_regex("regex")
@matcher.handle()
async def _(foo: Dict[str, Any] = RegexDict()): ...
```
### Matcher
获取当前事件响应器实例。
```python {7}
from nonebot import on_message
from nonebot.matcher import Matcher
foo = on_message()
@foo.handle()
async def _(matcher: Matcher): ...
```
### Received
获取某次 `receive` 接收的事件。
```python {8}
from nonebot import on_message
from nonebot.adapters import Event
from nonebot.params import Received
matcher = on_message()
@matcher.receive("id")
async def _(foo: Event = Received("id")): ...
```
### LastReceived
获取最近一次 `receive` 接收的事件。
```python {8}
from nonebot import on_message
from nonebot.adapters import Event
from nonebot.params import LastReceived
matcher = on_message()
@matcher.receive("any")
async def _(foo: Event = LastReceived()): ...
```
### Arg
获取某次 `got` 接收的参数。
```python {8-9}
from nonebot.params import Arg
from nonebot import on_message
from nonebot.adapters import Message
matcher = on_message()
@matcher.got("key")
async def _(key: Message = Arg()): ...
async def _(foo: Message = Arg("key")): ...
```
### ArgStr
获取某次 `got` 接收的参数,并转换为字符串。
```python {7-8}
from nonebot import on_message
from nonebot.params import ArgStr
matcher = on_message()
@matcher.got("key")
async def _(key: str = ArgStr()): ...
async def _(foo: str = ArgStr("key")): ...
```
### ArgPlainText
获取某次 `got` 接收的参数的纯文本部分。
```python {7-8}
from nonebot import on_message
from nonebot.params import ArgPlainText
matcher = on_message()
@matcher.got("key")
async def _(key: str = ArgPlainText()): ...
async def _(foo: str = ArgPlainText("key")): ...
```
### Exception
获取事件响应器运行中抛出的异常。
```python {4}
from nonebot.message import run_postprocessor
@run_postprocessor
async def _(e: Exception): ...
```
### Default
带有默认值的参数,便于复用依赖。
```python {1}
async def _(foo="bar"): ...
```

View File

@ -1,133 +0,0 @@
---
sidebar_position: 3
description: 定义事件响应器,对特定的事件进行处理
options:
menu:
weight: 26
category: guide
---
# 定义事件响应器
事件响应器(`Matcher`)是对接收到的事件进行响应的基本单元,所有的事件响应器都继承自 `Matcher` 基类。为了方便开发者编写插件NoneBot2 在 `nonebot.plugin` 模块中为插件开发定义了一些辅助函数。首先,让我们来了解一下 `Matcher` 由哪些部分组成。
## 事件响应器的基本组成
### 事件响应器类型 `type`
事件响应器的类型即是该响应器所要响应的事件类型,只有在接收到的事件类型与该响应器的类型相同时,才会触发该响应器。如果类型留空,该响应器将会响应所有类型的事件。
NoneBot 内置了四种主要类型:`meta_event`、`message`、`notice`、`request`。通常情况下,协议适配器会将事件合理地分类至这四种类型中。如果有其他类型的事件需要响应,可以自行定义新的类型。
<!-- TODO: move session updater to advanced -->
:::warning 注意
当会话状态更新时,会执行 `type_updater` 以更新 `type` 属性,以便会话收到新事件时能够正确匹配。
`type_updater` 默认将 `type` 修改为 `message`,你也可以自行定义 `type_updater` 来控制 `type` 属性更新。`type_updater` 是一个返回 `str` 的函数,可选依赖注入参数参考类型 `T_TypeUpdater`
```python {3-5}
matcher = on_request()
@matcher.type_updater
async def update_type():
return "message"
```
:::
### 事件匹配规则
事件响应器的匹配规则是一个 `Rule` 对象,它是一系列 `checker` 的集合,当所有的 `checker` 都返回 `True` 时,才会触发该响应器。
规则编写方法参考[进阶 - 自定义规则](../../advanced/rule.md)。
:::warning 注意
当会话状态更新时,`rule` 会被清空,以便会话收到新事件时能够正确匹配。
:::
### 事件触发权限 `permission`
事件响应器的触发权限是一个 `Permission` 对象,它也是一系列 `checker` 的集合,当其中一个 `checker` 返回 `True` 时,就会触发该响应器。
权限编写方法参考[进阶 - 自定义权限](../../advanced/permission.md)。
:::warning 注意
`rule` 不同的是,`permission` 不会在会话状态更新时丢失,因此 `permission` 通常用于会话的响应控制。
并且,当会话状态更新时,会执行 `permission_updater` 以更新 `permission`。默认情况下,`permission_updater` 会在原有的 `permission` 基础上添加一个 `USER` 条件,以检查事件的 `session_id` 是否与当前会话一致。
你可以自行定义 `permission_updater` 来控制会话的响应权限更新。`permission_updater` 是一个返回 `Permission` 的函数,可选依赖注入参数参考类型 `T_PermissionUpdater`
```python {3-5}
matcher = on_message()
@matcher.permission_updater
async def update_type(matcher: Matcher):
return matcher.permission # return same without session_id check
```
:::
### 优先级 `priority`
事件响应器的优先级代表事件响应器的执行顺序
:::warning 警告
同一优先级的事件响应器会**同时执行**,优先级数字**越小**越先响应!优先级请从 `1` 开始排序!
:::
### 阻断 `block`
当有任意事件响应器发出了阻止事件传递信号时,该事件将不再会传递给下一优先级,直接结束处理。
NoneBot 内置的事件响应器中,所有非 `command` 规则的 `message` 类型的事件响应器都会阻断事件传递,其他则不会。
在部分情况中,可以使用 `matcher.stop_propagation()` 方法动态阻止事件传播,该方法需要 `handler` 在参数中获取 `matcher` 实例后调用方法。
```python {5}
foo = on_request()
@foo.handle()
async def handle(matcher: Matcher):
matcher.stop_propagation()
```
### 有效期 `temp`/`expire_time`
事件响应器可以设置有效期,当事件响应器超过有效期时,将会被移除。
- `temp` 属性:配置事件响应器在下一次响应之后移除。
- `expire_time` 属性:配置事件响应器在指定时间之后移除。
## 创建事件响应器
在前面的介绍中,我们已经了解了事件响应器的组成,接下来我们就可以使用 `nonebot.plugin` 模块中定义的辅助函数来创建事件响应器。
```python {3}
from nonebot import on_message
matcher = on_message()
```
用于定义事件响应器的辅助函数已经在 `nonebot` 主模块中被 `re-export`,所以直接从 `nonebot` 导入即可。
辅助函数有以下几种:
1. `on`: 创建任何类型的事件响应器。
2. `on_metaevent`: 创建元事件响应器。
3. `on_message`: 创建消息事件响应器。
4. `on_request`: 创建请求事件响应器。
5. `on_notice`: 创建通知事件响应器。
6. `on_startswith`: 创建消息开头匹配事件响应器。
7. `on_endswith`: 创建消息结尾匹配事件响应器。
8. `on_fullmatch`: 创建消息完全匹配事件响应器。
9. `on_keyword`: 创建消息关键词匹配事件响应器。
10. `on_command`: 创建命令消息事件响应器。
11. `on_shell_command`: 创建 shell 命令消息事件响应器。
12. `on_regex`: 创建正则表达式匹配事件响应器。
13. `CommandGroup`: 创建具有共同命令名称前缀的命令组。
14. `MatcherGroup`: 创建具有共同参数的响应器组。
其中,`on_metaevent` `on_message` `on_request` `on_notice` 函数都是在 `on` 的基础上添加了对应的事件类型 `type``on_startswith` `on_endswith` `on_fullmatch` `on_keyword` `on_command` `on_shell_command` `on_regex` 函数都是在 `on_message` 的基础上添加了对应的匹配规则 `rule`

View File

@ -1,32 +0,0 @@
---
sidebar_position: 6
description: 简单插件示例
---
import CodeBlock from "@theme/CodeBlock";
import Messenger from "@site/src/components/Messenger";
# 插件示例
## 命令式问答示例
import WeatherSource from "!!raw-loader!@site/../tests/examples/weather.py";
import WeatherTest from "!!raw-loader!@site/../tests/test_examples/test_weather.py";
<CodeBlock className="language-python">{WeatherSource}</CodeBlock>
<Messenger
msgs={[
{ position: "right", msg: "/天气" },
{ position: "left", msg: "你想查询哪个城市的天气呢?" },
{ position: "right", msg: "上海" },
{ position: "left", msg: "上海的天气是..." },
]}
/>
<details>
<summary>测试示例</summary>
<CodeBlock className="language-python">{WeatherTest}</CodeBlock>
</details>

View File

@ -1,71 +0,0 @@
---
sidebar_position: 0
description: 插件入门
---
# 插件入门
## 插件结构
在编写插件之前,首先我们需要了解一下插件的概念。
在 NoneBot 中,插件可以是 Python 的一个模块 `module`,也可以是一个包 `package` 。NoneBot 会在导入时对这些模块或包做一些特殊的处理使得他们成为一个插件。插件间应尽量减少耦合可以进行有限制的插件间调用NoneBot 能够正确解析插件间的依赖关系。
下面详细介绍两种插件的结构:
### 模块插件(单文件形式)
在合适的路径创建一个 `.py` 文件即可。例如在[创建项目](../create-project.mdx)中创建的项目中,我们可以在 `awesome_bot/plugins/` 目录中创建一个文件 `foo.py`
```tree title=Project {4}
📦 AweSome-Bot
├── 📂 awesome_bot
│ └── 📂 plugins
| └── 📜 foo.py
├── 📜 .env
├── 📜 .env.dev
├── 📜 .env.prod
├── 📜 .gitignore
├── 📜 bot.py
├── 📜 docker-compose.yml
├── 📜 Dockerfile
├── 📜 pyproject.toml
└── 📜 README.md
```
这个时候它已经可以被称为一个插件了,尽管它还什么都没做。
### 包插件(文件夹形式)
在合适的路径创建一个文件夹,并在文件夹内创建文件 `__init__.py` 即可。例如在[创建项目](../create-project.mdx)中创建的项目中,我们可以在 `awesome_bot/plugins/` 目录中创建一个文件夹 `foo`,并在这个文件夹内创建一个文件 `__init__.py`
```tree title=Project {4,5}
📦 AweSome-Bot
├── 📂 awesome_bot
│ └── 📂 plugins
| └── 📂 foo
| └── 📜 __init__.py
├── 📜 .env
├── 📜 .env.dev
├── 📜 .env.prod
├── 📜 .gitignore
├── 📜 bot.py
├── 📜 docker-compose.yml
├── 📜 Dockerfile
├── 📜 pyproject.toml
└── 📜 README.md
```
这个时候 `foo` 就是一个合法的 Python 包了,同时也是合法的 NoneBot 插件,插件内容可以在 `__init__.py` 中编写。
## 创建插件
:::danger 警告
请注意,插件名称不能存在重复,即所有模块插件的文件名和所有包插件的文件夹名不能存在相同。
:::
除了通过手动创建的方式以外,还可以通过 nb-cli 来创建插件nb-cli 会为你在合适的位置创建一个模板包插件。
```bash
nb plugin create
```

View File

@ -1,138 +0,0 @@
---
sidebar_position: 1
description: 通过不同方式加载插件
options:
menu:
weight: 25
category: guide
---
# 加载插件
:::danger 警告
请勿在插件被加载前 `import` 插件模块,这会导致 NoneBot2 无法将其转换为插件而损失部分功能。
:::
加载插件通常在机器人的入口文件进行,例如在[创建项目](../create-project.mdx)中创建的项目中的 `bot.py` 文件。在 NoneBot2 初始化完成后即可加载插件。
```python title=bot.py {5}
import nonebot
nonebot.init()
# load your plugin here
nonebot.run()
```
加载插件的方式有多种,但在底层的加载逻辑是一致的。以下是为加载插件提供的几种方式:
## `load_plugin`
通过点分割模块名称来加载插件,通常用于加载单个插件或者是第三方插件。例如:
```python
nonebot.load_plugin("path.to.your.plugin")
```
## `load_plugins`
加载传入插件目录中的所有插件,通常用于加载一系列本地编写的插件。例如:
```python
nonebot.load_plugins("src/plugins", "path/to/your/plugins")
```
:::warning 警告
请注意,插件所在目录应该为相对机器人入口文件可导入的,例如与入口文件在同一目录下。
:::
## `load_all_plugins`
这种加载方式是以上两种方式的混合,加载所有传入的插件模块名称,以及所有给定目录下的插件。例如:
```python
nonebot.load_all_plugins(["path.to.your.plugin"], ["path/to/your/plugins"])
```
## `load_from_json`
通过 JSON 文件加载插件,是 [`load_all_plugins`](#load_all_plugins) 的 JSON 变种。通过读取 JSON 文件中的 `plugins` 字段和 `plugin_dirs` 字段进行加载。例如:
```json title=plugin_config.json
{
"plugins": ["path.to.your.plugin"],
"plugin_dirs": ["path/to/your/plugins"]
}
```
```python
nonebot.load_from_json("plugin_config.json", encoding="utf-8")
```
:::tip 提示
如果 JSON 配置文件中的字段无法满足你的需求,可以使用 [`load_all_plugins`](#load_all_plugins) 方法自行读取配置来加载插件。
:::
## `load_from_toml`
通过 TOML 文件加载插件,是 [`load_all_plugins`](#load_all_plugins) 的 TOML 变种。通过读取 TOML 文件中的 `[tool.nonebot]` Table 中的 `plugins``plugin_dirs` Array 进行加载。例如:
```toml title=plugin_config.toml
[tool.nonebot]
plugins = ["path.to.your.plugin"]
plugin_dirs = ["path/to/your/plugins"]
```
```python
nonebot.load_from_toml("plugin_config.toml", encoding="utf-8")
```
:::tip 提示
如果 TOML 配置文件中的字段无法满足你的需求,可以使用 [`load_all_plugins`](#load_all_plugins) 方法自行读取配置来加载插件。
:::
## `load_builtin_plugin`
加载一个内置插件,是 [`load_plugin`](#load_plugin) 的封装。例如:
```python
nonebot.load_builtin_plugin("echo")
```
## 确保插件加载和跨插件访问
倘若 `plugin_a`, `plugin_b` 均需被加载, 且 `plugin_b` 插件需要导入 `plugin_a` 才可运行, 可以在 `plugin_b` 利用 `require` 方法来确保插件加载, 同时可以直接 `import` 导入 `plugin_a` ,进行跨插件访问。
```python title=plugin_b.py
from nonebot import require
require('plugin_a')
import plugin_a
```
:::danger 警告
不用 `require` 方法也可以进行跨插件访问,但需要保证插件已加载。例如,以下两种方式均可确保插件正确加载:
```python title=bot.py
import nonebot
# 顺序加载
nonebot.load_plugin("plugin_a")
nonebot.load_plugin("plugin_b")
```
```python
import nonebot
# 同时加载
nonebot.load_all_plugins(["plugin_a", "plugin_b"], [])
```
:::
## 嵌套插件
<!-- TODO -->

View File

@ -1,146 +0,0 @@
---
sidebar_position: 5
description: 使用事件响应器操作,改变事件处理流程
options:
menu:
weight: 28
category: guide
---
# 事件响应器操作
在事件处理流程中,我们可以使用事件响应器操作来进行一些交互或改变事件处理流程。
## send
向用户回复一条消息。回复的方式或途径由协议适配器自行实现。
可以是 `str`、[`Message`](../../api/adapters/index.md#Message)、[`MessageSegment`](../../api/adapters/index.md#MessageSegment) 或 [`MessageTemplate`](../../api/adapters/index.md#MessageTemplate)。
这个操作等同于使用 `bot.send(event, message, **kwargs)` 但不需要自行传入 `event`
```python {3}
@matcher.handle()
async def _():
await matcher.send("Hello world!")
```
## finish
向用户回复一条消息(可选),并立即结束当前事件的整个处理流程。
参数与 [`send`](#send) 相同。
```python {3}
@matcher.handle()
async def _():
await matcher.finish("Hello world!")
# something never run
...
```
## pause
向用户回复一条消息(可选),并立即结束当前事件处理依赖并等待接收一个新的事件后进入下一个事件处理依赖。
类似于 `receive` 的行为但可以根据事件来决定是否接收新的事件。
```python {4}
@matcher.handle()
async def _():
if serious:
await matcher.pause("Confirm?")
@matcher.handle()
async def _():
...
```
## reject
向用户回复一条消息(可选),并立即结束当前事件处理依赖并等待接收一个新的事件后再次执行当前事件处理依赖。
通常用于拒绝当前 `receive` 接收的事件或 `got` 接收的参数(如:不符合格式或标准)。
```python {4}
@matcher.got("arg")
async def _(arg: str = ArgPlainText()):
if not is_valid(arg):
await matcher.reject("Invalid arg!")
```
## reject_arg
向用户回复一条消息(可选),并立即结束当前事件处理依赖并等待接收一个新的事件后再次执行当前事件处理依赖。
用于拒绝指定 `got` 接收的参数,通常在嵌套装饰器时使用。
```python {4}
@matcher.got("a")
@matcher.got("b")
async def _(a: str = ArgPlainText(), b: str = ArgPlainText()):
if a not in b:
await matcher.reject_arg("a", "Invalid a!")
```
## reject_receive
向用户回复一条消息(可选),并立即结束当前事件处理依赖并等待接收一个新的事件后再次执行当前事件处理依赖。
用于拒绝指定 `receive` 接收的事件,通常在嵌套装饰器时使用。
```python {4}
@matcher.receive("a")
@matcher.receive("b")
async def _(a: Event = Received("a"), b: Event = Received("b")):
if a.get_user_id() != b.get_user_id():
await matcher.reject_receive("a")
```
## skip
立即结束当前事件处理依赖,进入下一个事件处理依赖。
通常在子依赖中使用,用于跳过当前事件处理依赖的执行。
```python {2}
async def dependency(matcher: Matcher):
matcher.skip()
@matcher.handle()
async def _(sub=Depends(dependency)):
# never run
...
```
## get_receive
获取一个 `receive` 接收的事件。
## set_receive
设置/覆盖一个 `receive` 接收的事件。
## get_last_receive
获取最近一次 `receive` 接收的事件。
## get_arg
获取一个 `got` 接收的参数。
## set_arg
设置/覆盖一个 `got` 接收的参数。
## stop_propagation
阻止事件向更低优先级的事件响应器传播。
```python
@foo.handle()
async def _(matcher: Matcher):
matcher.stop_propagation()
```

View File

@ -1,253 +0,0 @@
---
sidebar_position: 9
description: 处理消息序列与消息段
options:
menu:
weight: 30
category: guide
---
# 处理消息
## NoneBot2 中的消息
在不同平台中,一条消息可能会有承载有各种不同的表现形式,它可能是一段纯文本、一张图片、一段语音、一篇富文本文章,也有可能是多种类型的组合等等。
在 NoneBot2 中,为确保消息的正常处理与跨平台兼容性,采用了扁平化的消息序列形式,即 `Message` 对象。
`Message` 是多个消息段 `MessageSegment` 的集合,它继承自 `List[MessageSegment]`,并在此基础上添加或强化了一些特性。
`MessageSegment` 是一个 [`dataclass`](https://docs.python.org/zh-cn/3/library/dataclasses.html#dataclasses.dataclass) ,它具有一个类型标识 `type`,以及一些对应的数据信息 `data`
此外NoneBot2 还提供了 `MessageTemplate` ,用于构建支持消息序列以及消息段的特殊消息模板。
## 使用消息序列
通常情况下,适配器在接收到消息时,会将消息转换为消息序列,可以通过 [`EventMessage`](./plugin/create-handler.md#EventMessage) 作为依赖注入, 或者使用 `event.get_message()` 获取。
由于它是`List[MessageSegment]`的子类, 所以你总是可以用和操作 List 类似的方式来处理消息序列
```python
>>> message = Message([
MessageSegment(type='text', data={'text':'hello'}),
MessageSegment(type='image', data={'url':'http://example.com/image.png'}),
MessageSegment(type='text', data={'text':'world'}),
])
>>> for segment in message:
... print(segment.type, segment.data)
...
text {'text': 'hello'}
image {'url': 'http://example.com/image.png'}
text {'text': 'world'}
>>> len(message)
3
```
### 构造消息序列
在使用事件响应器操作发送消息时,既可以使用 `str` 作为消息,也可以使用 `Message`、`MessageSegment` 或者 `MessageTemplate`。那么,我们就需要先构造一个消息序列。
#### 直接构造
`Message` 类可以直接实例化,支持 `str`、`MessageSegment`、`Iterable[MessageSegment]` 或适配器自定义类型的参数。
```python
# str
Message("Hello, world!")
# MessageSegment
Message(MessageSegment.text("Hello, world!"))
# List[MessageSegment]
Message([MessageSegment.text("Hello, world!")])
```
#### 运算构造
`Message` 对象可以通过 `str`、`MessageSegment` 相加构造,详情请参考[拼接消息](#拼接消息)。
#### 从字典数组构造
`Message` 对象支持 Pydantic 自定义类型构造,可以使用 Pydantic 的 `parse_obj_as` (`parse_raw_as`) 方法进行构造。
```python
from pydantic import parse_obj_as
# 由字典构造消息段
parse_obj_as(
MessageSegment, {"type": "text", "data": {"text": "text"}}
) == MessageSegment.text("text")
# 由字典数组构造消息序列
parse_obj_as(
Message,
[MessageSegment.text("text"), {"type": "text", "data": {"text": "text"}}],
) == Message([MessageSegment.text("text"), MessageSegment.text("text")])
```
:::tip 提示
以上示例中的字典数据仅做参考,具体的数据格式由适配器自行定义。
:::
### 获取消息纯文本
由于消息中存在各种类型的消息段,因此 `str(message)` 通常并不能得到消息的纯文本,而是一个消息序列的字符串表示。
NoneBot2 为消息段定义了一个方法 `is_text()` ,可以用于判断消息段是否为纯文本;也可以使用 `message.extract_plain_text()` 方法获取消息纯文本。
```python
# 判断消息段是否为纯文本
MessageSegment.text("text").is_text() == True
# 提取消息纯文本字符串
Message(
[MessageSegment.text("text"), MessageSegment.at(123)]
).extract_plain_text() == "text"
```
### 遍历
`Message` 继承自 `List[MessageSegment]` ,因此可以使用 `for` 循环遍历消息段。
```python
for segment in message:
...
```
### 索引与切片
`Message` 对列表的索引与切片进行了增强,在原有列表 int 索引与切片的基础上,支持 `type` 过滤索引与切片。
```python
message = Message(
[
MessageSegment.text("test"),
MessageSegment.image("test2"),
MessageSegment.image("test3"),
MessageSegment.text("test4"),
]
)
# 索引
message[0] == MessageSegment.text("test")
# 切片
message[0:2] == Message(
[MessageSegment.text("test"), MessageSegment.image("test2")]
)
# 类型过滤
message["image"] == Message(
[MessageSegment.image("test2"), MessageSegment.image("test3")]
)
# 类型索引
message["image", 0] == MessageSegment.image("test2")
# 类型切片
message["image", 0:2] == Message(
[MessageSegment.image("test2"), MessageSegment.image("test3")]
)
```
同样的,`Message` 对列表的 `index`、`count` 方法也进行了增强,可以用于索引指定类型的消息段。
```python
# 指定类型首个消息段索引
message.index("image") == 1
# 指定类型消息段数量
message.count("image") == 2
```
此外,`Message` 添加了一个 `get` 方法,可以用于获取指定类型指定个数的消息段。
```python
# 获取指定类型指定个数的消息段
message.get("image", 1) == Message([MessageSegment.image("test2")])
```
### 拼接消息
`str`、`Message`、`MessageSegment` 对象之间可以直接相加,相加均会返回一个新的 `Message` 对象。
```python
# 消息序列与消息段相加
Message([MessageSegment.text("text")]) + MessageSegment.text("text")
# 消息序列与字符串相加
Message([MessageSegment.text("text")]) + "text"
# 消息序列与消息序列相加
Message([MessageSegment.text("text")]) + Message([MessageSegment.text("text")])
# 字符串与消息序列相加
"text" + Message([MessageSegment.text("text")])
# 消息段与消息段相加
MessageSegment.text("text") + MessageSegment.text("text")
# 消息段与字符串相加
MessageSegment.text("text") + "text"
# 消息段与消息序列相加
MessageSegment.text("text") + Message([MessageSegment.text("text")])
# 字符串与消息段相加
"text" + MessageSegment.text("text")
```
如果需要在当前消息序列后直接拼接新的消息段,可以使用 `Message.append`、`Message.extend` 方法,或者使用自加。
```python
msg = Message([MessageSegment.text("text")])
# 自加
msg += "text"
msg += MessageSegment.text("text")
msg += Message([MessageSegment.text("text")])
# 附加
msg.append("text")
msg.append(MessageSegment.text("text"))
# 扩展
msg.extend([MessageSegment.text("text")])
```
## 使用消息模板
为了提供安全可靠的跨平台模板字符, 我们提供了一个消息模板功能来构建消息序列
它在以下常见场景中尤其有用:
- 多行富文本编排(包含图片,文字以及表情等)
- 客制化(由 Bot 最终用户提供消息模板时)
在事实上, 它的用法和`str.format`极为相近, 所以你在使用的时候, 总是可以参考[Python 文档](https://docs.python.org/zh-cn/3/library/stdtypes.html#str.format)来达到你想要的效果
这里给出几个简单的例子:
:::tip
这里面所有的`Message`均是用对应 Adapter 的实现导入的, 而不是抽象基类
:::
```python title="基础格式化用法"
>>> Message.template("{} {}").format("hello", "world")
Message(
MessageSegment.text("hello"),
MessageSegment.text(" "),
MessageSegment.text("world")
)
```
```python title="对消息段进行安全的拼接"
>>> Message.template("{}{}").format(MessageSegment.image("file:///..."), "world")
Message(
MessageSegment(type='image', data={'file': 'file:///...'}),
MessageSegment(type='text', data={'text': 'world'})
)
```
```python title="以消息对象作为模板"
>>> Message.template(
... MessageSegment.text('{user_id}') + MessageSegment.face(233) +
... MessageSegment.text('{message}')
... ).format_map({'user_id':123456, 'message':'hello world'}
...
Message(
MessageSegment(type='text', data={'text': '123456'}),
MessageSegment(type='face', data={'face': 233}),
MessageSegment(type='text', data={'text': 'hello world'})
)
```
```python title="使用消息段的拓展控制符"
>>> Message.template("{link:image}").format(link='https://...')
Message(MessageSegment(type='image', data={'file': 'https://...'}))
```

View File

@ -1,97 +0,0 @@
---
sidebar_position: 6
description: 协议适配器的功能与使用
options:
menu:
weight: 23
category: guide
---
# 使用适配器
:::tip 提示
如何**安装**协议适配器请参考[安装协议适配器](../start/install-adapter.mdx)。
:::
:::warning 提示
各适配器的具体配置与说明请跳转至 [商店 - 适配器](/store) 中各适配器右上角的主页或文档进行查看。
:::
## 协议适配器的功能
由于 NoneBot2 的跨平台特性,需要支持不同的协议,因此需要对特定的平台协议编写一个转换器。
协议适配器即是充当中间人的转换器,它将驱动器所收到的数据转换为可以被 NoneBot2 处理的事件 Event并将事件传递给 NoneBot2。
同时,协议适配器还会处理 API 调用,转换为可以被驱动器处理的数据发送出去。
## 注册协议适配器
NoneBot2 在默认情况下并不会加载任何协议适配器,需要自己手动注册。下方是个加载协议适配器的例子:
```python title=bot.py
import nonebot
from your_adapter_package import Adapter
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter(Adapter)
nonebot.run()
```
加载步骤如下:
### 导入协议适配器
首先从你需要的协议适配器的包中导入适配器类,通常为 `Adapter`
```python title=bot.py {2}
import nonebot
from your_adapter_package import Adapter
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter(Adapter)
nonebot.run()
```
### 获得驱动器实例
加载协议适配器需要通过驱动器来进行,因此,你需要先初始化 NoneBot2并获得驱动器实例。
```python title=bot.py {4,5}
import nonebot
from your_adapter_package import Adapter
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter(Adapter)
nonebot.run()
```
### 注册
获得驱动器实例后,你需要调用 `register_adapter` 方法来注册协议适配器。NoneBot 会通过协议适配器的 `get_name` 方法来获得协议适配器的名字。
:::warning 注意
你可以多次调用来注册多个协议适配器,但不能注册多次相同的协议适配器,发生这种情况时 NoneBot 会给出一个警告并忽略这次注册。
:::
```python title=bot.py {6}
import nonebot
from your_adapter_package import Adapter
nonebot.init()
driver = nonebot.get_driver()
driver.register_adapter(Adapter)
nonebot.run()
```
:::danger 警告
协议适配器需要在 NoneBot 启动前进行注册,即 `nonebot.run()` 之前,否则会出现未知的错误。
:::

View File

@ -1,50 +0,0 @@
{
"version-2.0.0-rc.1/tutorial": [
{
"type": "doc",
"id": "version-2.0.0-rc.1/index"
},
{
"type": "category",
"label": "开始",
"items": [
{
"type": "autogenerated",
"dirName": "start"
}
],
"collapsible": true,
"collapsed": true
},
{
"type": "category",
"label": "教程",
"items": [
{
"type": "autogenerated",
"dirName": "tutorial"
}
],
"collapsible": true,
"collapsed": true
},
{
"type": "category",
"label": "进阶",
"items": [
{
"type": "autogenerated",
"dirName": "advanced"
}
],
"collapsible": true,
"collapsed": true
}
],
"version-2.0.0-rc.1/api": [
{
"type": "autogenerated",
"dirName": "api"
}
]
}

View File

@ -1 +0,0 @@
["2.0.0-rc.1"]