mirror of
https://github.com/nonebot/nonebot2.git
synced 2025-02-20 17:46:51 +08:00
commit
1ee7c792e8
@ -1,41 +0,0 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.adapters 模块
|
||||
|
||||
|
||||
## _class_ `BaseBot`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
|
||||
## _class_ `BaseEvent`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
|
||||
### `_raw_event`
|
||||
|
||||
原始 event
|
||||
|
||||
|
||||
## _class_ `BaseMessageSegment`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
|
||||
## _class_ `BaseMessage`
|
||||
|
||||
基类:`list`, `abc.ABC`
|
||||
|
||||
|
||||
### `append(obj)`
|
||||
|
||||
Append object to the end of the list.
|
||||
|
||||
|
||||
### `extend(obj)`
|
||||
|
||||
Extend list by appending elements from the iterable.
|
@ -7,16 +7,10 @@
|
||||
* [nonebot](nonebot.html)
|
||||
|
||||
|
||||
* [nonebot.typing](typing.html)
|
||||
|
||||
|
||||
* [nonebot.config](config.html)
|
||||
|
||||
|
||||
* [nonebot.sched](sched.html)
|
||||
|
||||
|
||||
* [nonebot.log](log.html)
|
||||
* [nonebot.matcher](matcher.html)
|
||||
|
||||
|
||||
* [nonebot.rule](rule.html)
|
||||
@ -25,10 +19,28 @@
|
||||
* [nonebot.permission](permission.html)
|
||||
|
||||
|
||||
* [nonebot.sched](sched.html)
|
||||
|
||||
|
||||
* [nonebot.log](log.html)
|
||||
|
||||
|
||||
* [nonebot.utils](utils.html)
|
||||
|
||||
|
||||
* [nonebot.typing](typing.html)
|
||||
|
||||
|
||||
* [nonebot.exception](exception.html)
|
||||
|
||||
|
||||
* [nonebot.drivers](drivers/)
|
||||
|
||||
|
||||
* [nonebot.drivers.fastapi](drivers/fastapi.html)
|
||||
|
||||
|
||||
* [nonebot.adapters](adapters/)
|
||||
|
||||
|
||||
* [nonebot.adapters.cqhttp](adapters/cqhttp.html)
|
323
archive/2.0.0a3/api/adapters/README.md
Normal file
323
archive/2.0.0a3/api/adapters/README.md
Normal file
@ -0,0 +1,323 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.adapters 模块
|
||||
|
||||
## 协议适配基类
|
||||
|
||||
各协议请继承以下基类,并使用 `driver.register_adapter` 注册适配器
|
||||
|
||||
|
||||
## _class_ `BaseBot`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
Bot 基类。用于处理上报消息,并提供 API 调用接口。
|
||||
|
||||
|
||||
### _abstract_ `__init__(driver, connection_type, config, self_id, *, websocket=None)`
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `driver: Driver`: Driver 对象
|
||||
|
||||
|
||||
* `connection_type: str`: http 或者 websocket
|
||||
|
||||
|
||||
* `config: Config`: Config 对象
|
||||
|
||||
|
||||
* `self_id: str`: 机器人 ID
|
||||
|
||||
|
||||
* `websocket: Optional[WebSocket]`: Websocket 连接对象
|
||||
|
||||
|
||||
|
||||
### `driver`
|
||||
|
||||
Driver 对象
|
||||
|
||||
|
||||
### `connection_type`
|
||||
|
||||
连接类型
|
||||
|
||||
|
||||
### `config`
|
||||
|
||||
Config 配置对象
|
||||
|
||||
|
||||
### `self_id`
|
||||
|
||||
机器人 ID
|
||||
|
||||
|
||||
### `websocket`
|
||||
|
||||
Websocket 连接对象
|
||||
|
||||
|
||||
### _abstract property_ `type`
|
||||
|
||||
Adapter 类型
|
||||
|
||||
|
||||
### _abstract async_ `handle_message(message)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: dict`: 收到的上报消息
|
||||
|
||||
|
||||
|
||||
### _abstract async_ `call_api(api, **data)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `api: str`: API 名称
|
||||
|
||||
|
||||
* `**data`: API 数据
|
||||
|
||||
|
||||
|
||||
* **示例**
|
||||
|
||||
|
||||
```python
|
||||
await bot.call_api("send_msg", data={"message": "hello world"})
|
||||
await bot.send_msg(message="hello world")
|
||||
```
|
||||
|
||||
|
||||
### _abstract async_ `send(event, message, **kwargs)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
调用机器人基础发送消息接口
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `event: Event`: 上报事件
|
||||
|
||||
|
||||
* `message: Union[str, Message, MessageSegment]`: 要发送的消息
|
||||
|
||||
|
||||
* `**kwargs`
|
||||
|
||||
|
||||
|
||||
## _class_ `BaseEvent`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。
|
||||
|
||||
|
||||
### `__init__(raw_event)`
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `raw_event: dict`: 原始上报消息
|
||||
|
||||
|
||||
|
||||
### _property_ `raw_event`
|
||||
|
||||
原始上报消息
|
||||
|
||||
|
||||
### _abstract property_ `id`
|
||||
|
||||
事件 ID
|
||||
|
||||
|
||||
### _abstract property_ `name`
|
||||
|
||||
事件名称
|
||||
|
||||
|
||||
### _abstract property_ `self_id`
|
||||
|
||||
机器人 ID
|
||||
|
||||
|
||||
### _abstract property_ `time`
|
||||
|
||||
事件发生时间
|
||||
|
||||
|
||||
### _abstract property_ `type`
|
||||
|
||||
事件主类型
|
||||
|
||||
|
||||
### _abstract property_ `detail_type`
|
||||
|
||||
事件详细类型
|
||||
|
||||
|
||||
### _abstract property_ `sub_type`
|
||||
|
||||
事件子类型
|
||||
|
||||
|
||||
### _abstract property_ `user_id`
|
||||
|
||||
触发事件的主体 ID
|
||||
|
||||
|
||||
### _abstract property_ `group_id`
|
||||
|
||||
触发事件的主体群 ID
|
||||
|
||||
|
||||
### _abstract property_ `to_me`
|
||||
|
||||
事件是否为发送给机器人的消息
|
||||
|
||||
|
||||
### _abstract property_ `message`
|
||||
|
||||
消息内容
|
||||
|
||||
|
||||
### _abstract property_ `reply`
|
||||
|
||||
回复的消息
|
||||
|
||||
|
||||
### _abstract property_ `raw_message`
|
||||
|
||||
原始消息
|
||||
|
||||
|
||||
### _abstract property_ `plain_text`
|
||||
|
||||
纯文本消息
|
||||
|
||||
|
||||
### _abstract property_ `sender`
|
||||
|
||||
消息发送者信息
|
||||
|
||||
|
||||
## _class_ `BaseMessageSegment`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
消息段基类
|
||||
|
||||
|
||||
### `type`
|
||||
|
||||
|
||||
* 类型: `str`
|
||||
|
||||
|
||||
* 说明: 消息段类型
|
||||
|
||||
|
||||
### `data`
|
||||
|
||||
|
||||
* 类型: `Dict[str, Union[str, list]]`
|
||||
|
||||
|
||||
* 说明: 消息段数据
|
||||
|
||||
|
||||
## _class_ `BaseMessage`
|
||||
|
||||
基类:`list`, `abc.ABC`
|
||||
|
||||
消息数组
|
||||
|
||||
|
||||
### `__init__(message=None, *args, **kwargs)`
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: Union[str, dict, list, MessageSegment, Message]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### `append(obj)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
添加一个消息段到消息数组末尾
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `obj: Union[str, MessageSegment]`: 要添加的消息段
|
||||
|
||||
|
||||
|
||||
### `extend(obj)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
拼接一个消息数组或多个消息段到消息数组末尾
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `obj: Union[Message, Iterable[MessageSegment]]`: 要添加的消息数组
|
||||
|
||||
|
||||
|
||||
### `reduce()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
缩减消息数组,即拼接相邻纯文本消息段
|
||||
|
||||
|
||||
|
||||
### `extract_plain_text()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
提取消息内纯文本消息
|
@ -323,10 +323,10 @@ CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent)
|
||||
### _property_ `sub_type`
|
||||
|
||||
|
||||
* 类型: `str`
|
||||
* 类型: `Optional[str]`
|
||||
|
||||
|
||||
* 说明: 事件类型
|
||||
* 说明: 事件子类型
|
||||
|
||||
|
||||
### _property_ `user_id`
|
@ -194,10 +194,10 @@ SUPER_USERS=[12345789]
|
||||
### `nickname`
|
||||
|
||||
|
||||
* 类型: `Union[str, Set[str]]`
|
||||
* 类型: `Set[str]`
|
||||
|
||||
|
||||
* 默认值: `""`
|
||||
* 默认值: `set()`
|
||||
|
||||
|
||||
* 说明:
|
37
archive/2.0.0a3/api/drivers/README.md
Normal file
37
archive/2.0.0a3/api/drivers/README.md
Normal file
@ -0,0 +1,37 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.drivers 模块
|
||||
|
||||
## 后端驱动适配基类
|
||||
|
||||
各驱动请继承以下基类
|
||||
|
||||
|
||||
## _class_ `BaseDriver`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
Driver 基类。将后端框架封装,以满足适配器使用。
|
||||
|
||||
|
||||
### `_adapters`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Dict[str, Type[Bot]]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
已注册的适配器列表
|
||||
|
||||
|
||||
|
||||
### _abstract_ `__init__(env, config)`
|
||||
|
||||
Initialize self. See help(type(self)) for accurate signature.
|
16
archive/2.0.0a3/api/drivers/fastapi.md
Normal file
16
archive/2.0.0a3/api/drivers/fastapi.md
Normal file
@ -0,0 +1,16 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.drivers.fastapi 模块
|
||||
|
||||
|
||||
## _class_ `Driver`
|
||||
|
||||
基类:[`nonebot.drivers.BaseDriver`](#None)
|
||||
|
||||
|
||||
### `__init__(env, config)`
|
||||
|
||||
Initialize self. See help(type(self)) for accurate signature.
|
485
archive/2.0.0a3/api/matcher.md
Normal file
485
archive/2.0.0a3/api/matcher.md
Normal file
@ -0,0 +1,485 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.matcher 模块
|
||||
|
||||
## 事件响应器
|
||||
|
||||
该模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行 对话 。
|
||||
|
||||
|
||||
## `matchers`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Dict[int, List[Type[Matcher]]]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
用于存储当前所有的事件响应器
|
||||
|
||||
|
||||
|
||||
## _class_ `Matcher`
|
||||
|
||||
基类:`object`
|
||||
|
||||
事件响应器类
|
||||
|
||||
|
||||
### `module`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Optional[str]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器所在模块名称
|
||||
|
||||
|
||||
|
||||
### `type`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`str`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器类型
|
||||
|
||||
|
||||
|
||||
### `rule`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Rule`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器匹配规则
|
||||
|
||||
|
||||
|
||||
### `permission`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Permission`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器触发权限
|
||||
|
||||
|
||||
|
||||
### `priority`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`int`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器优先级
|
||||
|
||||
|
||||
|
||||
### `block`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`bool`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器是否阻止事件传播
|
||||
|
||||
|
||||
|
||||
### `temp`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`bool`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器是否为临时
|
||||
|
||||
|
||||
|
||||
### `expire_time`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Optional[datetime]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器过期时间点
|
||||
|
||||
|
||||
|
||||
### `_default_state`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`dict`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器默认状态
|
||||
|
||||
|
||||
|
||||
### `_default_parser`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Optional[ArgsParser]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器默认参数解析函数
|
||||
|
||||
|
||||
|
||||
### `__init__()`
|
||||
|
||||
实例化 Matcher 以便运行
|
||||
|
||||
|
||||
### `handlers`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`List[Handler]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器拥有的事件处理函数列表
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
创建一个新的事件响应器,并存储至 [matchers](#matchers)
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `type_: str`: 事件响应器类型,与 `event.type` 一致时触发,空字符串表示任意
|
||||
|
||||
|
||||
* `rule: Optional[Rule]`: 匹配规则
|
||||
|
||||
|
||||
* `permission: Optional[Permission]`: 权限
|
||||
|
||||
|
||||
* `handlers: Optional[List[Handler]]`: 事件处理函数列表
|
||||
|
||||
|
||||
* `temp: bool`: 是否为临时事件响应器,即触发一次后删除
|
||||
|
||||
|
||||
* `priority: int`: 响应优先级
|
||||
|
||||
|
||||
* `block: bool`: 是否阻止事件向更低优先级的响应器传播
|
||||
|
||||
|
||||
* `module: Optional[str]`: 事件响应器所在模块名称
|
||||
|
||||
|
||||
* `default_state: Optional[dict]`: 默认状态 `state`
|
||||
|
||||
|
||||
* `expire_time: Optional[datetime]`: 事件响应器最终有效时间点,过时即被删除
|
||||
|
||||
|
||||
|
||||
* **返回**
|
||||
|
||||
|
||||
* `Type[Matcher]`: 新的事件响应器类
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `check_perm(bot, event)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
检查是否满足触发权限
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `bot: Bot`: Bot 对象
|
||||
|
||||
|
||||
* `event: Event`: 上报事件
|
||||
|
||||
|
||||
|
||||
* **返回**
|
||||
|
||||
|
||||
* `bool`: 是否满足权限
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `check_rule(bot, event, state)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
检查是否满足匹配规则
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `bot: Bot`: Bot 对象
|
||||
|
||||
|
||||
* `event: Event`: 上报事件
|
||||
|
||||
|
||||
* `state: dict`: 当前状态
|
||||
|
||||
|
||||
|
||||
* **返回**
|
||||
|
||||
|
||||
* `bool`: 是否满足匹配规则
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `args_parser(func)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来更改当前事件响应器的默认参数解析函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `func: ArgsParser`: 参数解析函数
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `handle()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来向事件响应器直接添加一个处理函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* 无
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `receive()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* 无
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `got(key, prompt=None, args_parser=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来指示 NoneBot 当要获取的 `key` 不存在时接收用户新的一条消息并经过 `ArgsParser` 处理后再运行该函数,如果 `key` 已存在则直接继续运行
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `key: str`: 参数名
|
||||
|
||||
|
||||
* `prompt: Optional[Union[str, Message, MessageSegment]]`: 在参数不存在时向用户发送的消息
|
||||
|
||||
|
||||
* `args_parser: Optional[ArgsParser]`: 可选参数解析函数,空则使用默认解析函数
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `send(message)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `finish(message=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户并结束当前事件响应器
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `pause(prompt=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `reject(prompt=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后重新运行当前处理函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
## _class_ `MatcherGroup`
|
||||
|
||||
基类:`object`
|
||||
|
||||
事件响应器组合,统一管理。用法同 `Matcher`
|
||||
|
||||
|
||||
### `__init__(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
创建一个事件响应器组合,参数为默认值,与 `Matcher.new` 一致
|
||||
|
||||
|
||||
|
||||
### `matchers`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`List[Type[Matcher]]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
组内事件响应器列表
|
||||
|
||||
|
||||
|
||||
### `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
在组中创建一个新的事件响应器,参数留空则使用组合默认值
|
||||
|
||||
|
||||
:::danger 警告
|
||||
如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数
|
||||
:::
|
@ -5,6 +5,55 @@ sidebarDepth: 0
|
||||
|
||||
# NoneBot 模块
|
||||
|
||||
## 快捷导入
|
||||
|
||||
为方便使用,`nonebot` 模块从子模块导入了部分内容
|
||||
|
||||
|
||||
* `on_message` => `nonebot.plugin.on_message`
|
||||
|
||||
|
||||
* `on_notice` => `nonebot.plugin.on_notice`
|
||||
|
||||
|
||||
* `on_request` => `nonebot.plugin.on_request`
|
||||
|
||||
|
||||
* `on_metaevent` => `nonebot.plugin.on_metaevent`
|
||||
|
||||
|
||||
* `on_startswith` => `nonebot.plugin.on_startswith`
|
||||
|
||||
|
||||
* `on_endswith` => `nonebot.plugin.on_endswith`
|
||||
|
||||
|
||||
* `on_command` => `nonebot.plugin.on_command`
|
||||
|
||||
|
||||
* `on_regex` => `nonebot.plugin.on_regex`
|
||||
|
||||
|
||||
* `on_regex` => `nonebot.plugin.on_regex`
|
||||
|
||||
|
||||
* `on_regex` => `nonebot.plugin.on_regex`
|
||||
|
||||
|
||||
* `CommandGroup` => `nonebot.plugin.CommandGroup`
|
||||
|
||||
|
||||
* `load_plugin` => `nonebot.plugin.load_plugin`
|
||||
|
||||
|
||||
* `load_plugins` => `nonebot.plugin.load_plugins`
|
||||
|
||||
|
||||
* `load_builtin_plugins` => `nonebot.plugin.load_builtin_plugins`
|
||||
|
||||
|
||||
* `get_loaded_plugins` => `nonebot.plugin.get_loaded_plugins`
|
||||
|
||||
|
||||
## `get_driver()`
|
||||
|
@ -7,10 +7,10 @@ sidebarDepth: 0
|
||||
|
||||
## 规则
|
||||
|
||||
每个 `Matcher` 拥有一个 `Rule` ,其中是 **异步** `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。
|
||||
每个事件响应器 `Matcher` 拥有一个匹配规则 `Rule` ,其中是 **异步** `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。
|
||||
|
||||
:::tip 提示
|
||||
`RuleChecker` 既可以是 async function 也可以是 sync function
|
||||
`RuleChecker` 既可以是 async function 也可以是 sync function,但在最终会被 `nonebot.utils.run_sync` 转换为 async function
|
||||
:::
|
||||
|
||||
|
||||
@ -120,3 +120,83 @@ Rule(async_function, run_sync(sync_function))
|
||||
|
||||
|
||||
* `msg: str`: 消息结尾字符串
|
||||
|
||||
|
||||
|
||||
## `keyword(msg)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
匹配消息关键词
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `msg: str`: 关键词
|
||||
|
||||
|
||||
|
||||
## `command(command)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
命令形式匹配,根据配置里提供的 `command_start`, `command_sep` 判断消息是否为命令。
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `command: Tuples[str, ...]`: 命令内容
|
||||
|
||||
|
||||
|
||||
* **示例**
|
||||
|
||||
使用默认 `command_start`, `command_sep` 配置
|
||||
|
||||
命令 `("test",)` 可以匹配:`/test` 开头的消息
|
||||
命令 `("test", "sub")` 可以匹配”`/test.sub` 开头的消息
|
||||
|
||||
|
||||
:::tip 提示
|
||||
命令内容与后续消息间无需空格!
|
||||
:::
|
||||
|
||||
|
||||
## `regex(regex, flags=0)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
根据正则表达式进行匹配
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `regex: str`: 正则表达式
|
||||
|
||||
|
||||
* `flags: Union[int, re.RegexFlag]`: 正则标志
|
||||
|
||||
|
||||
|
||||
## `to_me()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
通过 `event.to_me` 判断消息是否是发送给机器人
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* 无
|
@ -20,11 +20,7 @@ NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人
|
||||
|
||||
## 它如何工作?
|
||||
|
||||
NoneBot 的运行离不开 酷 Q 和 CQHTTP 插件。酷 Q 扮演着「无头 QQ 客户端」的角色,它进行实际的消息、通知、请求的接收和发送,当 酷 Q 收到消息时,它将这个消息包装为一个事件(通知和请求同理),并通过它自己的插件机制将事件传送给 CQHTTP 插件,后者再根据其配置中的 `post_url` 或 `ws_reverse_url` 等项来将事件发送至 NoneBot。
|
||||
|
||||
在 NoneBot 收到事件前,它底层的 aiocqhttp 实际已经先看到了事件,aiocqhttp 根据事件的类型信息,通知到 NoneBot 的相应函数。特别地,对于消息类型的事件,还将消息内容转换成了 `aiocqhttp.message.Message` 类型,以便处理。
|
||||
|
||||
NoneBot 的事件处理函数收到通知后,对于不同类型的事件,再做相应的预处理和解析,然后调用对应的插件,并向其提供适合此类事件的会话(Session)对象。NoneBot 插件的编写者要做的,就是利用 Session 对象中提供的数据,在插件的处理函数中实现所需的功能。
|
||||
~~未填坑~~
|
||||
|
||||
## 特色
|
||||
|
@ -47,21 +47,13 @@
|
||||
"title": "nonebot 模块",
|
||||
"path": "nonebot"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.typing 模块",
|
||||
"path": "typing"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.config 模块",
|
||||
"path": "config"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.sched 模块",
|
||||
"path": "sched"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.log 模块",
|
||||
"path": "log"
|
||||
"title": "nonebot.matcher 模块",
|
||||
"path": "matcher"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.rule 模块",
|
||||
@ -71,14 +63,34 @@
|
||||
"title": "nonebot.permission 模块",
|
||||
"path": "permission"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.sched 模块",
|
||||
"path": "sched"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.log 模块",
|
||||
"path": "log"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.utils 模块",
|
||||
"path": "utils"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.typing 模块",
|
||||
"path": "typing"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.exception 模块",
|
||||
"path": "exception"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.drivers 模块",
|
||||
"path": "drivers/"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.drivers.fastapi 模块",
|
||||
"path": "drivers/fastapi"
|
||||
},
|
||||
{
|
||||
"title": "nonebot.adapters 模块",
|
||||
"path": "adapters/"
|
@ -88,21 +88,13 @@ module.exports = context => ({
|
||||
title: "nonebot 模块",
|
||||
path: "nonebot"
|
||||
},
|
||||
{
|
||||
title: "nonebot.typing 模块",
|
||||
path: "typing"
|
||||
},
|
||||
{
|
||||
title: "nonebot.config 模块",
|
||||
path: "config"
|
||||
},
|
||||
{
|
||||
title: "nonebot.sched 模块",
|
||||
path: "sched"
|
||||
},
|
||||
{
|
||||
title: "nonebot.log 模块",
|
||||
path: "log"
|
||||
title: "nonebot.matcher 模块",
|
||||
path: "matcher"
|
||||
},
|
||||
{
|
||||
title: "nonebot.rule 模块",
|
||||
@ -112,14 +104,34 @@ module.exports = context => ({
|
||||
title: "nonebot.permission 模块",
|
||||
path: "permission"
|
||||
},
|
||||
{
|
||||
title: "nonebot.sched 模块",
|
||||
path: "sched"
|
||||
},
|
||||
{
|
||||
title: "nonebot.log 模块",
|
||||
path: "log"
|
||||
},
|
||||
{
|
||||
title: "nonebot.utils 模块",
|
||||
path: "utils"
|
||||
},
|
||||
{
|
||||
title: "nonebot.typing 模块",
|
||||
path: "typing"
|
||||
},
|
||||
{
|
||||
title: "nonebot.exception 模块",
|
||||
path: "exception"
|
||||
},
|
||||
{
|
||||
title: "nonebot.drivers 模块",
|
||||
path: "drivers/"
|
||||
},
|
||||
{
|
||||
title: "nonebot.drivers.fastapi 模块",
|
||||
path: "drivers/fastapi"
|
||||
},
|
||||
{
|
||||
title: "nonebot.adapters 模块",
|
||||
path: "adapters/"
|
||||
|
@ -1,3 +1,3 @@
|
||||
[
|
||||
"2.0.0a2"
|
||||
"2.0.0a3"
|
||||
]
|
@ -7,16 +7,10 @@
|
||||
* [nonebot](nonebot.html)
|
||||
|
||||
|
||||
* [nonebot.typing](typing.html)
|
||||
|
||||
|
||||
* [nonebot.config](config.html)
|
||||
|
||||
|
||||
* [nonebot.sched](sched.html)
|
||||
|
||||
|
||||
* [nonebot.log](log.html)
|
||||
* [nonebot.matcher](matcher.html)
|
||||
|
||||
|
||||
* [nonebot.rule](rule.html)
|
||||
@ -25,10 +19,28 @@
|
||||
* [nonebot.permission](permission.html)
|
||||
|
||||
|
||||
* [nonebot.sched](sched.html)
|
||||
|
||||
|
||||
* [nonebot.log](log.html)
|
||||
|
||||
|
||||
* [nonebot.utils](utils.html)
|
||||
|
||||
|
||||
* [nonebot.typing](typing.html)
|
||||
|
||||
|
||||
* [nonebot.exception](exception.html)
|
||||
|
||||
|
||||
* [nonebot.drivers](drivers/)
|
||||
|
||||
|
||||
* [nonebot.drivers.fastapi](drivers/fastapi.html)
|
||||
|
||||
|
||||
* [nonebot.adapters](adapters/)
|
||||
|
||||
|
||||
* [nonebot.adapters.cqhttp](adapters/cqhttp.html)
|
||||
|
@ -5,37 +5,319 @@ sidebarDepth: 0
|
||||
|
||||
# NoneBot.adapters 模块
|
||||
|
||||
## 协议适配基类
|
||||
|
||||
各协议请继承以下基类,并使用 `driver.register_adapter` 注册适配器
|
||||
|
||||
|
||||
## _class_ `BaseBot`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
Bot 基类。用于处理上报消息,并提供 API 调用接口。
|
||||
|
||||
|
||||
### _abstract_ `__init__(driver, connection_type, config, self_id, *, websocket=None)`
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `driver: Driver`: Driver 对象
|
||||
|
||||
|
||||
* `connection_type: str`: http 或者 websocket
|
||||
|
||||
|
||||
* `config: Config`: Config 对象
|
||||
|
||||
|
||||
* `self_id: str`: 机器人 ID
|
||||
|
||||
|
||||
* `websocket: Optional[WebSocket]`: Websocket 连接对象
|
||||
|
||||
|
||||
|
||||
### `driver`
|
||||
|
||||
Driver 对象
|
||||
|
||||
|
||||
### `connection_type`
|
||||
|
||||
连接类型
|
||||
|
||||
|
||||
### `config`
|
||||
|
||||
Config 配置对象
|
||||
|
||||
|
||||
### `self_id`
|
||||
|
||||
机器人 ID
|
||||
|
||||
|
||||
### `websocket`
|
||||
|
||||
Websocket 连接对象
|
||||
|
||||
|
||||
### _abstract property_ `type`
|
||||
|
||||
Adapter 类型
|
||||
|
||||
|
||||
### _abstract async_ `handle_message(message)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: dict`: 收到的上报消息
|
||||
|
||||
|
||||
|
||||
### _abstract async_ `call_api(api, **data)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `api: str`: API 名称
|
||||
|
||||
|
||||
* `**data`: API 数据
|
||||
|
||||
|
||||
|
||||
* **示例**
|
||||
|
||||
|
||||
```python
|
||||
await bot.call_api("send_msg", data={"message": "hello world"})
|
||||
await bot.send_msg(message="hello world")
|
||||
```
|
||||
|
||||
|
||||
### _abstract async_ `send(event, message, **kwargs)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
调用机器人基础发送消息接口
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `event: Event`: 上报事件
|
||||
|
||||
|
||||
* `message: Union[str, Message, MessageSegment]`: 要发送的消息
|
||||
|
||||
|
||||
* `**kwargs`
|
||||
|
||||
|
||||
|
||||
## _class_ `BaseEvent`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。
|
||||
|
||||
### `_raw_event`
|
||||
|
||||
原始 event
|
||||
### `__init__(raw_event)`
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `raw_event: dict`: 原始上报消息
|
||||
|
||||
|
||||
|
||||
### _property_ `raw_event`
|
||||
|
||||
原始上报消息
|
||||
|
||||
|
||||
### _abstract property_ `id`
|
||||
|
||||
事件 ID
|
||||
|
||||
|
||||
### _abstract property_ `name`
|
||||
|
||||
事件名称
|
||||
|
||||
|
||||
### _abstract property_ `self_id`
|
||||
|
||||
机器人 ID
|
||||
|
||||
|
||||
### _abstract property_ `time`
|
||||
|
||||
事件发生时间
|
||||
|
||||
|
||||
### _abstract property_ `type`
|
||||
|
||||
事件主类型
|
||||
|
||||
|
||||
### _abstract property_ `detail_type`
|
||||
|
||||
事件详细类型
|
||||
|
||||
|
||||
### _abstract property_ `sub_type`
|
||||
|
||||
事件子类型
|
||||
|
||||
|
||||
### _abstract property_ `user_id`
|
||||
|
||||
触发事件的主体 ID
|
||||
|
||||
|
||||
### _abstract property_ `group_id`
|
||||
|
||||
触发事件的主体群 ID
|
||||
|
||||
|
||||
### _abstract property_ `to_me`
|
||||
|
||||
事件是否为发送给机器人的消息
|
||||
|
||||
|
||||
### _abstract property_ `message`
|
||||
|
||||
消息内容
|
||||
|
||||
|
||||
### _abstract property_ `reply`
|
||||
|
||||
回复的消息
|
||||
|
||||
|
||||
### _abstract property_ `raw_message`
|
||||
|
||||
原始消息
|
||||
|
||||
|
||||
### _abstract property_ `plain_text`
|
||||
|
||||
纯文本消息
|
||||
|
||||
|
||||
### _abstract property_ `sender`
|
||||
|
||||
消息发送者信息
|
||||
|
||||
|
||||
## _class_ `BaseMessageSegment`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
消息段基类
|
||||
|
||||
|
||||
### `type`
|
||||
|
||||
|
||||
* 类型: `str`
|
||||
|
||||
|
||||
* 说明: 消息段类型
|
||||
|
||||
|
||||
### `data`
|
||||
|
||||
|
||||
* 类型: `Dict[str, Union[str, list]]`
|
||||
|
||||
|
||||
* 说明: 消息段数据
|
||||
|
||||
|
||||
## _class_ `BaseMessage`
|
||||
|
||||
基类:`list`, `abc.ABC`
|
||||
|
||||
消息数组
|
||||
|
||||
|
||||
### `__init__(message=None, *args, **kwargs)`
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: Union[str, dict, list, MessageSegment, Message]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### `append(obj)`
|
||||
|
||||
Append object to the end of the list.
|
||||
|
||||
* **说明**
|
||||
|
||||
添加一个消息段到消息数组末尾
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `obj: Union[str, MessageSegment]`: 要添加的消息段
|
||||
|
||||
|
||||
|
||||
### `extend(obj)`
|
||||
|
||||
Extend list by appending elements from the iterable.
|
||||
|
||||
* **说明**
|
||||
|
||||
拼接一个消息数组或多个消息段到消息数组末尾
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `obj: Union[Message, Iterable[MessageSegment]]`: 要添加的消息数组
|
||||
|
||||
|
||||
|
||||
### `reduce()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
缩减消息数组,即拼接相邻纯文本消息段
|
||||
|
||||
|
||||
|
||||
### `extract_plain_text()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
提取消息内纯文本消息
|
||||
|
@ -323,10 +323,10 @@ CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent)
|
||||
### _property_ `sub_type`
|
||||
|
||||
|
||||
* 类型: `str`
|
||||
* 类型: `Optional[str]`
|
||||
|
||||
|
||||
* 说明: 事件类型
|
||||
* 说明: 事件子类型
|
||||
|
||||
|
||||
### _property_ `user_id`
|
||||
|
@ -194,10 +194,10 @@ SUPER_USERS=[12345789]
|
||||
### `nickname`
|
||||
|
||||
|
||||
* 类型: `Union[str, Set[str]]`
|
||||
* 类型: `Set[str]`
|
||||
|
||||
|
||||
* 默认值: `""`
|
||||
* 默认值: `set()`
|
||||
|
||||
|
||||
* 说明:
|
||||
|
37
docs/api/drivers/README.md
Normal file
37
docs/api/drivers/README.md
Normal file
@ -0,0 +1,37 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.drivers 模块
|
||||
|
||||
## 后端驱动适配基类
|
||||
|
||||
各驱动请继承以下基类
|
||||
|
||||
|
||||
## _class_ `BaseDriver`
|
||||
|
||||
基类:`abc.ABC`
|
||||
|
||||
Driver 基类。将后端框架封装,以满足适配器使用。
|
||||
|
||||
|
||||
### `_adapters`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Dict[str, Type[Bot]]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
已注册的适配器列表
|
||||
|
||||
|
||||
|
||||
### _abstract_ `__init__(env, config)`
|
||||
|
||||
Initialize self. See help(type(self)) for accurate signature.
|
16
docs/api/drivers/fastapi.md
Normal file
16
docs/api/drivers/fastapi.md
Normal file
@ -0,0 +1,16 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.drivers.fastapi 模块
|
||||
|
||||
|
||||
## _class_ `Driver`
|
||||
|
||||
基类:[`nonebot.drivers.BaseDriver`](#None)
|
||||
|
||||
|
||||
### `__init__(env, config)`
|
||||
|
||||
Initialize self. See help(type(self)) for accurate signature.
|
485
docs/api/matcher.md
Normal file
485
docs/api/matcher.md
Normal file
@ -0,0 +1,485 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
# NoneBot.matcher 模块
|
||||
|
||||
## 事件响应器
|
||||
|
||||
该模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行 对话 。
|
||||
|
||||
|
||||
## `matchers`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Dict[int, List[Type[Matcher]]]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
用于存储当前所有的事件响应器
|
||||
|
||||
|
||||
|
||||
## _class_ `Matcher`
|
||||
|
||||
基类:`object`
|
||||
|
||||
事件响应器类
|
||||
|
||||
|
||||
### `module`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Optional[str]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器所在模块名称
|
||||
|
||||
|
||||
|
||||
### `type`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`str`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器类型
|
||||
|
||||
|
||||
|
||||
### `rule`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Rule`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器匹配规则
|
||||
|
||||
|
||||
|
||||
### `permission`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Permission`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器触发权限
|
||||
|
||||
|
||||
|
||||
### `priority`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`int`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器优先级
|
||||
|
||||
|
||||
|
||||
### `block`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`bool`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器是否阻止事件传播
|
||||
|
||||
|
||||
|
||||
### `temp`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`bool`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器是否为临时
|
||||
|
||||
|
||||
|
||||
### `expire_time`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Optional[datetime]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器过期时间点
|
||||
|
||||
|
||||
|
||||
### `_default_state`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`dict`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器默认状态
|
||||
|
||||
|
||||
|
||||
### `_default_parser`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`Optional[ArgsParser]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器默认参数解析函数
|
||||
|
||||
|
||||
|
||||
### `__init__()`
|
||||
|
||||
实例化 Matcher 以便运行
|
||||
|
||||
|
||||
### `handlers`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`List[Handler]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
事件响应器拥有的事件处理函数列表
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
创建一个新的事件响应器,并存储至 [matchers](#matchers)
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `type_: str`: 事件响应器类型,与 `event.type` 一致时触发,空字符串表示任意
|
||||
|
||||
|
||||
* `rule: Optional[Rule]`: 匹配规则
|
||||
|
||||
|
||||
* `permission: Optional[Permission]`: 权限
|
||||
|
||||
|
||||
* `handlers: Optional[List[Handler]]`: 事件处理函数列表
|
||||
|
||||
|
||||
* `temp: bool`: 是否为临时事件响应器,即触发一次后删除
|
||||
|
||||
|
||||
* `priority: int`: 响应优先级
|
||||
|
||||
|
||||
* `block: bool`: 是否阻止事件向更低优先级的响应器传播
|
||||
|
||||
|
||||
* `module: Optional[str]`: 事件响应器所在模块名称
|
||||
|
||||
|
||||
* `default_state: Optional[dict]`: 默认状态 `state`
|
||||
|
||||
|
||||
* `expire_time: Optional[datetime]`: 事件响应器最终有效时间点,过时即被删除
|
||||
|
||||
|
||||
|
||||
* **返回**
|
||||
|
||||
|
||||
* `Type[Matcher]`: 新的事件响应器类
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `check_perm(bot, event)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
检查是否满足触发权限
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `bot: Bot`: Bot 对象
|
||||
|
||||
|
||||
* `event: Event`: 上报事件
|
||||
|
||||
|
||||
|
||||
* **返回**
|
||||
|
||||
|
||||
* `bool`: 是否满足权限
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `check_rule(bot, event, state)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
检查是否满足匹配规则
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `bot: Bot`: Bot 对象
|
||||
|
||||
|
||||
* `event: Event`: 上报事件
|
||||
|
||||
|
||||
* `state: dict`: 当前状态
|
||||
|
||||
|
||||
|
||||
* **返回**
|
||||
|
||||
|
||||
* `bool`: 是否满足匹配规则
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `args_parser(func)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来更改当前事件响应器的默认参数解析函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `func: ArgsParser`: 参数解析函数
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `handle()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来向事件响应器直接添加一个处理函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* 无
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `receive()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* 无
|
||||
|
||||
|
||||
|
||||
### _classmethod_ `got(key, prompt=None, args_parser=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
装饰一个函数来指示 NoneBot 当要获取的 `key` 不存在时接收用户新的一条消息并经过 `ArgsParser` 处理后再运行该函数,如果 `key` 已存在则直接继续运行
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `key: str`: 参数名
|
||||
|
||||
|
||||
* `prompt: Optional[Union[str, Message, MessageSegment]]`: 在参数不存在时向用户发送的消息
|
||||
|
||||
|
||||
* `args_parser: Optional[ArgsParser]`: 可选参数解析函数,空则使用默认解析函数
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `send(message)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `finish(message=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户并结束当前事件响应器
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `message: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `pause(prompt=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
### _async classmethod_ `reject(prompt=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后重新运行当前处理函数
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `prompt: Union[str, Message, MessageSegment]`: 消息内容
|
||||
|
||||
|
||||
|
||||
## _class_ `MatcherGroup`
|
||||
|
||||
基类:`object`
|
||||
|
||||
事件响应器组合,统一管理。用法同 `Matcher`
|
||||
|
||||
|
||||
### `__init__(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
创建一个事件响应器组合,参数为默认值,与 `Matcher.new` 一致
|
||||
|
||||
|
||||
|
||||
### `matchers`
|
||||
|
||||
|
||||
* **类型**
|
||||
|
||||
`List[Type[Matcher]]`
|
||||
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
组内事件响应器列表
|
||||
|
||||
|
||||
|
||||
### `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
在组中创建一个新的事件响应器,参数留空则使用组合默认值
|
||||
|
||||
|
||||
:::danger 警告
|
||||
如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数
|
||||
:::
|
@ -5,6 +5,55 @@ sidebarDepth: 0
|
||||
|
||||
# NoneBot 模块
|
||||
|
||||
## 快捷导入
|
||||
|
||||
为方便使用,`nonebot` 模块从子模块导入了部分内容
|
||||
|
||||
|
||||
* `on_message` => `nonebot.plugin.on_message`
|
||||
|
||||
|
||||
* `on_notice` => `nonebot.plugin.on_notice`
|
||||
|
||||
|
||||
* `on_request` => `nonebot.plugin.on_request`
|
||||
|
||||
|
||||
* `on_metaevent` => `nonebot.plugin.on_metaevent`
|
||||
|
||||
|
||||
* `on_startswith` => `nonebot.plugin.on_startswith`
|
||||
|
||||
|
||||
* `on_endswith` => `nonebot.plugin.on_endswith`
|
||||
|
||||
|
||||
* `on_command` => `nonebot.plugin.on_command`
|
||||
|
||||
|
||||
* `on_regex` => `nonebot.plugin.on_regex`
|
||||
|
||||
|
||||
* `on_regex` => `nonebot.plugin.on_regex`
|
||||
|
||||
|
||||
* `on_regex` => `nonebot.plugin.on_regex`
|
||||
|
||||
|
||||
* `CommandGroup` => `nonebot.plugin.CommandGroup`
|
||||
|
||||
|
||||
* `load_plugin` => `nonebot.plugin.load_plugin`
|
||||
|
||||
|
||||
* `load_plugins` => `nonebot.plugin.load_plugins`
|
||||
|
||||
|
||||
* `load_builtin_plugins` => `nonebot.plugin.load_builtin_plugins`
|
||||
|
||||
|
||||
* `get_loaded_plugins` => `nonebot.plugin.get_loaded_plugins`
|
||||
|
||||
|
||||
## `get_driver()`
|
||||
|
||||
|
@ -7,10 +7,10 @@ sidebarDepth: 0
|
||||
|
||||
## 规则
|
||||
|
||||
每个 `Matcher` 拥有一个 `Rule` ,其中是 **异步** `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。
|
||||
每个事件响应器 `Matcher` 拥有一个匹配规则 `Rule` ,其中是 **异步** `RuleChecker` 的集合,只有当所有 `RuleChecker` 检查结果为 `True` 时继续运行。
|
||||
|
||||
:::tip 提示
|
||||
`RuleChecker` 既可以是 async function 也可以是 sync function
|
||||
`RuleChecker` 既可以是 async function 也可以是 sync function,但在最终会被 `nonebot.utils.run_sync` 转换为 async function
|
||||
:::
|
||||
|
||||
|
||||
@ -120,3 +120,83 @@ Rule(async_function, run_sync(sync_function))
|
||||
|
||||
|
||||
* `msg: str`: 消息结尾字符串
|
||||
|
||||
|
||||
|
||||
## `keyword(msg)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
匹配消息关键词
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `msg: str`: 关键词
|
||||
|
||||
|
||||
|
||||
## `command(command)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
命令形式匹配,根据配置里提供的 `command_start`, `command_sep` 判断消息是否为命令。
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `command: Tuples[str, ...]`: 命令内容
|
||||
|
||||
|
||||
|
||||
* **示例**
|
||||
|
||||
使用默认 `command_start`, `command_sep` 配置
|
||||
|
||||
命令 `("test",)` 可以匹配:`/test` 开头的消息
|
||||
命令 `("test", "sub")` 可以匹配”`/test.sub` 开头的消息
|
||||
|
||||
|
||||
:::tip 提示
|
||||
命令内容与后续消息间无需空格!
|
||||
:::
|
||||
|
||||
|
||||
## `regex(regex, flags=0)`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
根据正则表达式进行匹配
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* `regex: str`: 正则表达式
|
||||
|
||||
|
||||
* `flags: Union[int, re.RegexFlag]`: 正则标志
|
||||
|
||||
|
||||
|
||||
## `to_me()`
|
||||
|
||||
|
||||
* **说明**
|
||||
|
||||
通过 `event.to_me` 判断消息是否是发送给机器人
|
||||
|
||||
|
||||
|
||||
* **参数**
|
||||
|
||||
|
||||
* 无
|
||||
|
@ -20,11 +20,7 @@ NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人
|
||||
|
||||
## 它如何工作?
|
||||
|
||||
NoneBot 的运行离不开 酷 Q 和 CQHTTP 插件。酷 Q 扮演着「无头 QQ 客户端」的角色,它进行实际的消息、通知、请求的接收和发送,当 酷 Q 收到消息时,它将这个消息包装为一个事件(通知和请求同理),并通过它自己的插件机制将事件传送给 CQHTTP 插件,后者再根据其配置中的 `post_url` 或 `ws_reverse_url` 等项来将事件发送至 NoneBot。
|
||||
|
||||
在 NoneBot 收到事件前,它底层的 aiocqhttp 实际已经先看到了事件,aiocqhttp 根据事件的类型信息,通知到 NoneBot 的相应函数。特别地,对于消息类型的事件,还将消息内容转换成了 `aiocqhttp.message.Message` 类型,以便处理。
|
||||
|
||||
NoneBot 的事件处理函数收到通知后,对于不同类型的事件,再做相应的预处理和解析,然后调用对应的插件,并向其提供适合此类事件的会话(Session)对象。NoneBot 插件的编写者要做的,就是利用 Session 对象中提供的数据,在插件的处理函数中实现所需的功能。
|
||||
~~未填坑~~
|
||||
|
||||
## 特色
|
||||
|
||||
|
@ -3,12 +3,16 @@ NoneBot Api Reference
|
||||
|
||||
:模块索引:
|
||||
- `nonebot <nonebot.html>`_
|
||||
- `nonebot.typing <typing.html>`_
|
||||
- `nonebot.config <config.html>`_
|
||||
- `nonebot.sched <sched.html>`_
|
||||
- `nonebot.log <log.html>`_
|
||||
- `nonebot.matcher <matcher.html>`_
|
||||
- `nonebot.rule <rule.html>`_
|
||||
- `nonebot.permission <permission.html>`_
|
||||
- `nonebot.sched <sched.html>`_
|
||||
- `nonebot.log <log.html>`_
|
||||
- `nonebot.utils <utils.html>`_
|
||||
- `nonebot.typing <typing.html>`_
|
||||
- `nonebot.exception <exception.html>`_
|
||||
- `nonebot.drivers <drivers/>`_
|
||||
- `nonebot.drivers.fastapi <drivers/fastapi.html>`_
|
||||
- `nonebot.adapters <adapters/>`_
|
||||
- `nonebot.adapters.cqhttp <adapters/cqhttp.html>`_
|
||||
|
@ -4,9 +4,10 @@ sidebarDepth: 0
|
||||
---
|
||||
|
||||
NoneBot.adapters 模块
|
||||
=================
|
||||
=====================
|
||||
|
||||
.. automodule:: nonebot.adapters
|
||||
:members:
|
||||
:private-members:
|
||||
:special-members: __init__
|
||||
:show-inheritance:
|
||||
|
@ -4,7 +4,7 @@ sidebarDepth: 0
|
||||
---
|
||||
|
||||
NoneBot.adapters.cqhttp 模块
|
||||
=================
|
||||
============================
|
||||
|
||||
.. automodule:: nonebot.adapters.cqhttp
|
||||
:members:
|
||||
|
13
docs_build/drivers/README.rst
Normal file
13
docs_build/drivers/README.rst
Normal file
@ -0,0 +1,13 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
NoneBot.drivers 模块
|
||||
=====================
|
||||
|
||||
.. automodule:: nonebot.drivers
|
||||
:members:
|
||||
:private-members:
|
||||
:special-members: __init__
|
||||
:show-inheritance:
|
13
docs_build/drivers/fastapi.rst
Normal file
13
docs_build/drivers/fastapi.rst
Normal file
@ -0,0 +1,13 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
NoneBot.drivers.fastapi 模块
|
||||
=====================
|
||||
|
||||
.. automodule:: nonebot.drivers.fastapi
|
||||
:members:
|
||||
:private-members:
|
||||
:special-members: __init__
|
||||
:show-inheritance:
|
13
docs_build/matcher.rst
Normal file
13
docs_build/matcher.rst
Normal file
@ -0,0 +1,13 @@
|
||||
---
|
||||
contentSidebar: true
|
||||
sidebarDepth: 0
|
||||
---
|
||||
|
||||
NoneBot.matcher 模块
|
||||
====================
|
||||
|
||||
.. automodule:: nonebot.matcher
|
||||
:members:
|
||||
:private-members:
|
||||
:special-members: __init__
|
||||
:show-inheritance:
|
@ -4,7 +4,7 @@ sidebarDepth: 0
|
||||
---
|
||||
|
||||
NoneBot.permission 模块
|
||||
====================
|
||||
=======================
|
||||
|
||||
.. automodule:: nonebot.permission
|
||||
:members:
|
||||
|
@ -1,5 +1,27 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
快捷导入
|
||||
========
|
||||
|
||||
为方便使用,``nonebot`` 模块从子模块导入了部分内容
|
||||
|
||||
- ``on_message`` => ``nonebot.plugin.on_message``
|
||||
- ``on_notice`` => ``nonebot.plugin.on_notice``
|
||||
- ``on_request`` => ``nonebot.plugin.on_request``
|
||||
- ``on_metaevent`` => ``nonebot.plugin.on_metaevent``
|
||||
- ``on_startswith`` => ``nonebot.plugin.on_startswith``
|
||||
- ``on_endswith`` => ``nonebot.plugin.on_endswith``
|
||||
- ``on_command`` => ``nonebot.plugin.on_command``
|
||||
- ``on_regex`` => ``nonebot.plugin.on_regex``
|
||||
- ``on_regex`` => ``nonebot.plugin.on_regex``
|
||||
- ``on_regex`` => ``nonebot.plugin.on_regex``
|
||||
- ``CommandGroup`` => ``nonebot.plugin.CommandGroup``
|
||||
- ``load_plugin`` => ``nonebot.plugin.load_plugin``
|
||||
- ``load_plugins`` => ``nonebot.plugin.load_plugins``
|
||||
- ``load_builtin_plugins`` => ``nonebot.plugin.load_builtin_plugins``
|
||||
- ``get_loaded_plugins`` => ``nonebot.plugin.get_loaded_plugins``
|
||||
"""
|
||||
|
||||
import importlib
|
||||
from nonebot.typing import Bot, Dict, Type, Union, Driver, Optional, NoReturn
|
||||
|
@ -1,5 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
协议适配基类
|
||||
============
|
||||
|
||||
各协议请继承以下基类,并使用 ``driver.register_adapter`` 注册适配器
|
||||
"""
|
||||
|
||||
import abc
|
||||
from functools import reduce, partial
|
||||
@ -11,6 +17,9 @@ from nonebot.typing import Any, Dict, Union, Optional, Callable, Iterable, Await
|
||||
|
||||
|
||||
class BaseBot(abc.ABC):
|
||||
"""
|
||||
Bot 基类。用于处理上报消息,并提供 API 调用接口。
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def __init__(self,
|
||||
@ -19,12 +28,25 @@ class BaseBot(abc.ABC):
|
||||
config: Config,
|
||||
self_id: str,
|
||||
*,
|
||||
websocket: WebSocket = None):
|
||||
websocket: Optional[WebSocket] = None):
|
||||
"""
|
||||
:参数:
|
||||
* ``driver: Driver``: Driver 对象
|
||||
* ``connection_type: str``: http 或者 websocket
|
||||
* ``config: Config``: Config 对象
|
||||
* ``self_id: str``: 机器人 ID
|
||||
* ``websocket: Optional[WebSocket]``: Websocket 连接对象
|
||||
"""
|
||||
self.driver = driver
|
||||
"""Driver 对象"""
|
||||
self.connection_type = connection_type
|
||||
"""连接类型"""
|
||||
self.config = config
|
||||
"""Config 配置对象"""
|
||||
self.self_id = self_id
|
||||
"""机器人 ID"""
|
||||
self.websocket = websocket
|
||||
"""Websocket 连接对象"""
|
||||
|
||||
def __getattr__(self, name: str) -> Callable[..., Awaitable[Any]]:
|
||||
return partial(self.call_api, name)
|
||||
@ -32,60 +54,99 @@ class BaseBot(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def type(self) -> str:
|
||||
"""Adapter 类型"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
async def handle_message(self, message: dict):
|
||||
"""
|
||||
:说明:
|
||||
处理上报消息的函数,转换为 ``Event`` 事件后调用 ``nonebot.message.handle_event`` 进一步处理事件。
|
||||
:参数:
|
||||
* ``message: dict``: 收到的上报消息
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
async def call_api(self, api: str, data: dict):
|
||||
async def call_api(self, api: str, **data):
|
||||
"""
|
||||
:说明:
|
||||
调用机器人 API 接口,可以通过该函数或直接通过 bot 属性进行调用
|
||||
:参数:
|
||||
* ``api: str``: API 名称
|
||||
* ``**data``: API 数据
|
||||
:示例:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
await bot.call_api("send_msg", data={"message": "hello world"})
|
||||
await bot.send_msg(message="hello world")
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
@abc.abstractmethod
|
||||
async def send(self, *args, **kwargs):
|
||||
async def send(self, event: "BaseEvent",
|
||||
message: Union[str, "BaseMessage",
|
||||
"BaseMessageSegment"], **kwargs):
|
||||
"""
|
||||
:说明:
|
||||
调用机器人基础发送消息接口
|
||||
:参数:
|
||||
* ``event: Event``: 上报事件
|
||||
* ``message: Union[str, Message, MessageSegment]``: 要发送的消息
|
||||
* ``**kwargs``
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
# TODO: improve event
|
||||
class BaseEvent(abc.ABC):
|
||||
"""
|
||||
Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。
|
||||
"""
|
||||
|
||||
def __init__(self, raw_event: dict):
|
||||
"""
|
||||
:参数:
|
||||
* ``raw_event: dict``: 原始上报消息
|
||||
"""
|
||||
self._raw_event = raw_event
|
||||
"""
|
||||
原始 event
|
||||
"""
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Event {self.self_id}: {self.name} {self.time}>"
|
||||
|
||||
@property
|
||||
def raw_event(self) -> dict:
|
||||
"""原始上报消息"""
|
||||
return self._raw_event
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def id(self) -> int:
|
||||
"""事件 ID"""
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def name(self) -> str:
|
||||
"""事件名称"""
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def self_id(self) -> str:
|
||||
"""机器人 ID"""
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def time(self) -> int:
|
||||
"""事件发生时间"""
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def type(self) -> str:
|
||||
"""事件主类型"""
|
||||
raise NotImplementedError
|
||||
|
||||
@type.setter
|
||||
@ -96,6 +157,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def detail_type(self) -> str:
|
||||
"""事件详细类型"""
|
||||
raise NotImplementedError
|
||||
|
||||
@detail_type.setter
|
||||
@ -106,6 +168,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def sub_type(self) -> Optional[str]:
|
||||
"""事件子类型"""
|
||||
raise NotImplementedError
|
||||
|
||||
@sub_type.setter
|
||||
@ -116,6 +179,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def user_id(self) -> Optional[int]:
|
||||
"""触发事件的主体 ID"""
|
||||
raise NotImplementedError
|
||||
|
||||
@user_id.setter
|
||||
@ -126,6 +190,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def group_id(self) -> Optional[int]:
|
||||
"""触发事件的主体群 ID"""
|
||||
raise NotImplementedError
|
||||
|
||||
@group_id.setter
|
||||
@ -136,6 +201,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def to_me(self) -> Optional[bool]:
|
||||
"""事件是否为发送给机器人的消息"""
|
||||
raise NotImplementedError
|
||||
|
||||
@to_me.setter
|
||||
@ -146,6 +212,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def message(self) -> Optional[Message]:
|
||||
"""消息内容"""
|
||||
raise NotImplementedError
|
||||
|
||||
@message.setter
|
||||
@ -156,6 +223,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def reply(self) -> Optional[dict]:
|
||||
"""回复的消息"""
|
||||
raise NotImplementedError
|
||||
|
||||
@reply.setter
|
||||
@ -166,6 +234,7 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def raw_message(self) -> Optional[str]:
|
||||
"""原始消息"""
|
||||
raise NotImplementedError
|
||||
|
||||
@raw_message.setter
|
||||
@ -176,11 +245,13 @@ class BaseEvent(abc.ABC):
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def plain_text(self) -> Optional[str]:
|
||||
"""纯文本消息"""
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
@abc.abstractmethod
|
||||
def sender(self) -> Optional[dict]:
|
||||
"""消息发送者信息"""
|
||||
raise NotImplementedError
|
||||
|
||||
@sender.setter
|
||||
@ -191,8 +262,17 @@ class BaseEvent(abc.ABC):
|
||||
|
||||
@dataclass
|
||||
class BaseMessageSegment(abc.ABC):
|
||||
"""消息段基类"""
|
||||
type: str
|
||||
data: Dict[str, Union[str, list]] = field(default_factory=lambda: {})
|
||||
"""
|
||||
- 类型: ``str``
|
||||
- 说明: 消息段类型
|
||||
"""
|
||||
data: Dict[str, Any] = field(default_factory=lambda: {})
|
||||
"""
|
||||
- 类型: ``Dict[str, Union[str, list]]``
|
||||
- 说明: 消息段数据
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def __str__(self):
|
||||
@ -202,14 +282,30 @@ class BaseMessageSegment(abc.ABC):
|
||||
def __add__(self, other):
|
||||
raise NotImplementedError
|
||||
|
||||
def __getitem__(self, key):
|
||||
return getattr(self, key)
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
return setattr(self, key, value)
|
||||
|
||||
@classmethod
|
||||
@abc.abstractmethod
|
||||
def text(cls, text: str) -> "BaseMessageSegment":
|
||||
return cls("text", {"text": text})
|
||||
|
||||
|
||||
class BaseMessage(list, abc.ABC):
|
||||
"""消息数组"""
|
||||
|
||||
def __init__(self,
|
||||
message: Union[str, dict, list, BaseMessageSegment,
|
||||
"BaseMessage"] = None,
|
||||
*args,
|
||||
**kwargs):
|
||||
"""
|
||||
:参数:
|
||||
* ``message: Union[str, dict, list, MessageSegment, Message]``: 消息内容
|
||||
"""
|
||||
super().__init__(*args, **kwargs)
|
||||
if isinstance(message, (str, dict, list)):
|
||||
self.extend(self._construct(message))
|
||||
@ -243,6 +339,12 @@ class BaseMessage(list, abc.ABC):
|
||||
return result.__add__(self)
|
||||
|
||||
def append(self, obj: Union[str, BaseMessageSegment]) -> "BaseMessage":
|
||||
"""
|
||||
:说明:
|
||||
添加一个消息段到消息数组末尾
|
||||
:参数:
|
||||
* ``obj: Union[str, MessageSegment]``: 要添加的消息段
|
||||
"""
|
||||
if isinstance(obj, BaseMessageSegment):
|
||||
if obj.type == "text" and self and self[-1].type == "text":
|
||||
self[-1].data["text"] += obj.data["text"]
|
||||
@ -257,11 +359,21 @@ class BaseMessage(list, abc.ABC):
|
||||
def extend(
|
||||
self, obj: Union["BaseMessage",
|
||||
Iterable[BaseMessageSegment]]) -> "BaseMessage":
|
||||
"""
|
||||
:说明:
|
||||
拼接一个消息数组或多个消息段到消息数组末尾
|
||||
:参数:
|
||||
* ``obj: Union[Message, Iterable[MessageSegment]]``: 要添加的消息数组
|
||||
"""
|
||||
for segment in obj:
|
||||
self.append(segment)
|
||||
return self
|
||||
|
||||
def reduce(self) -> None:
|
||||
"""
|
||||
:说明:
|
||||
缩减消息数组,即拼接相邻纯文本消息段
|
||||
"""
|
||||
index = 0
|
||||
while index < len(self):
|
||||
if index > 0 and self[
|
||||
@ -272,8 +384,13 @@ class BaseMessage(list, abc.ABC):
|
||||
index += 1
|
||||
|
||||
def extract_plain_text(self) -> str:
|
||||
"""
|
||||
:说明:
|
||||
提取消息内纯文本消息
|
||||
"""
|
||||
|
||||
def _concat(x: str, y: BaseMessageSegment) -> str:
|
||||
return f"{x} {y.data['text']}" if y.type == "text" else x
|
||||
|
||||
return reduce(_concat, self, "")
|
||||
plain_text = reduce(_concat, self, "")
|
||||
return plain_text[1:] if plain_text else plain_text
|
||||
|
@ -182,13 +182,13 @@ def _check_nickname(bot: "Bot", event: "Event"):
|
||||
|
||||
first_text = first_msg_seg.data["text"]
|
||||
|
||||
if bot.config.NICKNAME:
|
||||
if bot.config.nickname:
|
||||
# check if the user is calling me with my nickname
|
||||
if isinstance(bot.config.NICKNAME, str) or \
|
||||
not isinstance(bot.config.NICKNAME, Iterable):
|
||||
nicknames = (bot.config.NICKNAME,)
|
||||
if isinstance(bot.config.nickname, str) or \
|
||||
not isinstance(bot.config.nickname, Iterable):
|
||||
nicknames = (bot.config.nickname,)
|
||||
else:
|
||||
nicknames = filter(lambda n: n, bot.config.NICKNAME)
|
||||
nicknames = filter(lambda n: n, bot.config.nickname)
|
||||
nickname_regex = "|".join(nicknames)
|
||||
m = re.search(rf"^({nickname_regex})([\s,,]*|$)", first_text,
|
||||
re.IGNORECASE)
|
||||
@ -265,7 +265,7 @@ class Bot(BaseBot):
|
||||
config: Config,
|
||||
self_id: str,
|
||||
*,
|
||||
websocket: WebSocket = None):
|
||||
websocket: Optional[WebSocket] = None):
|
||||
if connection_type not in ["http", "websocket"]:
|
||||
raise ValueError("Unsupported connection type")
|
||||
|
||||
@ -521,7 +521,7 @@ class Event(BaseEvent):
|
||||
"""
|
||||
return self._raw_event.get("sub_type")
|
||||
|
||||
@type.setter
|
||||
@sub_type.setter
|
||||
@overrides(BaseEvent)
|
||||
def sub_type(self, value) -> None:
|
||||
self._raw_event["sub_type"] = value
|
||||
@ -637,9 +637,9 @@ class Event(BaseEvent):
|
||||
class MessageSegment(BaseMessageSegment):
|
||||
|
||||
@overrides(BaseMessageSegment)
|
||||
def __init__(self, type: str, data: Dict[str, Union[str, list]]) -> None:
|
||||
def __init__(self, type: str, data: Dict[str, Any]) -> None:
|
||||
if type == "text":
|
||||
data["text"] = unescape(data["text"]) # type: ignore
|
||||
data["text"] = unescape(data["text"])
|
||||
super().__init__(type=type, data=data)
|
||||
|
||||
@overrides(BaseMessageSegment)
|
||||
|
@ -791,7 +791,7 @@ class Event:
|
||||
def sub_type(self) -> Optional[str]:
|
||||
...
|
||||
|
||||
@type.setter
|
||||
@sub_type.setter
|
||||
def sub_type(self, value) -> None:
|
||||
...
|
||||
|
||||
@ -858,7 +858,7 @@ class Event:
|
||||
|
||||
class MessageSegment:
|
||||
|
||||
def __init__(self, type: str, data: Dict[str, Union[str, list]]) -> None:
|
||||
def __init__(self, type: str, data: Dict[str, Any]) -> None:
|
||||
...
|
||||
|
||||
def __str__(self):
|
||||
|
@ -211,10 +211,10 @@ class Config(BaseConfig):
|
||||
|
||||
SUPER_USERS=[12345789]
|
||||
"""
|
||||
nickname: Union[str, Set[str]] = ""
|
||||
nickname: Set[str] = set()
|
||||
"""
|
||||
- 类型: ``Union[str, Set[str]]``
|
||||
- 默认值: ``""``
|
||||
- 类型: ``Set[str]``
|
||||
- 默认值: ``set()``
|
||||
- 说明:
|
||||
机器人昵称。
|
||||
"""
|
||||
|
@ -1,5 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
后端驱动适配基类
|
||||
===============
|
||||
|
||||
各驱动请继承以下基类
|
||||
"""
|
||||
|
||||
import abc
|
||||
|
||||
@ -9,7 +15,15 @@ from nonebot.typing import Bot, Dict, Type, Union, Optional, Callable
|
||||
|
||||
|
||||
class BaseDriver(abc.ABC):
|
||||
"""
|
||||
Driver 基类。将后端框架封装,以满足适配器使用。
|
||||
"""
|
||||
|
||||
_adapters: Dict[str, Type[Bot]] = {}
|
||||
"""
|
||||
:类型: ``Dict[str, Type[Bot]]``
|
||||
:说明: 已注册的适配器列表
|
||||
"""
|
||||
|
||||
@abc.abstractmethod
|
||||
def __init__(self, env: Env, config: Config):
|
||||
|
@ -1,5 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
事件响应器
|
||||
==========
|
||||
|
||||
该模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行 对话 。
|
||||
"""
|
||||
|
||||
from nonebot.log import logger
|
||||
import typing
|
||||
@ -16,6 +22,10 @@ from nonebot.typing import Bot, Event, Handler, Message, ArgsParser, MessageSegm
|
||||
from nonebot.exception import PausedException, RejectedException, FinishedException
|
||||
|
||||
matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list)
|
||||
"""
|
||||
:类型: ``Dict[int, List[Type[Matcher]]]``
|
||||
:说明: 用于存储当前所有的事件响应器
|
||||
"""
|
||||
current_bot: ContextVar = ContextVar("current_bot")
|
||||
current_event: ContextVar = ContextVar("current_event")
|
||||
|
||||
@ -32,22 +42,65 @@ class MatcherMeta(type):
|
||||
|
||||
|
||||
class Matcher(metaclass=MatcherMeta):
|
||||
"""`Matcher`类
|
||||
"""
|
||||
"""事件响应器类"""
|
||||
module: Optional[str] = None
|
||||
"""
|
||||
:类型: ``Optional[str]``
|
||||
:说明: 事件响应器所在模块名称
|
||||
"""
|
||||
|
||||
type: str = ""
|
||||
"""
|
||||
:类型: ``str``
|
||||
:说明: 事件响应器类型
|
||||
"""
|
||||
rule: Rule = Rule()
|
||||
"""
|
||||
:类型: ``Rule``
|
||||
:说明: 事件响应器匹配规则
|
||||
"""
|
||||
permission: Permission = Permission()
|
||||
"""
|
||||
:类型: ``Permission``
|
||||
:说明: 事件响应器触发权限
|
||||
"""
|
||||
handlers: List[Handler] = []
|
||||
temp: bool = False
|
||||
expire_time: Optional[datetime] = None
|
||||
"""
|
||||
:类型: ``List[Handler]``
|
||||
:说明: 事件响应器拥有的事件处理函数列表
|
||||
"""
|
||||
priority: int = 1
|
||||
"""
|
||||
:类型: ``int``
|
||||
:说明: 事件响应器优先级
|
||||
"""
|
||||
block: bool = False
|
||||
"""
|
||||
:类型: ``bool``
|
||||
:说明: 事件响应器是否阻止事件传播
|
||||
"""
|
||||
temp: bool = False
|
||||
"""
|
||||
:类型: ``bool``
|
||||
:说明: 事件响应器是否为临时
|
||||
"""
|
||||
expire_time: Optional[datetime] = None
|
||||
"""
|
||||
:类型: ``Optional[datetime]``
|
||||
:说明: 事件响应器过期时间点
|
||||
"""
|
||||
|
||||
_default_state: dict = {}
|
||||
"""
|
||||
:类型: ``dict``
|
||||
:说明: 事件响应器默认状态
|
||||
"""
|
||||
|
||||
_default_parser: Optional[ArgsParser] = None
|
||||
"""
|
||||
:类型: ``Optional[ArgsParser]``
|
||||
:说明: 事件响应器默认参数解析函数
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""实例化 Matcher 以便运行
|
||||
@ -65,9 +118,9 @@ class Matcher(metaclass=MatcherMeta):
|
||||
@classmethod
|
||||
def new(cls,
|
||||
type_: str = "",
|
||||
rule: Rule = Rule(),
|
||||
permission: Permission = Permission(),
|
||||
handlers: Optional[list] = None,
|
||||
rule: Optional[Rule] = None,
|
||||
permission: Optional[Permission] = None,
|
||||
handlers: Optional[List[Handler]] = None,
|
||||
temp: bool = False,
|
||||
priority: int = 1,
|
||||
block: bool = False,
|
||||
@ -75,18 +128,30 @@ class Matcher(metaclass=MatcherMeta):
|
||||
module: Optional[str] = None,
|
||||
default_state: Optional[dict] = None,
|
||||
expire_time: Optional[datetime] = None) -> Type["Matcher"]:
|
||||
"""创建新的 Matcher
|
||||
|
||||
Returns:
|
||||
Type["Matcher"]: 新的 Matcher 类
|
||||
"""
|
||||
:说明:
|
||||
创建一个新的事件响应器,并存储至 `matchers <#matchers>`_
|
||||
:参数:
|
||||
* ``type_: str``: 事件响应器类型,与 ``event.type`` 一致时触发,空字符串表示任意
|
||||
* ``rule: Optional[Rule]``: 匹配规则
|
||||
* ``permission: Optional[Permission]``: 权限
|
||||
* ``handlers: Optional[List[Handler]]``: 事件处理函数列表
|
||||
* ``temp: bool``: 是否为临时事件响应器,即触发一次后删除
|
||||
* ``priority: int``: 响应优先级
|
||||
* ``block: bool``: 是否阻止事件向更低优先级的响应器传播
|
||||
* ``module: Optional[str]``: 事件响应器所在模块名称
|
||||
* ``default_state: Optional[dict]``: 默认状态 ``state``
|
||||
* ``expire_time: Optional[datetime]``: 事件响应器最终有效时间点,过时即被删除
|
||||
:返回:
|
||||
- ``Type[Matcher]``: 新的事件响应器类
|
||||
"""
|
||||
|
||||
NewMatcher = type(
|
||||
"Matcher", (Matcher,), {
|
||||
"module": module,
|
||||
"type": type_,
|
||||
"rule": rule,
|
||||
"permission": permission,
|
||||
"rule": rule or Rule(),
|
||||
"permission": permission or Permission(),
|
||||
"handlers": handlers or [],
|
||||
"temp": temp,
|
||||
"expire_time": expire_time,
|
||||
@ -101,29 +166,51 @@ class Matcher(metaclass=MatcherMeta):
|
||||
|
||||
@classmethod
|
||||
async def check_perm(cls, bot: Bot, event: Event) -> bool:
|
||||
"""
|
||||
:说明:
|
||||
检查是否满足触发权限
|
||||
:参数:
|
||||
* ``bot: Bot``: Bot 对象
|
||||
* ``event: Event``: 上报事件
|
||||
:返回:
|
||||
- ``bool``: 是否满足权限
|
||||
"""
|
||||
return await cls.permission(bot, event)
|
||||
|
||||
@classmethod
|
||||
async def check_rule(cls, bot: Bot, event: Event, state: dict) -> bool:
|
||||
"""检查 Matcher 的 Rule 是否成立
|
||||
|
||||
Args:
|
||||
event (Event): 消息事件
|
||||
|
||||
Returns:
|
||||
bool: 条件成立与否
|
||||
"""
|
||||
:说明:
|
||||
检查是否满足匹配规则
|
||||
:参数:
|
||||
* ``bot: Bot``: Bot 对象
|
||||
* ``event: Event``: 上报事件
|
||||
* ``state: dict``: 当前状态
|
||||
:返回:
|
||||
- ``bool``: 是否满足匹配规则
|
||||
"""
|
||||
return (event.type == (cls.type or event.type) and
|
||||
await cls.rule(bot, event, state))
|
||||
|
||||
@classmethod
|
||||
def args_parser(cls, func: ArgsParser) -> ArgsParser:
|
||||
"""
|
||||
:说明:
|
||||
装饰一个函数来更改当前事件响应器的默认参数解析函数
|
||||
:参数:
|
||||
* ``func: ArgsParser``: 参数解析函数
|
||||
"""
|
||||
cls._default_parser = func
|
||||
return func
|
||||
|
||||
@classmethod
|
||||
def handle(cls) -> Callable[[Handler], Handler]:
|
||||
"""直接处理消息事件"""
|
||||
"""
|
||||
:说明:
|
||||
装饰一个函数来向事件响应器直接添加一个处理函数
|
||||
:参数:
|
||||
* 无
|
||||
"""
|
||||
|
||||
def _decorator(func: Handler) -> Handler:
|
||||
cls.handlers.append(func)
|
||||
@ -133,7 +220,12 @@ class Matcher(metaclass=MatcherMeta):
|
||||
|
||||
@classmethod
|
||||
def receive(cls) -> Callable[[Handler], Handler]:
|
||||
"""接收一条新消息并处理"""
|
||||
"""
|
||||
:说明:
|
||||
装饰一个函数来指示 NoneBot 在接收用户新的一条消息后继续运行该函数
|
||||
:参数:
|
||||
* 无
|
||||
"""
|
||||
|
||||
async def _receive(bot: Bot, event: Event, state: dict) -> NoReturn:
|
||||
raise PausedException
|
||||
@ -154,9 +246,17 @@ class Matcher(metaclass=MatcherMeta):
|
||||
def got(
|
||||
cls,
|
||||
key: str,
|
||||
prompt: Optional[str] = None,
|
||||
prompt: Optional[Union[str, Message, MessageSegment]] = None,
|
||||
args_parser: Optional[ArgsParser] = None
|
||||
) -> Callable[[Handler], Handler]:
|
||||
"""
|
||||
:说明:
|
||||
装饰一个函数来指示 NoneBot 当要获取的 ``key`` 不存在时接收用户新的一条消息并经过 ``ArgsParser`` 处理后再运行该函数,如果 ``key`` 已存在则直接继续运行
|
||||
:参数:
|
||||
* ``key: str``: 参数名
|
||||
* ``prompt: Optional[Union[str, Message, MessageSegment]]``: 在参数不存在时向用户发送的消息
|
||||
* ``args_parser: Optional[ArgsParser]``: 可选参数解析函数,空则使用默认解析函数
|
||||
"""
|
||||
|
||||
async def _key_getter(bot: Bot, event: Event, state: dict):
|
||||
state["_current_key"] = key
|
||||
@ -197,15 +297,33 @@ class Matcher(metaclass=MatcherMeta):
|
||||
|
||||
return _decorator
|
||||
|
||||
@classmethod
|
||||
async def send(cls, message: Union[str, Message, MessageSegment]):
|
||||
"""
|
||||
:说明:
|
||||
发送一条消息给当前交互用户
|
||||
:参数:
|
||||
* ``message: Union[str, Message, MessageSegment]``: 消息内容
|
||||
"""
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
await bot.send(event=event, message=message)
|
||||
|
||||
@classmethod
|
||||
async def finish(
|
||||
cls,
|
||||
prompt: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
bot: Bot = current_bot.get()
|
||||
event: Event = current_event.get()
|
||||
if prompt:
|
||||
await bot.send(event=event, message=prompt)
|
||||
message: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
"""
|
||||
:说明:
|
||||
发送一条消息给当前交互用户并结束当前事件响应器
|
||||
:参数:
|
||||
* ``message: Union[str, Message, MessageSegment]``: 消息内容
|
||||
"""
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
if message:
|
||||
await bot.send(event=event, message=message)
|
||||
raise FinishedException
|
||||
|
||||
@classmethod
|
||||
@ -213,8 +331,14 @@ class Matcher(metaclass=MatcherMeta):
|
||||
cls,
|
||||
prompt: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
bot: Bot = current_bot.get()
|
||||
event: Event = current_event.get()
|
||||
"""
|
||||
:说明:
|
||||
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后继续下一个处理函数
|
||||
:参数:
|
||||
* ``prompt: Union[str, Message, MessageSegment]``: 消息内容
|
||||
"""
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
if prompt:
|
||||
await bot.send(event=event, message=prompt)
|
||||
raise PausedException
|
||||
@ -224,8 +348,14 @@ class Matcher(metaclass=MatcherMeta):
|
||||
cls,
|
||||
prompt: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
bot: Bot = current_bot.get()
|
||||
event: Event = current_event.get()
|
||||
"""
|
||||
:说明:
|
||||
发送一条消息给当前交互用户并暂停事件响应器,在接收用户新的一条消息后重新运行当前处理函数
|
||||
:参数:
|
||||
* ``prompt: Union[str, Message, MessageSegment]``: 消息内容
|
||||
"""
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
if prompt:
|
||||
await bot.send(event=event, message=prompt)
|
||||
raise RejectedException
|
||||
@ -281,11 +411,12 @@ class Matcher(metaclass=MatcherMeta):
|
||||
|
||||
|
||||
class MatcherGroup:
|
||||
"""事件响应器组合,统一管理。用法同 ``Matcher``"""
|
||||
|
||||
def __init__(self,
|
||||
type_: str = "",
|
||||
rule: Rule = Rule(),
|
||||
permission: Permission = Permission(),
|
||||
rule: Optional[Rule] = None,
|
||||
permission: Optional[Permission] = None,
|
||||
handlers: Optional[list] = None,
|
||||
temp: bool = False,
|
||||
priority: int = 1,
|
||||
@ -294,19 +425,30 @@ class MatcherGroup:
|
||||
module: Optional[str] = None,
|
||||
default_state: Optional[dict] = None,
|
||||
expire_time: Optional[datetime] = None):
|
||||
"""
|
||||
:说明:
|
||||
创建一个事件响应器组合,参数为默认值,与 ``Matcher.new`` 一致
|
||||
"""
|
||||
self.matchers: List[Type[Matcher]] = []
|
||||
"""
|
||||
:类型: ``List[Type[Matcher]]``
|
||||
:说明: 组内事件响应器列表
|
||||
"""
|
||||
|
||||
self.type = type_
|
||||
self.rule = rule
|
||||
self.permission = permission
|
||||
self.rule = rule or Rule()
|
||||
self.permission = permission or Permission()
|
||||
self.handlers = handlers
|
||||
self.temp = temp
|
||||
self.priority = priority
|
||||
self.block = block
|
||||
self.module = module
|
||||
self.default_state = default_state
|
||||
self.expire_time = expire_time
|
||||
|
||||
self._default_state = default_state
|
||||
|
||||
self._default_parser: Optional[ArgsParser] = None
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"<MatcherGroup from {self.module or 'unknow'}, type={self.type}, "
|
||||
@ -317,8 +459,8 @@ class MatcherGroup:
|
||||
|
||||
def new(self,
|
||||
type_: str = "",
|
||||
rule: Rule = Rule(),
|
||||
permission: Permission = Permission(),
|
||||
rule: Optional[Rule] = None,
|
||||
permission: Optional[Permission] = None,
|
||||
handlers: Optional[list] = None,
|
||||
temp: bool = False,
|
||||
priority: int = 1,
|
||||
@ -327,6 +469,14 @@ class MatcherGroup:
|
||||
module: Optional[str] = None,
|
||||
default_state: Optional[dict] = None,
|
||||
expire_time: Optional[datetime] = None) -> Type[Matcher]:
|
||||
"""
|
||||
:说明:
|
||||
在组中创建一个新的事件响应器,参数留空则使用组合默认值
|
||||
|
||||
\:\:\:danger 警告
|
||||
如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数
|
||||
\:\:\:
|
||||
"""
|
||||
matcher = Matcher.new(type_=type_ or self.type,
|
||||
rule=self.rule & rule,
|
||||
permission=permission or self.permission,
|
||||
@ -335,7 +485,8 @@ class MatcherGroup:
|
||||
priority=priority or self.priority,
|
||||
block=block or self.block,
|
||||
module=module or self.module,
|
||||
default_state=default_state or self.default_state,
|
||||
default_state=default_state or
|
||||
self._default_state,
|
||||
expire_time=expire_time or self.expire_time)
|
||||
self.matchers.append(matcher)
|
||||
return matcher
|
||||
@ -346,7 +497,6 @@ class MatcherGroup:
|
||||
return func
|
||||
|
||||
def handle(self) -> Callable[[Handler], Handler]:
|
||||
"""直接处理消息事件"""
|
||||
|
||||
def _decorator(func: Handler) -> Handler:
|
||||
self.handlers.append(func)
|
||||
@ -355,7 +505,6 @@ class MatcherGroup:
|
||||
return _decorator
|
||||
|
||||
def receive(self) -> Callable[[Handler], Handler]:
|
||||
"""接收一条新消息并处理"""
|
||||
|
||||
async def _receive(bot: Bot, event: Event, state: dict) -> NoReturn:
|
||||
raise PausedException
|
||||
@ -418,22 +567,27 @@ class MatcherGroup:
|
||||
|
||||
return _decorator
|
||||
|
||||
async def send(self, message: Union[str, Message, MessageSegment]):
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
await bot.send(event=event, message=message)
|
||||
|
||||
async def finish(
|
||||
self,
|
||||
prompt: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
bot: Bot = current_bot.get()
|
||||
event: Event = current_event.get()
|
||||
if prompt:
|
||||
await bot.send(event=event, message=prompt)
|
||||
message: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
if message:
|
||||
await bot.send(event=event, message=message)
|
||||
raise FinishedException
|
||||
|
||||
async def pause(
|
||||
self,
|
||||
prompt: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
bot: Bot = current_bot.get()
|
||||
event: Event = current_event.get()
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
if prompt:
|
||||
await bot.send(event=event, message=prompt)
|
||||
raise PausedException
|
||||
@ -442,8 +596,8 @@ class MatcherGroup:
|
||||
self,
|
||||
prompt: Optional[Union[str, Message,
|
||||
MessageSegment]] = None) -> NoReturn:
|
||||
bot: Bot = current_bot.get()
|
||||
event: Event = current_event.get()
|
||||
bot = current_bot.get()
|
||||
event = current_event.get()
|
||||
if prompt:
|
||||
await bot.send(event=event, message=prompt)
|
||||
raise RejectedException
|
||||
|
@ -74,7 +74,7 @@ async def handle_event(bot: Bot, event: Event):
|
||||
elif event.type == "request":
|
||||
log_msg += f"Request {event.raw_event}"
|
||||
elif event.type == "meta_event":
|
||||
log_msg += f"MetaEvent {event.raw_event}"
|
||||
log_msg += f"MetaEvent {event.detail_type}"
|
||||
logger.opt(colors=True).info(log_msg)
|
||||
|
||||
coros = []
|
||||
|
@ -1,10 +1,34 @@
|
||||
from functools import reduce
|
||||
|
||||
from nonebot.rule import to_me
|
||||
from nonebot.plugin import on_command
|
||||
from nonebot.typing import Bot, Event
|
||||
from nonebot.permission import SUPERUSER
|
||||
from nonebot.typing import Bot, Event, MessageSegment
|
||||
|
||||
say = on_command("say", to_me())
|
||||
say = on_command("say", to_me(), permission=SUPERUSER)
|
||||
|
||||
|
||||
@say.handle()
|
||||
async def repeat(bot: Bot, event: Event, state: dict):
|
||||
await bot.send(message=event.message, event=event)
|
||||
async def say_unescape(bot: Bot, event: Event, state: dict):
|
||||
Message = event.message.__class__
|
||||
|
||||
def _unescape(message: Message, segment: MessageSegment):
|
||||
if segment.type == "text":
|
||||
return message.append(segment.data["text"])
|
||||
return message.append(segment)
|
||||
|
||||
message = reduce(_unescape, event.message, Message()) # type: ignore
|
||||
await bot.send(message=message, event=event)
|
||||
|
||||
|
||||
echo = on_command("echo", to_me())
|
||||
|
||||
|
||||
@echo.handle()
|
||||
async def echo_escape(bot: Bot, event: Event, state: dict):
|
||||
Message = event.message.__class__
|
||||
MessageSegment = event.message[0].__class__
|
||||
|
||||
message = Message().append( # type: ignore
|
||||
MessageSegment.text(str(event.message)))
|
||||
await bot.send(message=message, event=event)
|
||||
|
@ -4,10 +4,10 @@
|
||||
规则
|
||||
====
|
||||
|
||||
每个 ``Matcher`` 拥有一个 ``Rule`` ,其中是 **异步** ``RuleChecker`` 的集合,只有当所有 ``RuleChecker`` 检查结果为 ``True`` 时继续运行。
|
||||
每个事件响应器 ``Matcher`` 拥有一个匹配规则 ``Rule`` ,其中是 **异步** ``RuleChecker`` 的集合,只有当所有 ``RuleChecker`` 检查结果为 ``True`` 时继续运行。
|
||||
|
||||
\:\:\:tip 提示
|
||||
``RuleChecker`` 既可以是 async function 也可以是 sync function
|
||||
``RuleChecker`` 既可以是 async function 也可以是 sync function,但在最终会被 ``nonebot.utils.run_sync`` 转换为 async function
|
||||
\:\:\:
|
||||
"""
|
||||
|
||||
@ -185,6 +185,12 @@ def endswith(msg: str) -> Rule:
|
||||
|
||||
|
||||
def keyword(msg: str) -> Rule:
|
||||
"""
|
||||
:说明:
|
||||
匹配消息关键词
|
||||
:参数:
|
||||
* ``msg: str``: 关键词
|
||||
"""
|
||||
|
||||
async def _keyword(bot: Bot, event: Event, state: dict) -> bool:
|
||||
return bool(event.plain_text and msg in event.plain_text)
|
||||
@ -193,6 +199,22 @@ def keyword(msg: str) -> Rule:
|
||||
|
||||
|
||||
def command(command: Tuple[str, ...]) -> Rule:
|
||||
"""
|
||||
:说明:
|
||||
命令形式匹配,根据配置里提供的 ``command_start``, ``command_sep`` 判断消息是否为命令。
|
||||
:参数:
|
||||
* ``command: Tuples[str, ...]``: 命令内容
|
||||
:示例:
|
||||
使用默认 ``command_start``, ``command_sep`` 配置
|
||||
|
||||
命令 ``("test",)`` 可以匹配:``/test`` 开头的消息
|
||||
命令 ``("test", "sub")`` 可以匹配”``/test.sub`` 开头的消息
|
||||
|
||||
\:\:\:tip 提示
|
||||
命令内容与后续消息间无需空格!
|
||||
\:\:\:
|
||||
"""
|
||||
|
||||
config = get_driver().config
|
||||
command_start = config.command_start
|
||||
command_sep = config.command_sep
|
||||
@ -210,6 +232,14 @@ def command(command: Tuple[str, ...]) -> Rule:
|
||||
|
||||
|
||||
def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule:
|
||||
"""
|
||||
:说明:
|
||||
根据正则表达式进行匹配
|
||||
:参数:
|
||||
* ``regex: str``: 正则表达式
|
||||
* ``flags: Union[int, re.RegexFlag]``: 正则标志
|
||||
"""
|
||||
|
||||
pattern = re.compile(regex, flags)
|
||||
|
||||
async def _regex(bot: Bot, event: Event, state: dict) -> bool:
|
||||
@ -219,6 +249,12 @@ def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule:
|
||||
|
||||
|
||||
def to_me() -> Rule:
|
||||
"""
|
||||
:说明:
|
||||
通过 ``event.to_me`` 判断消息是否是发送给机器人
|
||||
:参数:
|
||||
* 无
|
||||
"""
|
||||
|
||||
async def _to_me(bot: Bot, event: Event, state: dict) -> bool:
|
||||
return bool(event.to_me)
|
||||
|
959
poetry.lock
generated
959
poetry.lock
generated
File diff suppressed because it is too large
Load Diff
@ -1,6 +1,6 @@
|
||||
[tool.poetry]
|
||||
name = "nonebot2"
|
||||
version = "2.0.0a2"
|
||||
version = "2.0.0a3"
|
||||
description = "An asynchronous python bot framework."
|
||||
authors = ["yanyongyu <yanyongyu_1@126.com>"]
|
||||
license = "MIT"
|
||||
@ -31,7 +31,7 @@ fastapi = "^0.58.1"
|
||||
uvicorn = "^0.11.5"
|
||||
pydantic = { extras = ["dotenv"], version = "^1.6.1" }
|
||||
apscheduler = { version = "^3.6.3", optional = true }
|
||||
# nonebot-test = { version = "^0.1.0", optional = true }
|
||||
nonebot-test = { version = "^0.1.0", optional = true }
|
||||
nb-cli = { version="^0.1.0", optional = true }
|
||||
|
||||
[tool.poetry.dev-dependencies]
|
||||
@ -41,7 +41,7 @@ sphinx-markdown-builder = { git = "https://github.com/nonebot/sphinx-markdown-bu
|
||||
|
||||
[tool.poetry.extras]
|
||||
cli = ["nb-cli"]
|
||||
# test = ["nonebot-test"]
|
||||
test = ["nonebot-test"]
|
||||
scheduler = ["apscheduler"]
|
||||
full = ["nb-cli", "nonebot-test", "scheduler"]
|
||||
|
||||
|
@ -3,6 +3,9 @@ HOST=0.0.0.0
|
||||
PORT=2333
|
||||
DEBUG=true
|
||||
|
||||
SUPERUSERS=[123123123]
|
||||
NICKNAME=["bot"]
|
||||
|
||||
COMMAND_START=["", "/", "#"]
|
||||
COMMAND_SEP=["/", "."]
|
||||
|
||||
|
Loading…
x
Reference in New Issue
Block a user