diff --git a/README.md b/README.md index 58ebe0d0..10633bdd 100644 --- a/README.md +++ b/README.md @@ -12,24 +12,33 @@ _✨ Python 异步机器人框架 ✨_

- license + license - pypi + pypi - python - cqhttp
+ python
+ + cqhttp + + + ding + + + + +
- QQ Chat + QQ Chat - Telegram Chat + Telegram Chat - QQ Release + QQ Release - Telegram Release + Telegram Release

@@ -61,8 +70,8 @@ NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义 目前 NoneBot2 内置的协议适配: -- [CQHTTP(OneBot) 协议](https://github.com/howmanybots/onebot/blob/master/README.md) -- [钉钉](https://ding-doc.dingtalk.com/doc#/serverapi2/krgddi) _开发中_ +- [OneBot(CQHTTP) 协议](https://github.com/howmanybots/onebot/blob/master/README.md) (QQ 等) +- [钉钉](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) _开发中_ - [Telegram](https://core.telegram.org/bots/api) _计划中_ ## 即刻开始 diff --git a/archive/2.0.0a6/advanced/permission.md b/archive/2.0.0a6/advanced/permission.md deleted file mode 100644 index 30e20002..00000000 --- a/archive/2.0.0a6/advanced/permission.md +++ /dev/null @@ -1 +0,0 @@ -# 权限控制 \ No newline at end of file diff --git a/archive/2.0.0a6/advanced/runtime-hook.md b/archive/2.0.0a6/advanced/runtime-hook.md deleted file mode 100644 index ed3968a4..00000000 --- a/archive/2.0.0a6/advanced/runtime-hook.md +++ /dev/null @@ -1 +0,0 @@ -# 运行时插槽 \ No newline at end of file diff --git a/archive/2.0.0a6/advanced/scheduler.md b/archive/2.0.0a6/advanced/scheduler.md deleted file mode 100644 index 99d906d3..00000000 --- a/archive/2.0.0a6/advanced/scheduler.md +++ /dev/null @@ -1 +0,0 @@ -# 定时任务 \ No newline at end of file diff --git a/archive/2.0.0a6/api/adapters/cqhttp.md b/archive/2.0.0a6/api/adapters/cqhttp.md deleted file mode 100644 index aa6ad47f..00000000 --- a/archive/2.0.0a6/api/adapters/cqhttp.md +++ /dev/null @@ -1,424 +0,0 @@ ---- -contentSidebar: true -sidebarDepth: 0 ---- - -# NoneBot.adapters.cqhttp 模块 - -## CQHTTP (OneBot) v11 协议适配 - -协议详情请看: [CQHTTP](http://cqhttp.cc/) | [OneBot](https://github.com/howmanybots/onebot) - - -## `log(level, message)` - - -* **说明** - - 用于打印 CQHTTP 日志。 - - - -* **参数** - - - * `level: str`: 日志等级 - - - * `message: str`: 日志信息 - - - -## `escape(s, *, escape_comma=True)` - - -* **说明** - - 对字符串进行 CQ 码转义。 - - - -* **参数** - - - * `s: str`: 需要转义的字符串 - - - * `escape_comma: bool`: 是否转义逗号(`,`)。 - - - -## `unescape(s)` - - -* **说明** - - 对字符串进行 CQ 码去转义。 - - - -* **参数** - - - * `s: str`: 需要转义的字符串 - - - -## `_b2s(b)` - -转换布尔值为字符串。 - - -## _async_ `_check_reply(bot, event)` - - -* **说明** - - 检查消息中存在的回复,去除并赋值 `event.reply`, `event.to_me` - - - -* **参数** - - - * `bot: Bot`: Bot 对象 - - - * `event: Event`: Event 对象 - - - -## `_check_at_me(bot, event)` - - -* **说明** - - 检查消息开头或结尾是否存在 @机器人,去除并赋值 `event.to_me` - - - -* **参数** - - - * `bot: Bot`: Bot 对象 - - - * `event: Event`: Event 对象 - - - -## `_check_nickname(bot, event)` - - -* **说明** - - 检查消息开头是否存在,去除并赋值 `event.to_me` - - - -* **参数** - - - * `bot: Bot`: Bot 对象 - - - * `event: Event`: Event 对象 - - - -## `_handle_api_result(result)` - - -* **说明** - - 处理 API 请求返回值。 - - - -* **参数** - - - * `result: Optional[Dict[str, Any]]`: API 返回数据 - - - -* **返回** - - - * `Any`: API 调用返回数据 - - - -* **异常** - - - * `ActionFailed`: API 调用失败 - - - -## _class_ `Bot` - -基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot) - -CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 - - -### _property_ `type` - - -* 返回: `"cqhttp"` - - -### _async classmethod_ `check_permission(driver, connection_type, headers, body)` - - -* **说明** - - CQHTTP (OneBot) 协议鉴权。参考 [鉴权](https://github.com/howmanybots/onebot/blob/master/v11/specs/communication/authorization.md) - - - -### _async_ `handle_message(message)` - - -* **说明** - - 调用 [_check_reply](#async-check-reply-bot-event), [_check_at_me](#check-at-me-bot-event), [_check_nickname](#check-nickname-bot-event) 处理事件并转换为 [Event](#class-event) - - - -### _async_ `call_api(api, **data)` - - -* **说明** - - 调用 CQHTTP 协议 API - - - -* **参数** - - - * `api: str`: API 名称 - - - * `**data: Any`: API 参数 - - - -* **返回** - - - * `Any`: API 调用返回数据 - - - -* **异常** - - - * `NetworkError`: 网络错误 - - - * `ActionFailed`: API 调用失败 - - - -### _async_ `send(event, message, at_sender=False, **kwargs)` - - -* **说明** - - 根据 `event` 向触发事件的主体发送消息。 - - - -* **参数** - - - * `event: Event`: Event 对象 - - - * `message: Union[str, Message, MessageSegment]`: 要发送的消息 - - - * `at_sender: bool`: 是否 @ 事件主体 - - - * `**kwargs`: 覆盖默认参数 - - - -* **返回** - - - * `Any`: API 调用返回数据 - - - -* **异常** - - - * `ValueError`: 缺少 `user_id`, `group_id` - - - * `NetworkError`: 网络错误 - - - * `ActionFailed`: API 调用失败 - - - -## _class_ `Event` - -基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent) - -CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。 - - -### _property_ `id` - - -* 类型: `Optional[int]` - - -* 说明: 事件/消息 ID - - -### _property_ `name` - - -* 类型: `str` - - -* 说明: 事件名称,由类型与 `.` 组合而成 - - -### _property_ `self_id` - - -* 类型: `str` - - -* 说明: 机器人自身 ID - - -### _property_ `time` - - -* 类型: `int` - - -* 说明: 事件发生时间 - - -### _property_ `type` - - -* 类型: `str` - - -* 说明: 事件类型 - - -### _property_ `detail_type` - - -* 类型: `str` - - -* 说明: 事件详细类型 - - -### _property_ `sub_type` - - -* 类型: `Optional[str]` - - -* 说明: 事件子类型 - - -### _property_ `user_id` - - -* 类型: `Optional[int]` - - -* 说明: 事件主体 ID - - -### _property_ `group_id` - - -* 类型: `Optional[int]` - - -* 说明: 事件主体群 ID - - -### _property_ `to_me` - - -* 类型: `Optional[bool]` - - -* 说明: 消息是否与机器人相关 - - -### _property_ `message` - - -* 类型: `Optional[Message]` - - -* 说明: 消息内容 - - -### _property_ `reply` - - -* 类型: `Optional[dict]` - - -* 说明: 回复消息详情 - - -### _property_ `raw_message` - - -* 类型: `Optional[str]` - - -* 说明: 原始消息 - - -### _property_ `plain_text` - - -* 类型: `Optional[str]` - - -* 说明: 纯文本消息内容 - - -### _property_ `sender` - - -* 类型: `Optional[dict]` - - -* 说明: 消息发送者信息 - - -## _class_ `MessageSegment` - -基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment) - -CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 - - -## _class_ `Message` - -基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage) - -CQHTTP 协议 Message 适配。 diff --git a/archive/2.0.0a6/api/config.md b/archive/2.0.0a6/api/config.md deleted file mode 100644 index 6943427b..00000000 --- a/archive/2.0.0a6/api/config.md +++ /dev/null @@ -1,265 +0,0 @@ ---- -contentSidebar: true -sidebarDepth: 0 ---- - -# NoneBot.config 模块 - -## 配置 - -NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-dotenv](https://saurabh-kumar.com/python-dotenv/) 来读取配置。 - -配置项需符合特殊格式或 json 序列化格式。详情见 [pydantic Field Type](https://pydantic-docs.helpmanual.io/usage/types/) 文档。 - - -## _class_ `Env` - -基类:`pydantic.env_settings.BaseSettings` - -运行环境配置。大小写不敏感。 - -将会从 `nonebot.init 参数` > `环境变量` > `.env 环境配置文件` 的优先级读取配置。 - - -### `environment` - - -* 类型: `str` - - -* 默认值: `"prod"` - - -* 说明: -当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。 - - -## _class_ `Config` - -基类:`nonebot.config.BaseConfig` - -NoneBot 主要配置。大小写不敏感。 - -除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。 -这些配置将会在 json 反序列化后一起带入 `Config` 类中。 - - -### `driver` - - -* 类型: `str` - - -* 默认值: `"nonebot.drivers.fastapi"` - - -* 说明: -NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver` 。 - - -### `host` - - -* 类型: `IPvAnyAddress` - - -* 默认值: `127.0.0.1` - - -* 说明: -NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。 - - -### `port` - - -* 类型: `int` - - -* 默认值: `8080` - - -* 说明: -NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。 - - -### `debug` - - -* 类型: `bool` - - -* 默认值: `False` - - -* 说明: -是否以调试模式运行 NoneBot。 - - -### `api_root` - - -* 类型: `Dict[str, str]` - - -* 默认值: `{}` - - -* 说明: -以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。 - - -* 示例: - -```default -API_ROOT={"123456": "http://127.0.0.1:5700"} -``` - - -### `api_timeout` - - -* 类型: `Optional[float]` - - -* 默认值: `30.` - - -* 说明: -API 请求超时时间,单位: 秒。 - - -### `access_token` - - -* 类型: `Optional[str]` - - -* 默认值: `None` - - -* 说明: -API 请求以及上报所需密钥,在请求头中携带。 - - -* 示例: - -```http -POST /cqhttp/ HTTP/1.1 -Authorization: Bearer kSLuTF2GC2Q4q4ugm3 -``` - - -### `secret` - - -* 类型: `Optional[str]` - - -* 默认值: `None` - - -* 说明: -HTTP POST 形式上报所需签名,在请求头中携带。 - - -* 示例: - -```http -POST /cqhttp/ HTTP/1.1 -X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 -``` - - -### `superusers` - - -* 类型: `Set[int]` - - -* 默认值: `set()` - - -* 说明: -机器人超级用户。 - - -* 示例: - -```default -SUPER_USERS=[12345789] -``` - - -### `nickname` - - -* 类型: `Set[str]` - - -* 默认值: `set()` - - -* 说明: -机器人昵称。 - - -### `command_start` - - -* 类型: `Set[str]` - - -* 默认值: `{"/"}` - - -* 说明: -命令的起始标记,用于判断一条消息是不是命令。 - - -### `command_sep` - - -* 类型: `Set[str]` - - -* 默认值: `{"."}` - - -* 说明: -命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。 - - -### `session_expire_timeout` - - -* 类型: `timedelta` - - -* 默认值: `timedelta(minutes=2)` - - -* 说明: -等待用户回复的超时时间。 - - -* 示例: - -```default -SESSION_EXPIRE_TIMEOUT=120 # 单位: 秒 -SESSION_EXPIRE_TIMEOUT=[DD ][HH:MM]SS[.ffffff] -SESSION_EXPIRE_TIMEOUT=P[DD]DT[HH]H[MM]M[SS]S # ISO 8601 -``` - - -### `apscheduler_config` - - -* 类型: `dict` - - -* 默认值: `{"apscheduler.timezone": "Asia/Shanghai"}` - - -* 说明: -APScheduler 的配置对象,见 [Configuring the Scheduler](https://apscheduler.readthedocs.io/en/latest/userguide.html#configuring-the-scheduler) diff --git a/archive/2.0.0a6/api/plugin.md b/archive/2.0.0a6/api/plugin.md deleted file mode 100644 index 42cdf84f..00000000 --- a/archive/2.0.0a6/api/plugin.md +++ /dev/null @@ -1,629 +0,0 @@ ---- -contentSidebar: true -sidebarDepth: 0 ---- - -# NoneBot.plugin 模块 - -## 插件 - -为 NoneBot 插件开发提供便携的定义函数。 - - -## `plugins` - - -* **类型** - - `Dict[str, Plugin]` - - - -* **说明** - - 已加载的插件 - - - -## _class_ `Plugin` - -基类:`object` - -存储插件信息 - - -### `name` - - -* **类型**: `str` - - -* **说明**: 插件名称,使用 文件/文件夹 名称作为插件名 - - -### `module` - - -* **类型**: `ModuleType` - - -* **说明**: 插件模块对象 - - -### `matcher` - - -* **类型**: `Set[Type[Matcher]]` - - -* **说明**: 插件内定义的 `Matcher` - - -## `on(type='', rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` - - -* **说明** - - 注册一个基础事件响应器,可自定义类型。 - - - -* **参数** - - - * `type: str`: 事件响应器类型 - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `permission: Optional[Permission]`: 事件响应权限 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_metaevent(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` - - -* **说明** - - 注册一个元事件响应器。 - - - -* **参数** - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_message(rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=True, state=None)` - - -* **说明** - - 注册一个消息事件响应器。 - - - -* **参数** - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `permission: Optional[Permission]`: 事件响应权限 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_notice(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` - - -* **说明** - - 注册一个通知事件响应器。 - - - -* **参数** - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_request(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` - - -* **说明** - - 注册一个请求事件响应器。 - - - -* **参数** - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_startswith(msg, rule=None, **kwargs)` - - -* **说明** - - 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容开头时响应。 - - - -* **参数** - - - * `msg: str`: 指定消息开头内容 - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `permission: Optional[Permission]`: 事件响应权限 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_endswith(msg, rule=None, **kwargs)` - - -* **说明** - - 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容结尾时响应。 - - - -* **参数** - - - * `msg: str`: 指定消息结尾内容 - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `permission: Optional[Permission]`: 事件响应权限 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_keyword(keywords, rule=None, **kwargs)` - - -* **说明** - - 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 - - - -* **参数** - - - * `keywords: Set[str]`: 关键词列表 - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `permission: Optional[Permission]`: 事件响应权限 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_command(cmd, rule=None, aliases=None, **kwargs)` - - -* **说明** - - 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 - - 命令匹配规则参考: [命令形式匹配](rule.html#command-command) - - - -* **参数** - - - * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 - - - * `permission: Optional[Permission]`: 事件响应权限 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## `on_regex(pattern, flags=0, rule=None, **kwargs)` - - -* **说明** - - 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 - - 命令匹配规则参考: [正则匹配](rule.html#regex-regex-flags-0) - - - -* **参数** - - - * `pattern: str`: 正则表达式 - - - * `flags: Union[int, re.RegexFlag]`: 正则匹配标志 - - - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 - - - * `permission: Optional[Permission]`: 事件响应权限 - - - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 - - - * `temp: bool`: 是否为临时事件响应器(仅执行一次) - - - * `priority: int`: 事件响应器优先级 - - - * `block: bool`: 是否阻止事件向更低优先级传递 - - - * `state: Optional[dict]`: 默认的 state - - - -* **返回** - - - * `Type[Matcher]` - - - -## _class_ `CommandGroup` - -基类:`object` - -命令组,用于声明一组有相同名称前缀的命令。 - - -### `__init__(cmd, **kwargs)` - - -* **参数** - - - * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 - - - * `**kwargs`: 其他传递给 `on_command` 的参数默认值,参考 [on_command](#on-command-cmd-rule-none-aliases-none-kwargs) - - - -### `basecmd` - - -* **类型**: `Tuple[str, ...]` - - -* **说明**: 命令前缀 - - -### `base_kwargs` - - -* **类型**: `Dict[str, Any]` - - -* **说明**: 其他传递给 `on_command` 的参数默认值 - - -### `command(cmd, **kwargs)` - - -* **说明** - - 注册一个新的命令。 - - - -* **参数** - - - * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 - - - * `**kwargs`: 其他传递给 `on_command` 的参数,将会覆盖命令组默认值 - - - -* **返回** - - - * `Type[Matcher]` - - - -## `load_plugin(module_path)` - - -* **说明** - - 使用 `importlib` 加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。 - - - -* **参数** - - - * `module_path: str`: 插件名称 `path.to.your.plugin` - - - -* **返回** - - - * `Optional[Plugin]` - - - -## `load_plugins(*plugin_dir)` - - -* **说明** - - 导入目录下多个插件,以 `_` 开头的插件不会被导入! - - - -* **参数** - - - * `*plugin_dir: str`: 插件路径 - - - -* **返回** - - - * `Set[Plugin]` - - - -## `load_builtin_plugins()` - - -* **说明** - - 导入 NoneBot 内置插件 - - - -* **返回** - - - * `Plugin` - - - -## `get_loaded_plugins()` - - -* **说明** - - 获取当前已导入的插件。 - - - -* **返回** - - - * `Set[Plugin]` diff --git a/archive/2.0.0a6/api/sched.md b/archive/2.0.0a6/api/sched.md deleted file mode 100644 index 450fd7d0..00000000 --- a/archive/2.0.0a6/api/sched.md +++ /dev/null @@ -1,41 +0,0 @@ ---- -contentSidebar: true -sidebarDepth: 0 ---- - -# NoneBot.sched 模块 - -## 计划任务 - -计划任务使用第三方库 [APScheduler](https://github.com/agronholm/apscheduler) ,使用文档请参考 [APScheduler使用文档](https://apscheduler.readthedocs.io/en/latest/) 。 - - -## `scheduler` - - -* **类型** - - `Optional[apscheduler.schedulers.asyncio.AsyncIOScheduler]` - - - -* **说明** - - 当可选依赖 `APScheduler` 未安装时,`scheduler` 为 None - - 使用 `pip install nonebot[scheduler]` 安装可选依赖 - - - -* **常用示例** - - -```python -from nonebot import scheduler - -@scheduler.scheduled_job("cron", hour="*/2", id="xxx", args=[1], kwargs={arg2: 2}) -async def run_every_2_hour(arg1, arg2): - pass - -scheduler.add_job(run_every_day_from_program_start, "interval", days=1, id="xxx") -``` diff --git a/archive/2.0.0a6/api/typing.md b/archive/2.0.0a6/api/typing.md deleted file mode 100644 index 8f8a2223..00000000 --- a/archive/2.0.0a6/api/typing.md +++ /dev/null @@ -1,300 +0,0 @@ ---- -contentSidebar: true -sidebarDepth: 0 ---- - -# NoneBot.typing 模块 - -## 类型 - -下面的文档中,「类型」部分使用 Python 的 Type Hint 语法,见 [PEP 484](https://www.python.org/dev/peps/pep-0484/)、[PEP 526](https://www.python.org/dev/peps/pep-0526/) 和 [typing](https://docs.python.org/3/library/typing.html)。 - -除了 Python 内置的类型,下面还出现了如下 NoneBot 自定类型,实际上它们是 Python 内置类型的别名。 - -以下类型均可从 nonebot.typing 模块导入。 - - -## `Driver` - - -* **类型** - - `BaseDriver` - - - -* **说明** - - 所有 Driver 的基类。 - - - - -## `WebSocket` - - -* **类型** - - `BaseWebSocket` - - - -* **说明** - - 所有 WebSocket 的基类。 - - - - -## `Bot` - - -* **类型** - - `BaseBot` - - - -* **说明** - - 所有 Bot 的基类。 - - - - -## `Event` - - -* **类型** - - `BaseEvent` - - - -* **说明** - - 所有 Event 的基类。 - - - - -## `Message` - - -* **类型** - - `BaseMessage` - - - -* **说明** - - 所有 Message 的基类。 - - - - -## `MessageSegment` - - -* **类型** - - `BaseMessageSegment` - - - -* **说明** - - 所有 MessageSegment 的基类。 - - - - -## `EventPreProcessor` - - -* **类型** - - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` - - - -* **说明** - - 事件预处理函数 EventPreProcessor 类型 - - - - -## `EventPostProcessor` - - -* **类型** - - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` - - - -* **说明** - - 事件预处理函数 EventPostProcessor 类型 - - - - -## `RunPreProcessor` - - -* **类型** - - `Callable[[Matcher, Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` - - - -* **说明** - - 事件响应器运行前预处理函数 RunPreProcessor 类型 - - - - -## `RunPostProcessor` - - -* **类型** - - `Callable[[Matcher, Optional[Exception], Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` - - - -* **说明** - - 事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在) - - - - -## `Matcher` - - -* **类型** - - `Matcher` - - - -* **说明** - - Matcher 即响应事件的处理类。通过 Rule 判断是否响应事件,运行 Handler。 - - - - -## `MatcherGroup` - - -* **类型** - - `MatcherGroup` - - - -* **说明** - - MatcherGroup 为 Matcher 的集合。可以共享 Handler。 - - - - -## `Rule` - - -* **类型** - - `Rule` - - - -* **说明** - - Rule 即判断是否响应事件的处理类。内部存储 RuleChecker ,返回全为 True 则响应事件。 - - - - -## `RuleChecker` - - -* **类型** - - `Callable[[Bot, Event, dict], Union[bool, Awaitable[bool]]]` - - - -* **说明** - - RuleChecker 即判断是否响应事件的处理函数。 - - - - -## `Permission` - - -* **类型** - - `Permission` - - - -* **说明** - - Permission 即判断是否响应消息的处理类。内部存储 PermissionChecker ,返回只要有一个 True 则响应消息。 - - - - -## `PermissionChecker` - - -* **类型** - - `Callable[[Bot, Event], Union[bool, Awaitable[bool]]]` - - - -* **说明** - - RuleChecker 即判断是否响应消息的处理函数。 - - - - -## `Handler` - - -* **类型** - - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` - - - -* **说明** - - Handler 即事件的处理函数。 - - - - -## `ArgsParser` - - -* **类型** - - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` - - - -* **说明** - - ArgsParser 即消息参数解析函数,在 Matcher.got 获取参数时被运行。 diff --git a/archive/2.0.0a6/guide/end-or-start.md b/archive/2.0.0a6/guide/end-or-start.md deleted file mode 100644 index 11780114..00000000 --- a/archive/2.0.0a6/guide/end-or-start.md +++ /dev/null @@ -1,9 +0,0 @@ -# 结语 - -至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示: - -- 请千万注意事件处理器的优先级设定 -- 在匹配规则中请勿使用耗时极长的函数 -- 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍) - -如果你还不能满足,前往 [进阶](../advanced/README.md) 获得更多的功能信息。 diff --git a/archive/2.0.0a6/guide/getting-started.md b/archive/2.0.0a6/guide/getting-started.md deleted file mode 100644 index 9c358ead..00000000 --- a/archive/2.0.0a6/guide/getting-started.md +++ /dev/null @@ -1,146 +0,0 @@ -# 开始使用 - -一切都安装成功后,你就已经做好了进行简单配置以运行一个最小的 NoneBot 实例的准备。 - -## 最小实例 - -使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下: - -```python{3,4,7} -import nonebot - -nonebot.init() -nonebot.load_builtin_plugins() - -if __name__ == "__main__": - nonebot.run() -``` - -这几行高亮代码将依次: - -1. 使用默认配置初始化 NoneBot 包 -2. 加载 NoneBot 内置的插件 -3. 在地址 `127.0.0.1:8080` 运行 NoneBot - -在命令行使用如下命令即可运行这个 NoneBot 实例: - -```bash -python bot.py -``` - -运行后会产生如下日志: - -```default -09-14 21:02:00 [INFO] nonebot | Succeeded to import "nonebot.plugins.base" -09-14 21:02:00 [INFO] nonebot | Running NoneBot... -09-14 21:02:00 [INFO] uvicorn | Started server process [1234] -09-14 21:02:00 [INFO] uvicorn | Waiting for application startup. -09-14 21:02:00 [INFO] nonebot | Scheduler Started -09-14 21:02:00 [INFO] uvicorn | Application startup complete. -09-14 21:02:00 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit) -``` - -## 配置 QQ 协议端 - -单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 - -目前支持的协议有: - -- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot) - -QQ 协议端举例: - -- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai) -- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded) -- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api) -- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo)) -- [OICQ-http-api](https://github.com/takayama-lily/onebot) (基于 [OICQ](https://github.com/takayama-lily/oicq)) - -这里以 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) 为例 - -1. 下载 go-cqhttp 对应平台的 release 文件 -2. 双击 exe 文件或者使用 `./go-cqhttp` 启动 -3. 生成默认配置文件并修改默认配置 - -```json{2,3,30-31} -{ - "uin": 你的QQ号, - "password": "你的密码", - "encrypt_password": false, - "password_encrypted": "", - "enable_db": true, - "access_token": "", - "relogin": { - "enabled": true, - "relogin_delay": 3, - "max_relogin_times": 0 - }, - "ignore_invalid_cqcode": false, - "force_fragmented": true, - "heartbeat_interval": 0, - "http_config": { - "enabled": false, - "host": "0.0.0.0", - "port": 5700, - "timeout": 0, - "post_urls": {} - }, - "ws_config": { - "enabled": false, - "host": "0.0.0.0", - "port": 6700 - }, - "ws_reverse_servers": [ - { - "enabled": true, - "reverse_url": "ws://127.0.0.1:8080/cqhttp/ws", - "reverse_api_url": "", - "reverse_event_url": "", - "reverse_reconnect_interval": 3000 - } - ], - "post_message_format": "string", - "debug": false, - "log_level": "" -} -``` - -其中 `ws://127.0.0.1:8080/cqhttp/ws` 中的 `127.0.0.1` 和 `8080` 应分别对应 nonebot 配置的 HOST 和 PORT - -## 历史性的第一次对话 - -一旦新的配置文件正确生效之后,NoneBot 所在的控制台(如果正在运行的话)应该会输出类似下面的内容(两条访问日志): - -```default -09-14 21:31:16 [INFO] uvicorn | ('127.0.0.1', 12345) - "WebSocket /cqhttp/ws" [accepted] -09-14 21:31:16 [INFO] nonebot | WebSocket Connection from CQHTTP Bot 你的QQ号 Accepted! -``` - -这表示 QQ 协议端已经成功地使用 CQHTTP 协议连接上了 NoneBot。 - -:::warning 注意 -如果到这一步你没有看到上面这样的成功日志,CQHTTP 的日志中在不断地重连或无反应,请注意检查配置中的 IP 和端口是否确实可以访问。比较常见的出错点包括: - -- NoneBot 监听 `0.0.0.0`,然后在 CQHTTP 配置中填了 `ws://0.0.0.0:8080/cqhttp/ws` -- 在 Docker 容器内运行 CQHTTP,并通过 `127.0.0.1` 访问宿主机上的 NoneBot -- 想从公网访问,但没有修改云服务商的安全组策略或系统防火墙 -- NoneBot 所监听的端口存在冲突,已被其它程序占用 -- 弄混了 NoneBot 的 `host`、`port` 参数与 CQHTTP 配置中的 `host`、`port` 参数 -- 使用了 `ws_reverse_api_url` 和 `ws_reverse_event_url` 而非 universal client -- `ws://` 错填为 `http://` -- CQHTTP 或 NoneBot 启动时遭到外星武器干扰 - -请尝试重启 CQHTTP、重启 NoneBot、更换端口、修改防火墙、重启系统、仔细阅读前面的文档及提示、更新 CQHTTP 和 NoneBot 到最新版本等方式来解决。 -::: - -现在,尝试向你的 QQ 机器人账号发送如下内容: - -```default -/echo 你好,世界 -``` - -到这里如果一切 OK,你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅! - - - - diff --git a/archive/2.0.0a6/guide/installation.md b/archive/2.0.0a6/guide/installation.md deleted file mode 100644 index 907630c9..00000000 --- a/archive/2.0.0a6/guide/installation.md +++ /dev/null @@ -1,85 +0,0 @@ -# 安装 - -## NoneBot - -:::warning 注意 -请确保你的 Python 版本 >= 3.7。 -::: - -请在安装 nonebot2 之前卸载 nonebot 1.x - -```bash -pip uninstall nonebot -pip install nonebot2 -``` - -如果你需要使用最新的(可能尚未发布的)特性,可以直接从 GitHub 仓库安装: - -```bash -# master -poetry add git+https://github.com/nonebot/nonebot2.git#master -# dev -poetry add git+https://github.com/nonebot/nonebot2.git#dev -``` - -或者克隆 Git 仓库后手动安装: - -```bash -git clone https://github.com/nonebot/nonebot2.git -cd nonebot2 -poetry install --no-dev # 推荐 -pip install . # 不推荐 -``` - -## 额外依赖 - -### APScheduler - -A task scheduling library for Python. - -可用于计划任务,后台执行任务等 - -```bash -pip install nonebot2[scheduler] -poetry add nonebot2[scheduler] -``` - -[View On GitHub](https://github.com/agronholm/apscheduler) - -### NoneBot-Test - -A test frontend for nonebot2. - -通过前端展示 nonebot 已加载的插件以及运行状态,同时可以用于模拟发送事件测试机器人 - -```bash -pip install nonebot2[test] -poetry add nonebot2[test] -``` - -[View On GitHub](https://github.com/nonebot/nonebot-test) - -### CLI - -CLI for nonebot2. - -一个多功能脚手架 - -```bash -pip install nonebot2[cli] -poetry add nonebot2[cli] -``` - -[View On GitHub](https://github.com/yanyongyu/nb-cli) - -### 我全都要 - -```bash -pip install nonebot2[full] -poetry add nonebot2[full] -``` - -```bash -pip install nonebot2[cli,scheduler] -poetry add nonebot2[cli,scheduler] -``` diff --git a/archive/2.0.0a6/README.md b/archive/2.0.0a8/README.md similarity index 86% rename from archive/2.0.0a6/README.md rename to archive/2.0.0a8/README.md index a1607904..78cb0fc4 100644 --- a/archive/2.0.0a6/README.md +++ b/archive/2.0.0a8/README.md @@ -1,7 +1,7 @@ --- home: true heroImage: /logo.png -tagline: An asynchronous QQ bot framework. +tagline: An asynchronous bot framework. actionText: 开始使用 actionLink: guide/ features: @@ -11,5 +11,5 @@ features: details: 精心设计的消息处理流程使得你可以很方便地将原型扩充为具有大量实用功能的完整聊天机器人,并持续保证扩展性。 - title: 高性能 details: 采用异步 I/O,利用 WebSocket 进行通信,以获得极高的性能;同时,支持使用多账号同时接入,减少业务宕机的可能。 -footer: MIT Licensed | Copyright © 2020 NoneBot Team +footer: MIT Licensed | Copyright © 2018 - 2020 NoneBot Team --- diff --git a/archive/2.0.0a6/advanced/README.md b/archive/2.0.0a8/advanced/README.md similarity index 100% rename from archive/2.0.0a6/advanced/README.md rename to archive/2.0.0a8/advanced/README.md diff --git a/archive/2.0.0a8/advanced/export-and-require.md b/archive/2.0.0a8/advanced/export-and-require.md new file mode 100644 index 00000000..832b0e75 --- /dev/null +++ b/archive/2.0.0a8/advanced/export-and-require.md @@ -0,0 +1 @@ +# 跨插件访问 diff --git a/archive/2.0.0a8/advanced/overloaded-handlers.md b/archive/2.0.0a8/advanced/overloaded-handlers.md new file mode 100644 index 00000000..97ff3116 --- /dev/null +++ b/archive/2.0.0a8/advanced/overloaded-handlers.md @@ -0,0 +1 @@ +# 事件处理函数重载 diff --git a/archive/2.0.0a8/advanced/permission.md b/archive/2.0.0a8/advanced/permission.md new file mode 100644 index 00000000..7190bcdd --- /dev/null +++ b/archive/2.0.0a8/advanced/permission.md @@ -0,0 +1 @@ +# 权限控制 diff --git a/archive/2.0.0a8/advanced/publish-plugin.md b/archive/2.0.0a8/advanced/publish-plugin.md new file mode 100644 index 00000000..68e2e6f9 --- /dev/null +++ b/archive/2.0.0a8/advanced/publish-plugin.md @@ -0,0 +1 @@ +# 发布插件 diff --git a/archive/2.0.0a8/advanced/runtime-hook.md b/archive/2.0.0a8/advanced/runtime-hook.md new file mode 100644 index 00000000..58bca681 --- /dev/null +++ b/archive/2.0.0a8/advanced/runtime-hook.md @@ -0,0 +1 @@ +# 运行时插槽 diff --git a/archive/2.0.0a8/advanced/scheduler.md b/archive/2.0.0a8/advanced/scheduler.md new file mode 100644 index 00000000..86280b5f --- /dev/null +++ b/archive/2.0.0a8/advanced/scheduler.md @@ -0,0 +1,127 @@ +# 定时任务 + +[`APScheduler`](https://apscheduler.readthedocs.io/en/latest/index.html) —— 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. + +## 从 v1 迁移 + +`APScheduler` 作为 `nonebot` v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。`nonebot2` 已将 `APScheduler` 独立为 `nonebot_plugin_apscheduler` 插件,你可以在 [插件广场](https://v2.nonebot.dev/plugin-store.html) 中找到它。 + +相比于 `nonebot` v1 ,只需要安装插件并修改 `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` 从 `nonebot_plugin_apscheduler` 导入 `scheduler` 对象 + +2. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务 + +将上述步骤归纳为最小实现的代码如下: + +```python +from nonebot import require + +scheduler = require('nonebot_plugin_apscheduler').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` 方法来实现导入其他插件的内容,此处我们使用这个方法来导入 `scheduler` 对象。 + +`nonebot` 使用的 `scheduler` 对象为 `AsyncScheduler` 。 + +> 使用该方法传入的插件本身也需要有对应实现,关于该方法的更多介绍可以参阅 [这里](./export-and-require.md) + +```python +from nonebot import require + +scheduler = require('nonebot_plugin_apscheduler').scheduler +``` + +### 编写定时任务 + +由于本部分为标准的通过 `APScheduler` 配置定时任务,有关指南请参阅 [APScheduler 官方文档](https://apscheduler.readthedocs.io/en/latest/userguide.html#adding-jobs)。 + +### 配置插件选项 + +根据项目的 `.env` 文件设置,向 `.env.*` 或 `bot.py` 文件添加 `nonebot_plugin_apscheduler` 的可选配置项 + +:::warning 注意 +`.env.*` 文件的编写应遵循 nonebot2 对 `.env.*` 文件的编写要求 +::: + +#### `apscheduler_autostart` + +类型:`bool` + +默认值:`True` + +是否自动启动 `APScheduler`。 + +对于大多数情况,我们需要在 `nonebot2` 项目被启动时启动定时任务,则此处设为 `true` + +```bash +APSCHEDULER_AUTOSTART=true +``` + +```python +nonebot.init(apscheduler_autostart=True) +``` + +#### `apscheduler_config` + +类型:`dict` + +默认值:`{"apscheduler.timezone": "Asia/Shanghai"}` + +`APScheduler` 相关配置。修改/增加其中配置项需要确保 `prefix: apscheduler`。 + +对于 `APScheduler` 的相关配置,请参阅 [scheduler-config](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-config) 和 [BaseScheduler](https://apscheduler.readthedocs.io/en/latest/modules/schedulers/base.html#apscheduler.schedulers.base.BaseScheduler) + +> 官方文档在绝大多数时候能提供最准确和最具时效性的指南 + +```bash +APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"} +``` + +```python +nonebot.init(apscheduler_config={ + "apscheduler.timezone": "Asia/Shanghai" +}) +``` diff --git a/archive/2.0.0a6/api/README.md b/archive/2.0.0a8/api/README.md similarity index 92% rename from archive/2.0.0a6/api/README.md rename to archive/2.0.0a8/api/README.md index 75132b72..243733f8 100644 --- a/archive/2.0.0a6/api/README.md +++ b/archive/2.0.0a8/api/README.md @@ -25,9 +25,6 @@ * [nonebot.permission](permission.html) - * [nonebot.sched](sched.html) - - * [nonebot.log](log.html) @@ -50,3 +47,6 @@ * [nonebot.adapters.cqhttp](adapters/cqhttp.html) + + + * [nonebot.adapters.ding](adapters/ding.html) diff --git a/archive/2.0.0a6/api/adapters/README.md b/archive/2.0.0a8/api/adapters/README.md similarity index 61% rename from archive/2.0.0a6/api/adapters/README.md rename to archive/2.0.0a8/api/adapters/README.md index c2d2e399..96638ad5 100644 --- a/archive/2.0.0a6/api/adapters/README.md +++ b/archive/2.0.0a8/api/adapters/README.md @@ -10,7 +10,7 @@ sidebarDepth: 0 各协议请继承以下基类,并使用 `driver.register_adapter` 注册适配器 -## _class_ `BaseBot` +## _class_ `Bot` 基类:`abc.ABC` @@ -147,7 +147,7 @@ Adapter 类型 ```python -await bot.call_api("send_msg", message="hello world"}) +await bot.call_api("send_msg", message="hello world") await bot.send_msg(message="hello world") ``` @@ -174,104 +174,7 @@ await bot.send_msg(message="hello world") -## _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` +## _class_ `MessageSegment` 基类:`abc.ABC` @@ -296,7 +199,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * 说明: 消息段数据 -## _class_ `BaseMessage` +## _class_ `Message` 基类:`list`, `abc.ABC` @@ -309,7 +212,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **参数** - * `message: Union[str, dict, list, MessageSegment, Message]`: 消息内容 + * `message: Union[str, list, dict, MessageSegment, Message, Any]`: 消息内容 @@ -350,7 +253,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **说明** - 缩减消息数组,即拼接相邻纯文本消息段 + 缩减消息数组,即按 MessageSegment 的实现拼接相邻消息段 @@ -360,3 +263,161 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **说明** 提取消息内纯文本消息 + + + +## _class_ `Event` + +基类:`abc.ABC`, `pydantic.main.BaseModel` + +Event 基类。提供获取关键信息的方法,其余信息可直接获取。 + + +### _abstract_ `get_type()` + + +* **说明** + + 获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。 + + + +* **返回** + + + * `Literal["message", "notice", "request", "meta_event"]` + + + +### _abstract_ `get_event_name()` + + +* **说明** + + 获取事件名称的方法。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_event_description()` + + +* **说明** + + 获取事件描述的方法,通常为事件具体内容。 + + + +* **返回** + + + * `str` + + + +### `get_log_string()` + + +* **说明** + + 获取事件日志信息的方法,通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 `NoLogException` 异常。 + + + +* **返回** + + + * `str` + + + +* **异常** + + + * `NoLogException` + + + +### _abstract_ `get_user_id()` + + +* **说明** + + 获取事件主体 id 的方法,通常是用户 id 。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_session_id()` + + +* **说明** + + 获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_message()` + + +* **说明** + + 获取事件消息内容的方法。 + + + +* **返回** + + + * `Message` + + + +### `get_plaintext()` + + +* **说明** + + 获取消息纯文本的方法,通常不需要修改,默认通过 `get_message().extract_plain_text` 获取。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `is_tome()` + + +* **说明** + + 获取事件是否与机器人有关的方法。 + + + +* **返回** + + + * `bool` diff --git a/archive/2.0.0a8/api/adapters/cqhttp.md b/archive/2.0.0a8/api/adapters/cqhttp.md new file mode 100644 index 00000000..ca5d91cb --- /dev/null +++ b/archive/2.0.0a8/api/adapters/cqhttp.md @@ -0,0 +1,564 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.cqhttp 模块 + +## CQHTTP (OneBot) v11 协议适配 + +协议详情请看: [CQHTTP](https://github.com/howmanybots/onebot/blob/master/README.md) | [OneBot](https://github.com/howmanybots/onebot/blob/master/README.md) + +# NoneBot.adapters.cqhttp.utils 模块 + + +## `escape(s, *, escape_comma=True)` + + +* **说明** + + 对字符串进行 CQ 码转义。 + + + +* **参数** + + + * `s: str`: 需要转义的字符串 + + + * `escape_comma: bool`: 是否转义逗号(`,`)。 + + + +## `unescape(s)` + + +* **说明** + + 对字符串进行 CQ 码去转义。 + + + +* **参数** + + + * `s: str`: 需要转义的字符串 + + +# NoneBot.adapters.cqhttp.exception 模块 + + +## _exception_ `ActionFailed` + +基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException` + + +* **说明** + + API 请求返回错误信息。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + + +## _exception_ `NetworkError` + +基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException` + + +* **说明** + + 网络错误。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + +# NoneBot.adapters.cqhttp.bot 模块 + + +## _async_ `_check_reply(bot, event)` + + +* **说明** + + 检查消息中存在的回复,去除并赋值 `event.reply`, `event.to_me` + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + +## `_check_at_me(bot, event)` + + +* **说明** + + 检查消息开头或结尾是否存在 @机器人,去除并赋值 `event.to_me` + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + +## `_check_nickname(bot, event)` + + +* **说明** + + 检查消息开头是否存在,去除并赋值 `event.to_me` + + + +* **参数** + + + * `bot: Bot`: Bot 对象 + + + * `event: Event`: Event 对象 + + + +## `_handle_api_result(result)` + + +* **说明** + + 处理 API 请求返回值。 + + + +* **参数** + + + * `result: Optional[Dict[str, Any]]`: API 返回数据 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `ActionFailed`: API 调用失败 + + + +## _class_ `Bot` + +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) + +CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 + + +### _property_ `type` + + +* 返回: `"cqhttp"` + + +### _async classmethod_ `check_permission(driver, connection_type, headers, body)` + + +* **说明** + + CQHTTP (OneBot) 协议鉴权。参考 [鉴权](https://github.com/howmanybots/onebot/blob/master/v11/specs/communication/authorization.md) + + + +### _async_ `handle_message(message)` + + +* **说明** + + 调用 [_check_reply](#async-check-reply-bot-event), [_check_at_me](#check-at-me-bot-event), [_check_nickname](#check-nickname-bot-event) 处理事件并转换为 [Event](#class-event) + + + +### _async_ `call_api(api, **data)` + + +* **说明** + + 调用 CQHTTP 协议 API + + + +* **参数** + + + * `api: str`: API 名称 + + + * `**data: Any`: API 参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + + +### _async_ `send(event, message, at_sender=False, **kwargs)` + + +* **说明** + + 根据 `event` 向触发事件的主体发送消息。 + + + +* **参数** + + + * `event: Event`: Event 对象 + + + * `message: Union[str, Message, MessageSegment]`: 要发送的消息 + + + * `at_sender: bool`: 是否 @ 事件主体 + + + * `**kwargs`: 覆盖默认参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `ValueError`: 缺少 `user_id`, `group_id` + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + +# NoneBot.adapters.cqhttp.message 模块 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) + +CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + + +## _class_ `Message` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +CQHTTP 协议 Message 适配。 + +# NoneBot.adapters.cqhttp.permission 模块 + + +## `PRIVATE` + + +* **说明**: 匹配任意私聊消息类型事件 + + +## `PRIVATE_FRIEND` + + +* **说明**: 匹配任意好友私聊消息类型事件 + + +## `PRIVATE_GROUP` + + +* **说明**: 匹配任意群临时私聊消息类型事件 + + +## `PRIVATE_OTHER` + + +* **说明**: 匹配任意其他私聊消息类型事件 + + +## `GROUP` + + +* **说明**: 匹配任意群聊消息类型事件 + + +## `GROUP_MEMBER` + + +* **说明**: 匹配任意群员群聊消息类型事件 + +:::warning 警告 +该权限通过 event.sender 进行判断且不包含管理员以及群主! +::: + + +## `GROUP_ADMIN` + + +* **说明**: 匹配任意群管理员群聊消息类型事件 + + +## `GROUP_OWNER` + + +* **说明**: 匹配任意群主群聊消息类型事件 + +# NoneBot.adapters.cqhttp.event 模块 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +CQHTTP 协议事件,字段与 CQHTTP 一致。各事件字段参考 [CQHTTP 文档](https://github.com/howmanybots/onebot/blob/master/README.md) + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +消息事件 + + +### `to_me` + + +* **说明** + + 消息是否与机器人有关 + + + +* **类型** + + `bool` + + + +### `reply` + + +* **说明** + + 消息中提取的回复消息,内容为 `get_msg` API 返回结果 + + + +* **类型** + + `Optional[Reply]` + + + +## _class_ `PrivateMessageEvent` + +基类:`nonebot.adapters.cqhttp.event.MessageEvent` + +私聊消息 + + +## _class_ `GroupMessageEvent` + +基类:`nonebot.adapters.cqhttp.event.MessageEvent` + +群消息 + + +## _class_ `NoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +通知事件 + + +## _class_ `GroupUploadNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群文件上传事件 + + +## _class_ `GroupAdminNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群管理员变动 + + +## _class_ `GroupDecreaseNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群成员减少事件 + + +## _class_ `GroupIncreaseNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群成员增加事件 + + +## _class_ `GroupBanNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群禁言事件 + + +## _class_ `FriendAddNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +好友添加事件 + + +## _class_ `GroupRecallNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群消息撤回事件 + + +## _class_ `FriendRecallNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +好友消息撤回事件 + + +## _class_ `NotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +提醒事件 + + +## _class_ `PokeNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +戳一戳提醒事件 + + +## _class_ `LuckyKingNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +群红包运气王提醒事件 + + +## _class_ `HonorNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +群荣誉变更提醒事件 + + +## _class_ `RequestEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +请求事件 + + +## _class_ `FriendRequestEvent` + +基类:`nonebot.adapters.cqhttp.event.RequestEvent` + +加好友请求事件 + + +## _class_ `GroupRequestEvent` + +基类:`nonebot.adapters.cqhttp.event.RequestEvent` + +加群请求/邀请事件 + + +## _class_ `MetaEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +元事件 + + +## _class_ `LifecycleMetaEvent` + +基类:`nonebot.adapters.cqhttp.event.MetaEvent` + +生命周期元事件 + + +## _class_ `HeartbeatMetaEvent` + +基类:`nonebot.adapters.cqhttp.event.MetaEvent` + +心跳元事件 + + +## `get_event_model(event_name)` + + +* **说明** + + 根据事件名获取对应 `Event Model` 及 `FallBack Event Model` 列表 + + + +* **返回** + + + * `List[Type[Event]]` diff --git a/archive/2.0.0a8/api/adapters/ding.md b/archive/2.0.0a8/api/adapters/ding.md new file mode 100644 index 00000000..32fbb891 --- /dev/null +++ b/archive/2.0.0a8/api/adapters/ding.md @@ -0,0 +1,293 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.adapters.ding 模块 + +## 钉钉群机器人 协议适配 + +协议详情请看: [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) + +# NoneBot.adapters.ding.exception 模块 + + +## _exception_ `DingAdapterException` + +基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException) + + +* **说明** + + 钉钉 Adapter 错误基类 + + + +## _exception_ `ActionFailed` + +基类:[`nonebot.exception.ActionFailed`](../exception.md#nonebot.exception.ActionFailed), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + API 请求返回错误信息。 + + + +* **参数** + + + * `errcode: Optional[int]`: 错误码 + + + * `errmsg: Optional[str]`: 错误信息 + + + +## _exception_ `NetworkError` + +基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 网络错误。 + + + +* **参数** + + + * `retcode: Optional[int]`: 错误码 + + + +## _exception_ `SessionExpired` + +基类:`nonebot.adapters.ding.exception.ApiNotAvailable`, `nonebot.adapters.ding.exception.DingAdapterException` + + +* **说明** + + 发消息的 session 已经过期。 + + +# NoneBot.adapters.ding.bot 模块 + + +## _class_ `Bot` + +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) + +钉钉 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 + + +### _property_ `type` + + +* 返回: `"ding"` + + +### _async classmethod_ `check_permission(driver, connection_type, headers, body)` + + +* **说明** + + 钉钉协议鉴权。参考 [鉴权](https://ding-doc.dingtalk.com/doc#/serverapi2/elzz1p) + + + +### _async_ `call_api(api, event=None, **data)` + + +* **说明** + + 调用 钉钉 协议 API + + + +* **参数** + + + * `api: str`: API 名称 + + + * `**data: Any`: API 参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + + +### _async_ `send(event, message, at_sender=False, **kwargs)` + + +* **说明** + + 根据 `event` 向触发事件的主体发送消息。 + + + +* **参数** + + + * `event: Event`: Event 对象 + + + * `message: Union[str, Message, MessageSegment]`: 要发送的消息 + + + * `at_sender: bool`: 是否 @ 事件主体 + + + * `**kwargs`: 覆盖默认参数 + + + +* **返回** + + + * `Any`: API 调用返回数据 + + + +* **异常** + + + * `ValueError`: 缺少 `user_id`, `group_id` + + + * `NetworkError`: 网络错误 + + + * `ActionFailed`: API 调用失败 + + +# NoneBot.adapters.ding.message 模块 + + +## _class_ `MessageSegment` + +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) + +钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 + + +### _static_ `atAll()` + +@全体 + + +### _static_ `atMobiles(*mobileNumber)` + +@指定手机号人员 + + +### _static_ `text(text)` + +发送 `text` 类型消息 + + +### _static_ `image(picURL)` + +发送 `image` 类型消息 + + +### _static_ `extension(dict_)` + +"标记 text 文本的 extension 属性,需要与 text 消息段相加。 + + +### _static_ `markdown(title, text)` + +发送 `markdown` 类型消息 + + +### _static_ `actionCardSingleBtn(title, text, singleTitle, singleURL)` + +发送 `actionCardSingleBtn` 类型消息 + + +### _static_ `actionCardMultiBtns(title, text, btns, hideAvatar=False, btnOrientation='1')` + +发送 `actionCardMultiBtn` 类型消息 + + +* **参数** + + + * `btnOrientation`: 0:按钮竖直排列 1:按钮横向排列 + + + * `btns`: [{ "title": title, "actionURL": actionURL }, ...] + + + +### _static_ `feedCard(links)` + +发送 `feedCard` 类型消息 + + +* **参数** + + + * `links`: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...] + + + +## _class_ `Message` + +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) + +钉钉 协议 Message 适配。 + +# NoneBot.adapters.ding.event 模块 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +钉钉协议事件。各事件字段参考 [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) + + +## _class_ `ConversationType` + +基类:`str`, `enum.Enum` + +An enumeration. + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.ding.event.Event` + +消息事件 + + +## _class_ `PrivateMessageEvent` + +基类:`nonebot.adapters.ding.event.MessageEvent` + +私聊消息事件 + + +## _class_ `GroupMessageEvent` + +基类:`nonebot.adapters.ding.event.MessageEvent` + +群消息事件 diff --git a/archive/2.0.0a8/api/config.md b/archive/2.0.0a8/api/config.md new file mode 100644 index 00000000..2e7c6a4d --- /dev/null +++ b/archive/2.0.0a8/api/config.md @@ -0,0 +1,285 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.config 模块 + +## 配置 + +NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 以及 [python-dotenv](https://saurabh-kumar.com/python-dotenv/) 来读取配置。 + +配置项需符合特殊格式或 json 序列化格式。详情见 [pydantic Field Type](https://pydantic-docs.helpmanual.io/usage/types/) 文档。 + + +## _class_ `Env` + +基类:`pydantic.env_settings.BaseSettings` + +运行环境配置。大小写不敏感。 + +将会从 `nonebot.init 参数` > `环境变量` > `.env 环境配置文件` 的优先级读取配置。 + + +### `environment` + + +* **类型**: `str` + + +* **默认值**: `"prod"` + + +* **说明** + + 当前环境名。 NoneBot 将从 `.env.{environment}` 文件中加载配置。 + + + +## _class_ `Config` + +基类:`nonebot.config.BaseConfig` + +NoneBot 主要配置。大小写不敏感。 + +除了 NoneBot 的配置项外,还可以自行添加配置项到 `.env.{environment}` 文件中。 +这些配置将会在 json 反序列化后一起带入 `Config` 类中。 + + +### `driver` + + +* **类型**: `str` + + +* **默认值**: `"nonebot.drivers.fastapi"` + + +* **说明** + + NoneBot 运行所使用的 `Driver` 。继承自 `nonebot.driver.BaseDriver` 。 + + + +### `host` + + +* **类型**: `IPvAnyAddress` + + +* **默认值**: `127.0.0.1` + + +* **说明** + + NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。 + + + +### `port` + + +* **类型**: `int` + + +* **默认值**: `8080` + + +* **说明** + + NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。 + + + +### `debug` + + +* **类型**: `bool` + + +* **默认值**: `False` + + +* **说明** + + 是否以调试模式运行 NoneBot。 + + + +### `api_root` + + +* **类型**: `Dict[str, str]` + + +* **默认值**: `{}` + + +* **说明** + + 以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。 + + + +* **示例** + + +```default +API_ROOT={"123456": "http://127.0.0.1:5700"} +``` + + +### `api_timeout` + + +* **类型**: `Optional[float]` + + +* **默认值**: `30.` + + +* **说明** + + API 请求超时时间,单位: 秒。 + + + +### `access_token` + + +* **类型**: `Optional[str]` + + +* **默认值**: `None` + + +* **说明** + + API 请求以及上报所需密钥,在请求头中携带。 + + + +* **示例** + + +```http +POST /cqhttp/ HTTP/1.1 +Authorization: Bearer kSLuTF2GC2Q4q4ugm3 +``` + + +### `secret` + + +* **类型**: `Optional[str]` + + +* **默认值**: `None` + + +* **说明** + + HTTP POST 形式上报所需签名,在请求头中携带。 + + + +* **示例** + + +```http +POST /cqhttp/ HTTP/1.1 +X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 +``` + + +### `superusers` + + +* **类型**: `Set[str]` + + +* **默认值**: `set()` + + +* **说明** + + 机器人超级用户。 + + + +* **示例** + + +```default +SUPER_USERS=["12345789"] +``` + + +### `nickname` + + +* **类型**: `Set[str]` + + +* **默认值**: `set()` + + +* **说明** + + 机器人昵称。 + + + +### `command_start` + + +* **类型**: `Set[str]` + + +* **默认值**: `{"/"}` + + +* **说明** + + 命令的起始标记,用于判断一条消息是不是命令。 + + + +### `command_sep` + + +* **类型**: `Set[str]` + + +* **默认值**: `{"."}` + + +* **说明** + + 命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。 + + + +### `session_expire_timeout` + + +* **类型**: `timedelta` + + +* **默认值**: `timedelta(minutes=2)` + + +* **说明** + + 等待用户回复的超时时间。 + + + +* **示例** + + +```default +SESSION_EXPIRE_TIMEOUT=120 # 单位: 秒 +SESSION_EXPIRE_TIMEOUT=[DD ][HH:MM]SS[.ffffff] +SESSION_EXPIRE_TIMEOUT=P[DD]DT[HH]H[MM]M[SS]S # ISO 8601 +``` diff --git a/archive/2.0.0a6/api/drivers/README.md b/archive/2.0.0a8/api/drivers/README.md similarity index 73% rename from archive/2.0.0a6/api/drivers/README.md rename to archive/2.0.0a8/api/drivers/README.md index 624220ba..313717cb 100644 --- a/archive/2.0.0a6/api/drivers/README.md +++ b/archive/2.0.0a8/api/drivers/README.md @@ -10,7 +10,7 @@ sidebarDepth: 0 各驱动请继承以下基类 -## _class_ `BaseDriver` +## _class_ `Driver` 基类:`abc.ABC` @@ -32,6 +32,36 @@ Driver 基类。将后端框架封装,以满足适配器使用。 +### `_ws_connection_hook` + + +* **类型** + + `Set[T_WebSocketConnectionHook]` + + + +* **说明** + + WebSocket 连接建立时执行的函数 + + + +### `_ws_disconnection_hook` + + +* **类型** + + `Set[T_WebSocketDisconnectionHook]` + + + +* **说明** + + WebSocket 连接断开时执行的函数 + + + ### _abstract_ `__init__(env, config)` @@ -154,6 +184,48 @@ Driver 基类。将后端框架封装,以满足适配器使用。 注册一个在驱动停止时运行的函数 +### `on_bot_connect(func)` + + +* **说明** + + 装饰一个函数使他在 bot 通过 WebSocket 连接成功时执行。 + + + +* **函数参数** + + + * `bot: Bot`: 当前连接上的 Bot 对象 + + + +### `on_bot_disconnect(func)` + + +* **说明** + + 装饰一个函数使他在 bot 通过 WebSocket 连接断开时执行。 + + + +* **函数参数** + + + * `bot: Bot`: 当前连接上的 Bot 对象 + + + +### `_bot_connect(bot)` + +在 WebSocket 连接成功后,调用该函数来注册 bot 对象 + + +### `_bot_disconnect(bot)` + +在 WebSocket 连接断开后,调用该函数来注销 bot 对象 + + ### _abstract_ `run(host=None, port=None, *args, **kwargs)` @@ -189,7 +261,7 @@ Driver 基类。将后端框架封装,以满足适配器使用。 用于处理 WebSocket 类型请求的函数 -## _class_ `BaseWebSocket` +## _class_ `WebSocket` 基类:`object` diff --git a/archive/2.0.0a6/api/drivers/fastapi.md b/archive/2.0.0a8/api/drivers/fastapi.md similarity index 50% rename from archive/2.0.0a6/api/drivers/fastapi.md rename to archive/2.0.0a8/api/drivers/fastapi.md index 1f7f96ee..edd8e474 100644 --- a/archive/2.0.0a6/api/drivers/fastapi.md +++ b/archive/2.0.0a8/api/drivers/fastapi.md @@ -12,11 +12,27 @@ sidebarDepth: 0 ## _class_ `Driver` -基类:[`nonebot.drivers.BaseDriver`](README.md#nonebot.drivers.BaseDriver) +基类:[`nonebot.drivers.Driver`](README.md#nonebot.drivers.Driver) FastAPI 驱动框架 +* **上报地址** + + + * `/{adapter name}/`: HTTP POST 上报 + + + * `/{adapter name}/http/`: HTTP POST 上报 + + + * `/{adapter name}/ws`: WebSocket 上报 + + + * `/{adapter name}/ws/`: WebSocket 上报 + + + ### _property_ `type` 驱动名称: `fastapi` @@ -50,53 +66,3 @@ fastapi 使用的 logger ### `run(host=None, port=None, *, app=None, **kwargs)` 使用 `uvicorn` 启动 FastAPI - - -### _async_ `_handle_http(adapter, request, data=Body(Ellipsis))` - -用于处理 HTTP 类型请求的函数 - - -### _async_ `_handle_ws_reverse(adapter, websocket)` - -用于处理 WebSocket 类型请求的函数 - - -## _class_ `WebSocket` - -基类:[`nonebot.drivers.BaseWebSocket`](README.md#nonebot.drivers.BaseWebSocket) - - -### _property_ `closed` - - -* **类型** - - `bool` - - - -* **说明** - - 连接是否已经关闭 - - - -### _async_ `accept()` - -接受 WebSocket 连接请求 - - -### _async_ `close(code=1000)` - -关闭 WebSocket 连接请求 - - -### _async_ `receive()` - -接收一条 WebSocket 信息 - - -### _async_ `send(data)` - -发送一条 WebSocket 信息 diff --git a/archive/2.0.0a6/api/exception.md b/archive/2.0.0a8/api/exception.md similarity index 68% rename from archive/2.0.0a6/api/exception.md rename to archive/2.0.0a8/api/exception.md index 0a9876a8..ac2d28b2 100644 --- a/archive/2.0.0a6/api/exception.md +++ b/archive/2.0.0a8/api/exception.md @@ -11,11 +11,22 @@ sidebarDepth: 0 这些异常并非所有需要用户处理,在 NoneBot 内部运行时被捕获,并进行对应操作。 -## _exception_ `IgnoredException` +## _exception_ `NoneBotException` 基类:`Exception` +* **说明** + + 所有 NoneBot 发生的异常基类。 + + + +## _exception_ `IgnoredException` + +基类:`nonebot.exception.NoneBotException` + + * **说明** 指示 NoneBot 应该忽略该事件。可由 PreProcessor 抛出。 @@ -31,7 +42,7 @@ sidebarDepth: 0 ## _exception_ `PausedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -49,7 +60,7 @@ sidebarDepth: 0 ## _exception_ `RejectedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -67,7 +78,7 @@ sidebarDepth: 0 ## _exception_ `FinishedException` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -85,7 +96,7 @@ sidebarDepth: 0 ## _exception_ `StopPropagation` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -102,7 +113,7 @@ sidebarDepth: 0 ## _exception_ `RequestDenied` -基类:`Exception` +基类:`nonebot.exception.NoneBotException` * **说明** @@ -121,11 +132,40 @@ sidebarDepth: 0 -## _exception_ `ApiNotAvailable` +## _exception_ `AdapterException` + +基类:`nonebot.exception.NoneBotException` + + +* **说明** + + 代表 `Adapter` 抛出的异常,所有的 `Adapter` 都要在内部继承自这个 `Exception` + + + +* **参数** + + + * `adapter_name: str`: 标识 adapter + + + +## _exception_ `NoLogException` 基类:`Exception` +* **说明** + + 指示 NoneBot 对当前 `Event` 进行处理但不显示 Log 信息,可在 `get_log_string` 时抛出 + + + +## _exception_ `ApiNotAvailable` + +基类:`nonebot.exception.AdapterException` + + * **说明** 在 API 连接不可用时抛出。 @@ -134,7 +174,7 @@ sidebarDepth: 0 ## _exception_ `NetworkError` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** @@ -145,16 +185,9 @@ sidebarDepth: 0 ## _exception_ `ActionFailed` -基类:`Exception` +基类:`nonebot.exception.AdapterException` * **说明** API 请求成功返回数据,但 API 操作失败。 - - - -* **参数** - - - * `retcode: Optional[int]`: 错误代码 diff --git a/archive/2.0.0a6/api/log.md b/archive/2.0.0a8/api/log.md similarity index 70% rename from archive/2.0.0a6/api/log.md rename to archive/2.0.0a8/api/log.md index 77ce3609..e6096cff 100644 --- a/archive/2.0.0a6/api/log.md +++ b/archive/2.0.0a8/api/log.md @@ -40,16 +40,3 @@ NoneBot 使用 [loguru](https://github.com/Delgan/loguru) 来记录日志信息 ```python from nonebot.log import logger ``` - - -## _class_ `LoguruHandler` - -基类:`logging.Handler` - - -### `emit(record)` - -Do whatever it takes to actually log the specified logging record. - -This version is intended to be implemented by subclasses and so -raises a NotImplementedError. diff --git a/archive/2.0.0a6/api/matcher.md b/archive/2.0.0a8/api/matcher.md similarity index 79% rename from archive/2.0.0a6/api/matcher.md rename to archive/2.0.0a8/api/matcher.md index b061cd64..22eabc3b 100644 --- a/archive/2.0.0a6/api/matcher.md +++ b/archive/2.0.0a8/api/matcher.md @@ -157,7 +157,7 @@ sidebarDepth: 0 * **类型** - `dict` + `T_State` @@ -167,12 +167,27 @@ sidebarDepth: 0 +### `_default_state_factory` + + +* **类型** + + `Optional[T_State]` + + + +* **说明** + + 事件响应器默认工厂函数 + + + ### `_default_parser` * **类型** - `Optional[ArgsParser]` + `Optional[T_ArgsParser]` @@ -192,7 +207,7 @@ sidebarDepth: 0 * **类型** - `List[Handler]` + `List[T_Handler]` @@ -202,7 +217,7 @@ sidebarDepth: 0 -### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` +### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, default_state_factory=None, expire_time=None)` * **说明** @@ -214,7 +229,7 @@ sidebarDepth: 0 * **参数** - * `type_: str`: 事件响应器类型,与 `event.type` 一致时触发,空字符串表示任意 + * `type_: str`: 事件响应器类型,与 `event.get_type()` 一致时触发,空字符串表示任意 * `rule: Optional[Rule]`: 匹配规则 @@ -223,7 +238,7 @@ sidebarDepth: 0 * `permission: Optional[Permission]`: 权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器,即触发一次后删除 @@ -238,7 +253,10 @@ sidebarDepth: 0 * `module: Optional[str]`: 事件响应器所在模块名称 - * `default_state: Optional[dict]`: 默认状态 `state` + * `default_state: Optional[T_State]`: 默认状态 `state` + + + * `default_state_factory: Optional[T_StateFactory]`: 默认状态 `state` 的工厂函数 * `expire_time: Optional[datetime]`: 事件响应器最终有效时间点,过时即被删除 @@ -296,7 +314,7 @@ sidebarDepth: 0 * `event: Event`: 上报事件 - * `state: dict`: 当前状态 + * `state: T_State`: 当前状态 @@ -319,7 +337,7 @@ sidebarDepth: 0 * **参数** - * `func: ArgsParser`: 参数解析函数 + * `func: T_ArgsParser`: 参数解析函数 @@ -373,7 +391,7 @@ sidebarDepth: 0 * `prompt: Optional[Union[str, Message, MessageSegment]]`: 在参数不存在时向用户发送的消息 - * `args_parser: Optional[ArgsParser]`: 可选参数解析函数,空则使用默认解析函数 + * `args_parser: Optional[T_ArgsParser]`: 可选参数解析函数,空则使用默认解析函数 @@ -450,48 +468,3 @@ sidebarDepth: 0 * `**kwargs`: 其他传递给 `bot.send` 的参数,请参考对应 adapter 的 bot 对象 api - - - -## _class_ `MatcherGroup` - -基类:`object` - -事件响应器组合,统一管理。用法同 `Matcher` - - -### `__init__(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` - - -* **说明** - - 创建一个事件响应器组合,参数为默认值,与 `Matcher.new` 一致 - - - -### `matchers` - - -* **类型** - - `List[Type[Matcher]]` - - - -* **说明** - - 组内事件响应器列表 - - - -### `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` - - -* **说明** - - 在组中创建一个新的事件响应器,参数留空则使用组合默认值 - - -:::danger 警告 -如果使用 handlers 参数覆盖组合默认值则该事件响应器不会随组合一起添加新的事件处理函数 -::: diff --git a/archive/2.0.0a6/api/message.md b/archive/2.0.0a8/api/message.md similarity index 91% rename from archive/2.0.0a6/api/message.md rename to archive/2.0.0a8/api/message.md index c9d7c158..5bd6c332 100644 --- a/archive/2.0.0a6/api/message.md +++ b/archive/2.0.0a8/api/message.md @@ -30,7 +30,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State @@ -54,7 +54,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前事件运行前 State + * `state: T_State`: 当前事件运行前 State @@ -81,7 +81,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State @@ -111,7 +111,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State diff --git a/archive/2.0.0a6/api/nonebot.md b/archive/2.0.0a8/api/nonebot.md similarity index 94% rename from archive/2.0.0a6/api/nonebot.md rename to archive/2.0.0a8/api/nonebot.md index cdb72bdb..d2ef4eb4 100644 --- a/archive/2.0.0a6/api/nonebot.md +++ b/archive/2.0.0a8/api/nonebot.md @@ -40,6 +40,9 @@ sidebarDepth: 0 * `CommandGroup` => `nonebot.plugin.CommandGroup` +* `Matchergroup` => `nonebot.plugin.MatcherGroup` + + * `load_plugin` => `nonebot.plugin.load_plugin` @@ -49,9 +52,18 @@ sidebarDepth: 0 * `load_builtin_plugins` => `nonebot.plugin.load_builtin_plugins` +* `get_plugin` => `nonebot.plugin.get_plugin` + + * `get_loaded_plugins` => `nonebot.plugin.get_loaded_plugins` +* `export` => `nonebot.plugin.export` + + +* `require` => `nonebot.plugin.require` + + ## `get_driver()` diff --git a/archive/2.0.0a6/api/permission.md b/archive/2.0.0a8/api/permission.md similarity index 61% rename from archive/2.0.0a6/api/permission.md rename to archive/2.0.0a8/api/permission.md index 26d3cd34..1c42b2c8 100644 --- a/archive/2.0.0a6/api/permission.md +++ b/archive/2.0.0a8/api/permission.md @@ -50,72 +50,14 @@ sidebarDepth: 0 * **参数** - * `*user: int`: 白名单 + * `*user: str`: 白名单 * `perm: Permission`: 需要同时满足的权限 -## `PRIVATE` - - -* **说明**: 匹配任意私聊消息类型事件 - - -## `PRIVATE_FRIEND` - - -* **说明**: 匹配任意好友私聊消息类型事件 - - -## `PRIVATE_GROUP` - - -* **说明**: 匹配任意群临时私聊消息类型事件 - - -## `PRIVATE_OTHER` - - -* **说明**: 匹配任意其他私聊消息类型事件 - - -## `GROUP` - - -* **说明**: 匹配任意群聊消息类型事件 - - -## `GROUP_MEMBER` - - -* **说明**: 匹配任意群员群聊消息类型事件 - -:::warning 警告 -该权限通过 event.sender 进行判断且不包含管理员以及群主! -::: - - -## `GROUP_ADMIN` - - -* **说明**: 匹配任意群管理员群聊消息类型事件 - - -## `GROUP_OWNER` - - -* **说明**: 匹配任意群主群聊消息类型事件 - - ## `SUPERUSER` * **说明**: 匹配任意超级用户消息类型事件 - - -## `EVERYBODY` - - -* **说明**: 匹配任意消息类型事件 diff --git a/archive/2.0.0a8/api/plugin.md b/archive/2.0.0a8/api/plugin.md new file mode 100644 index 00000000..91e3e763 --- /dev/null +++ b/archive/2.0.0a8/api/plugin.md @@ -0,0 +1,1261 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.plugin 模块 + +## 插件 + +为 NoneBot 插件开发提供便携的定义函数。 + + +## `plugins` + + +* **类型** + + `Dict[str, Plugin]` + + + +* **说明** + + 已加载的插件 + + + +## _class_ `Export` + +基类:`dict` + + +* **说明** + + 插件导出内容以使得其他插件可以获得。 + + + +* **示例** + + +```python +nonebot.export().default = "bar" + +@nonebot.export() +def some_function(): + pass + +# this doesn't work before python 3.9 +# use +# export = nonebot.export(); @export.sub +# instead +# See also PEP-614: https://www.python.org/dev/peps/pep-0614/ +@nonebot.export().sub +def something_else(): + pass +``` + + +## _class_ `Plugin` + +基类:`object` + +存储插件信息 + + +### `name` + + +* **类型**: `str` + + +* **说明**: 插件名称,使用 文件/文件夹 名称作为插件名 + + +### `module` + + +* **类型**: `ModuleType` + + +* **说明**: 插件模块对象 + + +### `matcher` + + +* **类型**: `Set[Type[Matcher]]` + + +* **说明**: 插件内定义的 `Matcher` + + +### `export` + + +* **类型**: `Export` + + +* **说明**: 插件内定义的导出内容 + + +## `on(type='', rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个基础事件响应器,可自定义类型。 + + + +* **参数** + + + * `type: str`: 事件响应器类型 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_metaevent(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个元事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_message(rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=True, state=None, state_factory=None)` + + +* **说明** + + 注册一个消息事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_notice(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个通知事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_request(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` + + +* **说明** + + 注册一个请求事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_startswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容开头时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息开头内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_endswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容结尾时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息结尾内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_keyword(keywords, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + + + +* **参数** + + + * `keywords: Set[str]`: 关键词列表 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_command(cmd, rule=None, aliases=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 + + 命令匹配规则参考: [命令形式匹配](rule.html#command-command) + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `on_regex(pattern, flags=0, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 + + 命令匹配规则参考: [正则匹配](rule.html#regex-regex-flags-0) + + + +* **参数** + + + * `pattern: str`: 正则表达式 + + + * `flags: Union[int, re.RegexFlag]`: 正则匹配标志 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## _class_ `CommandGroup` + +基类:`object` + +命令组,用于声明一组有相同名称前缀的命令。 + + +### `__init__(cmd, **kwargs)` + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 + + + * `**kwargs`: 其他传递给 `on_command` 的参数默认值,参考 [on_command](#on-command-cmd-rule-none-aliases-none-kwargs) + + + +### `basecmd` + + +* **类型**: `Tuple[str, ...]` + + +* **说明**: 命令前缀 + + +### `base_kwargs` + + +* **类型**: `Dict[str, Any]` + + +* **说明**: 其他传递给 `on_command` 的参数默认值 + + +### `command(cmd, **kwargs)` + + +* **说明** + + 注册一个新的命令。 + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 命令前缀 + + + * `**kwargs`: 其他传递给 `on_command` 的参数,将会覆盖命令组默认值 + + + +* **返回** + + + * `Type[Matcher]` + + + +## _class_ `MatcherGroup` + +基类:`object` + +事件响应器组合,统一管理。为 `Matcher` 创建提供默认属性。 + + +### `__init__(**kwargs)` + + +* **说明** + + 创建一个事件响应器组合,参数为默认值,与 `on` 一致 + + + +### `matchers` + + +* **类型** + + `List[Type[Matcher]]` + + + +* **说明** + + 组内事件响应器列表 + + + +### `base_kwargs` + + +* **类型**: `Dict[str, Any]` + + +* **说明**: 其他传递给 `on` 的参数默认值 + + +### `on(**kwargs)` + + +* **说明** + + 注册一个基础事件响应器,可自定义类型。 + + + +* **参数** + + + * `type: str`: 事件响应器类型 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_metaevent(**kwargs)` + + +* **说明** + + 注册一个元事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_message(**kwargs)` + + +* **说明** + + 注册一个消息事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_notice(**kwargs)` + + +* **说明** + + 注册一个通知事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_request(**kwargs)` + + +* **说明** + + 注册一个请求事件响应器。 + + + +* **参数** + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_startswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容开头时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息开头内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_endswith(msg, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息的\*\*文本部分\*\*以指定内容结尾时响应。 + + + +* **参数** + + + * `msg: str`: 指定消息结尾内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_keyword(keywords, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息纯文本部分包含关键词时响应。 + + + +* **参数** + + + * `keywords: Set[str]`: 关键词列表 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_command(cmd, rule=None, aliases=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息以指定命令开头时响应。 + + 命令匹配规则参考: [命令形式匹配](rule.html#command-command) + + + +* **参数** + + + * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +### `on_regex(pattern, flags=0, rule=None, **kwargs)` + + +* **说明** + + 注册一个消息事件响应器,并且当消息匹配正则表达式时响应。 + + 命令匹配规则参考: [正则匹配](rule.html#regex-regex-flags-0) + + + +* **参数** + + + * `pattern: str`: 正则表达式 + + + * `flags: Union[int, re.RegexFlag]`: 正则匹配标志 + + + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 + + + * `permission: Optional[Permission]`: 事件响应权限 + + + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 + + + * `temp: bool`: 是否为临时事件响应器(仅执行一次) + + + * `priority: int`: 事件响应器优先级 + + + * `block: bool`: 是否阻止事件向更低优先级传递 + + + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 + + + +* **返回** + + + * `Type[Matcher]` + + + +## `load_plugin(module_path)` + + +* **说明** + + 使用 `importlib` 加载单个插件,可以是本地插件或是通过 `pip` 安装的插件。 + + + +* **参数** + + + * `module_path: str`: 插件名称 `path.to.your.plugin` + + + +* **返回** + + + * `Optional[Plugin]` + + + +## `load_plugins(*plugin_dir)` + + +* **说明** + + 导入目录下多个插件,以 `_` 开头的插件不会被导入! + + + +* **参数** + + + * `*plugin_dir: str`: 插件路径 + + + +* **返回** + + + * `Set[Plugin]` + + + +## `load_builtin_plugins()` + + +* **说明** + + 导入 NoneBot 内置插件 + + + +* **返回** + + + * `Plugin` + + + +## `get_plugin(name)` + + +* **说明** + + 获取当前导入的某个插件。 + + + +* **参数** + + + * `name: str`: 插件名,与 `load_plugin` 参数一致。如果为 `load_plugins` 导入的插件,则为文件(夹)名。 + + + +* **返回** + + + * `Optional[Plugin]` + + + +## `get_loaded_plugins()` + + +* **说明** + + 获取当前已导入的所有插件。 + + + +* **返回** + + + * `Set[Plugin]` + + + +## `export()` + + +* **说明** + + 获取插件的导出内容对象 + + + +* **返回** + + + * `Export` + + + +## `require(name)` + + +* **说明** + + 获取一个插件的导出内容 + + + +* **参数** + + + * `name: str`: 插件名,与 `load_plugin` 参数一致。如果为 `load_plugins` 导入的插件,则为文件(夹)名。 + + + +* **返回** + + + * `Optional[Export]` diff --git a/archive/2.0.0a6/api/rule.md b/archive/2.0.0a8/api/rule.md similarity index 91% rename from archive/2.0.0a6/api/rule.md rename to archive/2.0.0a8/api/rule.md index dade2a5b..cb3fd05f 100644 --- a/archive/2.0.0a6/api/rule.md +++ b/archive/2.0.0a8/api/rule.md @@ -42,7 +42,7 @@ Rule(async_function, run_sync(sync_function)) * **参数** - * `*checkers: Callable[[Bot, Event, dict], Awaitable[bool]]`: **异步** RuleChecker + * `*checkers: Callable[[Bot, Event, T_State], Awaitable[bool]]`: **异步** RuleChecker @@ -58,7 +58,7 @@ Rule(async_function, run_sync(sync_function)) * **类型** - * `Set[Callable[[Bot, Event, dict], Awaitable[bool]]]` + * `Set[Callable[[Bot, Event, T_State], Awaitable[bool]]]` @@ -80,7 +80,7 @@ Rule(async_function, run_sync(sync_function)) * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State @@ -200,7 +200,7 @@ Rule(async_function, run_sync(sync_function)) * **说明** - 通过 `event.to_me` 判断消息是否是发送给机器人 + 通过 `event.is_tome()` 判断事件是否与机器人有关 diff --git a/archive/2.0.0a8/api/typing.md b/archive/2.0.0a8/api/typing.md new file mode 100644 index 00000000..5d1b3d7b --- /dev/null +++ b/archive/2.0.0a8/api/typing.md @@ -0,0 +1,214 @@ +--- +contentSidebar: true +sidebarDepth: 0 +--- + +# NoneBot.typing 模块 + +## 类型 + +下面的文档中,「类型」部分使用 Python 的 Type Hint 语法,见 [PEP 484](https://www.python.org/dev/peps/pep-0484/)、[PEP 526](https://www.python.org/dev/peps/pep-0526/) 和 [typing](https://docs.python.org/3/library/typing.html)。 + +除了 Python 内置的类型,下面还出现了如下 NoneBot 自定类型,实际上它们是 Python 内置类型的别名。 + +以下类型均可从 nonebot.typing 模块导入。 + + +## `T_State` + + +* **类型** + + `Dict[Any, Any]` + + + +* **说明** + + 事件处理状态 State 类型 + + + + +## `T_StateFactory` + + +* **类型** + + `Callable[[Bot, Event], Awaitable[T_State]]` + + + +* **说明** + + 事件处理状态 State 类工厂函数 + + + + +## `T_WebSocketConnectionHook` + + +* **类型** + + `Callable[[Bot], Awaitable[None]]` + + + +* **说明** + + WebSocket 连接建立时执行的函数 + + + + +## `T_WebSocketDisconnectionHook` + + +* **类型** + + `Callable[[Bot], Awaitable[None]]` + + + +* **说明** + + WebSocket 连接断开时执行的函数 + + + + +## `T_EventPreProcessor` + + +* **类型** + + `Callable[[Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件预处理函数 EventPreProcessor 类型 + + + + +## `T_EventPostProcessor` + + +* **类型** + + `Callable[[Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件预处理函数 EventPostProcessor 类型 + + + + +## `T_RunPreProcessor` + + +* **类型** + + `Callable[[Matcher, Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件响应器运行前预处理函数 RunPreProcessor 类型 + + + + +## `T_RunPostProcessor` + + +* **类型** + + `Callable[[Matcher, Optional[Exception], Bot, Event, T_State], Awaitable[None]]` + + + +* **说明** + + 事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在) + + + + +## `T_RuleChecker` + + +* **类型** + + `Callable[[Bot, Event, T_State], Union[bool, Awaitable[bool]]]` + + + +* **说明** + + RuleChecker 即判断是否响应事件的处理函数。 + + + + +## `T_PermissionChecker` + + +* **类型** + + `Callable[[Bot, Event], Union[bool, Awaitable[bool]]]` + + + +* **说明** + + RuleChecker 即判断是否响应消息的处理函数。 + + + + +## `T_Handler` + + +* **类型** + + + * `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + Handler 即事件的处理函数。 + + + + +## `T_ArgsParser` + + +* **类型** + + `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + +* **说明** + + ArgsParser 即消息参数解析函数,在 Matcher.got 获取参数时被运行。 diff --git a/archive/2.0.0a6/api/utils.md b/archive/2.0.0a8/api/utils.md similarity index 73% rename from archive/2.0.0a6/api/utils.md rename to archive/2.0.0a8/api/utils.md index ed98fab9..ab3ea0c2 100644 --- a/archive/2.0.0a6/api/utils.md +++ b/archive/2.0.0a8/api/utils.md @@ -52,6 +52,28 @@ sidebarDepth: 0 +## `logger_wrapper` + + +* **说明** + + +用于打印 adapter 的日志。 + + +* **Log 参数** + + + +* `level: Literal['WARNING', 'DEBUG', 'INFO']`: 日志等级 + + +* `message: str`: 日志信息 + + +* `exception: Optional[Exception]`: 异常信息 + + ## _class_ `DataclassEncoder` 基类:`json.encoder.JSONEncoder` diff --git a/archive/2.0.0a6/guide/README.md b/archive/2.0.0a8/guide/README.md similarity index 55% rename from archive/2.0.0a6/guide/README.md rename to archive/2.0.0a8/guide/README.md index cacb58ac..4326ac1b 100644 --- a/archive/2.0.0a6/guide/README.md +++ b/archive/2.0.0a8/guide/README.md @@ -1,27 +1,30 @@ # 概览 -:::tip 提示 + :::tip 提示 初次使用时可能会觉得这里的概览过于枯燥,可以先简单略读之后直接前往 [安装](./installation.md) 查看安装方法,并进行后续的基础使用教程。 ::: -NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的消息进行解析和处理,并以插件化的形式,分发给消息所对应的命令处理器和自然语言处理器,来完成具体的功能。 +## 简介 -除了起到解析消息的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制,尤其对于命令处理器,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 +NoneBot2 是一个可扩展的 Python 异步机器人框架,它会对机器人收到的事件进行解析和处理,并以插件化的形式,按优先级分发给事件所对应的事件响应器,来完成具体的功能。 -目前 NoneBot2 在 [FastAPI](https://fastapi.tiangolo.com/) 的基础上封装了与 [CQHTTP(OneBot) 协议](http://cqhttp.cc/)插件的网络交互。 +除了起到解析事件的作用,NoneBot 还为插件提供了大量实用的预设操作和权限控制机制。对于命令处理,它更是提供了完善且易用的会话机制和内部调用机制,以分别适应命令的连续交互和插件内部功能复用等需求。 -得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制,NoneBot 处理消息的吞吐量有了很大的保障,再配合 WebSocket 通信方式(也是最建议的通信方式),NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。 +得益于 Python 的 [asyncio](https://docs.python.org/3/library/asyncio.html) 机制,NoneBot 处理事件的吞吐量有了很大的保障,再配合 WebSocket 通信方式(也是最建议的通信方式),NoneBot 的性能可以达到 HTTP 通信方式的两倍以上,相较于传统同步 I/O 的 HTTP 通信,更是有质的飞跃。 -需要注意的是,NoneBot 仅支持 Python 3.7+ 及 CQHTTP(OneBot) 插件 v11+。 +需要注意的是,NoneBot 仅支持 **Python 3.7+** ## 特色 -- 提供直观的测试前端 +NoneBot2 的驱动框架 `Driver` 以及通信协议 `Adapter` 均可**自定义**,并且可以作为插件进行**替换/添加**! + - 提供使用简易的脚手架 +- 提供丰富的官方插件 +- 提供可添加/替换的驱动以及协议选项 - 基于异步 I/O - 同时支持 HTTP 和反向 WebSocket 通信方式 - 支持多个机器人账号负载均衡 diff --git a/archive/2.0.0a6/guide/basic-configuration.md b/archive/2.0.0a8/guide/basic-configuration.md similarity index 69% rename from archive/2.0.0a6/guide/basic-configuration.md rename to archive/2.0.0a8/guide/basic-configuration.md index e4c4449f..0cd9156a 100644 --- a/archive/2.0.0a6/guide/basic-configuration.md +++ b/archive/2.0.0a8/guide/basic-configuration.md @@ -13,19 +13,30 @@ NoneBot 在启动时将会从系统环境变量或者 `.env` 文件中寻找变量 `ENVIRONMENT` (大小写不敏感),默认值为 `prod`。 这将引导 NoneBot 从系统环境变量或者 `.env.{ENVIRONMENT}` 文件中进一步加载具体配置。 -现在,我们在 `.env` 文件中写入当前环境信息 +现在,我们在 `.env` 文件中写入当前环境信息: ```bash # .env ENVIRONMENT=dev ``` +如你所想,之后 NoneBot 就会从 `.env.dev` 文件中加载环境变量。 + ## .env.\* 文件 -详细配置文件,使用 [pydantic](https://pydantic-docs.helpmanual.io/) 加载配置。在 NoneBot 初始化时可以指定忽略 `.env` 中的环境信息转而加载某个配置文件: `nonebot.init(_env_file=".env.dev")`。 +NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 进行配置管理,会从 `.env.{ENVIRONMENT}` 文件中获悉环境配置。 + +可以在 NoneBot 初始化时指定加载某个环境配置文件: `nonebot.init(_env_file=".env.dev")`,这将忽略你在 `.env` 中设置的环境信息。 :::warning 提示 -由于 `pydantic` 使用 JSON 加载配置项,请确保配置项值为 JSON 能够解析的数据。如果 JSON 解析失败将作为字符串处理。 +由于 `pydantic` 使用 JSON 解析配置项,请确保配置项值为 JSON 格式的数据。如: + +```bash +list=["123456789", "987654321", 1] +test={"hello": "world"} +``` + +如果配置项值解析失败将作为字符串处理。 ::: 示例及说明: @@ -46,6 +57,10 @@ CUSTOM_CONFIG2= # 留空则从系统环境变量读取,如不存在则为空 详细的配置项参考 [Config Reference](../api/config.md) 。 +## 系统环境变量 + +如果在系统环境变量中定义了配置,则一样会被读取。 + ## bot.py 文件 配置项也可以在 NoneBot 初始化时传入。此处可以传入任意合法 Python 变量。当然也可以在初始化完成后修改或新增。 @@ -65,4 +80,4 @@ config.custom_config4 = "new config after init" ## 优先级 -`bot.py init` > `env file` > `system env` +`bot.py init` > `system env` > `env file` diff --git a/archive/2.0.0a8/guide/cqhttp-guide.md b/archive/2.0.0a8/guide/cqhttp-guide.md new file mode 100644 index 00000000..356fa6c3 --- /dev/null +++ b/archive/2.0.0a8/guide/cqhttp-guide.md @@ -0,0 +1,101 @@ +# CQHTTP 协议使用指南 + +## 配置 CQHTTP 协议端(以 QQ 为例) + +单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 + +QQ 协议端举例: + +- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo)) +- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded) +- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai) +- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api) +- [OICQ-http-api](https://github.com/takayama-lily/onebot) (基于 [OICQ](https://github.com/takayama-lily/oicq)) + +这里以 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) 为例 + +1. 下载 go-cqhttp 对应平台的 release 文件,[点此前往](https://github.com/Mrs4s/go-cqhttp/releases) +2. 运行 exe 文件或者使用 `./go-cqhttp` 启动 +3. 生成默认配置文件并修改默认配置 + +```hjson{2,3,35-36,42} +{ + uin: 机器人QQ号 + password: 机器人密码 + encrypt_password: false + password_encrypted: "" + enable_db: true + access_token: "" + relogin: { + enabled: true + relogin_delay: 3 + max_relogin_times: 0 + } + _rate_limit: { + enabled: false + frequency: 1 + bucket_size: 1 + } + ignore_invalid_cqcode: false + force_fragmented: false + heartbeat_interval: 0 + http_config: { + enabled: false + host: "0.0.0.0" + port: 5700 + timeout: 0 + post_urls: {} + } + ws_config: { + enabled: false + host: "0.0.0.0" + port: 6700 + } + ws_reverse_servers: [ + { + enabled: true + reverse_url: ws://127.0.0.1:8080/cqhttp/ws + reverse_api_url: ws://you_websocket_api.server + reverse_event_url: ws://you_websocket_event.server + reverse_reconnect_interval: 3000 + } + ] + post_message_format: array + use_sso_address: false + debug: false + log_level: "" + web_ui: { + enabled: false + host: 127.0.0.1 + web_ui_port: 9999 + web_input: false + } +} +``` + +其中 `ws://127.0.0.1:8080/cqhttp/ws` 中的 `127.0.0.1` 和 `8080` 应分别对应 nonebot 配置的 HOST 和 PORT。 + +`cqhttp` 是前述 `register_adapter` 时传入的第一个参数,代表设置的 `CQHTTPBot` 适配器的路径,你可以对不同的适配器设置不同路径以作区别。 + +## 历史性的第一次对话 + +一旦新的配置文件正确生效之后,NoneBot 所在的控制台(如果正在运行的话)应该会输出类似下面的内容(两条访问日志): + +```default +09-14 21:31:16 [INFO] uvicorn | ('127.0.0.1', 12345) - "WebSocket /cqhttp/ws" [accepted] +09-14 21:31:16 [INFO] nonebot | WebSocket Connection from CQHTTP Bot 你的QQ号 Accepted! +``` + +这表示 CQHTTP 协议端已经成功地使用 CQHTTP 协议连接上了 NoneBot。 + +现在,尝试向你的机器人账号发送如下内容: + +```default +/echo 你好,世界 +``` + +到这里如果一切 OK,你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅! + + + + diff --git a/archive/2.0.0a6/guide/creating-a-handler.md b/archive/2.0.0a8/guide/creating-a-handler.md similarity index 61% rename from archive/2.0.0a6/guide/creating-a-handler.md rename to archive/2.0.0a8/guide/creating-a-handler.md index 725aaacf..5b6b0591 100644 --- a/archive/2.0.0a6/guide/creating-a-handler.md +++ b/archive/2.0.0a8/guide/creating-a-handler.md @@ -6,14 +6,14 @@ ```python{1,2,8,9} @weather.handle() -async def handle_first_receive(bot: Bot, event: Event, state: dict): - args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 +async def handle_first_receive(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 if args: state["city"] = args # 如果用户发送了参数则直接赋值 @weather.got("city", prompt="你想查询哪个城市的天气呢?") -async def handle_city(bot: Bot, event: Event, state: dict): +async def handle_city(bot: Bot, event: Event, state: T_State): city = state["city"] if city not in ["上海", "北京"]: await weather.reject("你想查询的城市暂不支持,请重新输入!") @@ -53,12 +53,12 @@ async def handle_city(bot: Bot, event: Event, state: dict): ```python @matcher.receive() -async def handle(bot: Bot, event: Event, state: dict): +async def handle(bot: Bot, event: Event, state: T_State): state["key"] = "hello" @matcher.got("key2", prompt="{key}!") -async def handle2(bot: Bot, event: Event, state: dict): +async def handle2(bot: Bot, event: Event, state: T_State): pass ``` @@ -69,23 +69,61 @@ async def handle2(bot: Bot, event: Event, state: dict): ```python @matcher.got("key1") @matcher.got("key2") -async def handle(bot: Bot, event: Event, state: dict): +async def handle(bot: Bot, event: Event, state: State): pass ``` ### 事件处理函数参数 -事件处理函数类型为 `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` 。 +事件处理函数类型为: + +- `Callable[[Bot, Event, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]` + +简单说就是:除了 `bot` 参数,其他都是可选的。 + +以下函数都是合法的事件处理函数(仅列举常用的): + +```python +async def handle(bot: Bot, event: Event, state: T_State): + pass + +async def handle(bot: Bot, event: Event, state: T_State, matcher: Matcher): + pass + +async def handle(bot: Bot, event: Event): + pass + +async def handle(bot: Bot, state: T_State): + pass + +async def handle(bot: Bot): + pass +``` + +:::danger 警告 +函数的参数名固定不能修改! +::: 参数分别为: -1. [nonebot.typing.Bot](../api/typing.md#bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。 -2. [nonebot.typing.Event](../api/typing.md#event): 即上报事件对象,可以获取到上报的所有信息。 -3. `state`: 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如: +1. [nonebot.adapters.Bot](../api/adapters/#class-bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。 +2. [nonebot.adapters.Event](../api/adapters/#class-event): 即上报事件对象,可以获取到上报的所有信息。 +3. [state](../api/typing.md#t-state): 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如: - `state["_current_key"]`: 存储当前 `got` 获取的参数名 - `state["_prefix"]`, `state["_suffix"]`: 存储当前 TRIE 匹配的前缀/后缀,可以通过该值获取用户命令的原始命令 +:::tip 提示 +NoneBot 会对不同类型的参数进行不同的操作,详情查看 [事件处理函数重载](../advanced/overloaded-handlers.md) +::: + ### 参数处理函数 args_parser 在使用 `got` 获取用户输入参数时,需要对用户的消息进行处理以转换为我们所需要的信息。在默认情况下,NoneBot 会把用户的消息字符串原封不动的赋值给 `state[key]` 。可以通过以下两种方式修改默认处理逻辑: @@ -93,11 +131,11 @@ async def handle(bot: Bot, event: Event, state: dict): - `@matcher.args_parser` 装饰器:直接装饰一个函数作为参数处理器 - `got(key, prompt, args_parser)`:直接把函数作为参数传入 -参数处理函数类型为:`Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`,即: +参数处理函数类型为:`Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`,即: ```python -async def parser(bot: Bot, event: Event, state: dict): - state[state["_current_key"]] = str(event.message) +async def parser(bot: Bot, event: Event, state: T_State): + state[state["_current_key"]] = str(event.get_message()) ``` 特别的,`state["_current_key"]` 中存储了当前获取的参数名 @@ -131,16 +169,16 @@ matcher = on_command("test") # 修改默认参数处理 @matcher.args_parser -async def parse(bot: Bot, event: Event, state: dict): - print(state["_current_key"], ":", str(event.message)) - state[state["_current_key"]] = str(event.message) +async def parse(bot: Bot, event: Event, state: State): + print(state["_current_key"], ":", str(event.get_message())) + state[state["_current_key"]] = str(event.get_message()) @matcher.handle() -async def first_receive(bot: Bot, event: Event, state: dict): +async def first_receive(bot: Bot, event: Event, state: State): # 获取用户原始命令,如:/test print(state["_prefix"]["raw_command"]) # 处理用户输入参数,如:/test arg1 arg2 - raw_args = str(event.message).strip() + raw_args = str(event.get_message()).strip() if raw_args: arg_list = raw_args.split() # 将参数存入state以阻止后续再向用户询问参数 @@ -148,12 +186,12 @@ async def first_receive(bot: Bot, event: Event, state: dict): @matcher.got("arg1", prompt="参数?") -async def arg_handle(bot: Bot, event: Event, state: dict): +async def arg_handle(bot: Bot, event: Event, state: State): # 在这里对参数进行验证 if state["arg1"] not in ["allow", "list"]: await matcher.reject("参数不正确!请重新输入") # 发送一些信息 - await bot.send("message") + await bot.send(event, "message") await matcher.send("message") await matcher.finish("message") ``` diff --git a/archive/2.0.0a6/guide/creating-a-matcher.md b/archive/2.0.0a8/guide/creating-a-matcher.md similarity index 84% rename from archive/2.0.0a6/guide/creating-a-matcher.md rename to archive/2.0.0a8/guide/creating-a-matcher.md index b603449a..09603855 100644 --- a/archive/2.0.0a6/guide/creating-a-matcher.md +++ b/archive/2.0.0a8/guide/creating-a-matcher.md @@ -7,20 +7,21 @@ ```python from nonebot import on_command from nonebot.rule import to_me -from nonebot.adapters.cqhttp import Bot, Event +from nonebot.typing import T_State +from nonebot.adapters import Bot, Event weather = on_command("天气", rule=to_me(), priority=5) @weather.handle() -async def handle_first_receive(bot: Bot, event: Event, state: dict): - args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 +async def handle_first_receive(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 if args: state["city"] = args # 如果用户发送了参数则直接赋值 @weather.got("city", prompt="你想查询哪个城市的天气呢?") -async def handle_city(bot: Bot, event: Event, state: dict): +async def handle_city(bot: Bot, event: Event, state: State): city = state["city"] if city not in ["上海", "北京"]: await weather.reject("你想查询的城市暂不支持,请重新输入!") @@ -42,7 +43,7 @@ async def get_weather(city: str): ## [事件响应器](../api/matcher.md) -```python{4} +```python{5} from nonebot import on_command from nonebot.rule import to_me from nonebot.permission import Permission @@ -62,7 +63,7 @@ weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5 ### 事件响应器类型 type -事件响应器类型其实就是对应事件的类型 `Event.type` ,NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些其他内置的事件响应器。 +事件响应器类型其实就是对应事件的类型 `Event.get_type()` ,NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些其他内置的事件响应器。 以下所有类型的事件响应器都是由 `on(type, rule)` 的形式进行了简化封装。 @@ -86,10 +87,10 @@ weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5 事件响应器的优先级代表事件响应器的执行顺序,同一优先级的事件响应器会 **同时执行!**,优先级数字**越小**越先响应!优先级请从 `1` 开始排序! :::tip 提示 -使用 `nonebot-test` 可以看到当前所有事件响应器的执行流程,有助理解事件响应流程! +使用 `nonebot-plugin-test` 可以在网页端查看当前所有事件响应器的执行流程,有助理解事件响应流程! ```bash -pip install nonebot2[test] +nb plugin install nonebot_plugin_test ``` ::: @@ -115,15 +116,15 @@ rule 的出现使得 nonebot 对事件的响应可以非常自由,nonebot 内 ```python from nonebot.rule import Rule -async def async_checker(bot: Bot, event: Event, state: dict) -> bool: +async def async_checker(bot: Bot, event: Event, state: State) -> bool: return True -def sync_checker(bot: Bot, event: Event, state: dict) -> bool: +def sync_checker(bot: Bot, event: Event, state: State) -> bool: return True def check(arg1, args2): - async def _checker(bot: Bot, event: Event, state: dict) -> bool: + async def _checker(bot: Bot, event: Event, state: State) -> bool: return bool(arg1 + arg2) return Rule(_check) diff --git a/archive/2.0.0a6/guide/creating-a-plugin.md b/archive/2.0.0a8/guide/creating-a-plugin.md similarity index 94% rename from archive/2.0.0a6/guide/creating-a-plugin.md rename to archive/2.0.0a8/guide/creating-a-plugin.md index fe52a25d..5ce12a28 100644 --- a/archive/2.0.0a6/guide/creating-a-plugin.md +++ b/archive/2.0.0a8/guide/creating-a-plugin.md @@ -2,6 +2,12 @@ 如果之前使用 `nb-cli` 生成了项目结构,那我们已经有了一个空的插件目录 `Awesome-Bot/awesome_bot/plugins`,并且它已在 `bot.py` 中被加载,我们现在可以开始创建插件了! +使用 `nb-cli` 创建包形式插件,或自行创建文件(夹) + +```bash +nb plugin new +``` + 插件通常有两种形式,下面分别介绍 ## 单文件形式 @@ -76,10 +82,10 @@ foo 示例: ```python -from pydantic import BaseSetting +from pydantic import BaseSettings -class Config(BaseSetting): +class Config(BaseSettings): # plugin custom config plugin_setting: str = "default" diff --git a/archive/2.0.0a6/guide/creating-a-project.md b/archive/2.0.0a8/guide/creating-a-project.md similarity index 82% rename from archive/2.0.0a6/guide/creating-a-project.md rename to archive/2.0.0a8/guide/creating-a-project.md index 74cdb24a..5933b5fa 100644 --- a/archive/2.0.0a6/guide/creating-a-project.md +++ b/archive/2.0.0a8/guide/creating-a-project.md @@ -1,19 +1,15 @@ # 创建一个完整的项目 -上一章中我们已经运行了一个最小的 NoneBot 实例,在这一章,我们将从零开始一个完整的项目。 +上一章中我们已经运行了一个简单的 NoneBot 实例,在这一章,我们将从零开始一个完整的项目。 ## 目录结构 -首先,我们可以使用 `nb-cli` 或者自行创建项目目录: +可以使用 `nb-cli` 或者自行创建完整的项目目录: ```bash -pip install nonebot2[cli] -# pip install nb-cli nb create ``` -这将创建默认的目录结构 - :::vue AweSome-Bot diff --git a/archive/2.0.0a8/guide/ding-guide.md b/archive/2.0.0a8/guide/ding-guide.md new file mode 100644 index 00000000..88c62ca9 --- /dev/null +++ b/archive/2.0.0a8/guide/ding-guide.md @@ -0,0 +1,3 @@ +# 钉钉机器人使用指南 + +~~TODO~~ diff --git a/archive/2.0.0a8/guide/end-or-start.md b/archive/2.0.0a8/guide/end-or-start.md new file mode 100644 index 00000000..9587c4bb --- /dev/null +++ b/archive/2.0.0a8/guide/end-or-start.md @@ -0,0 +1,9 @@ +# 结语 + +至此,相信你已经能够写出一个基础的插件了。这里给出几个小提示: + +- 请千万注意事件处理器的优先级设定 +- 在匹配规则中请勿使用耗时极长的函数 +- 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍) + +如果「指南」还不能满足你,前往 [进阶](../advanced/README.md) 查看更多的功能信息。 diff --git a/archive/2.0.0a8/guide/getting-started.md b/archive/2.0.0a8/guide/getting-started.md new file mode 100644 index 00000000..d35665a2 --- /dev/null +++ b/archive/2.0.0a8/guide/getting-started.md @@ -0,0 +1,86 @@ +# 开始使用 + +一切都安装成功后,你就已经做好了进行简单配置以运行一个最小的 NoneBot 实例的准备。 + +## 最小实例 + +如果你已经按照推荐方式安装了 `nb-cli`,使用脚手架创建一个空项目: + +```bash +nb create +``` + +根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`。 + +如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下(这里以 CQHTTP 为例): + +```python{4,6,7,10} +import nonebot +from nonebot.adapters.cqhttp import Bot as CQHTTPBot + +nonebot.init() +driver = nonebot.get_driver() +driver.register_adapter("cqhttp", CQHTTPBot) +nonebot.load_builtin_plugins() + +if __name__ == "__main__": + nonebot.run() +``` + +## 解读 + +在上方 `bot.py` 中,这几行高亮代码将依次: + +1. 使用默认配置初始化 NoneBot +2. 加载 NoneBot 内置的 CQHTTP 协议适配组件 + `register_adapter` 的第一个参数我们传入了一个字符串,该字符串将会在后文 [配置 CQHTTP 协议端](#配置-cqhttp-协议端-以-qq-为例) 时使用。 +3. 加载 NoneBot 内置的插件 +4. 在地址 `127.0.0.1:8080` 运行 NoneBot + +在命令行使用如下命令即可运行这个 NoneBot 实例: + +```bash +# nb-cli +nb run +# 其他 +python bot.py +``` + +运行后会产生如下日志: + +```plain +09-14 21:02:00 [INFO] nonebot | Succeeded to import "nonebot.plugins.base" +09-14 21:02:00 [INFO] nonebot | Running NoneBot... +09-14 21:02:00 [INFO] uvicorn | Started server process [1234] +09-14 21:02:00 [INFO] uvicorn | Waiting for application startup. +09-14 21:02:00 [INFO] uvicorn | Application startup complete. +09-14 21:02:00 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit) +``` + +## 配置协议端上报 + +在 `bot.py` 文件中使用 `register_adapter` 注册协议适配之后即可配置协议端来完成与 NoneBot 的通信,详细配置方法参考: + +- [配置 CQHTTP](./cqhttp-guide.md) +- [配置钉钉](./ding-guide.md) + +NoneBot 接受的上报地址与 `Driver` 有关,默认使用的 `FastAPI Driver` 所接受的上报地址有: + +- `/{adapter name}/`: HTTP POST 上报 +- `/{adapter name}/http/`: HTTP POST 上报 +- `/{adapter name}/ws`: WebSocket 上报 +- `/{adapter name}/ws/`: WebSocket 上报 + +:::warning 注意 +如果到这一步你没有在 NoneBot 看到连接成功日志,比较常见的出错点包括: + +- NoneBot 监听 `0.0.0.0`,然后在协议端上报配置中填了 `ws://0.0.0.0:8080/***/ws` +- 在 Docker 容器内运行协议端,并通过 `127.0.0.1` 访问宿主机上的 NoneBot +- 想从公网访问,但没有修改云服务商的安全组策略或系统防火墙 +- NoneBot 所监听的端口存在冲突,已被其它程序占用 +- 弄混了 NoneBot 的 `host`、`port` 参数与协议端上报配置中的 `host`、`port` 参数 +- `ws://` 错填为 `http://` +- 协议端或 NoneBot 启动时遭到外星武器干扰 + +请尝试重启协议端 NoneBot、更换端口、修改防火墙、重启系统、仔细阅读前面的文档及提示、更新协议端 和 NoneBot 到最新版本等方式来解决。 +::: diff --git a/archive/2.0.0a8/guide/installation.md b/archive/2.0.0a8/guide/installation.md new file mode 100644 index 00000000..9beedaaa --- /dev/null +++ b/archive/2.0.0a8/guide/installation.md @@ -0,0 +1,91 @@ +# 安装 + +## NoneBot + +:::warning 注意 +请确保你的 Python 版本 >= 3.7。 +::: + +:::warning 注意 +请在安装 nonebot2 之前卸载 nonebot 1.x + +```bash +pip uninstall nonebot +``` + +::: + +### 通过脚手架安装(推荐安装方式) + +1. (推荐)使用你喜欢的 Python 环境管理工具(如 `poetry`)创建新的虚拟环境。 +2. 使用 `pip` (或其他包管理工具) 安装 nb-cli,nonebot2 作为其依赖会一起被安装。 + + ```bash + pip install nb-cli + ``` + +3. 点个 star 吧 + + nonebot2: [![nb-cli](https://img.shields.io/github/stars/nonebot/nonebot2?style=social)](https://github.com/nonebot/nonebot2) + + nb-cli: [![nb-cli](https://img.shields.io/github/stars/nonebot/nb-cli?style=social)](https://github.com/nonebot/nb-cli) + +### 不使用脚手架(纯净安装) + +```bash +pip install nonebot2 +# 也可以通过 poetry 安装 +poetry add nonebot2 +``` + +如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 GitHub 仓库安装: + +:::warning 注意 +直接从 Github 仓库中安装意味着你将使用最新提交的代码,它们并没有进行充分的稳定性测试 +在任何情况下请不要将其应用于生产环境! +::: + +```bash +# master分支 +poetry add git+https://github.com/nonebot/nonebot2.git#master +# dev分支 +poetry add git+https://github.com/nonebot/nonebot2.git#dev +``` + +或者在克隆 Git 仓库后手动安装: + +```bash +git clone https://github.com/nonebot/nonebot2.git +cd nonebot2 +poetry install --no-dev # 推荐 +pip install . # 不推荐 +``` + +## 安装插件 + +插件可以通过 `nb-cli` 进行安装,也可以自行安装并加载插件。 + +```bash +# 列出所有的插件 +nb plugin list +# 搜索插件 +nb plugin search xxx +# 安装插件 +nb plugin install xxx +``` + +如果急于上线 Bot 或想要使用现成的插件,以下插件可作为参考: + +### 官方插件 + +~~自用插件~~ ~~确信~~ + +- [NoneBot-Plugin-Docs](https://github.com/nonebot/nonebot2/tree/master/packages/nonebot-plugin-docs) 离线文档插件 +- [NoneBot-Plugin-Test](https://github.com/nonebot/plugin-test) 本地机器人测试前端插件 +- [NoneBot-Plugin-APScheduler](https://github.com/nonebot/plugin-apscheduler) 定时任务插件 +- [NoneBot-Plugin-Sentry](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_sentry) Sentry 在线日志分析插件 +- [NoneBot-Plugin-Status](https://github.com/cscs181/QQ-GitHub-Bot/tree/master/src/plugins/nonebot_plugin_status) 服务器状态查看插件 + +### 其他插件 + +还有更多的插件在 [这里](/plugin-store.md) 等着你发现~ diff --git a/archive/2.0.0a6/guide/loading-a-plugin.md b/archive/2.0.0a8/guide/loading-a-plugin.md similarity index 80% rename from archive/2.0.0a6/guide/loading-a-plugin.md rename to archive/2.0.0a8/guide/loading-a-plugin.md index b648b4b6..f026bbe0 100644 --- a/archive/2.0.0a6/guide/loading-a-plugin.md +++ b/archive/2.0.0a8/guide/loading-a-plugin.md @@ -11,7 +11,7 @@ import nonebot nonebot.init() # 加载 nonebot 内置插件 -nonebot.load_bulitin_plugins() +nonebot.load_builtin_plugins() app = nonebot.get_asgi() @@ -48,16 +48,11 @@ if __name__ == "__main__": ::: :::warning 提示 -**插件不能存在相同名称!** +**不能存在相同名称的插件!** ::: :::danger 警告 -插件间不应该存在过多的耦合,如果确实需要导入某个插件内的数据,可以使用如下两种方法: - -1. (推荐) `from plugin_name import xxx` 而非 `from awesome_bot.plugins.plugin_name import xxx` -2. 在需要导入其他插件的文件中添加 `__package__ = "plugins"; from .plugin_name import xxx` (将共同的上层目录设定为父包后使用相对导入) - -具体可以参考:[nonebot/nonebot2#32](https://github.com/nonebot/nonebot2/issues/32) +插件间不应该存在过多的耦合,如果确实需要导入某个插件内的数据,可以参考 [进阶-跨插件访问](../advanced/export-and-require.md) ::: ## 加载单个插件 @@ -81,8 +76,6 @@ if __name__ == "__main__": ## 子插件(嵌套插件) - - 在插件中同样可以加载子插件,例如如下插件目录结构: @@ -113,10 +106,6 @@ _sub_plugins |= nonebot.load_plugins( 插件将会被加载并存储于 `_sub_plugins` 中。 -:::tip 提示 -如果在父插件中需要定义事件响应器,应在**子插件被加载后**进行定义 -::: - ## 运行结果 尝试运行 `nb run` 或者 `python bot.py`,可以看到日志输出了类似如下内容: diff --git a/archive/2.0.0a6/sidebar.config.json b/archive/2.0.0a8/sidebar.config.json similarity index 85% rename from archive/2.0.0a6/sidebar.config.json rename to archive/2.0.0a8/sidebar.config.json index bee7b291..9d660a4b 100644 --- a/archive/2.0.0a6/sidebar.config.json +++ b/archive/2.0.0a8/sidebar.config.json @@ -58,6 +58,15 @@ "creating-a-handler", "end-or-start" ] + }, + { + "title": "协议适配", + "collapsable": false, + "sidebar": "auto", + "children": [ + "cqhttp-guide", + "ding-guide" + ] } ], "/advanced/": [ @@ -69,7 +78,17 @@ "", "scheduler", "permission", - "runtime-hook" + "runtime-hook", + "export-and-require", + "overloaded-handlers" + ] + }, + { + "title": "发布", + "collapsable": false, + "sidebar": "auto", + "children": [ + "publish-plugin" ] } ], @@ -107,10 +126,6 @@ "title": "nonebot.permission 模块", "path": "permission" }, - { - "title": "nonebot.sched 模块", - "path": "sched" - }, { "title": "nonebot.log 模块", "path": "log" @@ -142,6 +157,10 @@ { "title": "nonebot.adapters.cqhttp 模块", "path": "adapters/cqhttp" + }, + { + "title": "nonebot.adapters.ding 模块", + "path": "adapters/ding" } ] } diff --git a/docs/.vuepress/components/Plugins.vue b/docs/.vuepress/components/Plugins.vue index 435e7938..5855fe67 100644 --- a/docs/.vuepress/components/Plugins.vue +++ b/docs/.vuepress/components/Plugins.vue @@ -26,7 +26,7 @@ color="primary" target="_blank" rel="noopener noreferrer" - href="https://github.com/nonebot/nonebot2/issues/new?template=plugin-publish.md" + href="https://github.com/nonebot/nonebot2/issues/new?labels=Plugin&template=plugin-publish.md&title=Plugin%3A+blabla+的插件" >Publish Your Plugin diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 5d7cf2fb..516d7ce0 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -111,6 +111,12 @@ module.exports = context => ({ "creating-a-handler", "end-or-start" ] + }, + { + title: "协议适配", + collapsable: false, + sidebar: "auto", + children: ["cqhttp-guide", "ding-guide"] } ], "/advanced/": [ @@ -123,7 +129,8 @@ module.exports = context => ({ "scheduler", "permission", "runtime-hook", - "export-and-require" + "export-and-require", + "overloaded-handlers" ] }, { diff --git a/docs/.vuepress/versions.json b/docs/.vuepress/versions.json index be230268..39a1ab33 100644 --- a/docs/.vuepress/versions.json +++ b/docs/.vuepress/versions.json @@ -1,4 +1,4 @@ [ - "2.0.0a7", - "2.0.0a6" + "2.0.0a8", + "2.0.0a7" ] \ No newline at end of file diff --git a/docs/README.md b/docs/README.md index c093eb5c..78cb0fc4 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,7 +1,7 @@ --- home: true heroImage: /logo.png -tagline: An asynchronous QQ bot framework. +tagline: An asynchronous bot framework. actionText: 开始使用 actionLink: guide/ features: diff --git a/docs/advanced/overloaded-handlers.md b/docs/advanced/overloaded-handlers.md new file mode 100644 index 00000000..97ff3116 --- /dev/null +++ b/docs/advanced/overloaded-handlers.md @@ -0,0 +1 @@ +# 事件处理函数重载 diff --git a/docs/advanced/scheduler.md b/docs/advanced/scheduler.md index 53e6cedc..86280b5f 100644 --- a/docs/advanced/scheduler.md +++ b/docs/advanced/scheduler.md @@ -1 +1,127 @@ # 定时任务 + +[`APScheduler`](https://apscheduler.readthedocs.io/en/latest/index.html) —— 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. + +## 从 v1 迁移 + +`APScheduler` 作为 `nonebot` v1 的可选依赖,为众多 bot 提供了方便的定时任务功能。`nonebot2` 已将 `APScheduler` 独立为 `nonebot_plugin_apscheduler` 插件,你可以在 [插件广场](https://v2.nonebot.dev/plugin-store.html) 中找到它。 + +相比于 `nonebot` v1 ,只需要安装插件并修改 `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` 从 `nonebot_plugin_apscheduler` 导入 `scheduler` 对象 + +2. 在该对象的基础上,根据 `APScheduler` 的使用方法进一步配置定时任务 + +将上述步骤归纳为最小实现的代码如下: + +```python +from nonebot import require + +scheduler = require('nonebot_plugin_apscheduler').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` 方法来实现导入其他插件的内容,此处我们使用这个方法来导入 `scheduler` 对象。 + +`nonebot` 使用的 `scheduler` 对象为 `AsyncScheduler` 。 + +> 使用该方法传入的插件本身也需要有对应实现,关于该方法的更多介绍可以参阅 [这里](./export-and-require.md) + +```python +from nonebot import require + +scheduler = require('nonebot_plugin_apscheduler').scheduler +``` + +### 编写定时任务 + +由于本部分为标准的通过 `APScheduler` 配置定时任务,有关指南请参阅 [APScheduler 官方文档](https://apscheduler.readthedocs.io/en/latest/userguide.html#adding-jobs)。 + +### 配置插件选项 + +根据项目的 `.env` 文件设置,向 `.env.*` 或 `bot.py` 文件添加 `nonebot_plugin_apscheduler` 的可选配置项 + +:::warning 注意 +`.env.*` 文件的编写应遵循 nonebot2 对 `.env.*` 文件的编写要求 +::: + +#### `apscheduler_autostart` + +类型:`bool` + +默认值:`True` + +是否自动启动 `APScheduler`。 + +对于大多数情况,我们需要在 `nonebot2` 项目被启动时启动定时任务,则此处设为 `true` + +```bash +APSCHEDULER_AUTOSTART=true +``` + +```python +nonebot.init(apscheduler_autostart=True) +``` + +#### `apscheduler_config` + +类型:`dict` + +默认值:`{"apscheduler.timezone": "Asia/Shanghai"}` + +`APScheduler` 相关配置。修改/增加其中配置项需要确保 `prefix: apscheduler`。 + +对于 `APScheduler` 的相关配置,请参阅 [scheduler-config](https://apscheduler.readthedocs.io/en/latest/userguide.html#scheduler-config) 和 [BaseScheduler](https://apscheduler.readthedocs.io/en/latest/modules/schedulers/base.html#apscheduler.schedulers.base.BaseScheduler) + +> 官方文档在绝大多数时候能提供最准确和最具时效性的指南 + +```bash +APSCHEDULER_CONFIG={"apscheduler.timezone": "Asia/Shanghai"} +``` + +```python +nonebot.init(apscheduler_config={ + "apscheduler.timezone": "Asia/Shanghai" +}) +``` diff --git a/docs/api/adapters/README.md b/docs/api/adapters/README.md index 1a1dd85b..96638ad5 100644 --- a/docs/api/adapters/README.md +++ b/docs/api/adapters/README.md @@ -10,7 +10,7 @@ sidebarDepth: 0 各协议请继承以下基类,并使用 `driver.register_adapter` 注册适配器 -## _class_ `BaseBot` +## _class_ `Bot` 基类:`abc.ABC` @@ -147,7 +147,7 @@ Adapter 类型 ```python -await bot.call_api("send_msg", message="hello world"}) +await bot.call_api("send_msg", message="hello world") await bot.send_msg(message="hello world") ``` @@ -174,104 +174,7 @@ await bot.send_msg(message="hello world") -## _class_ `BaseEvent` - -基类:`abc.ABC`, `typing.Generic` - -Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。 - - -### `__init__(raw_event)` - - -* **参数** - - - * `raw_event: Union[dict, T]`: 原始上报消息 - - - -### _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` +## _class_ `MessageSegment` 基类:`abc.ABC` @@ -296,7 +199,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * 说明: 消息段数据 -## _class_ `BaseMessage` +## _class_ `Message` 基类:`list`, `abc.ABC` @@ -309,7 +212,7 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **参数** - * `message: Union[str, dict, list, BaseModel, MessageSegment, Message]`: 消息内容 + * `message: Union[str, list, dict, MessageSegment, Message, Any]`: 消息内容 @@ -360,3 +263,161 @@ Event 基类。提供上报信息的关键信息,其余信息可从原始上 * **说明** 提取消息内纯文本消息 + + + +## _class_ `Event` + +基类:`abc.ABC`, `pydantic.main.BaseModel` + +Event 基类。提供获取关键信息的方法,其余信息可直接获取。 + + +### _abstract_ `get_type()` + + +* **说明** + + 获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。 + + + +* **返回** + + + * `Literal["message", "notice", "request", "meta_event"]` + + + +### _abstract_ `get_event_name()` + + +* **说明** + + 获取事件名称的方法。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_event_description()` + + +* **说明** + + 获取事件描述的方法,通常为事件具体内容。 + + + +* **返回** + + + * `str` + + + +### `get_log_string()` + + +* **说明** + + 获取事件日志信息的方法,通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 `NoLogException` 异常。 + + + +* **返回** + + + * `str` + + + +* **异常** + + + * `NoLogException` + + + +### _abstract_ `get_user_id()` + + +* **说明** + + 获取事件主体 id 的方法,通常是用户 id 。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_session_id()` + + +* **说明** + + 获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `get_message()` + + +* **说明** + + 获取事件消息内容的方法。 + + + +* **返回** + + + * `Message` + + + +### `get_plaintext()` + + +* **说明** + + 获取消息纯文本的方法,通常不需要修改,默认通过 `get_message().extract_plain_text` 获取。 + + + +* **返回** + + + * `str` + + + +### _abstract_ `is_tome()` + + +* **说明** + + 获取事件是否与机器人有关的方法。 + + + +* **返回** + + + * `bool` diff --git a/docs/api/adapters/cqhttp.md b/docs/api/adapters/cqhttp.md index b80d6ad1..ca5d91cb 100644 --- a/docs/api/adapters/cqhttp.md +++ b/docs/api/adapters/cqhttp.md @@ -5,6 +5,12 @@ sidebarDepth: 0 # NoneBot.adapters.cqhttp 模块 +## CQHTTP (OneBot) v11 协议适配 + +协议详情请看: [CQHTTP](https://github.com/howmanybots/onebot/blob/master/README.md) | [OneBot](https://github.com/howmanybots/onebot/blob/master/README.md) + +# NoneBot.adapters.cqhttp.utils 模块 + ## `escape(s, *, escape_comma=True)` @@ -40,10 +46,7 @@ sidebarDepth: 0 * `s: str`: 需要转义的字符串 - -## _exception_ `CQHTTPAdapterException` - -基类:[`nonebot.exception.AdapterException`](../exception.md#nonebot.exception.AdapterException) +# NoneBot.adapters.cqhttp.exception 模块 ## _exception_ `ActionFailed` @@ -81,10 +84,7 @@ sidebarDepth: 0 * `retcode: Optional[int]`: 错误码 - -## _exception_ `ApiNotAvailable` - -基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.cqhttp.exception.CQHTTPAdapterException` +# NoneBot.adapters.cqhttp.bot 模块 ## _async_ `_check_reply(bot, event)` @@ -176,7 +176,7 @@ sidebarDepth: 0 ## _class_ `Bot` -基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot) +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 @@ -285,158 +285,280 @@ CQHTTP 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 * `ActionFailed`: API 调用失败 - -## _class_ `Event` - -基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent) - -CQHTTP 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。 - - -### _property_ `id` - - -* 类型: `Optional[int]` - - -* 说明: 事件/消息 ID - - -### _property_ `name` - - -* 类型: `str` - - -* 说明: 事件名称,由类型与 `.` 组合而成 - - -### _property_ `self_id` - - -* 类型: `str` - - -* 说明: 机器人自身 ID - - -### _property_ `time` - - -* 类型: `int` - - -* 说明: 事件发生时间 - - -### _property_ `type` - - -* 类型: `str` - - -* 说明: 事件类型 - - -### _property_ `detail_type` - - -* 类型: `str` - - -* 说明: 事件详细类型 - - -### _property_ `sub_type` - - -* 类型: `Optional[str]` - - -* 说明: 事件子类型 - - -### _property_ `user_id` - - -* 类型: `Optional[int]` - - -* 说明: 事件主体 ID - - -### _property_ `group_id` - - -* 类型: `Optional[int]` - - -* 说明: 事件主体群 ID - - -### _property_ `to_me` - - -* 类型: `Optional[bool]` - - -* 说明: 消息是否与机器人相关 - - -### _property_ `message` - - -* 类型: `Optional[Message]` - - -* 说明: 消息内容 - - -### _property_ `reply` - - -* 类型: `Optional[dict]` - - -* 说明: 回复消息详情 - - -### _property_ `raw_message` - - -* 类型: `Optional[str]` - - -* 说明: 原始消息 - - -### _property_ `plain_text` - - -* 类型: `Optional[str]` - - -* 说明: 纯文本消息内容 - - -### _property_ `sender` - - -* 类型: `Optional[dict]` - - -* 说明: 消息发送者信息 +# NoneBot.adapters.cqhttp.message 模块 ## _class_ `MessageSegment` -基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment) +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) CQHTTP 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 ## _class_ `Message` -基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage) +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) CQHTTP 协议 Message 适配。 + +# NoneBot.adapters.cqhttp.permission 模块 + + +## `PRIVATE` + + +* **说明**: 匹配任意私聊消息类型事件 + + +## `PRIVATE_FRIEND` + + +* **说明**: 匹配任意好友私聊消息类型事件 + + +## `PRIVATE_GROUP` + + +* **说明**: 匹配任意群临时私聊消息类型事件 + + +## `PRIVATE_OTHER` + + +* **说明**: 匹配任意其他私聊消息类型事件 + + +## `GROUP` + + +* **说明**: 匹配任意群聊消息类型事件 + + +## `GROUP_MEMBER` + + +* **说明**: 匹配任意群员群聊消息类型事件 + +:::warning 警告 +该权限通过 event.sender 进行判断且不包含管理员以及群主! +::: + + +## `GROUP_ADMIN` + + +* **说明**: 匹配任意群管理员群聊消息类型事件 + + +## `GROUP_OWNER` + + +* **说明**: 匹配任意群主群聊消息类型事件 + +# NoneBot.adapters.cqhttp.event 模块 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +CQHTTP 协议事件,字段与 CQHTTP 一致。各事件字段参考 [CQHTTP 文档](https://github.com/howmanybots/onebot/blob/master/README.md) + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +消息事件 + + +### `to_me` + + +* **说明** + + 消息是否与机器人有关 + + + +* **类型** + + `bool` + + + +### `reply` + + +* **说明** + + 消息中提取的回复消息,内容为 `get_msg` API 返回结果 + + + +* **类型** + + `Optional[Reply]` + + + +## _class_ `PrivateMessageEvent` + +基类:`nonebot.adapters.cqhttp.event.MessageEvent` + +私聊消息 + + +## _class_ `GroupMessageEvent` + +基类:`nonebot.adapters.cqhttp.event.MessageEvent` + +群消息 + + +## _class_ `NoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +通知事件 + + +## _class_ `GroupUploadNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群文件上传事件 + + +## _class_ `GroupAdminNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群管理员变动 + + +## _class_ `GroupDecreaseNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群成员减少事件 + + +## _class_ `GroupIncreaseNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群成员增加事件 + + +## _class_ `GroupBanNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群禁言事件 + + +## _class_ `FriendAddNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +好友添加事件 + + +## _class_ `GroupRecallNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +群消息撤回事件 + + +## _class_ `FriendRecallNoticeEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +好友消息撤回事件 + + +## _class_ `NotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NoticeEvent` + +提醒事件 + + +## _class_ `PokeNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +戳一戳提醒事件 + + +## _class_ `LuckyKingNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +群红包运气王提醒事件 + + +## _class_ `HonorNotifyEvent` + +基类:`nonebot.adapters.cqhttp.event.NotifyEvent` + +群荣誉变更提醒事件 + + +## _class_ `RequestEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +请求事件 + + +## _class_ `FriendRequestEvent` + +基类:`nonebot.adapters.cqhttp.event.RequestEvent` + +加好友请求事件 + + +## _class_ `GroupRequestEvent` + +基类:`nonebot.adapters.cqhttp.event.RequestEvent` + +加群请求/邀请事件 + + +## _class_ `MetaEvent` + +基类:`nonebot.adapters.cqhttp.event.Event` + +元事件 + + +## _class_ `LifecycleMetaEvent` + +基类:`nonebot.adapters.cqhttp.event.MetaEvent` + +生命周期元事件 + + +## _class_ `HeartbeatMetaEvent` + +基类:`nonebot.adapters.cqhttp.event.MetaEvent` + +心跳元事件 + + +## `get_event_model(event_name)` + + +* **说明** + + 根据事件名获取对应 `Event Model` 及 `FallBack Event Model` 列表 + + + +* **返回** + + + * `List[Type[Event]]` diff --git a/docs/api/adapters/ding.md b/docs/api/adapters/ding.md index 0bbdd6d8..32fbb891 100644 --- a/docs/api/adapters/ding.md +++ b/docs/api/adapters/ding.md @@ -5,6 +5,12 @@ sidebarDepth: 0 # NoneBot.adapters.ding 模块 +## 钉钉群机器人 协议适配 + +协议详情请看: [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) + +# NoneBot.adapters.ding.exception 模块 + ## _exception_ `DingAdapterException` @@ -38,11 +44,6 @@ sidebarDepth: 0 -## _exception_ `ApiNotAvailable` - -基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException` - - ## _exception_ `NetworkError` 基类:[`nonebot.exception.NetworkError`](../exception.md#nonebot.exception.NetworkError), `nonebot.adapters.ding.exception.DingAdapterException` @@ -63,7 +64,7 @@ sidebarDepth: 0 ## _exception_ `SessionExpired` -基类:[`nonebot.exception.ApiNotAvailable`](../exception.md#nonebot.exception.ApiNotAvailable), `nonebot.adapters.ding.exception.DingAdapterException` +基类:`nonebot.adapters.ding.exception.ApiNotAvailable`, `nonebot.adapters.ding.exception.DingAdapterException` * **说明** @@ -71,10 +72,12 @@ sidebarDepth: 0 发消息的 session 已经过期。 +# NoneBot.adapters.ding.bot 模块 + ## _class_ `Bot` -基类:[`nonebot.adapters.BaseBot`](README.md#nonebot.adapters.BaseBot) +基类:[`nonebot.adapters.Bot`](README.md#nonebot.adapters.Bot) 钉钉 协议 Bot 适配。继承属性参考 [BaseBot](./#class-basebot) 。 @@ -94,22 +97,6 @@ sidebarDepth: 0 -### _async_ `handle_message(body)` - - -* **说明** - - 处理上报消息的函数,转换为 `Event` 事件后调用 `nonebot.message.handle_event` 进一步处理事件。 - - - -* **参数** - - - * `message: dict`: 收到的上报消息 - - - ### _async_ `call_api(api, event=None, **data)` @@ -190,162 +177,54 @@ sidebarDepth: 0 * `ActionFailed`: API 调用失败 - -## _class_ `Event` - -基类:[`nonebot.adapters.BaseEvent`](README.md#nonebot.adapters.BaseEvent) - -钉钉 协议 Event 适配。继承属性参考 [BaseEvent](./#class-baseevent) 。 - - -### _property_ `raw_event` - -原始上报消息 - - -### _property_ `id` - - -* 类型: `Optional[str]` - - -* 说明: 消息 ID - - -### _property_ `name` - - -* 类型: `str` - - -* 说明: 事件名称,由 type.\`detail_type\` 组合而成 - - -### _property_ `self_id` - - -* 类型: `str` - - -* 说明: 机器人自身 ID - - -### _property_ `time` - - -* 类型: `int` - - -* 说明: 消息的时间戳,单位 s - - -### _property_ `type` - - -* 类型: `str` - - -* 说明: 事件类型 - - -### _property_ `detail_type` - - -* 类型: `str` - - -* 说明: 事件详细类型 - - -### _property_ `sub_type` - - -* 类型: `None` - - -* 说明: 钉钉适配器无事件子类型 - - -### _property_ `user_id` - - -* 类型: `Optional[str]` - - -* 说明: 发送者 ID - - -### _property_ `group_id` - - -* 类型: `Optional[str]` - - -* 说明: 事件主体群 ID - - -### _property_ `to_me` - - -* 类型: `Optional[bool]` - - -* 说明: 消息是否与机器人相关 - - -### _property_ `message` - - -* 类型: `Optional[Message]` - - -* 说明: 消息内容 - - -### _property_ `reply` - - -* 类型: `None` - - -* 说明: 回复消息详情 - - -### _property_ `raw_message` - - -* 类型: `Optional[str]` - - -* 说明: 原始消息 - - -### _property_ `plain_text` - - -* 类型: `Optional[str]` - - -* 说明: 纯文本消息内容 - - -### _property_ `sender` - - -* 类型: `Optional[dict]` - - -* 说明: 消息发送者信息 +# NoneBot.adapters.ding.message 模块 ## _class_ `MessageSegment` -基类:[`nonebot.adapters.BaseMessageSegment`](README.md#nonebot.adapters.BaseMessageSegment) +基类:[`nonebot.adapters.MessageSegment`](README.md#nonebot.adapters.MessageSegment) 钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 -### _static_ `actionCardSingleMultiBtns(title, text, btns=[], hideAvatar=False, btnOrientation='1')` +### _static_ `atAll()` + +@全体 + + +### _static_ `atMobiles(*mobileNumber)` + +@指定手机号人员 + + +### _static_ `text(text)` + +发送 `text` 类型消息 + + +### _static_ `image(picURL)` + +发送 `image` 类型消息 + + +### _static_ `extension(dict_)` + +"标记 text 文本的 extension 属性,需要与 text 消息段相加。 + + +### _static_ `markdown(title, text)` + +发送 `markdown` 类型消息 + + +### _static_ `actionCardSingleBtn(title, text, singleTitle, singleURL)` + +发送 `actionCardSingleBtn` 类型消息 + + +### _static_ `actionCardMultiBtns(title, text, btns, hideAvatar=False, btnOrientation='1')` + +发送 `actionCardMultiBtn` 类型消息 * **参数** @@ -358,7 +237,9 @@ sidebarDepth: 0 -### _static_ `feedCard(links=[])` +### _static_ `feedCard(links)` + +发送 `feedCard` 类型消息 * **参数** @@ -368,13 +249,45 @@ sidebarDepth: 0 -### _static_ `empty()` - -不想回复消息到群里 - - ## _class_ `Message` -基类:[`nonebot.adapters.BaseMessage`](README.md#nonebot.adapters.BaseMessage) +基类:[`nonebot.adapters.Message`](README.md#nonebot.adapters.Message) 钉钉 协议 Message 适配。 + +# NoneBot.adapters.ding.event 模块 + + +## _class_ `Event` + +基类:[`nonebot.adapters.Event`](README.md#nonebot.adapters.Event) + +钉钉协议事件。各事件字段参考 [钉钉文档](https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p) + + +## _class_ `ConversationType` + +基类:`str`, `enum.Enum` + +An enumeration. + + +## _class_ `MessageEvent` + +基类:`nonebot.adapters.ding.event.Event` + +消息事件 + + +## _class_ `PrivateMessageEvent` + +基类:`nonebot.adapters.ding.event.MessageEvent` + +私聊消息事件 + + +## _class_ `GroupMessageEvent` + +基类:`nonebot.adapters.ding.event.MessageEvent` + +群消息事件 diff --git a/docs/api/config.md b/docs/api/config.md index f2eaa4d4..2e7c6a4d 100644 --- a/docs/api/config.md +++ b/docs/api/config.md @@ -195,7 +195,7 @@ X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 ### `superusers` -* **类型**: `Set[int]` +* **类型**: `Set[str]` * **默认值**: `set()` @@ -211,7 +211,7 @@ X-Signature: sha1=f9ddd4863ace61e64f462d41ca311e3d2c1176e2 ```default -SUPER_USERS=[12345789] +SUPER_USERS=["12345789"] ``` diff --git a/docs/api/drivers/README.md b/docs/api/drivers/README.md index 624220ba..313717cb 100644 --- a/docs/api/drivers/README.md +++ b/docs/api/drivers/README.md @@ -10,7 +10,7 @@ sidebarDepth: 0 各驱动请继承以下基类 -## _class_ `BaseDriver` +## _class_ `Driver` 基类:`abc.ABC` @@ -32,6 +32,36 @@ Driver 基类。将后端框架封装,以满足适配器使用。 +### `_ws_connection_hook` + + +* **类型** + + `Set[T_WebSocketConnectionHook]` + + + +* **说明** + + WebSocket 连接建立时执行的函数 + + + +### `_ws_disconnection_hook` + + +* **类型** + + `Set[T_WebSocketDisconnectionHook]` + + + +* **说明** + + WebSocket 连接断开时执行的函数 + + + ### _abstract_ `__init__(env, config)` @@ -154,6 +184,48 @@ Driver 基类。将后端框架封装,以满足适配器使用。 注册一个在驱动停止时运行的函数 +### `on_bot_connect(func)` + + +* **说明** + + 装饰一个函数使他在 bot 通过 WebSocket 连接成功时执行。 + + + +* **函数参数** + + + * `bot: Bot`: 当前连接上的 Bot 对象 + + + +### `on_bot_disconnect(func)` + + +* **说明** + + 装饰一个函数使他在 bot 通过 WebSocket 连接断开时执行。 + + + +* **函数参数** + + + * `bot: Bot`: 当前连接上的 Bot 对象 + + + +### `_bot_connect(bot)` + +在 WebSocket 连接成功后,调用该函数来注册 bot 对象 + + +### `_bot_disconnect(bot)` + +在 WebSocket 连接断开后,调用该函数来注销 bot 对象 + + ### _abstract_ `run(host=None, port=None, *args, **kwargs)` @@ -189,7 +261,7 @@ Driver 基类。将后端框架封装,以满足适配器使用。 用于处理 WebSocket 类型请求的函数 -## _class_ `BaseWebSocket` +## _class_ `WebSocket` 基类:`object` diff --git a/docs/api/drivers/fastapi.md b/docs/api/drivers/fastapi.md index b4f5c6fb..edd8e474 100644 --- a/docs/api/drivers/fastapi.md +++ b/docs/api/drivers/fastapi.md @@ -12,7 +12,7 @@ sidebarDepth: 0 ## _class_ `Driver` -基类:[`nonebot.drivers.BaseDriver`](README.md#nonebot.drivers.BaseDriver) +基类:[`nonebot.drivers.Driver`](README.md#nonebot.drivers.Driver) FastAPI 驱动框架 @@ -66,53 +66,3 @@ fastapi 使用的 logger ### `run(host=None, port=None, *, app=None, **kwargs)` 使用 `uvicorn` 启动 FastAPI - - -### _async_ `_handle_http(adapter, request, data=Body(Ellipsis))` - -用于处理 HTTP 类型请求的函数 - - -### _async_ `_handle_ws_reverse(adapter, websocket)` - -用于处理 WebSocket 类型请求的函数 - - -## _class_ `WebSocket` - -基类:[`nonebot.drivers.BaseWebSocket`](README.md#nonebot.drivers.BaseWebSocket) - - -### _property_ `closed` - - -* **类型** - - `bool` - - - -* **说明** - - 连接是否已经关闭 - - - -### _async_ `accept()` - -接受 WebSocket 连接请求 - - -### _async_ `close(code=1000)` - -关闭 WebSocket 连接请求 - - -### _async_ `receive()` - -接收一条 WebSocket 信息 - - -### _async_ `send(data)` - -发送一条 WebSocket 信息 diff --git a/docs/api/exception.md b/docs/api/exception.md index 0c584f75..ac2d28b2 100644 --- a/docs/api/exception.md +++ b/docs/api/exception.md @@ -150,6 +150,17 @@ sidebarDepth: 0 +## _exception_ `NoLogException` + +基类:`Exception` + + +* **说明** + + 指示 NoneBot 对当前 `Event` 进行处理但不显示 Log 信息,可在 `get_log_string` 时抛出 + + + ## _exception_ `ApiNotAvailable` 基类:`nonebot.exception.AdapterException` diff --git a/docs/api/log.md b/docs/api/log.md index 77ce3609..e6096cff 100644 --- a/docs/api/log.md +++ b/docs/api/log.md @@ -40,16 +40,3 @@ NoneBot 使用 [loguru](https://github.com/Delgan/loguru) 来记录日志信息 ```python from nonebot.log import logger ``` - - -## _class_ `LoguruHandler` - -基类:`logging.Handler` - - -### `emit(record)` - -Do whatever it takes to actually log the specified logging record. - -This version is intended to be implemented by subclasses and so -raises a NotImplementedError. diff --git a/docs/api/matcher.md b/docs/api/matcher.md index 9e72b658..22eabc3b 100644 --- a/docs/api/matcher.md +++ b/docs/api/matcher.md @@ -157,7 +157,7 @@ sidebarDepth: 0 * **类型** - `dict` + `T_State` @@ -167,12 +167,27 @@ sidebarDepth: 0 +### `_default_state_factory` + + +* **类型** + + `Optional[T_State]` + + + +* **说明** + + 事件响应器默认工厂函数 + + + ### `_default_parser` * **类型** - `Optional[ArgsParser]` + `Optional[T_ArgsParser]` @@ -192,7 +207,7 @@ sidebarDepth: 0 * **类型** - `List[Handler]` + `List[T_Handler]` @@ -202,7 +217,7 @@ sidebarDepth: 0 -### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, expire_time=None)` +### _classmethod_ `new(type_='', rule=None, permission=None, handlers=None, temp=False, priority=1, block=False, *, module=None, default_state=None, default_state_factory=None, expire_time=None)` * **说明** @@ -214,7 +229,7 @@ sidebarDepth: 0 * **参数** - * `type_: str`: 事件响应器类型,与 `event.type` 一致时触发,空字符串表示任意 + * `type_: str`: 事件响应器类型,与 `event.get_type()` 一致时触发,空字符串表示任意 * `rule: Optional[Rule]`: 匹配规则 @@ -223,7 +238,7 @@ sidebarDepth: 0 * `permission: Optional[Permission]`: 权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器,即触发一次后删除 @@ -238,7 +253,10 @@ sidebarDepth: 0 * `module: Optional[str]`: 事件响应器所在模块名称 - * `default_state: Optional[dict]`: 默认状态 `state` + * `default_state: Optional[T_State]`: 默认状态 `state` + + + * `default_state_factory: Optional[T_StateFactory]`: 默认状态 `state` 的工厂函数 * `expire_time: Optional[datetime]`: 事件响应器最终有效时间点,过时即被删除 @@ -296,7 +314,7 @@ sidebarDepth: 0 * `event: Event`: 上报事件 - * `state: dict`: 当前状态 + * `state: T_State`: 当前状态 @@ -319,7 +337,7 @@ sidebarDepth: 0 * **参数** - * `func: ArgsParser`: 参数解析函数 + * `func: T_ArgsParser`: 参数解析函数 @@ -373,7 +391,7 @@ sidebarDepth: 0 * `prompt: Optional[Union[str, Message, MessageSegment]]`: 在参数不存在时向用户发送的消息 - * `args_parser: Optional[ArgsParser]`: 可选参数解析函数,空则使用默认解析函数 + * `args_parser: Optional[T_ArgsParser]`: 可选参数解析函数,空则使用默认解析函数 diff --git a/docs/api/message.md b/docs/api/message.md index c9d7c158..5bd6c332 100644 --- a/docs/api/message.md +++ b/docs/api/message.md @@ -30,7 +30,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State @@ -54,7 +54,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前事件运行前 State + * `state: T_State`: 当前事件运行前 State @@ -81,7 +81,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State @@ -111,7 +111,7 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State diff --git a/docs/api/permission.md b/docs/api/permission.md index 26d3cd34..1c42b2c8 100644 --- a/docs/api/permission.md +++ b/docs/api/permission.md @@ -50,72 +50,14 @@ sidebarDepth: 0 * **参数** - * `*user: int`: 白名单 + * `*user: str`: 白名单 * `perm: Permission`: 需要同时满足的权限 -## `PRIVATE` - - -* **说明**: 匹配任意私聊消息类型事件 - - -## `PRIVATE_FRIEND` - - -* **说明**: 匹配任意好友私聊消息类型事件 - - -## `PRIVATE_GROUP` - - -* **说明**: 匹配任意群临时私聊消息类型事件 - - -## `PRIVATE_OTHER` - - -* **说明**: 匹配任意其他私聊消息类型事件 - - -## `GROUP` - - -* **说明**: 匹配任意群聊消息类型事件 - - -## `GROUP_MEMBER` - - -* **说明**: 匹配任意群员群聊消息类型事件 - -:::warning 警告 -该权限通过 event.sender 进行判断且不包含管理员以及群主! -::: - - -## `GROUP_ADMIN` - - -* **说明**: 匹配任意群管理员群聊消息类型事件 - - -## `GROUP_OWNER` - - -* **说明**: 匹配任意群主群聊消息类型事件 - - ## `SUPERUSER` * **说明**: 匹配任意超级用户消息类型事件 - - -## `EVERYBODY` - - -* **说明**: 匹配任意消息类型事件 diff --git a/docs/api/plugin.md b/docs/api/plugin.md index 91d7320e..91e3e763 100644 --- a/docs/api/plugin.md +++ b/docs/api/plugin.md @@ -100,7 +100,7 @@ def something_else(): * **说明**: 插件内定义的导出内容 -## `on(type='', rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` +## `on(type='', rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` * **说明** @@ -115,13 +115,13 @@ def something_else(): * `type: str`: 事件响应器类型 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -133,7 +133,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -144,7 +147,7 @@ def something_else(): -## `on_metaevent(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` +## `on_metaevent(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` * **说明** @@ -156,10 +159,10 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -171,7 +174,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -182,7 +188,7 @@ def something_else(): -## `on_message(rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=True, state=None)` +## `on_message(rule=None, permission=None, *, handlers=None, temp=False, priority=1, block=True, state=None, state_factory=None)` * **说明** @@ -194,13 +200,13 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -212,7 +218,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -223,7 +232,7 @@ def something_else(): -## `on_notice(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` +## `on_notice(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` * **说明** @@ -235,10 +244,10 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -250,7 +259,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -261,7 +273,7 @@ def something_else(): -## `on_request(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None)` +## `on_request(rule=None, *, handlers=None, temp=False, priority=1, block=False, state=None, state_factory=None)` * **说明** @@ -273,10 +285,10 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -288,7 +300,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -314,13 +329,13 @@ def something_else(): * `msg: str`: 指定消息开头内容 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -332,7 +347,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -358,13 +376,13 @@ def something_else(): * `msg: str`: 指定消息结尾内容 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -376,7 +394,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -402,13 +423,13 @@ def something_else(): * `keywords: Set[str]`: 关键词列表 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -420,7 +441,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -448,7 +472,7 @@ def something_else(): * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 @@ -457,7 +481,7 @@ def something_else(): * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -469,7 +493,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -500,13 +527,13 @@ def something_else(): * `flags: Union[int, re.RegexFlag]`: 正则匹配标志 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -518,7 +545,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -648,13 +678,13 @@ def something_else(): * `type: str`: 事件响应器类型 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -666,7 +696,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -689,10 +722,10 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -704,7 +737,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -727,13 +763,13 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -745,7 +781,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -768,10 +807,10 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -783,7 +822,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -806,10 +848,10 @@ def something_else(): * **参数** - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -821,7 +863,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -847,13 +892,13 @@ def something_else(): * `msg: str`: 指定消息开头内容 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -865,7 +910,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -891,13 +939,13 @@ def something_else(): * `msg: str`: 指定消息结尾内容 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -909,7 +957,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -935,13 +986,13 @@ def something_else(): * `keywords: Set[str]`: 关键词列表 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -953,7 +1004,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -981,7 +1035,7 @@ def something_else(): * `cmd: Union[str, Tuple[str, ...]]`: 指定命令内容 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `aliases: Optional[Set[Union[str, Tuple[str, ...]]]]`: 命令别名 @@ -990,7 +1044,7 @@ def something_else(): * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -1002,7 +1056,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 @@ -1033,13 +1090,13 @@ def something_else(): * `flags: Union[int, re.RegexFlag]`: 正则匹配标志 - * `rule: Optional[Union[Rule, RuleChecker]]`: 事件响应规则 + * `rule: Optional[Union[Rule, T_RuleChecker]]`: 事件响应规则 * `permission: Optional[Permission]`: 事件响应权限 - * `handlers: Optional[List[Handler]]`: 事件处理函数列表 + * `handlers: Optional[List[T_Handler]]`: 事件处理函数列表 * `temp: bool`: 是否为临时事件响应器(仅执行一次) @@ -1051,7 +1108,10 @@ def something_else(): * `block: bool`: 是否阻止事件向更低优先级传递 - * `state: Optional[dict]`: 默认的 state + * `state: Optional[T_State]`: 默认 state + + + * `state_factory: Optional[T_StateFactory]`: 默认 state 的工厂函数 diff --git a/docs/api/rule.md b/docs/api/rule.md index dade2a5b..cb3fd05f 100644 --- a/docs/api/rule.md +++ b/docs/api/rule.md @@ -42,7 +42,7 @@ Rule(async_function, run_sync(sync_function)) * **参数** - * `*checkers: Callable[[Bot, Event, dict], Awaitable[bool]]`: **异步** RuleChecker + * `*checkers: Callable[[Bot, Event, T_State], Awaitable[bool]]`: **异步** RuleChecker @@ -58,7 +58,7 @@ Rule(async_function, run_sync(sync_function)) * **类型** - * `Set[Callable[[Bot, Event, dict], Awaitable[bool]]]` + * `Set[Callable[[Bot, Event, T_State], Awaitable[bool]]]` @@ -80,7 +80,7 @@ Rule(async_function, run_sync(sync_function)) * `event: Event`: Event 对象 - * `state: dict`: 当前 State + * `state: T_State`: 当前 State @@ -200,7 +200,7 @@ Rule(async_function, run_sync(sync_function)) * **说明** - 通过 `event.to_me` 判断消息是否是发送给机器人 + 通过 `event.is_tome()` 判断事件是否与机器人有关 diff --git a/docs/api/typing.md b/docs/api/typing.md index 8f8a2223..5d1b3d7b 100644 --- a/docs/api/typing.md +++ b/docs/api/typing.md @@ -14,108 +14,76 @@ sidebarDepth: 0 以下类型均可从 nonebot.typing 模块导入。 -## `Driver` +## `T_State` * **类型** - `BaseDriver` + `Dict[Any, Any]` * **说明** - 所有 Driver 的基类。 + 事件处理状态 State 类型 -## `WebSocket` +## `T_StateFactory` * **类型** - `BaseWebSocket` + `Callable[[Bot, Event], Awaitable[T_State]]` * **说明** - 所有 WebSocket 的基类。 + 事件处理状态 State 类工厂函数 -## `Bot` +## `T_WebSocketConnectionHook` * **类型** - `BaseBot` + `Callable[[Bot], Awaitable[None]]` * **说明** - 所有 Bot 的基类。 + WebSocket 连接建立时执行的函数 -## `Event` +## `T_WebSocketDisconnectionHook` * **类型** - `BaseEvent` + `Callable[[Bot], Awaitable[None]]` * **说明** - 所有 Event 的基类。 + WebSocket 连接断开时执行的函数 -## `Message` +## `T_EventPreProcessor` * **类型** - `BaseMessage` - - - -* **说明** - - 所有 Message 的基类。 - - - - -## `MessageSegment` - - -* **类型** - - `BaseMessageSegment` - - - -* **说明** - - 所有 MessageSegment 的基类。 - - - - -## `EventPreProcessor` - - -* **类型** - - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + `Callable[[Bot, Event, T_State], Awaitable[None]]` @@ -126,12 +94,12 @@ sidebarDepth: 0 -## `EventPostProcessor` +## `T_EventPostProcessor` * **类型** - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + `Callable[[Bot, Event, T_State], Awaitable[None]]` @@ -142,12 +110,12 @@ sidebarDepth: 0 -## `RunPreProcessor` +## `T_RunPreProcessor` * **类型** - `Callable[[Matcher, Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + `Callable[[Matcher, Bot, Event, T_State], Awaitable[None]]` @@ -158,12 +126,12 @@ sidebarDepth: 0 -## `RunPostProcessor` +## `T_RunPostProcessor` * **类型** - `Callable[[Matcher, Optional[Exception], Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + `Callable[[Matcher, Optional[Exception], Bot, Event, T_State], Awaitable[None]]` @@ -174,60 +142,12 @@ sidebarDepth: 0 -## `Matcher` +## `T_RuleChecker` * **类型** - `Matcher` - - - -* **说明** - - Matcher 即响应事件的处理类。通过 Rule 判断是否响应事件,运行 Handler。 - - - - -## `MatcherGroup` - - -* **类型** - - `MatcherGroup` - - - -* **说明** - - MatcherGroup 为 Matcher 的集合。可以共享 Handler。 - - - - -## `Rule` - - -* **类型** - - `Rule` - - - -* **说明** - - Rule 即判断是否响应事件的处理类。内部存储 RuleChecker ,返回全为 True 则响应事件。 - - - - -## `RuleChecker` - - -* **类型** - - `Callable[[Bot, Event, dict], Union[bool, Awaitable[bool]]]` + `Callable[[Bot, Event, T_State], Union[bool, Awaitable[bool]]]` @@ -238,23 +158,7 @@ sidebarDepth: 0 -## `Permission` - - -* **类型** - - `Permission` - - - -* **说明** - - Permission 即判断是否响应消息的处理类。内部存储 PermissionChecker ,返回只要有一个 True 则响应消息。 - - - - -## `PermissionChecker` +## `T_PermissionChecker` * **类型** @@ -270,12 +174,22 @@ sidebarDepth: 0 -## `Handler` +## `T_Handler` * **类型** - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + + * `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` + + + * `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]` @@ -286,12 +200,12 @@ sidebarDepth: 0 -## `ArgsParser` +## `T_ArgsParser` * **类型** - `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` + `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` diff --git a/docs/api/utils.md b/docs/api/utils.md index 52cf5766..ab3ea0c2 100644 --- a/docs/api/utils.md +++ b/docs/api/utils.md @@ -52,8 +52,32 @@ sidebarDepth: 0 +## `logger_wrapper` + + +* **说明** + + +用于打印 adapter 的日志。 + + +* **Log 参数** + + + +* `level: Literal['WARNING', 'DEBUG', 'INFO']`: 日志等级 + + +* `message: str`: 日志信息 + + +* `exception: Optional[Exception]`: 异常信息 + + ## _class_ `DataclassEncoder` +基类:`json.encoder.JSONEncoder` + * **说明** diff --git a/docs/guide/basic-configuration.md b/docs/guide/basic-configuration.md index e4c4449f..0cd9156a 100644 --- a/docs/guide/basic-configuration.md +++ b/docs/guide/basic-configuration.md @@ -13,19 +13,30 @@ NoneBot 在启动时将会从系统环境变量或者 `.env` 文件中寻找变量 `ENVIRONMENT` (大小写不敏感),默认值为 `prod`。 这将引导 NoneBot 从系统环境变量或者 `.env.{ENVIRONMENT}` 文件中进一步加载具体配置。 -现在,我们在 `.env` 文件中写入当前环境信息 +现在,我们在 `.env` 文件中写入当前环境信息: ```bash # .env ENVIRONMENT=dev ``` +如你所想,之后 NoneBot 就会从 `.env.dev` 文件中加载环境变量。 + ## .env.\* 文件 -详细配置文件,使用 [pydantic](https://pydantic-docs.helpmanual.io/) 加载配置。在 NoneBot 初始化时可以指定忽略 `.env` 中的环境信息转而加载某个配置文件: `nonebot.init(_env_file=".env.dev")`。 +NoneBot 使用 [pydantic](https://pydantic-docs.helpmanual.io/) 进行配置管理,会从 `.env.{ENVIRONMENT}` 文件中获悉环境配置。 + +可以在 NoneBot 初始化时指定加载某个环境配置文件: `nonebot.init(_env_file=".env.dev")`,这将忽略你在 `.env` 中设置的环境信息。 :::warning 提示 -由于 `pydantic` 使用 JSON 加载配置项,请确保配置项值为 JSON 能够解析的数据。如果 JSON 解析失败将作为字符串处理。 +由于 `pydantic` 使用 JSON 解析配置项,请确保配置项值为 JSON 格式的数据。如: + +```bash +list=["123456789", "987654321", 1] +test={"hello": "world"} +``` + +如果配置项值解析失败将作为字符串处理。 ::: 示例及说明: @@ -46,6 +57,10 @@ CUSTOM_CONFIG2= # 留空则从系统环境变量读取,如不存在则为空 详细的配置项参考 [Config Reference](../api/config.md) 。 +## 系统环境变量 + +如果在系统环境变量中定义了配置,则一样会被读取。 + ## bot.py 文件 配置项也可以在 NoneBot 初始化时传入。此处可以传入任意合法 Python 变量。当然也可以在初始化完成后修改或新增。 @@ -65,4 +80,4 @@ config.custom_config4 = "new config after init" ## 优先级 -`bot.py init` > `env file` > `system env` +`bot.py init` > `system env` > `env file` diff --git a/docs/guide/cqhttp-guide.md b/docs/guide/cqhttp-guide.md new file mode 100644 index 00000000..356fa6c3 --- /dev/null +++ b/docs/guide/cqhttp-guide.md @@ -0,0 +1,101 @@ +# CQHTTP 协议使用指南 + +## 配置 CQHTTP 协议端(以 QQ 为例) + +单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 + +QQ 协议端举例: + +- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo)) +- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded) +- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai) +- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api) +- [OICQ-http-api](https://github.com/takayama-lily/onebot) (基于 [OICQ](https://github.com/takayama-lily/oicq)) + +这里以 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) 为例 + +1. 下载 go-cqhttp 对应平台的 release 文件,[点此前往](https://github.com/Mrs4s/go-cqhttp/releases) +2. 运行 exe 文件或者使用 `./go-cqhttp` 启动 +3. 生成默认配置文件并修改默认配置 + +```hjson{2,3,35-36,42} +{ + uin: 机器人QQ号 + password: 机器人密码 + encrypt_password: false + password_encrypted: "" + enable_db: true + access_token: "" + relogin: { + enabled: true + relogin_delay: 3 + max_relogin_times: 0 + } + _rate_limit: { + enabled: false + frequency: 1 + bucket_size: 1 + } + ignore_invalid_cqcode: false + force_fragmented: false + heartbeat_interval: 0 + http_config: { + enabled: false + host: "0.0.0.0" + port: 5700 + timeout: 0 + post_urls: {} + } + ws_config: { + enabled: false + host: "0.0.0.0" + port: 6700 + } + ws_reverse_servers: [ + { + enabled: true + reverse_url: ws://127.0.0.1:8080/cqhttp/ws + reverse_api_url: ws://you_websocket_api.server + reverse_event_url: ws://you_websocket_event.server + reverse_reconnect_interval: 3000 + } + ] + post_message_format: array + use_sso_address: false + debug: false + log_level: "" + web_ui: { + enabled: false + host: 127.0.0.1 + web_ui_port: 9999 + web_input: false + } +} +``` + +其中 `ws://127.0.0.1:8080/cqhttp/ws` 中的 `127.0.0.1` 和 `8080` 应分别对应 nonebot 配置的 HOST 和 PORT。 + +`cqhttp` 是前述 `register_adapter` 时传入的第一个参数,代表设置的 `CQHTTPBot` 适配器的路径,你可以对不同的适配器设置不同路径以作区别。 + +## 历史性的第一次对话 + +一旦新的配置文件正确生效之后,NoneBot 所在的控制台(如果正在运行的话)应该会输出类似下面的内容(两条访问日志): + +```default +09-14 21:31:16 [INFO] uvicorn | ('127.0.0.1', 12345) - "WebSocket /cqhttp/ws" [accepted] +09-14 21:31:16 [INFO] nonebot | WebSocket Connection from CQHTTP Bot 你的QQ号 Accepted! +``` + +这表示 CQHTTP 协议端已经成功地使用 CQHTTP 协议连接上了 NoneBot。 + +现在,尝试向你的机器人账号发送如下内容: + +```default +/echo 你好,世界 +``` + +到这里如果一切 OK,你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅! + + + + diff --git a/docs/guide/creating-a-handler.md b/docs/guide/creating-a-handler.md index ca65b1a6..5b6b0591 100644 --- a/docs/guide/creating-a-handler.md +++ b/docs/guide/creating-a-handler.md @@ -6,14 +6,14 @@ ```python{1,2,8,9} @weather.handle() -async def handle_first_receive(bot: Bot, event: Event, state: dict): - args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 +async def handle_first_receive(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 if args: state["city"] = args # 如果用户发送了参数则直接赋值 @weather.got("city", prompt="你想查询哪个城市的天气呢?") -async def handle_city(bot: Bot, event: Event, state: dict): +async def handle_city(bot: Bot, event: Event, state: T_State): city = state["city"] if city not in ["上海", "北京"]: await weather.reject("你想查询的城市暂不支持,请重新输入!") @@ -53,12 +53,12 @@ async def handle_city(bot: Bot, event: Event, state: dict): ```python @matcher.receive() -async def handle(bot: Bot, event: Event, state: dict): +async def handle(bot: Bot, event: Event, state: T_State): state["key"] = "hello" @matcher.got("key2", prompt="{key}!") -async def handle2(bot: Bot, event: Event, state: dict): +async def handle2(bot: Bot, event: Event, state: T_State): pass ``` @@ -69,23 +69,61 @@ async def handle2(bot: Bot, event: Event, state: dict): ```python @matcher.got("key1") @matcher.got("key2") -async def handle(bot: Bot, event: Event, state: dict): +async def handle(bot: Bot, event: Event, state: State): pass ``` ### 事件处理函数参数 -事件处理函数类型为 `Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]` 。 +事件处理函数类型为: + +- `Callable[[Bot, Event, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, T_State, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot, Matcher], Union[Awaitable[None], Awaitable[NoReturn]]]` +- `Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]` + +简单说就是:除了 `bot` 参数,其他都是可选的。 + +以下函数都是合法的事件处理函数(仅列举常用的): + +```python +async def handle(bot: Bot, event: Event, state: T_State): + pass + +async def handle(bot: Bot, event: Event, state: T_State, matcher: Matcher): + pass + +async def handle(bot: Bot, event: Event): + pass + +async def handle(bot: Bot, state: T_State): + pass + +async def handle(bot: Bot): + pass +``` + +:::danger 警告 +函数的参数名固定不能修改! +::: 参数分别为: -1. [nonebot.typing.Bot](../api/typing.md#bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。 -2. [nonebot.typing.Event](../api/typing.md#event): 即上报事件对象,可以获取到上报的所有信息。 -3. `state`: 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如: +1. [nonebot.adapters.Bot](../api/adapters/#class-bot): 即事件上报连接对应的 Bot 对象,为 BaseBot 的子类。特别注意,此处的类型注释可以替换为指定的 Bot 类型,例如:`nonebot.adapters.cqhttp.Bot`,只有在上报事件的 Bot 类型与类型注释相符时才会执行该处理函数!可用于多平台进行不同的处理。 +2. [nonebot.adapters.Event](../api/adapters/#class-event): 即上报事件对象,可以获取到上报的所有信息。 +3. [state](../api/typing.md#t-state): 状态字典,可以存储任意的信息,其中还包含一些特殊的值以获取 NoneBot 内部处理时的一些信息,如: - `state["_current_key"]`: 存储当前 `got` 获取的参数名 - `state["_prefix"]`, `state["_suffix"]`: 存储当前 TRIE 匹配的前缀/后缀,可以通过该值获取用户命令的原始命令 +:::tip 提示 +NoneBot 会对不同类型的参数进行不同的操作,详情查看 [事件处理函数重载](../advanced/overloaded-handlers.md) +::: + ### 参数处理函数 args_parser 在使用 `got` 获取用户输入参数时,需要对用户的消息进行处理以转换为我们所需要的信息。在默认情况下,NoneBot 会把用户的消息字符串原封不动的赋值给 `state[key]` 。可以通过以下两种方式修改默认处理逻辑: @@ -93,11 +131,11 @@ async def handle(bot: Bot, event: Event, state: dict): - `@matcher.args_parser` 装饰器:直接装饰一个函数作为参数处理器 - `got(key, prompt, args_parser)`:直接把函数作为参数传入 -参数处理函数类型为:`Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`,即: +参数处理函数类型为:`Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`,即: ```python -async def parser(bot: Bot, event: Event, state: dict): - state[state["_current_key"]] = str(event.message) +async def parser(bot: Bot, event: Event, state: T_State): + state[state["_current_key"]] = str(event.get_message()) ``` 特别的,`state["_current_key"]` 中存储了当前获取的参数名 @@ -131,16 +169,16 @@ matcher = on_command("test") # 修改默认参数处理 @matcher.args_parser -async def parse(bot: Bot, event: Event, state: dict): - print(state["_current_key"], ":", str(event.message)) - state[state["_current_key"]] = str(event.message) +async def parse(bot: Bot, event: Event, state: State): + print(state["_current_key"], ":", str(event.get_message())) + state[state["_current_key"]] = str(event.get_message()) @matcher.handle() -async def first_receive(bot: Bot, event: Event, state: dict): +async def first_receive(bot: Bot, event: Event, state: State): # 获取用户原始命令,如:/test print(state["_prefix"]["raw_command"]) # 处理用户输入参数,如:/test arg1 arg2 - raw_args = str(event.message).strip() + raw_args = str(event.get_message()).strip() if raw_args: arg_list = raw_args.split() # 将参数存入state以阻止后续再向用户询问参数 @@ -148,7 +186,7 @@ async def first_receive(bot: Bot, event: Event, state: dict): @matcher.got("arg1", prompt="参数?") -async def arg_handle(bot: Bot, event: Event, state: dict): +async def arg_handle(bot: Bot, event: Event, state: State): # 在这里对参数进行验证 if state["arg1"] not in ["allow", "list"]: await matcher.reject("参数不正确!请重新输入") diff --git a/docs/guide/creating-a-matcher.md b/docs/guide/creating-a-matcher.md index b603449a..09603855 100644 --- a/docs/guide/creating-a-matcher.md +++ b/docs/guide/creating-a-matcher.md @@ -7,20 +7,21 @@ ```python from nonebot import on_command from nonebot.rule import to_me -from nonebot.adapters.cqhttp import Bot, Event +from nonebot.typing import T_State +from nonebot.adapters import Bot, Event weather = on_command("天气", rule=to_me(), priority=5) @weather.handle() -async def handle_first_receive(bot: Bot, event: Event, state: dict): - args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 +async def handle_first_receive(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 if args: state["city"] = args # 如果用户发送了参数则直接赋值 @weather.got("city", prompt="你想查询哪个城市的天气呢?") -async def handle_city(bot: Bot, event: Event, state: dict): +async def handle_city(bot: Bot, event: Event, state: State): city = state["city"] if city not in ["上海", "北京"]: await weather.reject("你想查询的城市暂不支持,请重新输入!") @@ -42,7 +43,7 @@ async def get_weather(city: str): ## [事件响应器](../api/matcher.md) -```python{4} +```python{5} from nonebot import on_command from nonebot.rule import to_me from nonebot.permission import Permission @@ -62,7 +63,7 @@ weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5 ### 事件响应器类型 type -事件响应器类型其实就是对应事件的类型 `Event.type` ,NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些其他内置的事件响应器。 +事件响应器类型其实就是对应事件的类型 `Event.get_type()` ,NoneBot 提供了一个基础类型事件响应器 `on()` 以及一些其他内置的事件响应器。 以下所有类型的事件响应器都是由 `on(type, rule)` 的形式进行了简化封装。 @@ -86,10 +87,10 @@ weather = on_command("天气", rule=to_me(), permission=Permission(), priority=5 事件响应器的优先级代表事件响应器的执行顺序,同一优先级的事件响应器会 **同时执行!**,优先级数字**越小**越先响应!优先级请从 `1` 开始排序! :::tip 提示 -使用 `nonebot-test` 可以看到当前所有事件响应器的执行流程,有助理解事件响应流程! +使用 `nonebot-plugin-test` 可以在网页端查看当前所有事件响应器的执行流程,有助理解事件响应流程! ```bash -pip install nonebot2[test] +nb plugin install nonebot_plugin_test ``` ::: @@ -115,15 +116,15 @@ rule 的出现使得 nonebot 对事件的响应可以非常自由,nonebot 内 ```python from nonebot.rule import Rule -async def async_checker(bot: Bot, event: Event, state: dict) -> bool: +async def async_checker(bot: Bot, event: Event, state: State) -> bool: return True -def sync_checker(bot: Bot, event: Event, state: dict) -> bool: +def sync_checker(bot: Bot, event: Event, state: State) -> bool: return True def check(arg1, args2): - async def _checker(bot: Bot, event: Event, state: dict) -> bool: + async def _checker(bot: Bot, event: Event, state: State) -> bool: return bool(arg1 + arg2) return Rule(_check) diff --git a/docs/guide/creating-a-plugin.md b/docs/guide/creating-a-plugin.md index 0a6678db..5ce12a28 100644 --- a/docs/guide/creating-a-plugin.md +++ b/docs/guide/creating-a-plugin.md @@ -82,10 +82,10 @@ foo 示例: ```python -from pydantic import BaseSetting +from pydantic import BaseSettings -class Config(BaseSetting): +class Config(BaseSettings): # plugin custom config plugin_setting: str = "default" diff --git a/docs/guide/creating-a-project.md b/docs/guide/creating-a-project.md index b8ac3b77..5933b5fa 100644 --- a/docs/guide/creating-a-project.md +++ b/docs/guide/creating-a-project.md @@ -1,10 +1,10 @@ # 创建一个完整的项目 -上一章中我们已经运行了一个最小的 NoneBot 实例,在这一章,我们将从零开始一个完整的项目。 +上一章中我们已经运行了一个简单的 NoneBot 实例,在这一章,我们将从零开始一个完整的项目。 ## 目录结构 -首先,我们可以使用 `nb-cli` 或者自行创建完整的项目目录: +可以使用 `nb-cli` 或者自行创建完整的项目目录: ```bash nb create diff --git a/docs/guide/ding-guide.md b/docs/guide/ding-guide.md new file mode 100644 index 00000000..88c62ca9 --- /dev/null +++ b/docs/guide/ding-guide.md @@ -0,0 +1,3 @@ +# 钉钉机器人使用指南 + +~~TODO~~ diff --git a/docs/guide/end-or-start.md b/docs/guide/end-or-start.md index 11780114..9587c4bb 100644 --- a/docs/guide/end-or-start.md +++ b/docs/guide/end-or-start.md @@ -1,9 +1,9 @@ # 结语 -至此,相信你已经能够写出一个基础的插件了,更多的用法将会在 进阶 部分进行介绍,这里给出几个小提示: +至此,相信你已经能够写出一个基础的插件了。这里给出几个小提示: - 请千万注意事件处理器的优先级设定 - 在匹配规则中请勿使用耗时极长的函数 - 同一个用户可以**跨群**(**私聊**)继续他的事件处理(除非做出权限限制,将在后续介绍) -如果你还不能满足,前往 [进阶](../advanced/README.md) 获得更多的功能信息。 +如果「指南」还不能满足你,前往 [进阶](../advanced/README.md) 查看更多的功能信息。 diff --git a/docs/guide/getting-started.md b/docs/guide/getting-started.md index 8ed182eb..d35665a2 100644 --- a/docs/guide/getting-started.md +++ b/docs/guide/getting-started.md @@ -12,9 +12,9 @@ nb create 根据脚手架引导,将在当前目录下创建一个项目目录,项目目录内包含 `bot.py`。 -如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下: +如果未安装 `nb-cli`,使用你最熟悉的编辑器或 IDE,创建一个名为 `bot.py` 的文件,内容如下(这里以 CQHTTP 为例): -```python{3,4,7} +```python{4,6,7,10} import nonebot from nonebot.adapters.cqhttp import Bot as CQHTTPBot @@ -32,8 +32,10 @@ if __name__ == "__main__": 在上方 `bot.py` 中,这几行高亮代码将依次: 1. 使用默认配置初始化 NoneBot -2. 加载 NoneBot 内置的插件 -3. 在地址 `127.0.0.1:8080` 运行 NoneBot +2. 加载 NoneBot 内置的 CQHTTP 协议适配组件 + `register_adapter` 的第一个参数我们传入了一个字符串,该字符串将会在后文 [配置 CQHTTP 协议端](#配置-cqhttp-协议端-以-qq-为例) 时使用。 +3. 加载 NoneBot 内置的插件 +4. 在地址 `127.0.0.1:8080` 运行 NoneBot 在命令行使用如下命令即可运行这个 NoneBot 实例: @@ -55,119 +57,30 @@ python bot.py 09-14 21:02:00 [INFO] uvicorn | Uvicorn running on http://127.0.0.1:8080 (Press CTRL+C to quit) ``` -## 配置 QQ 协议端 +## 配置协议端上报 -单纯运行 NoneBot 实例并不会产生任何效果,因为此刻 QQ 这边还不知道 NoneBot 的存在,也就无法把消息发送给它,因此现在需要使用一个无头 QQ 来把消息等事件上报给 NoneBot。 +在 `bot.py` 文件中使用 `register_adapter` 注册协议适配之后即可配置协议端来完成与 NoneBot 的通信,详细配置方法参考: -目前支持的协议有: +- [配置 CQHTTP](./cqhttp-guide.md) +- [配置钉钉](./ding-guide.md) -- [OneBot(CQHTTP)](https://github.com/howmanybots/onebot/blob/master/README.md) +NoneBot 接受的上报地址与 `Driver` 有关,默认使用的 `FastAPI Driver` 所接受的上报地址有: -QQ 协议端举例: - -- [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) (基于 [MiraiGo](https://github.com/Mrs4s/MiraiGo)) -- [cqhttp-mirai-embedded](https://github.com/yyuueexxiinngg/cqhttp-mirai/tree/embedded) -- [Mirai](https://github.com/mamoe/mirai) + [cqhttp-mirai](https://github.com/yyuueexxiinngg/cqhttp-mirai) -- [Mirai](https://github.com/mamoe/mirai) + [Mirai Native](https://github.com/iTXTech/mirai-native) + [CQHTTP](https://github.com/richardchien/coolq-http-api) -- [OICQ-http-api](https://github.com/takayama-lily/onebot) (基于 [OICQ](https://github.com/takayama-lily/oicq)) - -这里以 [go-cqhttp](https://github.com/Mrs4s/go-cqhttp) 为例 - -1. 下载 go-cqhttp 对应平台的 release 文件,[点此前往](https://github.com/Mrs4s/go-cqhttp/releases) -2. 运行 exe 文件或者使用 `./go-cqhttp` 启动 -3. 生成默认配置文件并修改默认配置 - -```json{2,3,35-36,42} -{ - "uin": 你的QQ号, - "password": "你的密码", - "encrypt_password": false, - "password_encrypted": "", - "enable_db": true, - "access_token": "", - "relogin": { - "enabled": true, - "relogin_delay": 3, - "max_relogin_times": 0 - }, - "_rate_limit": { - "enabled": false, - "frequency": 0, - "bucket_size": 0 - }, - "ignore_invalid_cqcode": false, - "force_fragmented": true, - "heartbeat_interval": 0, - "http_config": { - "enabled": false, - "host": "0.0.0.0", - "port": 5700, - "timeout": 0, - "post_urls": {} - }, - "ws_config": { - "enabled": false, - "host": "0.0.0.0", - "port": 6700 - }, - "ws_reverse_servers": [ - { - "enabled": true, - "reverse_url": "ws://127.0.0.1:8080/cqhttp/ws", - "reverse_api_url": "", - "reverse_event_url": "", - "reverse_reconnect_interval": 3000 - } - ], - "post_message_format": "array", - "use_sso_address": false, - "debug": false, - "log_level": "", - "web_ui": { - "enabled": true, - "host": "0.0.0.0", - "web_ui_port": 9999, - "web_input": false - } -} -``` - -其中 `ws://127.0.0.1:8080/cqhttp/ws` 中的 `127.0.0.1` 和 `8080` 应分别对应 nonebot 配置的 HOST 和 PORT - -## 历史性的第一次对话 - -一旦新的配置文件正确生效之后,NoneBot 所在的控制台(如果正在运行的话)应该会输出类似下面的内容(两条访问日志): - -```default -09-14 21:31:16 [INFO] uvicorn | ('127.0.0.1', 12345) - "WebSocket /cqhttp/ws" [accepted] -09-14 21:31:16 [INFO] nonebot | WebSocket Connection from CQHTTP Bot 你的QQ号 Accepted! -``` - -这表示 QQ 协议端已经成功地使用 CQHTTP 协议连接上了 NoneBot。 +- `/{adapter name}/`: HTTP POST 上报 +- `/{adapter name}/http/`: HTTP POST 上报 +- `/{adapter name}/ws`: WebSocket 上报 +- `/{adapter name}/ws/`: WebSocket 上报 :::warning 注意 -如果到这一步你没有看到上面这样的成功日志,CQHTTP 的日志中在不断地重连或无反应,请注意检查配置中的 IP 和端口是否确实可以访问。比较常见的出错点包括: +如果到这一步你没有在 NoneBot 看到连接成功日志,比较常见的出错点包括: -- NoneBot 监听 `0.0.0.0`,然后在 CQHTTP 配置中填了 `ws://0.0.0.0:8080/cqhttp/ws` -- 在 Docker 容器内运行 CQHTTP,并通过 `127.0.0.1` 访问宿主机上的 NoneBot +- NoneBot 监听 `0.0.0.0`,然后在协议端上报配置中填了 `ws://0.0.0.0:8080/***/ws` +- 在 Docker 容器内运行协议端,并通过 `127.0.0.1` 访问宿主机上的 NoneBot - 想从公网访问,但没有修改云服务商的安全组策略或系统防火墙 - NoneBot 所监听的端口存在冲突,已被其它程序占用 -- 弄混了 NoneBot 的 `host`、`port` 参数与 CQHTTP 配置中的 `host`、`port` 参数 -- 使用了 `ws_reverse_api_url` 和 `ws_reverse_event_url` 而非 universal client +- 弄混了 NoneBot 的 `host`、`port` 参数与协议端上报配置中的 `host`、`port` 参数 - `ws://` 错填为 `http://` -- CQHTTP 或 NoneBot 启动时遭到外星武器干扰 +- 协议端或 NoneBot 启动时遭到外星武器干扰 -请尝试重启 CQHTTP、重启 NoneBot、更换端口、修改防火墙、重启系统、仔细阅读前面的文档及提示、更新 CQHTTP 和 NoneBot 到最新版本等方式来解决。 +请尝试重启协议端 NoneBot、更换端口、修改防火墙、重启系统、仔细阅读前面的文档及提示、更新协议端 和 NoneBot 到最新版本等方式来解决。 ::: - -现在,尝试向你的 QQ 机器人账号发送如下内容: - -```default -/echo 你好,世界 -``` - -到这里如果一切 OK,你应该会收到机器人给你回复了 `你好,世界`。这一历史性的对话标志着你已经成功地运行了一个 NoneBot 的最小实例,开始了编写更强大的 QQ 机器人的创意之旅! - - - - diff --git a/docs/guide/installation.md b/docs/guide/installation.md index b7259254..9beedaaa 100644 --- a/docs/guide/installation.md +++ b/docs/guide/installation.md @@ -17,8 +17,8 @@ pip uninstall nonebot ### 通过脚手架安装(推荐安装方式) -1. (可选)使用你喜欢的 Python 环境管理工具创建新的虚拟环境。 -2. 使用 `pip` (或其他) 安装 NoneBot 脚手架。 +1. (推荐)使用你喜欢的 Python 环境管理工具(如 `poetry`)创建新的虚拟环境。 +2. 使用 `pip` (或其他包管理工具) 安装 nb-cli,nonebot2 作为其依赖会一起被安装。 ```bash pip install nb-cli @@ -33,22 +33,26 @@ pip uninstall nonebot ### 不使用脚手架(纯净安装) ```bash -# poetry -poetry add nonebot2 -# pip pip install nonebot2 +# 也可以通过 poetry 安装 +poetry add nonebot2 ``` 如果你需要使用最新的(可能**尚未发布**的)特性,可以直接从 GitHub 仓库安装: +:::warning 注意 +直接从 Github 仓库中安装意味着你将使用最新提交的代码,它们并没有进行充分的稳定性测试 +在任何情况下请不要将其应用于生产环境! +::: + ```bash -# master +# master分支 poetry add git+https://github.com/nonebot/nonebot2.git#master -# dev +# dev分支 poetry add git+https://github.com/nonebot/nonebot2.git#dev ``` -或者克隆 Git 仓库后手动安装: +或者在克隆 Git 仓库后手动安装: ```bash git clone https://github.com/nonebot/nonebot2.git diff --git a/docs/guide/loading-a-plugin.md b/docs/guide/loading-a-plugin.md index e69c52a8..f026bbe0 100644 --- a/docs/guide/loading-a-plugin.md +++ b/docs/guide/loading-a-plugin.md @@ -48,7 +48,7 @@ if __name__ == "__main__": ::: :::warning 提示 -**插件不能存在相同名称!** +**不能存在相同名称的插件!** ::: :::danger 警告 diff --git a/docs_build/adapters/cqhttp.rst b/docs_build/adapters/cqhttp.rst index 4714296d..17d5816a 100644 --- a/docs_build/adapters/cqhttp.rst +++ b/docs_build/adapters/cqhttp.rst @@ -4,30 +4,51 @@ sidebarDepth: 0 --- NoneBot.adapters.cqhttp 模块 -============================ +============================= + +.. automodule:: nonebot.adapters.cqhttp + +NoneBot.adapters.cqhttp.utils 模块 +=================================== .. automodule:: nonebot.adapters.cqhttp.utils :members: :show-inheritance: +NoneBot.adapters.cqhttp.exception 模块 +======================================= + .. automodule:: nonebot.adapters.cqhttp.exception :members: :show-inheritance: +NoneBot.adapters.cqhttp.bot 模块 +================================= .. automodule:: nonebot.adapters.cqhttp.bot :members: :private-members: :show-inheritance: - -.. automodule:: nonebot.adapters.cqhttp.event - :members: - :private-members: - :show-inheritance: - +NoneBot.adapters.cqhttp.message 模块 +===================================== .. automodule:: nonebot.adapters.cqhttp.message :members: :private-members: :show-inheritance: + +NoneBot.adapters.cqhttp.permission 模块 +======================================== + +.. automodule:: nonebot.adapters.cqhttp.permission + :members: + :show-inheritance: + +NoneBot.adapters.cqhttp.event 模块 +=================================== + +.. automodule:: nonebot.adapters.cqhttp.event + :members: + :private-members: + :show-inheritance: diff --git a/docs_build/adapters/ding.rst b/docs_build/adapters/ding.rst index cff5979f..3b12564b 100644 --- a/docs_build/adapters/ding.rst +++ b/docs_build/adapters/ding.rst @@ -4,26 +4,39 @@ sidebarDepth: 0 --- NoneBot.adapters.ding 模块 -============================ +=========================== + +.. automodule:: nonebot.adapters.ding + +NoneBot.adapters.ding.exception 模块 +===================================== .. automodule:: nonebot.adapters.ding.exception :members: :show-inheritance: +NoneBot.adapters.ding.bot 模块 +=============================== + .. automodule:: nonebot.adapters.ding.bot :members: :private-members: :show-inheritance: -.. automodule:: nonebot.adapters.ding.event - :members: - :private-members: - :show-inheritance: - +NoneBot.adapters.ding.message 模块 +=================================== .. automodule:: nonebot.adapters.ding.message :members: :private-members: :show-inheritance: + + +NoneBot.adapters.ding.event 模块 +================================= + +.. automodule:: nonebot.adapters.ding.event + :members: + :show-inheritance: diff --git a/docs_build/conf.py b/docs_build/conf.py index 5ac18b11..fdd06451 100644 --- a/docs_build/conf.py +++ b/docs_build/conf.py @@ -72,6 +72,7 @@ html_static_path = ['_static'] # -- Options for autodoc extension ---------------------------------------------- autodoc_default_options = {'member-order': 'bysource'} +autodoc_inherit_docstrings = False # -- Options for todo extension ---------------------------------------------- diff --git a/docs_build/utils.rst b/docs_build/utils.rst index 5e7acd8d..ff724b1a 100644 --- a/docs_build/utils.rst +++ b/docs_build/utils.rst @@ -9,6 +9,6 @@ NoneBot.utils 模块 .. autofunction:: nonebot.utils.escape_tag .. autodecorator:: nonebot.utils.run_sync -.. autoclass:: nonebot.utils.DataclassEncoder .. autodecorator:: nonebot.utils.logger_wrapper +.. autoclass:: nonebot.utils.DataclassEncoder :show-inheritance: diff --git a/nonebot/__init__.py b/nonebot/__init__.py index abf1eb58..11dad7cd 100644 --- a/nonebot/__init__.py +++ b/nonebot/__init__.py @@ -26,7 +26,13 @@ import importlib import pkg_resources -from nonebot.typing import Bot, Dict, Type, Union, Driver, Optional, NoReturn +from typing import Dict, Type, Optional + +from nonebot.adapters import Bot +from nonebot.drivers import Driver +from nonebot.utils import escape_tag +from nonebot.config import Env, Config +from nonebot.log import logger, default_filter _dist: pkg_resources.Distribution = pkg_resources.get_distribution("nonebot2") __version__ = _dist.version @@ -35,7 +41,7 @@ VERSION = _dist.parsed_version _driver: Optional[Driver] = None -def get_driver() -> Union[NoReturn, Driver]: +def get_driver() -> Driver: """ :说明: @@ -111,7 +117,7 @@ def get_asgi(): return driver.asgi -def get_bots() -> Union[NoReturn, Dict[str, Bot]]: +def get_bots() -> Dict[str, Bot]: """ :说明: @@ -136,11 +142,6 @@ def get_bots() -> Union[NoReturn, Dict[str, Bot]]: return driver.bots -from nonebot.utils import escape_tag -from nonebot.config import Env, Config -from nonebot.log import logger, default_filter - - def init(*, _env_file: Optional[str] = None, **kwargs): """ :说明: diff --git a/nonebot/adapters/__init__.py b/nonebot/adapters/__init__.py index 692c691f..18c2e755 100644 --- a/nonebot/adapters/__init__.py +++ b/nonebot/adapters/__init__.py @@ -6,29 +6,34 @@ """ import abc +from copy import copy +from typing_extensions import Literal from functools import reduce, partial from dataclasses import dataclass, field +from typing import Any, Dict, Union, TypeVar, Mapping, Optional, Callable, Iterable, Iterator, Awaitable, TYPE_CHECKING from pydantic import BaseModel from nonebot.config import Config -from nonebot.typing import Driver, Message, WebSocket -from nonebot.typing import Any, Dict, Union, Optional, NoReturn, Callable, Iterable, Awaitable, TypeVar, Generic +from nonebot.utils import DataclassEncoder + +if TYPE_CHECKING: + from nonebot.drivers import Driver, WebSocket -class BaseBot(abc.ABC): +class Bot(abc.ABC): """ Bot 基类。用于处理上报消息,并提供 API 调用接口。 """ @abc.abstractmethod def __init__(self, - driver: Driver, + driver: "Driver", connection_type: str, config: Config, self_id: str, *, - websocket: Optional[WebSocket] = None): + websocket: Optional["WebSocket"] = None): """ :参数: @@ -60,9 +65,8 @@ class BaseBot(abc.ABC): @classmethod @abc.abstractmethod - async def check_permission(cls, driver: Driver, connection_type: str, - headers: dict, - body: Optional[dict]) -> Union[str, NoReturn]: + async def check_permission(cls, driver: "Driver", connection_type: str, + headers: dict, body: Optional[dict]) -> str: """ :说明: @@ -114,15 +118,14 @@ class BaseBot(abc.ABC): .. code-block:: python - await bot.call_api("send_msg", message="hello world"}) + await bot.call_api("send_msg", message="hello world") await bot.send_msg(message="hello world") """ raise NotImplementedError @abc.abstractmethod - async def send(self, event: "BaseEvent", - message: Union[str, "BaseMessage", - "BaseMessageSegment"], **kwargs): + async def send(self, event: "Event", + message: Union[str, "Message", "MessageSegment"], **kwargs): """ :说明: @@ -137,173 +140,12 @@ class BaseBot(abc.ABC): raise NotImplementedError -T = TypeVar("T", bound=BaseModel) - - -class BaseEvent(abc.ABC, Generic[T]): - """ - Event 基类。提供上报信息的关键信息,其余信息可从原始上报消息获取。 - """ - - def __init__(self, raw_event: Union[dict, T]): - """ - :参数: - - * ``raw_event: Union[dict, T]``: 原始上报消息 - """ - self._raw_event = raw_event - - def __repr__(self) -> str: - return f"" - - @property - def raw_event(self) -> Union[dict, T]: - """原始上报消息""" - 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 - @abc.abstractmethod - def type(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def detail_type(self) -> str: - """事件详细类型""" - raise NotImplementedError - - @detail_type.setter - @abc.abstractmethod - def detail_type(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def sub_type(self) -> Optional[str]: - """事件子类型""" - raise NotImplementedError - - @sub_type.setter - @abc.abstractmethod - def sub_type(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def user_id(self) -> Optional[int]: - """触发事件的主体 ID""" - raise NotImplementedError - - @user_id.setter - @abc.abstractmethod - def user_id(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def group_id(self) -> Optional[int]: - """触发事件的主体群 ID""" - raise NotImplementedError - - @group_id.setter - @abc.abstractmethod - def group_id(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def to_me(self) -> Optional[bool]: - """事件是否为发送给机器人的消息""" - raise NotImplementedError - - @to_me.setter - @abc.abstractmethod - def to_me(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def message(self) -> Optional[Message]: - """消息内容""" - raise NotImplementedError - - @message.setter - @abc.abstractmethod - def message(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def reply(self) -> Optional[dict]: - """回复的消息""" - raise NotImplementedError - - @reply.setter - @abc.abstractmethod - def reply(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def raw_message(self) -> Optional[str]: - """原始消息""" - raise NotImplementedError - - @raw_message.setter - @abc.abstractmethod - def raw_message(self, value) -> None: - raise NotImplementedError - - @property - @abc.abstractmethod - def plain_text(self) -> Optional[str]: - """纯文本消息""" - raise NotImplementedError - - @property - @abc.abstractmethod - def sender(self) -> Optional[dict]: - """消息发送者信息""" - raise NotImplementedError - - @sender.setter - @abc.abstractmethod - def sender(self, value) -> None: - raise NotImplementedError +T_Message = TypeVar("T_Message", bound="Message") +T_MessageSegment = TypeVar("T_MessageSegment", bound="MessageSegment") @dataclass -class BaseMessageSegment(abc.ABC): +class MessageSegment(abc.ABC): """消息段基类""" type: str """ @@ -317,19 +159,34 @@ class BaseMessageSegment(abc.ABC): """ @abc.abstractmethod - def __str__(self): + def __str__(self: T_MessageSegment) -> str: """该消息段所代表的 str,在命令匹配部分使用""" raise NotImplementedError @abc.abstractmethod - def __add__(self, other): + def __add__(self: T_MessageSegment, other: Union[str, T_MessageSegment, + T_Message]) -> T_Message: """你需要在这里实现不同消息段的合并: 比如: if isinstance(other, str): ... elif isinstance(other, MessageSegment): ... - 注意:不能返回 self,需要返回一个新生成的对象 + 注意:需要返回一个新生成的对象 + """ + raise NotImplementedError + + @abc.abstractmethod + def __radd__( + self: T_MessageSegment, other: Union[str, dict, list, T_MessageSegment, + T_Message]) -> "T_Message": + """你需要在这里实现不同消息段的合并: + 比如: + if isinstance(other, str): + ... + elif isinstance(other, MessageSegment): + ... + 注意:需要返回一个新生成的对象 """ raise NotImplementedError @@ -342,58 +199,80 @@ class BaseMessageSegment(abc.ABC): def get(self, key, default=None): return getattr(self, key, default) - @classmethod + def copy(self: T_MessageSegment) -> T_MessageSegment: + return copy(self) + @abc.abstractmethod - def text(cls, text: str) -> "BaseMessageSegment": - return cls("text", {"text": text}) + def is_text(self) -> bool: + raise NotImplementedError -class BaseMessage(list, abc.ABC): +class Message(list, abc.ABC): """消息数组""" def __init__(self, - message: Union[str, dict, list, BaseModel, BaseMessageSegment, - "BaseMessage"] = None, + message: Union[str, Mapping, Iterable[Mapping], + T_MessageSegment, T_Message, Any] = None, *args, **kwargs): """ :参数: - * ``message: Union[str, dict, list, BaseModel, MessageSegment, Message]``: 消息内容 + * ``message: Union[str, list, dict, MessageSegment, Message, Any]``: 消息内容 """ super().__init__(*args, **kwargs) - if isinstance(message, (str, dict, list, BaseModel)): - self.extend(self._construct(message)) - elif isinstance(message, BaseMessage): + if isinstance(message, Message): self.extend(message) - elif isinstance(message, BaseMessageSegment): + elif isinstance(message, MessageSegment): self.append(message) + else: + self.extend(self._construct(message)) def __str__(self): return ''.join((str(seg) for seg in self)) + @classmethod + def __get_validators__(cls): + yield cls._validate + + @classmethod + def _validate(cls, value): + return cls(value) + @staticmethod @abc.abstractmethod - def _construct(msg: Union[str, dict, list]) -> Iterable[BaseMessageSegment]: + def _construct( + msg: Union[str, Mapping, Iterable[Mapping], Any] + ) -> Iterable[T_MessageSegment]: raise NotImplementedError - def __add__( - self, other: Union[str, BaseMessageSegment, - "BaseMessage"]) -> "BaseMessage": + def __add__(self: T_Message, other: Union[str, T_MessageSegment, + T_Message]) -> T_Message: result = self.__class__(self) if isinstance(other, str): result.extend(self._construct(other)) - elif isinstance(other, BaseMessageSegment): + elif isinstance(other, MessageSegment): result.append(other) - elif isinstance(other, BaseMessage): + elif isinstance(other, Message): result.extend(other) return result - def __radd__(self, other: Union[str, BaseMessageSegment, "BaseMessage"]): + def __radd__(self: T_Message, other: Union[str, T_MessageSegment, + T_Message]) -> T_Message: result = self.__class__(other) return result.__add__(self) - def append(self, obj: Union[str, BaseMessageSegment]) -> "BaseMessage": + def __iadd__(self: T_Message, other: Union[str, T_MessageSegment, + T_Message]) -> T_Message: + if isinstance(other, str): + self.extend(self._construct(other)) + elif isinstance(other, MessageSegment): + self.append(other) + elif isinstance(other, Message): + self.extend(other) + return self + + def append(self: T_Message, obj: Union[str, T_MessageSegment]) -> T_Message: """ :说明: @@ -403,7 +282,7 @@ class BaseMessage(list, abc.ABC): * ``obj: Union[str, MessageSegment]``: 要添加的消息段 """ - if isinstance(obj, BaseMessageSegment): + if isinstance(obj, MessageSegment): super().append(obj) elif isinstance(obj, str): self.extend(self._construct(obj)) @@ -411,9 +290,8 @@ class BaseMessage(list, abc.ABC): raise ValueError(f"Unexpected type: {type(obj)} {obj}") return self - def extend( - self, obj: Union["BaseMessage", - Iterable[BaseMessageSegment]]) -> "BaseMessage": + def extend(self: T_Message, + obj: Union[T_Message, Iterable[T_MessageSegment]]) -> T_Message: """ :说明: @@ -427,7 +305,7 @@ class BaseMessage(list, abc.ABC): self.append(segment) return self - def reduce(self) -> None: + def reduce(self: T_Message) -> None: """ :说明: @@ -435,22 +313,152 @@ class BaseMessage(list, abc.ABC): """ index = 0 while index < len(self): - if index > 0 and self[ - index - 1].type == "text" and self[index].type == "text": + if index > 0 and self[index - + 1].is_text() and self[index].is_text(): self[index - 1] += self[index] del self[index] else: index += 1 - def extract_plain_text(self) -> str: + def extract_plain_text(self: T_Message) -> str: """ :说明: 提取消息内纯文本消息 """ - def _concat(x: str, y: BaseMessageSegment) -> str: - return f"{x} {y}" if y.type == "text" else x + def _concat(x: str, y: T_MessageSegment) -> str: + return f"{x} {y}" if y.is_text() else x plain_text = reduce(_concat, self, "") return plain_text[1:] if plain_text else plain_text + + +class Event(abc.ABC, BaseModel): + """Event 基类。提供获取关键信息的方法,其余信息可直接获取。""" + + class Config: + extra = "allow" + json_encoders = {Message: DataclassEncoder} + + @abc.abstractmethod + def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: + """ + :说明: + + 获取事件类型的方法,类型通常为 NoneBot 内置的四种类型。 + + :返回: + + * ``Literal["message", "notice", "request", "meta_event"]`` + """ + raise NotImplementedError + + @abc.abstractmethod + def get_event_name(self) -> str: + """ + :说明: + + 获取事件名称的方法。 + + :返回: + + * ``str`` + """ + raise NotImplementedError + + @abc.abstractmethod + def get_event_description(self) -> str: + """ + :说明: + + 获取事件描述的方法,通常为事件具体内容。 + + :返回: + + * ``str`` + """ + raise NotImplementedError + + def __str__(self) -> str: + return f"[{self.get_event_name()}]: {self.get_event_description()}" + + def get_log_string(self) -> str: + """ + :说明: + + 获取事件日志信息的方法,通常你不需要修改这个方法,只有当希望 NoneBot 隐藏该事件日志时,可以抛出 ``NoLogException`` 异常。 + + :返回: + + * ``str`` + + :异常: + + - ``NoLogException`` + """ + return f"[{self.get_event_name()}]: {self.get_event_description()}" + + @abc.abstractmethod + def get_user_id(self) -> str: + """ + :说明: + + 获取事件主体 id 的方法,通常是用户 id 。 + + :返回: + + * ``str`` + """ + raise NotImplementedError + + @abc.abstractmethod + def get_session_id(self) -> str: + """ + :说明: + + 获取会话 id 的方法,用于判断当前事件属于哪一个会话,通常是用户 id、群组 id 组合。 + + :返回: + + * ``str`` + """ + raise NotImplementedError + + @abc.abstractmethod + def get_message(self) -> "Message": + """ + :说明: + + 获取事件消息内容的方法。 + + :返回: + + * ``Message`` + """ + raise NotImplementedError + + def get_plaintext(self) -> str: + """ + :说明: + + 获取消息纯文本的方法,通常不需要修改,默认通过 ``get_message().extract_plain_text`` 获取。 + + :返回: + + * ``str`` + """ + return self.get_message().extract_plain_text() + + @abc.abstractmethod + def is_tome(self) -> bool: + """ + :说明: + + 获取事件是否与机器人有关的方法。 + + :返回: + + * ``bool`` + """ + raise NotImplementedError diff --git a/nonebot/adapters/cqhttp/__init__.py b/nonebot/adapters/cqhttp/__init__.py index 14635eda..be901d60 100644 --- a/nonebot/adapters/cqhttp/__init__.py +++ b/nonebot/adapters/cqhttp/__init__.py @@ -10,7 +10,8 @@ CQHTTP (OneBot) v11 协议适配 https://github.com/howmanybots/onebot/blob/master/README.md """ -from .event import Event +from .event import * +from .permission import * from .message import Message, MessageSegment from .utils import log, escape, unescape, _b2s from .bot import Bot, _check_at_me, _check_nickname, _check_reply, _handle_api_result diff --git a/nonebot/adapters/cqhttp/bot.py b/nonebot/adapters/cqhttp/bot.py index 929cd095..aa2783f3 100644 --- a/nonebot/adapters/cqhttp/bot.py +++ b/nonebot/adapters/cqhttp/bot.py @@ -3,25 +3,26 @@ import sys import hmac import json import asyncio +from typing import Any, Dict, Union, Optional, TYPE_CHECKING import httpx - from nonebot.log import logger from nonebot.config import Config -from nonebot.adapters import BaseBot +from nonebot.typing import overrides from nonebot.message import handle_event +from nonebot.adapters import Bot as BaseBot from nonebot.exception import RequestDenied -from nonebot.typing import Any, Dict, Union, Optional -from nonebot.typing import overrides, Driver, WebSocket, NoReturn -from .event import Event +from .utils import log, escape from .message import Message, MessageSegment +from .event import Reply, Event, MessageEvent, get_event_model from .exception import NetworkError, ApiNotAvailable, ActionFailed -from .utils import log + +if TYPE_CHECKING: + from nonebot.drivers import Driver, WebSocket -def get_auth_bearer( - access_token: Optional[str] = None) -> Union[Optional[str], NoReturn]: +def get_auth_bearer(access_token: Optional[str] = None) -> Optional[str]: if not access_token: return None scheme, _, param = access_token.partition(" ") @@ -41,7 +42,7 @@ async def _check_reply(bot: "Bot", event: "Event"): * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 """ - if event.type != "message": + if not isinstance(event, MessageEvent): return try: @@ -50,9 +51,10 @@ async def _check_reply(bot: "Bot", event: "Event"): except ValueError: return msg_seg = event.message[index] - event.reply = await bot.get_msg(message_id=msg_seg.data["id"]) + event.reply = Reply.parse_obj(await + bot.get_msg(message_id=msg_seg.data["id"])) # ensure string comparation - if str(event.reply["sender"]["user_id"]) == str(event.self_id): + if str(event.reply.sender.user_id) == str(event.self_id): event.to_me = True del event.message[index] if len(event.message) > index and event.message[index].type == "at": @@ -77,10 +79,10 @@ def _check_at_me(bot: "Bot", event: "Event"): * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 """ - if event.type != "message": + if not isinstance(event, MessageEvent): return - if event.detail_type == "private": + if event.message_type == "private": event.to_me = True else: at_me_seg = MessageSegment.at(event.self_id) @@ -131,7 +133,7 @@ def _check_nickname(bot: "Bot", event: "Event"): * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 """ - if event.type != "message": + if not isinstance(event, MessageEvent): return first_msg_seg = event.message[0] @@ -153,8 +155,7 @@ def _check_nickname(bot: "Bot", event: "Event"): first_msg_seg.data["text"] = first_text[m.end():] -def _handle_api_result( - result: Optional[Dict[str, Any]]) -> Union[Any, NoReturn]: +def _handle_api_result(result: Optional[Dict[str, Any]]) -> Any: """ :说明: @@ -174,7 +175,7 @@ def _handle_api_result( """ if isinstance(result, dict): if result.get("status") == "failed": - raise ActionFailed(retcode=result.get("retcode")) + raise ActionFailed(**result) return result.get("data") @@ -214,12 +215,12 @@ class Bot(BaseBot): """ def __init__(self, - driver: Driver, + driver: "Driver", connection_type: str, config: Config, self_id: str, *, - websocket: Optional[WebSocket] = None): + websocket: Optional["WebSocket"] = None): super().__init__(driver, connection_type, @@ -237,9 +238,8 @@ class Bot(BaseBot): @classmethod @overrides(BaseBot) - async def check_permission(cls, driver: Driver, connection_type: str, - headers: dict, - body: Optional[dict]) -> Union[str, NoReturn]: + async def check_permission(cls, driver: "Driver", connection_type: str, + headers: dict, body: Optional[dict]) -> str: """ :说明: @@ -296,7 +296,20 @@ class Bot(BaseBot): return try: - event = Event(message) + post_type = message['post_type'] + detail_type = message.get(f"{post_type}_type") + detail_type = f".{detail_type}" if detail_type else "" + sub_type = message.get("sub_type") + sub_type = f".{sub_type}" if sub_type else "" + models = get_event_model(post_type + detail_type + sub_type) + for model in models: + try: + event = model.parse_obj(message) + break + except Exception as e: + log("DEBUG", "Event Parser Error", e) + else: + event = Event.parse_obj(message) # Check whether user is calling me await _check_reply(self, event) @@ -310,7 +323,7 @@ class Bot(BaseBot): ) @overrides(BaseBot) - async def call_api(self, api: str, **data) -> Union[Any, NoReturn]: + async def call_api(self, api: str, **data) -> Any: """ :说明: @@ -382,7 +395,7 @@ class Bot(BaseBot): event: Event, message: Union[str, Message, MessageSegment], at_sender: bool = False, - **kwargs) -> Union[Any, NoReturn]: + **kwargs) -> Any: """ :说明: @@ -405,15 +418,16 @@ class Bot(BaseBot): - ``NetworkError``: 网络错误 - ``ActionFailed``: API 调用失败 """ + message = escape(message) if isinstance(message, str) else message msg = message if isinstance(message, Message) else Message(message) - at_sender = at_sender and bool(event.user_id) + at_sender = at_sender and hasattr(event, "user_id") params = {} - if event.user_id: - params["user_id"] = event.user_id - if event.group_id: - params["group_id"] = event.group_id + if hasattr(event, "user_id"): + params["user_id"] = getattr(event, "user_id") + if hasattr(event, "group_id"): + params["group_id"] = getattr(event, "group_id") params.update(kwargs) if "message_type" not in params: diff --git a/nonebot/adapters/cqhttp/bot.pyi b/nonebot/adapters/cqhttp/bot.pyi index 745b4941..7ba09f8a 100644 --- a/nonebot/adapters/cqhttp/bot.pyi +++ b/nonebot/adapters/cqhttp/bot.pyi @@ -1,15 +1,15 @@ import asyncio +from typing import Any, Dict, List, Union, Optional from nonebot.config import Config -from nonebot.adapters import BaseBot -from nonebot.typing import Any, Dict, List, Union, Driver, Optional, NoReturn, WebSocket +from nonebot.adapters import Bot as BaseBot +from nonebot.drivers import Driver, WebSocket from .event import Event from .message import Message, MessageSegment -def get_auth_bearer( - access_token: Optional[str] = ...) -> Union[Optional[str], NoReturn]: +def get_auth_bearer(access_token: Optional[str] = ...) -> Optional[str]: ... @@ -25,8 +25,7 @@ def _check_nickname(bot: "Bot", event: Event): ... -def _handle_api_result( - result: Optional[Dict[str, Any]]) -> Union[Any, NoReturn]: +def _handle_api_result(result: Optional[Dict[str, Any]]) -> Any: ... @@ -63,19 +62,18 @@ class Bot(BaseBot): @classmethod async def check_permission(cls, driver: Driver, connection_type: str, - headers: dict, - body: Optional[dict]) -> Union[str, NoReturn]: + headers: dict, body: Optional[dict]) -> str: ... async def handle_message(self, message: dict): ... - async def call_api(self, api: str, **data) -> Union[Any, NoReturn]: + async def call_api(self, api: str, **data) -> Any: ... async def send(self, event: Event, message: Union[str, Message, MessageSegment], - **kwargs) -> Union[Any, NoReturn]: + **kwargs) -> Any: ... async def send_private_msg(self, diff --git a/nonebot/adapters/cqhttp/event.py b/nonebot/adapters/cqhttp/event.py index 5bc959c9..5d1cdb2f 100644 --- a/nonebot/adapters/cqhttp/event.py +++ b/nonebot/adapters/cqhttp/event.py @@ -1,204 +1,449 @@ -from nonebot.adapters import BaseEvent -from nonebot.typing import Optional, overrides +import inspect +from typing_extensions import Literal +from typing import Type, List, Optional + +from pydantic import BaseModel +from pygtrie import StringTrie +from nonebot.utils import escape_tag +from nonebot.typing import overrides +from nonebot.exception import NoLogException +from nonebot.adapters import Event as BaseEvent from .message import Message class Event(BaseEvent): """ - CQHTTP 协议 Event 适配。继承属性参考 `BaseEvent <./#class-baseevent>`_ 。 + CQHTTP 协议事件,字段与 CQHTTP 一致。各事件字段参考 `CQHTTP 文档`_ + + .. _CQHTTP 文档: + https://github.com/howmanybots/onebot/blob/master/README.md + """ + __event__ = "" + time: int + self_id: int + post_type: Literal["message", "notice", "request", "meta_event"] + + @overrides(BaseEvent) + def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: + return self.post_type + + @overrides(BaseEvent) + def get_event_name(self) -> str: + return self.post_type + + @overrides(BaseEvent) + def get_event_description(self) -> str: + return str(self.dict()) + + @overrides(BaseEvent) + def get_message(self) -> Message: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def get_plaintext(self) -> str: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def get_user_id(self) -> str: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def get_session_id(self) -> str: + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def is_tome(self) -> bool: + return False + + +# Models +class Sender(BaseModel): + user_id: Optional[int] = None + nickname: Optional[str] = None + sex: Optional[str] = None + age: Optional[int] = None + card: Optional[str] = None + area: Optional[str] = None + level: Optional[str] = None + role: Optional[str] = None + title: Optional[str] = None + + class Config: + extra = "allow" + + +class Reply(BaseModel): + time: int + message_type: str + message_id: int + real_id: int + sender: Sender + message: Message + + class Config: + extra = "allow" + + +class Anonymous(BaseModel): + id: int + name: str + flag: str + + class Config: + extra = "allow" + + +class File(BaseModel): + id: str + name: str + size: int + busid: int + + class Config: + extra = "allow" + + +class Status(BaseModel): + online: bool + good: bool + + class Config: + extra = "allow" + + +# Message Events +class MessageEvent(Event): + """消息事件""" + __event__ = "message" + post_type: Literal["message"] + sub_type: str + user_id: int + message_type: str + message_id: int + message: Message + raw_message: str + font: int + sender: Sender + to_me: bool = False + """ + :说明: 消息是否与机器人有关 + + :类型: ``bool`` + """ + reply: Optional[Reply] = None + """ + :说明: 消息中提取的回复消息,内容为 ``get_msg`` API 返回结果 + + :类型: ``Optional[Reply]`` """ - def __init__(self, raw_event: dict): - if "message" in raw_event: - raw_event["message"] = Message(raw_event["message"]) + @overrides(Event) + def get_event_name(self) -> str: + sub_type = getattr(self, "sub_type", None) + return f"{self.post_type}.{self.message_type}" + (f".{sub_type}" + if sub_type else "") - super().__init__(raw_event) + @overrides(Event) + def get_message(self) -> Message: + return self.message - @property - @overrides(BaseEvent) - def id(self) -> Optional[int]: - """ - - 类型: ``Optional[int]`` - - 说明: 事件/消息 ID - """ - return self._raw_event.get("message_id") or self._raw_event.get("flag") + @overrides(Event) + def get_plaintext(self) -> str: + return self.message.extract_plain_text() - @property - @overrides(BaseEvent) - def name(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件名称,由类型与 ``.`` 组合而成 - """ - n = self.type + "." + self.detail_type - if self.sub_type: - n += "." + self.sub_type - return n + @overrides(Event) + def get_user_id(self) -> str: + return str(self.user_id) - @property - @overrides(BaseEvent) - def self_id(self) -> str: - """ - - 类型: ``str`` - - 说明: 机器人自身 ID - """ - return str(self._raw_event["self_id"]) + @overrides(Event) + def get_session_id(self) -> str: + return str(self.user_id) - @property - @overrides(BaseEvent) - def time(self) -> int: - """ - - 类型: ``int`` - - 说明: 事件发生时间 - """ - return self._raw_event["time"] + @overrides(Event) + def is_tome(self) -> bool: + return self.to_me - @property - @overrides(BaseEvent) - def type(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件类型 - """ - return self._raw_event["post_type"] - @type.setter - @overrides(BaseEvent) - def type(self, value) -> None: - self._raw_event["post_type"] = value +class PrivateMessageEvent(MessageEvent): + """私聊消息""" + __event__ = "message.private" + message_type: Literal["private"] - @property - @overrides(BaseEvent) - def detail_type(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件详细类型 - """ - return self._raw_event[f"{self.type}_type"] + @overrides(Event) + def get_event_description(self) -> str: + return (f'Message {self.message_id} from {self.user_id} "' + "".join( + map( + lambda x: escape_tag(str(x)) + if x.is_text() else f"{escape_tag(str(x))}", + self.message)) + '"') - @detail_type.setter - @overrides(BaseEvent) - def detail_type(self, value) -> None: - self._raw_event[f"{self.type}_type"] = value - @property - @overrides(BaseEvent) - def sub_type(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 事件子类型 - """ - return self._raw_event.get("sub_type") +class GroupMessageEvent(MessageEvent): + """群消息""" + __event__ = "message.group" + message_type: Literal["group"] + group_id: int + anonymous: Anonymous - @sub_type.setter - @overrides(BaseEvent) - def sub_type(self, value) -> None: - self._raw_event["sub_type"] = value + @overrides(Event) + def get_event_description(self) -> str: + return ( + f'Message {self.message_id} from {self.user_id}@[群:{self.group_id}] "' + + "".join( + map( + lambda x: escape_tag(str(x)) + if x.is_text() else f"{escape_tag(str(x))}", + self.message)) + '"') - @property - @overrides(BaseEvent) - def user_id(self) -> Optional[int]: - """ - - 类型: ``Optional[int]`` - - 说明: 事件主体 ID - """ - return self._raw_event.get("user_id") - @user_id.setter - @overrides(BaseEvent) - def user_id(self, value) -> None: - self._raw_event["user_id"] = value +# Notice Events +class NoticeEvent(Event): + """通知事件""" + __event__ = "notice" + post_type: Literal["notice"] + notice_type: str - @property - @overrides(BaseEvent) - def group_id(self) -> Optional[int]: - """ - - 类型: ``Optional[int]`` - - 说明: 事件主体群 ID - """ - return self._raw_event.get("group_id") + @overrides(Event) + def get_event_name(self) -> str: + sub_type = getattr(self, "sub_type", None) + return f"{self.post_type}.{self.notice_type}" + (f".{sub_type}" + if sub_type else "") - @group_id.setter - @overrides(BaseEvent) - def group_id(self, value) -> None: - self._raw_event["group_id"] = value - @property - @overrides(BaseEvent) - def to_me(self) -> Optional[bool]: - """ - - 类型: ``Optional[bool]`` - - 说明: 消息是否与机器人相关 - """ - return self._raw_event.get("to_me") +class GroupUploadNoticeEvent(NoticeEvent): + """群文件上传事件""" + __event__ = "notice.group_upload" + notice_type: Literal["group_upload"] + user_id: int + group_id: int + file: File - @to_me.setter - @overrides(BaseEvent) - def to_me(self, value) -> None: - self._raw_event["to_me"] = value - @property - @overrides(BaseEvent) - def message(self) -> Optional["Message"]: - """ - - 类型: ``Optional[Message]`` - - 说明: 消息内容 - """ - return self._raw_event.get("message") +class GroupAdminNoticeEvent(NoticeEvent): + """群管理员变动""" + __event__ = "notice.group_admin" + notice_type: Literal["group_admin"] + sub_type: str + user_id: int + group_id: int - @message.setter - @overrides(BaseEvent) - def message(self, value) -> None: - self._raw_event["message"] = value + @overrides(Event) + def is_tome(self) -> bool: + return self.user_id == self.self_id - @property - @overrides(BaseEvent) - def reply(self) -> Optional[dict]: - """ - - 类型: ``Optional[dict]`` - - 说明: 回复消息详情 - """ - return self._raw_event.get("reply") - @reply.setter - @overrides(BaseEvent) - def reply(self, value) -> None: - self._raw_event["reply"] = value +class GroupDecreaseNoticeEvent(NoticeEvent): + """群成员减少事件""" + __event__ = "notice.group_decrease" + notice_type: Literal["group_decrease"] + sub_type: str + user_id: int + group_id: int + operator_id: int - @property - @overrides(BaseEvent) - def raw_message(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 原始消息 - """ - return self._raw_event.get("raw_message") + @overrides(Event) + def is_tome(self) -> bool: + return self.user_id == self.self_id - @raw_message.setter - @overrides(BaseEvent) - def raw_message(self, value) -> None: - self._raw_event["raw_message"] = value - @property - @overrides(BaseEvent) - def plain_text(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 纯文本消息内容 - """ - return self.message and self.message.extract_plain_text() +class GroupIncreaseNoticeEvent(NoticeEvent): + """群成员增加事件""" + __event__ = "notice.group_increase" + notice_type: Literal["group_increase"] + sub_type: str + user_id: int + group_id: int + operator_id: int - @property - @overrides(BaseEvent) - def sender(self) -> Optional[dict]: - """ - - 类型: ``Optional[dict]`` - - 说明: 消息发送者信息 - """ - return self._raw_event.get("sender") + @overrides(Event) + def is_tome(self) -> bool: + return self.user_id == self.self_id - @sender.setter - @overrides(BaseEvent) - def sender(self, value) -> None: - self._raw_event["sender"] = value + +class GroupBanNoticeEvent(NoticeEvent): + """群禁言事件""" + __event__ = "notice.group_ban" + notice_type: Literal["group_ban"] + sub_type: str + user_id: int + group_id: int + operator_id: int + duration: int + + @overrides(Event) + def is_tome(self) -> bool: + return self.user_id == self.self_id + + +class FriendAddNoticeEvent(NoticeEvent): + """好友添加事件""" + __event__ = "notice.friend_add" + notice_type: Literal["friend_add"] + user_id: int + + +class GroupRecallNoticeEvent(NoticeEvent): + """群消息撤回事件""" + __event__ = "notice.group_recall" + notice_type: Literal["group_recall"] + user_id: int + group_id: int + operator_id: int + message_id: int + + @overrides(Event) + def is_tome(self) -> bool: + return self.user_id == self.self_id + + +class FriendRecallNoticeEvent(NoticeEvent): + """好友消息撤回事件""" + __event__ = "notice.friend_recall" + notice_type: Literal["friend_recall"] + user_id: int + message_id: int + + +class NotifyEvent(NoticeEvent): + """提醒事件""" + __event__ = "notice.notify" + notice_type: Literal["notify"] + sub_type: str + user_id: int + group_id: int + + +class PokeNotifyEvent(NotifyEvent): + """戳一戳提醒事件""" + __event__ = "notice.notify.poke" + sub_type: Literal["poke"] + target_id: int + + @overrides(Event) + def is_tome(self) -> bool: + return self.target_id == self.self_id + + +class LuckyKingNotifyEvent(NotifyEvent): + """群红包运气王提醒事件""" + __event__ = "notice.notify.lucky_king" + sub_type: Literal["lucky_king"] + target_id: int + + @overrides(Event) + def is_tome(self) -> bool: + return self.target_id == self.self_id + + +class HonorNotifyEvent(NotifyEvent): + """群荣誉变更提醒事件""" + __event__ = "notice.notify.honor" + sub_type: Literal["honor"] + honor_type: str + + @overrides(Event) + def is_tome(self) -> bool: + return self.user_id == self.self_id + + +# Request Events +class RequestEvent(Event): + """请求事件""" + __event__ = "request" + post_type: Literal["request"] + request_type: str + + @overrides(Event) + def get_event_name(self) -> str: + sub_type = getattr(self, "sub_type", None) + return f"{self.post_type}.{self.request_type}" + (f".{sub_type}" + if sub_type else "") + + +class FriendRequestEvent(RequestEvent): + """加好友请求事件""" + __event__ = "request.friend" + request_type: Literal["friend"] + user_id: int + comment: str + flag: str + + +class GroupRequestEvent(RequestEvent): + """加群请求/邀请事件""" + __event__ = "request.group" + request_type: Literal["group"] + sub_type: str + group_id: int + user_id: int + comment: str + flag: str + + +# Meta Events +class MetaEvent(Event): + """元事件""" + __event__ = "meta_event" + post_type: Literal["meta_event"] + meta_event_type: str + + @overrides(Event) + def get_event_name(self) -> str: + sub_type = getattr(self, "sub_type", None) + return f"{self.post_type}.{self.meta_event_type}" + (f".{sub_type}" if + sub_type else "") + + @overrides(Event) + def get_log_string(self) -> str: + raise NoLogException + + +class LifecycleMetaEvent(MetaEvent): + """生命周期元事件""" + __event__ = "meta_event.lifecycle" + meta_event_type: Literal["lifecycle"] + sub_type: str + + +class HeartbeatMetaEvent(MetaEvent): + """心跳元事件""" + __event__ = "meta_event.heartbeat" + meta_event_type: Literal["heartbeat"] + status: Status + interval: int + + +_t = StringTrie(separator=".") + +# define `model` first to avoid globals changing while `for` +model = None +for model in globals().values(): + if not inspect.isclass(model) or not issubclass(model, Event): + continue + _t["." + model.__event__] = model + + +def get_event_model(event_name) -> List[Type[Event]]: + """ + :说明: + + 根据事件名获取对应 ``Event Model`` 及 ``FallBack Event Model`` 列表 + + :返回: + + - ``List[Type[Event]]`` + """ + return [model.value for model in _t.prefixes("." + event_name)][::-1] + + +__all__ = [ + "Event", "MessageEvent", "PrivateMessageEvent", "GroupMessageEvent", + "NoticeEvent", "GroupUploadNoticeEvent", "GroupAdminNoticeEvent", + "GroupDecreaseNoticeEvent", "GroupIncreaseNoticeEvent", + "GroupBanNoticeEvent", "FriendAddNoticeEvent", "GroupRecallNoticeEvent", + "FriendRecallNoticeEvent", "NotifyEvent", "PokeNotifyEvent", + "LuckyKingNotifyEvent", "HonorNotifyEvent", "RequestEvent", + "FriendRequestEvent", "GroupRequestEvent", "MetaEvent", + "LifecycleMetaEvent", "HeartbeatMetaEvent", "get_event_model" +] diff --git a/nonebot/adapters/cqhttp/exception.py b/nonebot/adapters/cqhttp/exception.py index 2bcc73f4..aeeb11be 100644 --- a/nonebot/adapters/cqhttp/exception.py +++ b/nonebot/adapters/cqhttp/exception.py @@ -1,4 +1,5 @@ -from nonebot.typing import Optional +from typing import Optional + from nonebot.exception import (AdapterException, ActionFailed as BaseActionFailed, NetworkError as BaseNetworkError, ApiNotAvailable as @@ -22,12 +23,12 @@ class ActionFailed(BaseActionFailed, CQHTTPAdapterException): * ``retcode: Optional[int]``: 错误码 """ - def __init__(self, retcode: Optional[int] = None): + def __init__(self, **kwargs): super().__init__() - self.retcode = retcode + self.info = kwargs def __repr__(self): - return f"" + return f"" def __str__(self): return self.__repr__() diff --git a/nonebot/adapters/cqhttp/message.py b/nonebot/adapters/cqhttp/message.py index 47d21bc8..1a7bd538 100644 --- a/nonebot/adapters/cqhttp/message.py +++ b/nonebot/adapters/cqhttp/message.py @@ -1,7 +1,8 @@ import re +from typing import Any, Dict, Union, Tuple, Mapping, Iterable, Optional -from nonebot.typing import Any, Dict, Union, Tuple, Iterable, Optional, overrides -from nonebot.adapters import BaseMessage, BaseMessageSegment +from nonebot.typing import overrides +from nonebot.adapters import Message as BaseMessage, MessageSegment as BaseMessageSegment from .utils import log, escape, unescape, _b2s @@ -13,12 +14,10 @@ class MessageSegment(BaseMessageSegment): @overrides(BaseMessageSegment) def __init__(self, type: str, data: Dict[str, Any]) -> None: - if type == "text": - data["text"] = unescape(data["text"]) super().__init__(type=type, data=data) @overrides(BaseMessageSegment) - def __str__(self): + def __str__(self) -> str: type_ = self.type data = self.data.copy() @@ -36,6 +35,14 @@ class MessageSegment(BaseMessageSegment): def __add__(self, other) -> "Message": return Message(self) + other + @overrides(BaseMessageSegment) + def __radd__(self, other) -> "Message": + return Message(other) + self + + @overrides(BaseMessageSegment) + def is_text(self) -> bool: + return self.type == "text" + @staticmethod def anonymous(ignore_failure: Optional[bool] = None) -> "MessageSegment": return MessageSegment("anonymous", {"ignore": _b2s(ignore_failure)}) @@ -44,6 +51,10 @@ class MessageSegment(BaseMessageSegment): def at(user_id: Union[int, str]) -> "MessageSegment": return MessageSegment("at", {"qq": str(user_id)}) + @staticmethod + def contact(type_: str, id: int) -> "MessageSegment": + return MessageSegment("contact", {"type": type_, "id": str(id)}) + @staticmethod def contact_group(group_id: int) -> "MessageSegment": return MessageSegment("contact", {"type": "group", "id": str(group_id)}) @@ -140,7 +151,14 @@ class MessageSegment(BaseMessageSegment): cache: Optional[bool] = None, proxy: Optional[bool] = None, timeout: Optional[int] = None) -> "MessageSegment": - return MessageSegment("record", {"file": file, "magic": _b2s(magic)}) + return MessageSegment( + "record", { + "file": file, + "magic": _b2s(magic), + "cache": cache, + "proxy": proxy, + "timeout": timeout + }) @staticmethod def reply(id_: int) -> "MessageSegment": @@ -194,11 +212,13 @@ class Message(BaseMessage): @staticmethod @overrides(BaseMessage) - def _construct(msg: Union[str, dict, list]) -> Iterable[MessageSegment]: - if isinstance(msg, dict): + def _construct( + msg: Union[str, Mapping, + Iterable[Mapping]]) -> Iterable[MessageSegment]: + if isinstance(msg, Mapping): yield MessageSegment(msg["type"], msg.get("data") or {}) return - elif isinstance(msg, list): + elif isinstance(msg, Iterable) and not isinstance(msg, str): for seg in msg: yield MessageSegment(seg["type"], seg.get("data") or {}) return @@ -208,22 +228,21 @@ class Message(BaseMessage): for cqcode in re.finditer( r"\[CQ:(?P[a-zA-Z0-9-_.]+)" r"(?P" - r"(?:,[a-zA-Z0-9-_.]+=?[^,\]]*)*" + r"(?:,[a-zA-Z0-9-_.]+=[^,\]]+)*" r"),?\]", msg): - yield "text", unescape(msg[text_begin:cqcode.pos + - cqcode.start()]) + yield "text", msg[text_begin:cqcode.pos + cqcode.start()] text_begin = cqcode.pos + cqcode.end() yield cqcode.group("type"), cqcode.group("params").lstrip(",") - yield "text", unescape(msg[text_begin:]) + yield "text", msg[text_begin:] for type_, data in _iter_message(msg): if type_ == "text": if data: # only yield non-empty text segment - yield MessageSegment(type_, {"text": data}) + yield MessageSegment(type_, {"text": unescape(data)}) else: data = { - k: v for k, v in map( + k: unescape(v) for k, v in map( lambda x: x.split("=", maxsplit=1), filter(lambda x: x, ( x.lstrip() for x in data.split(",")))) diff --git a/nonebot/adapters/cqhttp/permission.py b/nonebot/adapters/cqhttp/permission.py new file mode 100644 index 00000000..5a9cfea8 --- /dev/null +++ b/nonebot/adapters/cqhttp/permission.py @@ -0,0 +1,86 @@ +from typing import TYPE_CHECKING + +from nonebot.permission import Permission + +from .event import PrivateMessageEvent, GroupMessageEvent + +if TYPE_CHECKING: + from nonebot.adapters import Bot, Event + + +async def _private(bot: "Bot", event: "Event") -> bool: + return isinstance(event, PrivateMessageEvent) + + +async def _private_friend(bot: "Bot", event: "Event") -> bool: + return isinstance(event, PrivateMessageEvent) and event.sub_type == "friend" + + +async def _private_group(bot: "Bot", event: "Event") -> bool: + return isinstance(event, PrivateMessageEvent) and event.sub_type == "group" + + +async def _private_other(bot: "Bot", event: "Event") -> bool: + return isinstance(event, PrivateMessageEvent) and event.sub_type == "other" + + +PRIVATE = Permission(_private) +""" +- **说明**: 匹配任意私聊消息类型事件 +""" +PRIVATE_FRIEND = Permission(_private_friend) +""" +- **说明**: 匹配任意好友私聊消息类型事件 +""" +PRIVATE_GROUP = Permission(_private_group) +""" +- **说明**: 匹配任意群临时私聊消息类型事件 +""" +PRIVATE_OTHER = Permission(_private_other) +""" +- **说明**: 匹配任意其他私聊消息类型事件 +""" + + +async def _group(bot: "Bot", event: "Event") -> bool: + return isinstance(event, GroupMessageEvent) + + +async def _group_member(bot: "Bot", event: "Event") -> bool: + return isinstance(event, + GroupMessageEvent) and event.sender.role == "member" + + +async def _group_admin(bot: "Bot", event: "Event") -> bool: + return isinstance(event, GroupMessageEvent) and event.sender.role == "admin" + + +async def _group_owner(bot: "Bot", event: "Event") -> bool: + return isinstance(event, GroupMessageEvent) and event.sender.role == "owner" + + +GROUP = Permission(_group) +""" +- **说明**: 匹配任意群聊消息类型事件 +""" +GROUP_MEMBER = Permission(_group_member) +""" +- **说明**: 匹配任意群员群聊消息类型事件 + +\:\:\:warning 警告 +该权限通过 event.sender 进行判断且不包含管理员以及群主! +\:\:\: +""" +GROUP_ADMIN = Permission(_group_admin) +""" +- **说明**: 匹配任意群管理员群聊消息类型事件 +""" +GROUP_OWNER = Permission(_group_owner) +""" +- **说明**: 匹配任意群主群聊消息类型事件 +""" + +__all__ = [ + "PRIVATE", "PRIVATE_FRIEND", "PRIVATE_GROUP", "PRIVATE_OTHER", "GROUP", + "GROUP_MEMBER", "GROUP_ADMIN", "GROUP_OWNER" +] diff --git a/nonebot/adapters/cqhttp/utils.py b/nonebot/adapters/cqhttp/utils.py index ecfee872..747b964f 100644 --- a/nonebot/adapters/cqhttp/utils.py +++ b/nonebot/adapters/cqhttp/utils.py @@ -1,4 +1,5 @@ -from nonebot.typing import Optional +from typing import Optional + from nonebot.utils import logger_wrapper log = logger_wrapper("CQHTTP") diff --git a/nonebot/adapters/ding/__init__.py b/nonebot/adapters/ding/__init__.py index 4eb33e28..b1901cfb 100644 --- a/nonebot/adapters/ding/__init__.py +++ b/nonebot/adapters/ding/__init__.py @@ -5,13 +5,12 @@ 协议详情请看: `钉钉文档`_ .. _钉钉文档: - https://ding-doc.dingtalk.com/doc#/serverapi2/krgddi - + https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p """ from .utils import log from .bot import Bot -from .event import Event from .message import Message, MessageSegment +from .event import Event, MessageEvent, PrivateMessageEvent, GroupMessageEvent from .exception import (DingAdapterException, ApiNotAvailable, NetworkError, ActionFailed, SessionExpired) diff --git a/nonebot/adapters/ding/bot.py b/nonebot/adapters/ding/bot.py index 0f0a10a8..e46febc5 100644 --- a/nonebot/adapters/ding/bot.py +++ b/nonebot/adapters/ding/bot.py @@ -1,20 +1,25 @@ import hmac import base64 from datetime import datetime +from typing import Any, Union, Optional, TYPE_CHECKING import httpx from nonebot.log import logger from nonebot.config import Config -from nonebot.adapters import BaseBot +from nonebot.typing import overrides from nonebot.message import handle_event +from nonebot.adapters import Bot as BaseBot from nonebot.exception import RequestDenied -from nonebot.typing import Any, Union, Driver, Optional, NoReturn from .utils import log -from .event import Event -from .model import MessageModel from .message import Message, MessageSegment from .exception import NetworkError, ApiNotAvailable, ActionFailed, SessionExpired +from .event import Event, MessageEvent, PrivateMessageEvent, GroupMessageEvent, ConversationType + +if TYPE_CHECKING: + from nonebot.drivers import Driver + +SEND_BY_SESSION_WEBHOOK = "send_by_sessionWebhook" class Bot(BaseBot): @@ -22,7 +27,7 @@ class Bot(BaseBot): 钉钉 协议 Bot 适配。继承属性参考 `BaseBot <./#class-basebot>`_ 。 """ - def __init__(self, driver: Driver, connection_type: str, config: Config, + def __init__(self, driver: "Driver", connection_type: str, config: Config, self_id: str, **kwargs): super().__init__(driver, connection_type, config, self_id, **kwargs) @@ -35,7 +40,8 @@ class Bot(BaseBot): return "ding" @classmethod - async def check_permission(cls, driver: Driver, connection_type: str, + @overrides(BaseBot) + async def check_permission(cls, driver: "Driver", connection_type: str, headers: dict, body: Optional[dict]) -> str: """ :说明: @@ -47,7 +53,8 @@ class Bot(BaseBot): # 检查连接方式 if connection_type not in ["http"]: - raise RequestDenied(405, "Unsupported connection type") + raise RequestDenied( + 405, "Unsupported connection type, available type: `http`") # 检查 timestamp if not timestamp: @@ -69,13 +76,25 @@ class Bot(BaseBot): log("WARNING", "Ding signature check ignored!") return body["chatbotUserId"] - async def handle_message(self, body: dict): - message = MessageModel.parse_obj(body) + @overrides(BaseBot) + async def handle_message(self, message: dict): if not message: return + # 判断消息类型,生成不同的 Event + try: + conversation_type = message["conversationType"] + if conversation_type == ConversationType.private: + event = PrivateMessageEvent.parse_obj(message) + elif conversation_type == ConversationType.group: + event = GroupMessageEvent.parse_obj(message) + else: + raise ValueError("Unsupported conversation type") + except Exception as e: + log("ERROR", "Event Parser Error", e) + return + try: - event = Event(message) await handle_event(self, event) except Exception as e: logger.opt(colors=True, exception=e).error( @@ -83,10 +102,11 @@ class Bot(BaseBot): ) return + @overrides(BaseBot) async def call_api(self, api: str, - event: Optional[Event] = None, - **data) -> Union[Any, NoReturn]: + event: Optional[MessageEvent] = None, + **data) -> Any: """ :说明: @@ -117,28 +137,27 @@ class Bot(BaseBot): log("DEBUG", f"Calling API {api}") - if api == "send_message": + if api == SEND_BY_SESSION_WEBHOOK: if event: # 确保 sessionWebhook 没有过期 if int(datetime.now().timestamp()) > int( - event.raw_event.sessionWebhookExpiredTime / 1000): + event.sessionWebhookExpiredTime / 1000): raise SessionExpired - target = event.raw_event.sessionWebhook + target = event.sessionWebhook else: - target = None - - if not target: raise ApiNotAvailable headers = {} - segment: MessageSegment = data["message"][0] + message: Message = data.get("message", None) + if not message: + raise ValueError("Message not found") try: async with httpx.AsyncClient(headers=headers) as client: response = await client.post( target, params={"access_token": self.config.access_token}, - json=segment.data, + json=message._produce(), timeout=self.config.api_timeout) if 200 <= response.status_code < 300: @@ -155,11 +174,12 @@ class Bot(BaseBot): except httpx.HTTPError: raise NetworkError("HTTP request failed") + @overrides(BaseBot) async def send(self, - event: Event, + event: MessageEvent, message: Union[str, "Message", "MessageSegment"], at_sender: bool = False, - **kwargs) -> Union[Any, NoReturn]: + **kwargs) -> Any: """ :说明: @@ -184,14 +204,14 @@ class Bot(BaseBot): """ msg = message if isinstance(message, Message) else Message(message) - at_sender = at_sender and bool(event.user_id) + at_sender = at_sender and bool(event.senderId) params = {} params["event"] = event params.update(kwargs) - if at_sender and event.detail_type != "private": - params["message"] = f"@{event.user_id} " + msg + if at_sender and event.conversationType != ConversationType.private: + params["message"] = f"@{event.senderNick} " + msg else: params["message"] = msg - return await self.call_api("send_message", **params) + return await self.call_api(SEND_BY_SESSION_WEBHOOK, **params) diff --git a/nonebot/adapters/ding/event.py b/nonebot/adapters/ding/event.py index 876ad493..23406df1 100644 --- a/nonebot/adapters/ding/event.py +++ b/nonebot/adapters/ding/event.py @@ -1,196 +1,145 @@ -from nonebot.adapters import BaseEvent -from nonebot.typing import Union, Optional +from enum import Enum +from typing import List, Optional +from typing_extensions import Literal + +from pydantic import BaseModel, root_validator + +from nonebot.typing import overrides +from nonebot.adapters import Event as BaseEvent from .message import Message -from .model import MessageModel, ConversationType, TextMessage class Event(BaseEvent): """ - 钉钉 协议 Event 适配。继承属性参考 `BaseEvent <./#class-baseevent>`_ 。 + 钉钉协议事件。各事件字段参考 `钉钉文档`_ + + .. _钉钉文档: + https://ding-doc.dingtalk.com/document#/org-dev-guide/elzz1p """ - def __init__(self, message: MessageModel): - super().__init__(message) + chatbotUserId: str + + @overrides(BaseEvent) + def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: + raise ValueError("Event has no type!") + + @overrides(BaseEvent) + def get_event_name(self) -> str: + raise ValueError("Event has no name!") + + @overrides(BaseEvent) + def get_event_description(self) -> str: + raise ValueError("Event has no description!") + + @overrides(BaseEvent) + def get_message(self) -> "Message": + raise ValueError("Event has no message!") + + @overrides(BaseEvent) + def get_plaintext(self) -> str: + raise ValueError("Event has no plaintext!") + + @overrides(BaseEvent) + def get_user_id(self) -> str: + raise ValueError("Event has no user_id!") + + @overrides(BaseEvent) + def get_session_id(self) -> str: + raise ValueError("Event has no session_id!") + + @overrides(BaseEvent) + def is_tome(self) -> bool: + return True + + +class TextMessage(BaseModel): + content: str + + +class AtUsersItem(BaseModel): + dingtalkId: str + staffId: Optional[str] + + +class ConversationType(str, Enum): + private = "1" + group = "2" + + +class MessageEvent(Event): + """消息事件""" + msgtype: str + text: TextMessage + msgId: str + createAt: int # ms + conversationType: ConversationType + conversationId: str + senderId: str + senderNick: str + senderCorpId: str + sessionWebhook: str + sessionWebhookExpiredTime: int + isAdmin: bool + + message: Message + + @root_validator(pre=True) + def gen_message(cls, values: dict): + assert "msgtype" in values, "msgtype must be specified" # 其实目前钉钉机器人只能接收到 text 类型的消息 - self._message = Message(getattr(message, message.msgtype or "text")) + assert values[ + "msgtype"] in values, f"{values['msgtype']} must be specified" + content = values[values['msgtype']]['content'] + # 如果是被 @,第一个字符将会为空格,移除特殊情况 + if content[0] == ' ': + content = content[1:] + values["message"] = content + return values - @property - def raw_event(self) -> MessageModel: - """原始上报消息""" - return self._raw_event - - @property - def id(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 消息 ID - """ - return self.raw_event.msgId - - @property - def name(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件名称,由 `type`.`detail_type` 组合而成 - """ - return self.type + "." + self.detail_type - - @property - def self_id(self) -> str: - """ - - 类型: ``str`` - - 说明: 机器人自身 ID - """ - return str(self.raw_event.chatbotUserId) - - @property - def time(self) -> int: - """ - - 类型: ``int`` - - 说明: 消息的时间戳,单位 s - """ - # 单位 ms -> s - return int(self.raw_event.createAt / 1000) - - @property - def type(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件类型 - """ + @overrides(Event) + def get_type(self) -> Literal["message", "notice", "request", "meta_event"]: return "message" - @type.setter - def type(self, value) -> None: - pass + @overrides(Event) + def get_event_name(self) -> str: + return f"{self.get_type()}.{self.conversationType.name}" - @property - def detail_type(self) -> str: - """ - - 类型: ``str`` - - 说明: 事件详细类型 - """ - return self.raw_event.conversationType.name + @overrides(Event) + def get_event_description(self) -> str: + return f'Message[{self.msgtype}] {self.msgId} from {self.senderId} "{self.text.content}"' - @detail_type.setter - def detail_type(self, value) -> None: - if value == "private": - self.raw_event.conversationType = ConversationType.private - if value == "group": - self.raw_event.conversationType = ConversationType.group + @overrides(Event) + def get_message(self) -> Message: + return self.message - @property - def sub_type(self) -> None: - """ - - 类型: ``None`` - - 说明: 钉钉适配器无事件子类型 - """ - return None + @overrides(Event) + def get_plaintext(self) -> str: + return self.text.content - @sub_type.setter - def sub_type(self, value) -> None: - pass + @overrides(Event) + def get_user_id(self) -> str: + return self.senderId - @property - def user_id(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 发送者 ID - """ - return self.raw_event.senderId + @overrides(Event) + def get_session_id(self) -> str: + return self.senderId - @user_id.setter - def user_id(self, value) -> None: - self.raw_event.senderId = value - @property - def group_id(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 事件主体群 ID - """ - return self.raw_event.conversationId +class PrivateMessageEvent(MessageEvent): + """私聊消息事件""" + chatbotCorpId: str + senderStaffId: Optional[str] + conversationType: ConversationType = ConversationType.private - @group_id.setter - def group_id(self, value) -> None: - self.raw_event.conversationId = value - @property - def to_me(self) -> Optional[bool]: - """ - - 类型: ``Optional[bool]`` - - 说明: 消息是否与机器人相关 - """ - return self.detail_type == "private" or self.raw_event.isInAtList +class GroupMessageEvent(MessageEvent): + """群消息事件""" + atUsers: List[AtUsersItem] + conversationType: ConversationType = ConversationType.group + conversationTitle: str + isInAtList: bool - @property - def message(self) -> Optional["Message"]: - """ - - 类型: ``Optional[Message]`` - - 说明: 消息内容 - """ - return self._message - - @message.setter - def message(self, value) -> None: - self._message = value - - @property - def reply(self) -> None: - """ - - 类型: ``None`` - - 说明: 回复消息详情 - """ - raise ValueError("暂不支持 reply") - - @property - def raw_message(self) -> Optional[Union[TextMessage]]: - """ - - 类型: ``Optional[str]`` - - 说明: 原始消息 - """ - return getattr(self.raw_event, self.raw_event.msgtype) - - @raw_message.setter - def raw_message(self, value) -> None: - setattr(self.raw_event, self.raw_event.msgtype, value) - - @property - def plain_text(self) -> Optional[str]: - """ - - 类型: ``Optional[str]`` - - 说明: 纯文本消息内容 - """ - return self.message and self.message.extract_plain_text().strip() - - @property - def sender(self) -> Optional[dict]: - """ - - 类型: ``Optional[dict]`` - - 说明: 消息发送者信息 - """ - result = { - # 加密的发送者ID。 - "senderId": self.raw_event.senderId, - # 发送者昵称。 - "senderNick": self.raw_event.senderNick, - # 企业内部群有的发送者当前群的企业 corpId。 - "senderCorpId": self.raw_event.senderCorpId, - # 企业内部群有的发送者在企业内的 userId。 - "senderStaffId": self.raw_event.senderStaffId, - "role": "admin" if self.raw_event.isAdmin else "member" - } - return result - - @sender.setter - def sender(self, value) -> None: - - def set_wrapper(name): - if value.get(name): - setattr(self.raw_event, name, value.get(name)) - - set_wrapper("senderId") - set_wrapper("senderNick") - set_wrapper("senderCorpId") - set_wrapper("senderStaffId") + @overrides(MessageEvent) + def is_tome(self) -> bool: + return self.isInAtList diff --git a/nonebot/adapters/ding/exception.py b/nonebot/adapters/ding/exception.py index b1d74d14..df416932 100644 --- a/nonebot/adapters/ding/exception.py +++ b/nonebot/adapters/ding/exception.py @@ -1,4 +1,5 @@ -from nonebot.typing import Optional +from typing import Optional + from nonebot.exception import (AdapterException, ActionFailed as BaseActionFailed, ApiNotAvailable as BaseApiNotAvailable, NetworkError as @@ -36,7 +37,10 @@ class ActionFailed(BaseActionFailed, DingAdapterException): self.errmsg = errmsg def __repr__(self): - return f"" + return f"" + + def __str__(self): + return self.__repr__() class ApiNotAvailable(BaseApiNotAvailable, DingAdapterException): @@ -65,7 +69,7 @@ class NetworkError(BaseNetworkError, DingAdapterException): return self.__repr__() -class SessionExpired(BaseApiNotAvailable, DingAdapterException): +class SessionExpired(ApiNotAvailable, DingAdapterException): """ :说明: @@ -74,3 +78,6 @@ class SessionExpired(BaseApiNotAvailable, DingAdapterException): def __repr__(self) -> str: return f"" + + def __str__(self): + return self.__repr__() diff --git a/nonebot/adapters/ding/message.py b/nonebot/adapters/ding/message.py index d8e88314..f32774e0 100644 --- a/nonebot/adapters/ding/message.py +++ b/nonebot/adapters/ding/message.py @@ -1,7 +1,8 @@ -from nonebot.typing import Any, Dict, Union, Iterable -from nonebot.adapters import BaseMessage, BaseMessageSegment -from .utils import log -from .model import TextMessage +from copy import copy +from typing import Any, Dict, Union, Mapping, Iterable + +from nonebot.typing import overrides +from nonebot.adapters import Message as BaseMessage, MessageSegment as BaseMessageSegment class MessageSegment(BaseMessageSegment): @@ -9,106 +10,128 @@ class MessageSegment(BaseMessageSegment): 钉钉 协议 MessageSegment 适配。具体方法参考协议消息段类型或源码。 """ - def __init__(self, type_: str, msg: Dict[str, Any]) -> None: - data = { - "msgtype": type_, - } - if msg: - data.update(msg) - log("DEBUG", f"data {data}") + @overrides(BaseMessageSegment) + def __init__(self, type_: str, data: Dict[str, Any]) -> None: super().__init__(type=type_, data=data) - @classmethod - def from_segment(cls, segment: "MessageSegment"): - return MessageSegment(segment.type, segment.data) - + @overrides(BaseMessageSegment) def __str__(self): - log("DEBUG", f"__str__: self.type {self.type} data {self.data}") if self.type == "text": - return str(self.data["text"]["content"].strip()) + return str(self.data["content"]) + elif self.type == "markdown": + return str(self.data["text"]) return "" + @overrides(BaseMessageSegment) def __add__(self, other) -> "Message": - if isinstance(other, str): - if self.type == 'text': - self.data['text']['content'] += other - return MessageSegment.from_segment(self) return Message(self) + other - def atMobile(self, mobileNumber): - self.data.setdefault("at", {}) - self.data["at"].setdefault("atMobiles", []) - self.data["at"]["atMobiles"].append(mobileNumber) + @overrides(BaseMessageSegment) + def __radd__(self, other) -> "Message": + return Message(other) + self - def atAll(self, value): - self.data.setdefault("at", {}) - self.data["at"]["isAtAll"] = value + @overrides(BaseMessageSegment) + def is_text(self) -> bool: + return self.type == "text" @staticmethod - def text(text_: str) -> "MessageSegment": - return MessageSegment("text", {"text": {"content": text_.strip()}}) + def atAll() -> "MessageSegment": + """@全体""" + return MessageSegment("at", {"isAtAll": True}) + + @staticmethod + def atMobiles(*mobileNumber: str) -> "MessageSegment": + """@指定手机号人员""" + return MessageSegment("at", {"atMobiles": list(mobileNumber)}) + + @staticmethod + def text(text: str) -> "MessageSegment": + """发送 ``text`` 类型消息""" + return MessageSegment("text", {"content": text}) + + @staticmethod + def image(picURL: str) -> "MessageSegment": + """发送 ``image`` 类型消息""" + return MessageSegment("image", {"picURL": picURL}) + + @staticmethod + def extension(dict_: dict) -> "MessageSegment": + """"标记 text 文本的 extension 属性,需要与 text 消息段相加。""" + return MessageSegment("extension", dict_) @staticmethod def markdown(title: str, text: str) -> "MessageSegment": - return MessageSegment("markdown", { - "markdown": { + """发送 ``markdown`` 类型消息""" + return MessageSegment( + "markdown", + { "title": title, "text": text, }, - }) + ) @staticmethod - def actionCardSingleBtn(title: str, text: str, btnTitle: str, - btnUrl) -> "MessageSegment": + def actionCardSingleBtn(title: str, text: str, singleTitle: str, + singleURL) -> "MessageSegment": + """发送 ``actionCardSingleBtn`` 类型消息""" return MessageSegment( "actionCard", { - "actionCard": { - "title": title, - "text": text, - "singleTitle": btnTitle, - "singleURL": btnUrl - } + "title": title, + "text": text, + "singleTitle": singleTitle, + "singleURL": singleURL }) @staticmethod - def actionCardSingleMultiBtns( + def actionCardMultiBtns( title: str, text: str, - btns: list = [], + btns: list, hideAvatar: bool = False, btnOrientation: str = '1', ) -> "MessageSegment": """ + 发送 ``actionCardMultiBtn`` 类型消息 + :参数: * ``btnOrientation``: 0:按钮竖直排列 1:按钮横向排列 - * ``btns``: [{ "title": title, "actionURL": actionURL }, ...] """ return MessageSegment( "actionCard", { - "actionCard": { - "title": title, - "text": text, - "hideAvatar": "1" if hideAvatar else "0", - "btnOrientation": btnOrientation, - "btns": btns - } + "title": title, + "text": text, + "hideAvatar": "1" if hideAvatar else "0", + "btnOrientation": btnOrientation, + "btns": btns }) @staticmethod - def feedCard(links: list = [],) -> "MessageSegment": + def feedCard(links: list) -> "MessageSegment": """ + 发送 ``feedCard`` 类型消息 + :参数: * ``links``: [{ "title": xxx, "messageURL": xxx, "picURL": xxx }, ...] """ - return MessageSegment("feedCard", {"feedCard": {"links": links}}) + return MessageSegment("feedCard", {"links": links}) @staticmethod - def empty() -> "MessageSegment": - """不想回复消息到群里""" - return MessageSegment("empty") + def raw(data) -> "MessageSegment": + return MessageSegment('raw', data) + + def to_dict(self) -> dict: + # 让用户可以直接发送原始的消息格式 + if self.type == "raw": + return copy(self.data) + + # 不属于消息内容,只是作为消息段的辅助 + if self.type in ["at", "extension"]: + return {self.type: copy(self.data)} + + return {"msgtype": self.type, self.type: copy(self.data)} class Message(BaseMessage): @@ -117,17 +140,27 @@ class Message(BaseMessage): """ @staticmethod + @overrides(BaseMessage) def _construct( - msg: Union[str, dict, list, - TextMessage]) -> Iterable[MessageSegment]: - if isinstance(msg, dict): + msg: Union[str, Mapping, + Iterable[Mapping]]) -> Iterable[MessageSegment]: + if isinstance(msg, Mapping): yield MessageSegment(msg["type"], msg.get("data") or {}) - return - elif isinstance(msg, list): - for seg in msg: - yield MessageSegment(seg["type"], seg.get("data") or {}) - return - elif isinstance(msg, TextMessage): - yield MessageSegment("text", {"text": msg.dict()}) elif isinstance(msg, str): yield MessageSegment.text(msg) + elif isinstance(msg, Iterable): + for seg in msg: + yield MessageSegment(seg["type"], seg.get("data") or {}) + + def _produce(self) -> dict: + data = {} + segment: MessageSegment + for segment in self: + # text 可以和 text 合并 + if segment.type == "text" and data.get("msgtype") == 'text': + data.setdefault("text", {}) + data["text"]["content"] = data["text"].setdefault( + "content", "") + segment.data["content"] + else: + data.update(segment.to_dict()) + return data diff --git a/nonebot/adapters/ding/model.py b/nonebot/adapters/ding/model.py deleted file mode 100644 index d317ea5b..00000000 --- a/nonebot/adapters/ding/model.py +++ /dev/null @@ -1,47 +0,0 @@ -from typing import List, Optional -from enum import Enum -from pydantic import BaseModel - - -class Headers(BaseModel): - sign: str - token: str - # ms - timestamp: int - - -class TextMessage(BaseModel): - content: str - - -class AtUsersItem(BaseModel): - dingtalkId: str - staffId: Optional[str] - - -class ConversationType(str, Enum): - private = '1' - group = '2' - - -class MessageModel(BaseModel): - msgtype: str = None - text: Optional[TextMessage] = None - msgId: str - # ms - createAt: int = None - conversationType: ConversationType = None - conversationId: str = None - conversationTitle: str = None - senderId: str = None - senderNick: str = None - senderCorpId: str = None - senderStaffId: str = None - chatbotUserId: str = None - chatbotCorpId: str = None - atUsers: List[AtUsersItem] = None - sessionWebhook: str = None - # ms - sessionWebhookExpiredTime: int = None - isAdmin: bool = None - isInAtList: bool = None diff --git a/nonebot/config.py b/nonebot/config.py index 756ef945..43ed4fbc 100644 --- a/nonebot/config.py +++ b/nonebot/config.py @@ -18,12 +18,11 @@ import os from pathlib import Path from datetime import timedelta from ipaddress import IPv4Address +from typing import Any, Set, Dict, Union, Mapping, Optional from pydantic import BaseSettings, IPvAnyAddress from pydantic.env_settings import SettingsError, env_file_sentinel, read_env_file -from nonebot.typing import Any, Set, Dict, Union, Mapping, Optional - class BaseConfig(BaseSettings): @@ -56,7 +55,7 @@ class BaseConfig(BaseSettings): for field in self.__fields__.values(): env_val: Optional[str] = None - for env_name in field.field_info.extra['env_names']: + for env_name in field.field_info.extra["env_names"]: env_val = env_vars.get(env_name) if env_name in env_file_vars: del env_file_vars[env_name] @@ -104,6 +103,7 @@ class Env(BaseSettings): """ - **类型**: ``str`` - **默认值**: ``"prod"`` + :说明: 当前环境名。 NoneBot 将从 ``.env.{environment}`` 文件中加载配置。 """ @@ -124,6 +124,7 @@ class Config(BaseConfig): """ - **类型**: ``str`` - **默认值**: ``"nonebot.drivers.fastapi"`` + :说明: NoneBot 运行所使用的 ``Driver`` 。继承自 ``nonebot.driver.BaseDriver`` 。 @@ -132,6 +133,7 @@ class Config(BaseConfig): """ - **类型**: ``IPvAnyAddress`` - **默认值**: ``127.0.0.1`` + :说明: NoneBot 的 HTTP 和 WebSocket 服务端监听的 IP/主机名。 @@ -140,6 +142,7 @@ class Config(BaseConfig): """ - **类型**: ``int`` - **默认值**: ``8080`` + :说明: NoneBot 的 HTTP 和 WebSocket 服务端监听的端口。 @@ -148,6 +151,7 @@ class Config(BaseConfig): """ - **类型**: ``bool`` - **默认值**: ``False`` + :说明: 是否以调试模式运行 NoneBot。 @@ -158,6 +162,7 @@ class Config(BaseConfig): """ - **类型**: ``Dict[str, str]`` - **默认值**: ``{}`` + :说明: 以机器人 ID 为键,上报地址为值的字典,环境变量或文件中应使用 json 序列化。 @@ -172,6 +177,7 @@ class Config(BaseConfig): """ - **类型**: ``Optional[float]`` - **默认值**: ``30.`` + :说明: API 请求超时时间,单位: 秒。 @@ -180,6 +186,7 @@ class Config(BaseConfig): """ - **类型**: ``Optional[str]`` - **默认值**: ``None`` + :说明: API 请求以及上报所需密钥,在请求头中携带。 @@ -195,6 +202,7 @@ class Config(BaseConfig): """ - **类型**: ``Optional[str]`` - **默认值**: ``None`` + :说明: HTTP POST 形式上报所需签名,在请求头中携带。 @@ -208,10 +216,11 @@ class Config(BaseConfig): """ # bot runtime configs - superusers: Set[int] = set() + superusers: Set[str] = set() """ - - **类型**: ``Set[int]`` + - **类型**: ``Set[str]`` - **默认值**: ``set()`` + :说明: 机器人超级用户。 @@ -220,12 +229,13 @@ class Config(BaseConfig): .. code-block:: default - SUPER_USERS=[12345789] + SUPER_USERS=["12345789"] """ nickname: Set[str] = set() """ - **类型**: ``Set[str]`` - **默认值**: ``set()`` + :说明: 机器人昵称。 @@ -234,6 +244,7 @@ class Config(BaseConfig): """ - **类型**: ``Set[str]`` - **默认值**: ``{"/"}`` + :说明: 命令的起始标记,用于判断一条消息是不是命令。 @@ -242,6 +253,7 @@ class Config(BaseConfig): """ - **类型**: ``Set[str]`` - **默认值**: ``{"."}`` + :说明: 命令的分隔标记,用于将文本形式的命令切分为元组(实际的命令名)。 @@ -250,6 +262,7 @@ class Config(BaseConfig): """ - **类型**: ``timedelta`` - **默认值**: ``timedelta(minutes=2)`` + :说明: 等待用户回复的超时时间。 diff --git a/nonebot/drivers/__init__.py b/nonebot/drivers/__init__.py index 8227690f..7e95ee91 100644 --- a/nonebot/drivers/__init__.py +++ b/nonebot/drivers/__init__.py @@ -6,22 +6,37 @@ """ import abc +import asyncio +from typing import Set, Dict, Type, Optional, Callable, TYPE_CHECKING from nonebot.log import logger from nonebot.config import Env, Config -from nonebot.typing import Bot, Dict, Type, Union, Optional, Callable +from nonebot.typing import T_WebSocketConnectionHook, T_WebSocketDisconnectionHook + +if TYPE_CHECKING: + from nonebot.adapters import Bot -class BaseDriver(abc.ABC): +class Driver(abc.ABC): """ Driver 基类。将后端框架封装,以满足适配器使用。 """ - _adapters: Dict[str, Type[Bot]] = {} + _adapters: Dict[str, Type["Bot"]] = {} """ :类型: ``Dict[str, Type[Bot]]`` :说明: 已注册的适配器列表 """ + _ws_connection_hook: Set[T_WebSocketConnectionHook] = set() + """ + :类型: ``Set[T_WebSocketConnectionHook]`` + :说明: WebSocket 连接建立时执行的函数 + """ + _ws_disconnection_hook: Set[T_WebSocketDisconnectionHook] = set() + """ + :类型: ``Set[T_WebSocketDisconnectionHook]`` + :说明: WebSocket 连接断开时执行的函数 + """ @abc.abstractmethod def __init__(self, env: Env, config: Config): @@ -41,14 +56,14 @@ class BaseDriver(abc.ABC): :类型: ``Config`` :说明: 配置对象 """ - self._clients: Dict[str, Bot] = {} + self._clients: Dict[str, "Bot"] = {} """ :类型: ``Dict[str, Bot]`` :说明: 已连接的 Bot """ @classmethod - def register_adapter(cls, name: str, adapter: Type[Bot]): + def register_adapter(cls, name: str, adapter: Type["Bot"]): """ :说明: @@ -88,10 +103,14 @@ class BaseDriver(abc.ABC): raise NotImplementedError @property - def bots(self) -> Dict[str, Bot]: + def bots(self) -> Dict[str, "Bot"]: """ - :类型: ``Dict[str, Bot]`` - :说明: 获取当前所有已连接的 Bot + :类型: + + ``Dict[str, Bot]`` + :说明: + + 获取当前所有已连接的 Bot """ return self._clients @@ -105,6 +124,68 @@ class BaseDriver(abc.ABC): """注册一个在驱动停止时运行的函数""" raise NotImplementedError + def on_bot_connect( + self, func: T_WebSocketConnectionHook) -> T_WebSocketConnectionHook: + """ + :说明: + + 装饰一个函数使他在 bot 通过 WebSocket 连接成功时执行。 + + :函数参数: + + * ``bot: Bot``: 当前连接上的 Bot 对象 + """ + self._ws_connection_hook.add(func) + return func + + def on_bot_disconnect( + self, + func: T_WebSocketDisconnectionHook) -> T_WebSocketDisconnectionHook: + """ + :说明: + + 装饰一个函数使他在 bot 通过 WebSocket 连接断开时执行。 + + :函数参数: + + * ``bot: Bot``: 当前连接上的 Bot 对象 + """ + self._ws_disconnection_hook.add(func) + return func + + def _bot_connect(self, bot: "Bot") -> None: + """在 WebSocket 连接成功后,调用该函数来注册 bot 对象""" + self._clients[bot.self_id] = bot + + async def _run_hook(bot: "Bot") -> None: + coros = list(map(lambda x: x(bot), self._ws_connection_hook)) + if coros: + try: + await asyncio.gather(*coros) + except Exception as e: + logger.opt(colors=True, exception=e).error( + "Error when running WebSocketConnection hook. " + "Running cancelled!") + + asyncio.create_task(_run_hook(bot)) + + def _bot_disconnect(self, bot: "Bot") -> None: + """在 WebSocket 连接断开后,调用该函数来注销 bot 对象""" + if bot.self_id in self._clients: + del self._clients[bot.self_id] + + async def _run_hook(bot: "Bot") -> None: + coros = list(map(lambda x: x(bot), self._ws_disconnection_hook)) + if coros: + try: + await asyncio.gather(*coros) + except Exception as e: + logger.opt(colors=True, exception=e).error( + "Error when running WebSocketDisConnection hook. " + "Running cancelled!") + + asyncio.create_task(_run_hook(bot)) + @abc.abstractmethod def run(self, host: Optional[str] = None, @@ -137,7 +218,7 @@ class BaseDriver(abc.ABC): raise NotImplementedError -class BaseWebSocket(object): +class WebSocket(object): """WebSocket 连接封装,统一接口方便外部调用。""" @abc.abstractmethod diff --git a/nonebot/drivers/fastapi.py b/nonebot/drivers/fastapi.py index 841b82e5..42e21490 100644 --- a/nonebot/drivers/fastapi.py +++ b/nonebot/drivers/fastapi.py @@ -8,34 +8,22 @@ FastAPI 驱动适配 https://fastapi.tiangolo.com/ """ -import hmac import json import asyncio import logging +from typing import Optional, Callable import uvicorn from fastapi.responses import Response -from fastapi import Body, status, Header, Request, FastAPI, Depends, HTTPException +from fastapi import Body, status, Request, FastAPI, HTTPException from starlette.websockets import WebSocketDisconnect, WebSocket as FastAPIWebSocket from nonebot.log import logger +from nonebot.typing import overrides from nonebot.config import Env, Config from nonebot.utils import DataclassEncoder from nonebot.exception import RequestDenied -from nonebot.drivers import BaseDriver, BaseWebSocket -from nonebot.typing import Optional, Callable, overrides - - -def get_auth_bearer(access_token: Optional[str] = Header( - None, alias="Authorization")): - if not access_token: - return None - scheme, _, param = access_token.partition(" ") - if scheme.lower() not in ["bearer", "token"]: - raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, - detail="Not authenticated", - headers={"WWW-Authenticate": "Bearer"}) - return param +from nonebot.drivers import Driver as BaseDriver, WebSocket as BaseWebSocket class Driver(BaseDriver): @@ -145,7 +133,9 @@ class Driver(BaseDriver): raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) if adapter not in self._adapters: - logger.warning("Unknown adapter") + logger.warning( + f"Unknown adapter {adapter}. Please register the adapter before use." + ) raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="adapter not found") @@ -174,7 +164,9 @@ class Driver(BaseDriver): ws = WebSocket(websocket) if adapter not in self._adapters: - logger.warning("Unknown adapter") + logger.warning( + f"Unknown adapter {adapter}. Please register the adapter before use." + ) await ws.close(code=status.WS_1008_POLICY_VIOLATION) return @@ -196,11 +188,12 @@ class Driver(BaseDriver): bot = BotClass(self, "websocket", self.config, x_self_id, websocket=ws) await ws.accept() - self._clients[x_self_id] = bot logger.opt(colors=True).info( f"WebSocket Connection from {adapter.upper()} " f"Bot {x_self_id} Accepted!") + self._bot_connect(bot) + try: while not ws.closed: data = await ws.receive() @@ -210,14 +203,14 @@ class Driver(BaseDriver): asyncio.create_task(bot.handle_message(data)) finally: - del self._clients[x_self_id] + self._bot_disconnect(bot) class WebSocket(BaseWebSocket): def __init__(self, websocket: FastAPIWebSocket): super().__init__(websocket) - self._closed = None + self._closed = False @property @overrides(BaseWebSocket) diff --git a/nonebot/exception.py b/nonebot/exception.py index 6a4b65dc..815ac714 100644 --- a/nonebot/exception.py +++ b/nonebot/exception.py @@ -130,6 +130,15 @@ class AdapterException(NoneBotException): self.adapter_name = adapter_name +class NoLogException(Exception): + """ + :说明: + + 指示 NoneBot 对当前 ``Event`` 进行处理但不显示 Log 信息,可在 ``get_log_string`` 时抛出 + """ + pass + + class ApiNotAvailable(AdapterException): """ :说明: diff --git a/nonebot/matcher.py b/nonebot/matcher.py index 1c2eabe6..4ab2c28f 100644 --- a/nonebot/matcher.py +++ b/nonebot/matcher.py @@ -5,19 +5,21 @@ 该模块实现事件响应器的创建与运行,并提供一些快捷方法来帮助用户更好的与机器人进行 对话 。 """ -from nonebot.log import logger -import typing import inspect from functools import wraps from datetime import datetime from contextvars import ContextVar from collections import defaultdict +from typing import Type, List, Dict, Union, Callable, Optional, NoReturn, TYPE_CHECKING from nonebot.rule import Rule +from nonebot.log import logger from nonebot.permission import Permission, USER -from nonebot.typing import Type, List, Dict, Union, Callable, Optional, NoReturn -from nonebot.typing import Bot, Event, Handler, Message, ArgsParser, MessageSegment -from nonebot.exception import PausedException, RejectedException, FinishedException +from nonebot.typing import T_State, T_StateFactory, T_Handler, T_ArgsParser +from nonebot.exception import PausedException, RejectedException, FinishedException, StopPropagation + +if TYPE_CHECKING: + from nonebot.adapters import Bot, Event, Message, MessageSegment matchers: Dict[int, List[Type["Matcher"]]] = defaultdict(list) """ @@ -62,9 +64,9 @@ class Matcher(metaclass=MatcherMeta): :类型: ``Permission`` :说明: 事件响应器触发权限 """ - handlers: List[Handler] = [] + handlers: List[T_Handler] = [] """ - :类型: ``List[Handler]`` + :类型: ``List[T_Handler]`` :说明: 事件响应器拥有的事件处理函数列表 """ priority: int = 1 @@ -88,15 +90,20 @@ class Matcher(metaclass=MatcherMeta): :说明: 事件响应器过期时间点 """ - _default_state: dict = {} + _default_state: T_State = {} """ - :类型: ``dict`` + :类型: ``T_State`` :说明: 事件响应器默认状态 """ - - _default_parser: Optional[ArgsParser] = None + _default_state_factory: Optional[T_StateFactory] = None """ - :类型: ``Optional[ArgsParser]`` + :类型: ``Optional[T_State]`` + :说明: 事件响应器默认工厂函数 + """ + + _default_parser: Optional[T_ArgsParser] = None + """ + :类型: ``Optional[T_ArgsParser]`` :说明: 事件响应器默认参数解析函数 """ @@ -106,7 +113,7 @@ class Matcher(metaclass=MatcherMeta): self.state = self._default_state.copy() def __repr__(self) -> str: - return (f"") def __str__(self) -> str: @@ -117,13 +124,14 @@ class Matcher(metaclass=MatcherMeta): type_: str = "", rule: Optional[Rule] = None, permission: Optional[Permission] = None, - handlers: Optional[List[Handler]] = None, + handlers: Optional[List[T_Handler]] = None, temp: bool = False, priority: int = 1, block: bool = False, *, module: Optional[str] = None, - default_state: Optional[dict] = None, + default_state: Optional[T_State] = None, + default_state_factory: Optional[T_StateFactory] = None, expire_time: Optional[datetime] = None) -> Type["Matcher"]: """ :说明: @@ -132,15 +140,16 @@ class Matcher(metaclass=MatcherMeta): :参数: - * ``type_: str``: 事件响应器类型,与 ``event.type`` 一致时触发,空字符串表示任意 + * ``type_: str``: 事件响应器类型,与 ``event.get_type()`` 一致时触发,空字符串表示任意 * ``rule: Optional[Rule]``: 匹配规则 * ``permission: Optional[Permission]``: 权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器,即触发一次后删除 * ``priority: int``: 响应优先级 * ``block: bool``: 是否阻止事件向更低优先级的响应器传播 * ``module: Optional[str]``: 事件响应器所在模块名称 - * ``default_state: Optional[dict]``: 默认状态 ``state`` + * ``default_state: Optional[T_State]``: 默认状态 ``state`` + * ``default_state_factory: Optional[T_StateFactory]``: 默认状态 ``state`` 的工厂函数 * ``expire_time: Optional[datetime]``: 事件响应器最终有效时间点,过时即被删除 :返回: @@ -150,16 +159,29 @@ class Matcher(metaclass=MatcherMeta): NewMatcher = type( "Matcher", (Matcher,), { - "module": module, - "type": type_, - "rule": rule or Rule(), - "permission": permission or Permission(), - "handlers": handlers or [], - "temp": temp, - "expire_time": expire_time, - "priority": priority, - "block": block, - "_default_state": default_state or {} + "module": + module, + "type": + type_, + "rule": + rule or Rule(), + "permission": + permission or Permission(), + "handlers": + handlers or [], + "temp": + temp, + "expire_time": + expire_time, + "priority": + priority, + "block": + block, + "_default_state": + default_state or {}, + "_default_state_factory": + staticmethod(default_state_factory) + if default_state_factory else None }) matchers[priority].append(NewMatcher) @@ -167,7 +189,7 @@ class Matcher(metaclass=MatcherMeta): return NewMatcher @classmethod - async def check_perm(cls, bot: Bot, event: Event) -> bool: + async def check_perm(cls, bot: "Bot", event: "Event") -> bool: """ :说明: @@ -185,7 +207,8 @@ class Matcher(metaclass=MatcherMeta): return await cls.permission(bot, event) @classmethod - async def check_rule(cls, bot: Bot, event: Event, state: dict) -> bool: + async def check_rule(cls, bot: "Bot", event: "Event", + state: T_State) -> bool: """ :说明: @@ -195,17 +218,18 @@ class Matcher(metaclass=MatcherMeta): * ``bot: Bot``: Bot 对象 * ``event: Event``: 上报事件 - * ``state: dict``: 当前状态 + * ``state: T_State``: 当前状态 :返回: - ``bool``: 是否满足匹配规则 """ - return (event.type == (cls.type or event.type) and + event_type = event.get_type() + return (event_type == (cls.type or event_type) and await cls.rule(bot, event, state)) @classmethod - def args_parser(cls, func: ArgsParser) -> ArgsParser: + def args_parser(cls, func: T_ArgsParser) -> T_ArgsParser: """ :说明: @@ -213,13 +237,35 @@ class Matcher(metaclass=MatcherMeta): :参数: - * ``func: ArgsParser``: 参数解析函数 + * ``func: T_ArgsParser``: 参数解析函数 """ cls._default_parser = func return func + @staticmethod + def process_handler(handler: T_Handler) -> T_Handler: + signature = inspect.signature(handler, follow_wrapped=False) + bot = signature.parameters.get("bot") + event = signature.parameters.get("event") + state = signature.parameters.get("state") + matcher = signature.parameters.get("matcher") + if not bot: + raise ValueError("Handler missing parameter 'bot'") + handler.__params__ = { + "bot": bot.annotation, + "event": event.annotation if event else None, + "state": T_State if state else None, + "matcher": matcher.annotation if matcher else None + } + return handler + @classmethod - def handle(cls) -> Callable[[Handler], Handler]: + def append_handler(cls, handler: T_Handler) -> None: + # Process handler first + cls.handlers.append(cls.process_handler(handler)) + + @classmethod + def handle(cls) -> Callable[[T_Handler], T_Handler]: """ :说明: @@ -230,14 +276,14 @@ class Matcher(metaclass=MatcherMeta): * 无 """ - def _decorator(func: Handler) -> Handler: - cls.handlers.append(func) + def _decorator(func: T_Handler) -> T_Handler: + cls.append_handler(func) return func return _decorator @classmethod - def receive(cls) -> Callable[[Handler], Handler]: + def receive(cls) -> Callable[[T_Handler], T_Handler]: """ :说明: @@ -248,16 +294,17 @@ class Matcher(metaclass=MatcherMeta): * 无 """ - async def _receive(bot: Bot, event: Event, state: dict) -> NoReturn: + async def _receive(bot: "Bot", event: "Event", + state: T_State) -> NoReturn: raise PausedException if cls.handlers: # 已有前置handlers则接受一条新的消息,否则视为接收初始消息 - cls.handlers.append(_receive) + cls.append_handler(_receive) - def _decorator(func: Handler) -> Handler: + def _decorator(func: T_Handler) -> T_Handler: if not cls.handlers or cls.handlers[-1] is not func: - cls.handlers.append(func) + cls.append_handler(func) return func @@ -267,9 +314,9 @@ class Matcher(metaclass=MatcherMeta): def got( cls, key: str, - prompt: Optional[Union[str, Message, MessageSegment]] = None, - args_parser: Optional[ArgsParser] = None - ) -> Callable[[Handler], Handler]: + prompt: Optional[Union[str, "Message", "MessageSegment"]] = None, + args_parser: Optional[T_ArgsParser] = None + ) -> Callable[[T_Handler], T_Handler]: """ :说明: @@ -279,10 +326,10 @@ class Matcher(metaclass=MatcherMeta): * ``key: str``: 参数名 * ``prompt: Optional[Union[str, Message, MessageSegment]]``: 在参数不存在时向用户发送的消息 - * ``args_parser: Optional[ArgsParser]``: 可选参数解析函数,空则使用默认解析函数 + * ``args_parser: Optional[T_ArgsParser]``: 可选参数解析函数,空则使用默认解析函数 """ - async def _key_getter(bot: Bot, event: Event, state: dict): + async def _key_getter(bot: "Bot", event: "Event", state: T_State): state["_current_key"] = key if key not in state: if prompt: @@ -292,38 +339,42 @@ class Matcher(metaclass=MatcherMeta): else: state["_skip_key"] = True - async def _key_parser(bot: Bot, event: Event, state: dict): + async def _key_parser(bot: "Bot", event: "Event", state: T_State): if key in state and state.get("_skip_key"): del state["_skip_key"] return parser = args_parser or cls._default_parser if parser: + # parser = cast(T_ArgsParser["Bot", "Event"], parser) await parser(bot, event, state) else: - state[state["_current_key"]] = str(event.message) + state[state["_current_key"]] = str(event.get_message()) - cls.handlers.append(_key_getter) - cls.handlers.append(_key_parser) + cls.append_handler(_key_getter) + cls.append_handler(_key_parser) - def _decorator(func: Handler) -> Handler: + def _decorator(func: T_Handler) -> T_Handler: if not hasattr(cls.handlers[-1], "__wrapped__"): + cls.process_handler(func) parser = cls.handlers.pop() @wraps(func) - async def wrapper(bot: Bot, event: Event, state: dict): - await parser(bot, event, state) - await func(bot, event, state) + async def wrapper(bot: "Bot", event: "Event", state: T_State, + matcher: Matcher): + await matcher.run_handler(parser, bot, event, state) + await matcher.run_handler(func, bot, event, state) if "_current_key" in state: del state["_current_key"] - cls.handlers.append(wrapper) + cls.append_handler(wrapper) return func return _decorator @classmethod - async def send(cls, message: Union[str, Message, MessageSegment], **kwargs): + async def send(cls, message: Union[str, "Message", "MessageSegment"], + **kwargs): """ :说明: @@ -340,8 +391,8 @@ class Matcher(metaclass=MatcherMeta): @classmethod async def finish(cls, - message: Optional[Union[str, Message, - MessageSegment]] = None, + message: Optional[Union[str, "Message", + "MessageSegment"]] = None, **kwargs) -> NoReturn: """ :说明: @@ -361,8 +412,8 @@ class Matcher(metaclass=MatcherMeta): @classmethod async def pause(cls, - prompt: Optional[Union[str, Message, - MessageSegment]] = None, + prompt: Optional[Union[str, "Message", + "MessageSegment"]] = None, **kwargs) -> NoReturn: """ :说明: @@ -382,8 +433,8 @@ class Matcher(metaclass=MatcherMeta): @classmethod async def reject(cls, - prompt: Optional[Union[str, Message, - MessageSegment]] = None, + prompt: Optional[Union[str, "Message", + "MessageSegment"]] = None, **kwargs) -> NoReturn: """ :说明: @@ -401,29 +452,56 @@ class Matcher(metaclass=MatcherMeta): await bot.send(event=event, message=prompt, **kwargs) raise RejectedException + def stop_propagation(self): + self.block = True + + async def run_handler(self, handler: T_Handler, bot: "Bot", event: "Event", + state: T_State): + if not hasattr(handler, "__params__"): + self.process_handler(handler) + params = getattr(handler, "__params__") + + BotType = ((params["bot"] is not inspect.Parameter.empty) and + inspect.isclass(params["bot"]) and params["bot"]) + if BotType and not isinstance(bot, BotType): + logger.debug( + f"Matcher {self} bot type {type(bot)} not match annotation {BotType}, ignored" + ) + return + + EventType = ((params["event"] is not inspect.Parameter.empty) and + inspect.isclass(params["event"]) and params["event"]) + if EventType and not isinstance(event, EventType): + logger.debug( + f"Matcher {self} event type {type(event)} not match annotation {EventType}, ignored" + ) + return + + args = {"bot": bot, "event": event, "state": state, "matcher": self} + await handler( + **{k: v for k, v in args.items() if params[k] is not None}) + # 运行handlers - async def run(self, bot: Bot, event: Event, state: dict): + async def run(self, bot: "Bot", event: "Event", state: T_State): b_t = current_bot.set(bot) e_t = current_event.set(event) try: # Refresh preprocess state - self.state.update(state) + state_ = await self._default_state_factory( + bot, event) if self._default_state_factory else self.state + state_.update(state) for _ in range(len(self.handlers)): handler = self.handlers.pop(0) - annotation = typing.get_type_hints(handler) - BotType = annotation.get("bot") - if BotType and inspect.isclass(BotType) and not isinstance( - bot, BotType): - continue - await handler(bot, event, self.state) + await self.run_handler(handler, bot, event, state_) except RejectedException: self.handlers.insert(0, handler) # type: ignore Matcher.new( self.type, Rule(), - USER(event.user_id, perm=self.permission), # type:ignore + USER(event.get_session_id(), + perm=self.permission), # type:ignore self.handlers, temp=True, priority=0, @@ -435,7 +513,8 @@ class Matcher(metaclass=MatcherMeta): Matcher.new( self.type, Rule(), - USER(event.user_id, perm=self.permission), # type:ignore + USER(event.get_session_id(), + perm=self.permission), # type:ignore self.handlers, temp=True, priority=0, @@ -445,6 +524,8 @@ class Matcher(metaclass=MatcherMeta): expire_time=datetime.now() + bot.config.session_expire_timeout) except FinishedException: pass + except StopPropagation: + self.block = True finally: logger.info(f"Matcher {self} running complete") current_bot.reset(b_t) diff --git a/nonebot/message.py b/nonebot/message.py index 425b476a..5b3c8b6f 100644 --- a/nonebot/message.py +++ b/nonebot/message.py @@ -7,22 +7,24 @@ NoneBot 内部处理并按优先级分发事件给所有事件响应器,提供 import asyncio from datetime import datetime +from typing import Set, Type, Optional, Iterable, TYPE_CHECKING from nonebot.log import logger from nonebot.rule import TrieRule -from nonebot.utils import escape_tag from nonebot.matcher import matchers, Matcher -from nonebot.typing import Set, Type, Union, Optional, Iterable, NoReturn, Bot, Event -from nonebot.exception import IgnoredException, StopPropagation -from nonebot.typing import EventPreProcessor, RunPreProcessor, EventPostProcessor, RunPostProcessor +from nonebot.exception import IgnoredException, StopPropagation, NoLogException +from nonebot.typing import T_State, T_EventPreProcessor, T_RunPreProcessor, T_EventPostProcessor, T_RunPostProcessor -_event_preprocessors: Set[EventPreProcessor] = set() -_event_postprocessors: Set[EventPostProcessor] = set() -_run_preprocessors: Set[RunPreProcessor] = set() -_run_postprocessors: Set[RunPostProcessor] = set() +if TYPE_CHECKING: + from nonebot.adapters import Bot, Event + +_event_preprocessors: Set[T_EventPreProcessor] = set() +_event_postprocessors: Set[T_EventPostProcessor] = set() +_run_preprocessors: Set[T_RunPreProcessor] = set() +_run_postprocessors: Set[T_RunPostProcessor] = set() -def event_preprocessor(func: EventPreProcessor) -> EventPreProcessor: +def event_preprocessor(func: T_EventPreProcessor) -> T_EventPreProcessor: """ :说明: @@ -34,13 +36,13 @@ def event_preprocessor(func: EventPreProcessor) -> EventPreProcessor: * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 - * ``state: dict``: 当前 State + * ``state: T_State``: 当前 State """ _event_preprocessors.add(func) return func -def event_postprocessor(func: EventPostProcessor) -> EventPostProcessor: +def event_postprocessor(func: T_EventPostProcessor) -> T_EventPostProcessor: """ :说明: @@ -52,13 +54,13 @@ def event_postprocessor(func: EventPostProcessor) -> EventPostProcessor: * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 - * ``state: dict``: 当前事件运行前 State + * ``state: T_State``: 当前事件运行前 State """ _event_postprocessors.add(func) return func -def run_preprocessor(func: RunPreProcessor) -> RunPreProcessor: +def run_preprocessor(func: T_RunPreProcessor) -> T_RunPreProcessor: """ :说明: @@ -71,13 +73,13 @@ def run_preprocessor(func: RunPreProcessor) -> RunPreProcessor: * ``matcher: Matcher``: 当前要运行的事件响应器 * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 - * ``state: dict``: 当前 State + * ``state: T_State``: 当前 State """ _run_preprocessors.add(func) return func -def run_postprocessor(func: RunPostProcessor) -> RunPostProcessor: +def run_postprocessor(func: T_RunPostProcessor) -> T_RunPostProcessor: """ :说明: @@ -91,18 +93,18 @@ def run_postprocessor(func: RunPostProcessor) -> RunPostProcessor: * ``exception: Optional[Exception]``: 事件响应器运行错误(如果存在) * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 - * ``state: dict``: 当前 State + * ``state: T_State``: 当前 State """ _run_postprocessors.add(func) return func -async def _check_matcher(priority: int, bot: Bot, event: Event, - state: dict) -> Iterable[Type[Matcher]]: +async def _check_matcher(priority: int, bot: "Bot", event: "Event", + state: T_State) -> Iterable[Type[Matcher]]: current_matchers = matchers[priority].copy() - async def _check(Matcher: Type[Matcher], bot: Bot, event: Event, - state: dict) -> Optional[Type[Matcher]]: + async def _check(Matcher: Type[Matcher], bot: "Bot", event: "Event", + state: T_State) -> Optional[Type[Matcher]]: try: if (not Matcher.expire_time or datetime.now() <= Matcher.expire_time ) and await Matcher.check_perm( @@ -128,16 +130,16 @@ async def _check_matcher(priority: int, bot: Bot, event: Event, ] results = await asyncio.gather(*checking_tasks, return_exceptions=True) expired = await asyncio.gather(*checking_expire_tasks) - for expired_matcher in filter(lambda x: x and x in results, expired): + for expired_matcher in filter(lambda x: x, expired): try: - matchers[priority].remove(expired_matcher) + matchers[priority].remove(expired_matcher) # type: ignore except Exception: pass return filter(lambda x: x, results) -async def _run_matcher(Matcher: Type[Matcher], bot: Bot, event: Event, - state: dict) -> Union[None, NoReturn]: +async def _run_matcher(Matcher: Type[Matcher], bot: "Bot", event: "Event", + state: T_State) -> None: logger.info(f"Event will be handled by {Matcher}") matcher = Matcher() @@ -162,8 +164,6 @@ async def _run_matcher(Matcher: Type[Matcher], bot: Bot, event: Event, try: logger.debug(f"Running matcher {matcher}") await matcher.run(bot, event, state) - except StopPropagation as e: - exception = e except Exception as e: logger.opt(colors=True, exception=e).error( f"Running matcher {matcher} failed." @@ -181,11 +181,12 @@ async def _run_matcher(Matcher: Type[Matcher], bot: Bot, event: Event, "Error when running RunPostProcessors" ) - if matcher.block or isinstance(exception, StopPropagation): + if matcher.block: raise StopPropagation + return -async def handle_event(bot: Bot, event: Event): +async def handle_event(bot: "Bot", event: "Event"): """ :说明: @@ -204,24 +205,10 @@ async def handle_event(bot: Bot, event: Event): asyncio.create_task(handle_event(bot, event)) """ show_log = True - log_msg = f"{bot.type.upper()} | {event.self_id} [{event.name}]: " - if event.type == "message": - log_msg += f"Message {event.id} from " - log_msg += str(event.user_id) - if event.detail_type == "group": - log_msg += f"@[群:{event.group_id}]:" - - log_msg += ' "' + "".join( - map( - lambda x: escape_tag(str(x)) - if x.type == "text" else f"{escape_tag(str(x))}", - event.message)) + '"' # type: ignore - elif event.type == "notice": - log_msg += f"Notice {event.raw_event}" - elif event.type == "request": - log_msg += f"Request {event.raw_event}" - elif event.type == "meta_event": - # log_msg += f"MetaEvent {event.detail_type}" + log_msg = f"{bot.type.upper()} {bot.self_id} | " + try: + log_msg += event.get_log_string() + except NoLogException: show_log = False if show_log: logger.opt(colors=True).info(log_msg) @@ -233,8 +220,8 @@ async def handle_event(bot: Bot, event: Event): logger.debug("Running PreProcessors...") await asyncio.gather(*coros) except IgnoredException: - logger.opt( - colors=True).info(f"Event {event.name} is ignored") + logger.opt(colors=True).info( + f"Event {event.get_event_name()} is ignored") return except Exception as e: logger.opt(colors=True, exception=e).error( diff --git a/nonebot/permission.py b/nonebot/permission.py index f4c793b0..751dae8b 100644 --- a/nonebot/permission.py +++ b/nonebot/permission.py @@ -10,16 +10,21 @@ """ import asyncio +from typing import Union, Optional, Callable, NoReturn, Awaitable, TYPE_CHECKING from nonebot.utils import run_sync -from nonebot.typing import Bot, Event, Union, NoReturn, Optional, Callable, Awaitable, PermissionChecker +from nonebot.typing import T_PermissionChecker + +if TYPE_CHECKING: + from nonebot.adapters import Bot, Event class Permission: __slots__ = ("checkers",) - def __init__(self, *checkers: Callable[[Bot, Event], - Awaitable[bool]]) -> None: + def __init__( + self, *checkers: Callable[["Bot", "Event"], + Awaitable[bool]]) -> None: """ :参数: @@ -36,7 +41,7 @@ class Permission: * ``Set[Callable[[Bot, Event], Awaitable[bool]]]`` """ - async def __call__(self, bot: Bot, event: Event) -> bool: + async def __call__(self, bot: "Bot", event: "Event") -> bool: """ :说明: @@ -62,7 +67,7 @@ class Permission: def __or__( self, other: Optional[Union["Permission", - PermissionChecker]]) -> "Permission": + T_PermissionChecker]]) -> "Permission": checkers = self.checkers.copy() if other is None: return self @@ -75,20 +80,20 @@ class Permission: return Permission(*checkers) -async def _message(bot: Bot, event: Event) -> bool: - return event.type == "message" +async def _message(bot: "Bot", event: "Event") -> bool: + return event.get_type() == "message" -async def _notice(bot: Bot, event: Event) -> bool: - return event.type == "notice" +async def _notice(bot: "Bot", event: "Event") -> bool: + return event.get_type() == "notice" -async def _request(bot: Bot, event: Event) -> bool: - return event.type == "request" +async def _request(bot: "Bot", event: "Event") -> bool: + return event.get_type() == "request" -async def _metaevent(bot: Bot, event: Event) -> bool: - return event.type == "meta_event" +async def _metaevent(bot: "Bot", event: "Event") -> bool: + return event.get_type() == "meta_event" MESSAGE = Permission(_message) @@ -109,7 +114,7 @@ METAEVENT = Permission(_metaevent) """ -def USER(*user: int, perm: Permission = Permission()): +def USER(*user: str, perm: Permission = Permission()): """ :说明: @@ -117,104 +122,27 @@ def USER(*user: int, perm: Permission = Permission()): :参数: - * ``*user: int``: 白名单 + * ``*user: str``: 白名单 * ``perm: Permission``: 需要同时满足的权限 """ - async def _user(bot: Bot, event: Event) -> bool: - return event.type == "message" and event.user_id in user and await perm( - bot, event) + async def _user(bot: "Bot", event: "Event") -> bool: + return event.get_type() == "message" and event.get_session_id( + ) in user and await perm(bot, event) return Permission(_user) -async def _private(bot: Bot, event: Event) -> bool: - return event.type == "message" and event.detail_type == "private" - - -async def _private_friend(bot: Bot, event: Event) -> bool: - return (event.type == "message" and event.detail_type == "private" and - event.sub_type == "friend") - - -async def _private_group(bot: Bot, event: Event) -> bool: - return (event.type == "message" and event.detail_type == "private" and - event.sub_type == "group") - - -async def _private_other(bot: Bot, event: Event) -> bool: - return (event.type == "message" and event.detail_type == "private" and - event.sub_type == "other") - - -PRIVATE = Permission(_private) -""" -- **说明**: 匹配任意私聊消息类型事件 -""" -PRIVATE_FRIEND = Permission(_private_friend) -""" -- **说明**: 匹配任意好友私聊消息类型事件 -""" -PRIVATE_GROUP = Permission(_private_group) -""" -- **说明**: 匹配任意群临时私聊消息类型事件 -""" -PRIVATE_OTHER = Permission(_private_other) -""" -- **说明**: 匹配任意其他私聊消息类型事件 -""" - - -async def _group(bot: Bot, event: Event) -> bool: - return event.type == "message" and event.detail_type == "group" - - -async def _group_member(bot: Bot, event: Event) -> bool: - return (event.type == "message" and event.detail_type == "group" and - event.sender.get("role") == "member") - - -async def _group_admin(bot: Bot, event: Event) -> bool: - return (event.type == "message" and event.detail_type == "group" and - event.sender.get("role") == "admin") - - -async def _group_owner(bot: Bot, event: Event) -> bool: - return (event.type == "message" and event.detail_type == "group" and - event.sender.get("role") == "owner") - - -GROUP = Permission(_group) -""" -- **说明**: 匹配任意群聊消息类型事件 -""" -GROUP_MEMBER = Permission(_group_member) -""" -- **说明**: 匹配任意群员群聊消息类型事件 - -\:\:\:warning 警告 -该权限通过 event.sender 进行判断且不包含管理员以及群主! -\:\:\: -""" -GROUP_ADMIN = Permission(_group_admin) -""" -- **说明**: 匹配任意群管理员群聊消息类型事件 -""" -GROUP_OWNER = Permission(_group_owner) -""" -- **说明**: 匹配任意群主群聊消息类型事件 -""" - - -async def _superuser(bot: Bot, event: Event) -> bool: - return event.type == "message" and event.user_id in bot.config.superusers +async def _superuser(bot: "Bot", event: "Event") -> bool: + return event.get_type() == "message" and event.get_user_id( + ) in bot.config.superusers SUPERUSER = Permission(_superuser) """ - **说明**: 匹配任意超级用户消息类型事件 """ -EVERYBODY = MESSAGE -""" -- **说明**: 匹配任意消息类型事件 -""" +# EVERYBODY = MESSAGE +# """ +# - **说明**: 匹配任意消息类型事件 +# """ diff --git a/nonebot/plugin.py b/nonebot/plugin.py index 57410566..de4073c9 100644 --- a/nonebot/plugin.py +++ b/nonebot/plugin.py @@ -9,17 +9,20 @@ import re import sys import pkgutil import importlib -from datetime import datetime +from types import ModuleType from dataclasses import dataclass from importlib._bootstrap import _load from contextvars import Context, ContextVar, copy_context +from typing import Any, Set, List, Dict, Type, Tuple, Union, Optional, TYPE_CHECKING from nonebot.log import logger from nonebot.matcher import Matcher from nonebot.permission import Permission -from nonebot.typing import Handler, RuleChecker +from nonebot.typing import T_State, T_StateFactory, T_Handler, T_RuleChecker from nonebot.rule import Rule, startswith, endswith, keyword, command, regex -from nonebot.typing import Any, Set, List, Dict, Type, Tuple, Union, Optional, ArgsParser, ModuleType + +if TYPE_CHECKING: + from nonebot.adapters import Bot, Event plugins: Dict[str, "Plugin"] = {} """ @@ -27,8 +30,8 @@ plugins: Dict[str, "Plugin"] = {} :说明: 已加载的插件 """ -_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ContextVar("_tmp_matchers") _export: ContextVar["Export"] = ContextVar("_export") +_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ContextVar("_tmp_matchers") class Export(dict): @@ -101,14 +104,15 @@ class Plugin(object): def on(type: str = "", - rule: Optional[Union[Rule, RuleChecker]] = None, + rule: Optional[Union[Rule, T_RuleChecker]] = None, permission: Optional[Permission] = None, *, - handlers: Optional[List[Handler]] = None, + handlers: Optional[List[T_Handler]] = None, temp: bool = False, priority: int = 1, block: bool = False, - state: Optional[dict] = None) -> Type[Matcher]: + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = None) -> Type[Matcher]: """ :说明: @@ -117,13 +121,14 @@ def on(type: str = "", :参数: * ``type: str``: 事件响应器类型 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -136,18 +141,21 @@ def on(type: str = "", priority=priority, block=block, handlers=handlers, - default_state=state) + default_state=state, + default_state_factory=state_factory) _tmp_matchers.get().add(matcher) return matcher -def on_metaevent(rule: Optional[Union[Rule, RuleChecker]] = None, - *, - handlers: Optional[List[Handler]] = None, - temp: bool = False, - priority: int = 1, - block: bool = False, - state: Optional[dict] = None) -> Type[Matcher]: +def on_metaevent( + rule: Optional[Union[Rule, T_RuleChecker]] = None, + *, + handlers: Optional[List[T_Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = False, + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = None) -> Type[Matcher]: """ :说明: @@ -155,12 +163,13 @@ def on_metaevent(rule: Optional[Union[Rule, RuleChecker]] = None, :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -173,19 +182,21 @@ def on_metaevent(rule: Optional[Union[Rule, RuleChecker]] = None, priority=priority, block=block, handlers=handlers, - default_state=state) + default_state=state, + default_state_factory=state_factory) _tmp_matchers.get().add(matcher) return matcher -def on_message(rule: Optional[Union[Rule, RuleChecker]] = None, +def on_message(rule: Optional[Union[Rule, T_RuleChecker]] = None, permission: Optional[Permission] = None, *, - handlers: Optional[List[Handler]] = None, + handlers: Optional[List[T_Handler]] = None, temp: bool = False, priority: int = 1, block: bool = True, - state: Optional[dict] = None) -> Type[Matcher]: + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = None) -> Type[Matcher]: """ :说明: @@ -193,13 +204,14 @@ def on_message(rule: Optional[Union[Rule, RuleChecker]] = None, :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -212,18 +224,20 @@ def on_message(rule: Optional[Union[Rule, RuleChecker]] = None, priority=priority, block=block, handlers=handlers, - default_state=state) + default_state=state, + default_state_factory=state_factory) _tmp_matchers.get().add(matcher) return matcher -def on_notice(rule: Optional[Union[Rule, RuleChecker]] = None, +def on_notice(rule: Optional[Union[Rule, T_RuleChecker]] = None, *, - handlers: Optional[List[Handler]] = None, + handlers: Optional[List[T_Handler]] = None, temp: bool = False, priority: int = 1, block: bool = False, - state: Optional[dict] = None) -> Type[Matcher]: + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = None) -> Type[Matcher]: """ :说明: @@ -231,12 +245,13 @@ def on_notice(rule: Optional[Union[Rule, RuleChecker]] = None, :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -249,18 +264,20 @@ def on_notice(rule: Optional[Union[Rule, RuleChecker]] = None, priority=priority, block=block, handlers=handlers, - default_state=state) + default_state=state, + default_state_factory=state_factory) _tmp_matchers.get().add(matcher) return matcher -def on_request(rule: Optional[Union[Rule, RuleChecker]] = None, +def on_request(rule: Optional[Union[Rule, T_RuleChecker]] = None, *, - handlers: Optional[List[Handler]] = None, + handlers: Optional[List[T_Handler]] = None, temp: bool = False, priority: int = 1, block: bool = False, - state: Optional[dict] = None) -> Type[Matcher]: + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = None) -> Type[Matcher]: """ :说明: @@ -268,12 +285,13 @@ def on_request(rule: Optional[Union[Rule, RuleChecker]] = None, :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -286,13 +304,14 @@ def on_request(rule: Optional[Union[Rule, RuleChecker]] = None, priority=priority, block=block, handlers=handlers, - default_state=state) + default_state=state, + default_state_factory=state_factory) _tmp_matchers.get().add(matcher) return matcher def on_startswith(msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = None, + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = None, **kwargs) -> Type[Matcher]: """ :说明: @@ -302,13 +321,14 @@ def on_startswith(msg: str, :参数: * ``msg: str``: 指定消息开头内容 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -318,7 +338,7 @@ def on_startswith(msg: str, def on_endswith(msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = None, + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = None, **kwargs) -> Type[Matcher]: """ :说明: @@ -328,13 +348,14 @@ def on_endswith(msg: str, :参数: * ``msg: str``: 指定消息结尾内容 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -344,7 +365,7 @@ def on_endswith(msg: str, def on_keyword(keywords: Set[str], - rule: Optional[Union[Rule, RuleChecker]] = None, + rule: Optional[Union[Rule, T_RuleChecker]] = None, **kwargs) -> Type[Matcher]: """ :说明: @@ -354,13 +375,14 @@ def on_keyword(keywords: Set[str], :参数: * ``keywords: Set[str]``: 关键词列表 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -370,7 +392,7 @@ def on_keyword(keywords: Set[str], def on_command(cmd: Union[str, Tuple[str, ...]], - rule: Optional[Union[Rule, RuleChecker]] = None, + rule: Optional[Union[Rule, T_RuleChecker]] = None, aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, **kwargs) -> Type[Matcher]: """ @@ -383,24 +405,29 @@ def on_command(cmd: Union[str, Tuple[str, ...]], :参数: * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: - ``Type[Matcher]`` """ - async def _strip_cmd(bot, event, state: dict): - message = event.message - event.message = message.__class__( - str(message)[len(state["_prefix"]["raw_command"]):].strip()) + async def _strip_cmd(bot: "Bot", event: "Event", state: T_State): + message = event.get_message() + segment = message.pop(0) + new_message = message.__class__( + str(segment) + [len(state["_prefix"]["raw_command"]):].strip()) # type: ignore + for new_segment in reversed(new_message): + message.insert(0, new_segment) handlers = kwargs.pop("handlers", []) handlers.insert(0, _strip_cmd) @@ -424,13 +451,14 @@ def on_regex(pattern: str, * ``pattern: str``: 正则表达式 * ``flags: Union[int, re.RegexFlag]``: 正则匹配标志 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -515,13 +543,14 @@ class MatcherGroup: :参数: * ``type: str``: 事件响应器类型 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -529,9 +558,8 @@ class MatcherGroup: """ final_kwargs = self.base_kwargs.copy() final_kwargs.update(kwargs) - matcher = Matcher.new(**final_kwargs) + matcher = on(**final_kwargs) self.matchers.append(matcher) - _tmp_matchers.get().add(matcher) return matcher def on_metaevent(self, **kwargs) -> Type[Matcher]: @@ -542,12 +570,13 @@ class MatcherGroup: :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -556,9 +585,8 @@ class MatcherGroup: final_kwargs = self.base_kwargs.copy() final_kwargs.update(kwargs) final_kwargs.pop("type", None) - matcher = Matcher.new("meta_event", **final_kwargs) + matcher = on_metaevent(**final_kwargs) self.matchers.append(matcher) - _tmp_matchers.get().add(matcher) return matcher def on_message(self, **kwargs) -> Type[Matcher]: @@ -569,13 +597,14 @@ class MatcherGroup: :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -584,9 +613,8 @@ class MatcherGroup: final_kwargs = self.base_kwargs.copy() final_kwargs.update(kwargs) final_kwargs.pop("type", None) - matcher = Matcher.new("message", **final_kwargs) + matcher = on_message(**final_kwargs) self.matchers.append(matcher) - _tmp_matchers.get().add(matcher) return matcher def on_notice(self, **kwargs) -> Type[Matcher]: @@ -597,12 +625,13 @@ class MatcherGroup: :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -611,9 +640,8 @@ class MatcherGroup: final_kwargs = self.base_kwargs.copy() final_kwargs.update(kwargs) final_kwargs.pop("type", None) - matcher = Matcher.new("notice", **final_kwargs) + matcher = on_notice(**final_kwargs) self.matchers.append(matcher) - _tmp_matchers.get().add(matcher) return matcher def on_request(self, **kwargs) -> Type[Matcher]: @@ -624,12 +652,13 @@ class MatcherGroup: :参数: - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -638,14 +667,14 @@ class MatcherGroup: final_kwargs = self.base_kwargs.copy() final_kwargs.update(kwargs) final_kwargs.pop("type", None) - matcher = Matcher.new("request", **final_kwargs) + matcher = on_request(**final_kwargs) self.matchers.append(matcher) - _tmp_matchers.get().add(matcher) return matcher def on_startswith(self, msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = None, + rule: Optional[Optional[Union[Rule, + T_RuleChecker]]] = None, **kwargs) -> Type[Matcher]: """ :说明: @@ -655,13 +684,14 @@ class MatcherGroup: :参数: * ``msg: str``: 指定消息开头内容 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -671,7 +701,7 @@ class MatcherGroup: def on_endswith(self, msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = None, + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = None, **kwargs) -> Type[Matcher]: """ :说明: @@ -681,13 +711,14 @@ class MatcherGroup: :参数: * ``msg: str``: 指定消息结尾内容 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -697,7 +728,7 @@ class MatcherGroup: def on_keyword(self, keywords: Set[str], - rule: Optional[Union[Rule, RuleChecker]] = None, + rule: Optional[Union[Rule, T_RuleChecker]] = None, **kwargs) -> Type[Matcher]: """ :说明: @@ -707,13 +738,14 @@ class MatcherGroup: :参数: * ``keywords: Set[str]``: 关键词列表 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -723,7 +755,7 @@ class MatcherGroup: def on_command(self, cmd: Union[str, Tuple[str, ...]], - rule: Optional[Union[Rule, RuleChecker]] = None, + rule: Optional[Union[Rule, T_RuleChecker]] = None, aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = None, **kwargs) -> Type[Matcher]: """ @@ -736,24 +768,29 @@ class MatcherGroup: :参数: * ``cmd: Union[str, Tuple[str, ...]]``: 指定命令内容 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``aliases: Optional[Set[Union[str, Tuple[str, ...]]]]``: 命令别名 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: - ``Type[Matcher]`` """ - async def _strip_cmd(bot, event, state: dict): - message = event.message - event.message = message.__class__( - str(message)[len(state["_prefix"]["raw_command"]):].strip()) + async def _strip_cmd(bot: "Bot", event: "Event", state: T_State): + message = event.get_message() + segment = message.pop(0) + new_message = message.__class__( + str(segment) + [len(state["_prefix"]["raw_command"]):].strip()) # type: ignore + for new_segment in reversed(new_message): + message.insert(0, new_segment) handlers = kwargs.pop("handlers", []) handlers.insert(0, _strip_cmd) @@ -779,13 +816,14 @@ class MatcherGroup: * ``pattern: str``: 正则表达式 * ``flags: Union[int, re.RegexFlag]``: 正则匹配标志 - * ``rule: Optional[Union[Rule, RuleChecker]]``: 事件响应规则 + * ``rule: Optional[Union[Rule, T_RuleChecker]]``: 事件响应规则 * ``permission: Optional[Permission]``: 事件响应权限 - * ``handlers: Optional[List[Handler]]``: 事件处理函数列表 + * ``handlers: Optional[List[T_Handler]]``: 事件处理函数列表 * ``temp: bool``: 是否为临时事件响应器(仅执行一次) * ``priority: int``: 事件响应器优先级 * ``block: bool``: 是否阻止事件向更低优先级传递 - * ``state: Optional[dict]``: 默认的 state + * ``state: Optional[T_State]``: 默认 state + * ``state_factory: Optional[T_StateFactory]``: 默认 state 的工厂函数 :返回: @@ -819,7 +857,7 @@ def load_plugin(module_path: str) -> Optional[Plugin]: logger.warning( f"Module {module_path} has been loaded by other plugins! Ignored" ) - return + return None module = importlib.import_module(module_path) for m in _tmp_matchers.get(): m.module = module_path @@ -859,15 +897,18 @@ def load_plugins(*plugin_dir: str) -> Set[Plugin]: _export.set(Export()) name = module_info.name if name.startswith("_"): - return + return None spec = module_info.module_finder.find_spec(name, None) - if spec.name in plugins: - return + if not spec: + logger.warning( + f"Module {name} cannot be loaded! Check module name first.") + elif spec.name in plugins: + return None elif spec.name in sys.modules: logger.warning( f"Module {spec.name} has been loaded by other plugin! Ignored") - return + return None try: module = _load(spec) @@ -962,5 +1003,5 @@ def require(name: str) -> Optional[Export]: - ``Optional[Export]`` """ - plugin = get_plugin(name) + plugin = get_plugin(name) or load_plugin(name) return plugin.export if plugin else None diff --git a/nonebot/plugin.pyi b/nonebot/plugin.pyi index 607c1d27..db31ad3d 100644 --- a/nonebot/plugin.pyi +++ b/nonebot/plugin.pyi @@ -1,13 +1,17 @@ import re +from types import ModuleType from contextvars import ContextVar +from typing import Any, Set, List, Dict, Type, Tuple, Union, Optional -from nonebot.typing import Rule, Matcher, Handler, Permission, RuleChecker -from nonebot.typing import Set, List, Dict, Type, Tuple, Union, Optional, ModuleType +from nonebot.rule import Rule +from nonebot.matcher import Matcher +from nonebot.permission import Permission +from nonebot.typing import T_State, T_StateFactory, T_Handler, T_RuleChecker plugins: Dict[str, "Plugin"] = ... -_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ... _export: ContextVar["Export"] = ... +_tmp_matchers: ContextVar[Set[Type[Matcher]]] = ... class Export(dict): @@ -30,104 +34,115 @@ class Plugin(object): def on(type: str = ..., - rule: Optional[Union[Rule, RuleChecker]] = ..., + rule: Optional[Union[Rule, T_RuleChecker]] = ..., permission: Optional[Permission] = ..., *, - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... -def on_metaevent(rule: Optional[Union[Rule, RuleChecker]] = ..., - *, - handlers: Optional[List[Handler]] = ..., - temp: bool = ..., - priority: int = ..., - block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: +def on_metaevent( + rule: Optional[Union[Rule, T_RuleChecker]] = ..., + *, + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... -def on_message(rule: Optional[Union[Rule, RuleChecker]] = ..., +def on_message(rule: Optional[Union[Rule, T_RuleChecker]] = ..., permission: Optional[Permission] = ..., *, - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... -def on_notice(rule: Optional[Union[Rule, RuleChecker]] = ..., +def on_notice(rule: Optional[Union[Rule, T_RuleChecker]] = ..., *, - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... -def on_request(rule: Optional[Union[Rule, RuleChecker]] = ..., +def on_request(rule: Optional[Union[Rule, T_RuleChecker]] = ..., *, - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... -def on_startswith(msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., - *, - permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., - temp: bool = ..., - priority: int = ..., - block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: +def on_startswith( + msg: str, + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ..., + *, + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... def on_endswith(msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ..., *, permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... def on_keyword(keywords: Set[str], - rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ..., *, permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... def on_command(cmd: Union[str, Tuple[str, ...]], - rule: Optional[Union[Rule, RuleChecker]] = ..., + rule: Optional[Union[Rule, T_RuleChecker]] = ..., aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., *, permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... @@ -136,11 +151,12 @@ def on_regex(pattern: str, rule: Optional[Rule] = ..., *, permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... @@ -176,27 +192,29 @@ class CommandGroup: def __init__(self, cmd: Union[str, Tuple[str, ...]], - rule: Optional[Union[Rule, RuleChecker]] = ..., + rule: Optional[Union[Rule, T_RuleChecker]] = ..., permission: Optional[Permission] = ..., *, - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...): - ... + state: Optional[T_State] = ...): + self.basecmd: Tuple[str, ...] = ... + self.base_kwargs: Dict[str, Any] = ... def command(self, cmd: Union[str, Tuple[str, ...]], *, - rule: Optional[Union[Rule, RuleChecker]] = ..., + rule: Optional[Union[Rule, T_RuleChecker]] = ..., aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... @@ -205,126 +223,145 @@ class MatcherGroup: def __init__(self, *, type: str = ..., - rule: Optional[Union[Rule, RuleChecker]] = ..., + rule: Optional[Union[Rule, T_RuleChecker]] = ..., permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...): + state: Optional[T_State] = ...): ... def on(self, *, type: str = ..., - rule: Optional[Union[Rule, RuleChecker]] = ..., + rule: Optional[Union[Rule, T_RuleChecker]] = ..., permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., + handlers: Optional[List[T_Handler]] = ..., temp: bool = ..., priority: int = ..., block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_metaevent(self, - *, - rule: Optional[Union[Rule, RuleChecker]] = None, - handlers: Optional[List[Handler]] = None, - temp: bool = False, - priority: int = 1, - block: bool = False, - state: Optional[dict] = None) -> Type[Matcher]: + def on_metaevent( + self, + *, + rule: Optional[Union[Rule, T_RuleChecker]] = None, + handlers: Optional[List[T_Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = False, + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_message(self, - *, - rule: Optional[Union[Rule, RuleChecker]] = None, - permission: Optional[Permission] = None, - handlers: Optional[List[Handler]] = None, - temp: bool = False, - priority: int = 1, - block: bool = True, - state: Optional[dict] = None) -> Type[Matcher]: + def on_message( + self, + *, + rule: Optional[Union[Rule, T_RuleChecker]] = None, + permission: Optional[Permission] = None, + handlers: Optional[List[T_Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = True, + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_notice(self, - *, - rule: Optional[Union[Rule, RuleChecker]] = None, - handlers: Optional[List[Handler]] = None, - temp: bool = False, - priority: int = 1, - block: bool = False, - state: Optional[dict] = None) -> Type[Matcher]: + def on_notice( + self, + *, + rule: Optional[Union[Rule, T_RuleChecker]] = None, + handlers: Optional[List[T_Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = False, + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_request(self, - *, - rule: Optional[Union[Rule, RuleChecker]] = None, - handlers: Optional[List[Handler]] = None, - temp: bool = False, - priority: int = 1, - block: bool = False, - state: Optional[dict] = None) -> Type[Matcher]: + def on_request( + self, + *, + rule: Optional[Union[Rule, T_RuleChecker]] = None, + handlers: Optional[List[T_Handler]] = None, + temp: bool = False, + priority: int = 1, + block: bool = False, + state: Optional[T_State] = None, + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_startswith(self, - *, - msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., - permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., - temp: bool = ..., - priority: int = ..., - block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + def on_startswith( + self, + *, + msg: str, + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_endswith(self, - *, - msg: str, - rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., - permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., - temp: bool = ..., - priority: int = ..., - block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + def on_endswith( + self, + *, + msg: str, + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_keyword(self, - *, - keywords: Set[str], - rule: Optional[Optional[Union[Rule, RuleChecker]]] = ..., - permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., - temp: bool = ..., - priority: int = ..., - block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + def on_keyword( + self, + *, + keywords: Set[str], + rule: Optional[Optional[Union[Rule, T_RuleChecker]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_command(self, - *, - cmd: Union[str, Tuple[str, ...]], - rule: Optional[Union[Rule, RuleChecker]] = ..., - aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., - permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., - temp: bool = ..., - priority: int = ..., - block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + def on_command( + self, + *, + cmd: Union[str, Tuple[str, ...]], + rule: Optional[Union[Rule, T_RuleChecker]] = ..., + aliases: Optional[Set[Union[str, Tuple[str, ...]]]] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... - def on_regex(self, - *, - pattern: str, - flags: Union[int, re.RegexFlag] = 0, - rule: Optional[Rule] = ..., - permission: Optional[Permission] = ..., - handlers: Optional[List[Handler]] = ..., - temp: bool = ..., - priority: int = ..., - block: bool = ..., - state: Optional[dict] = ...) -> Type[Matcher]: + def on_regex( + self, + *, + pattern: str, + flags: Union[int, re.RegexFlag] = 0, + rule: Optional[Rule] = ..., + permission: Optional[Permission] = ..., + handlers: Optional[List[T_Handler]] = ..., + temp: bool = ..., + priority: int = ..., + block: bool = ..., + state: Optional[T_State] = ..., + state_factory: Optional[T_StateFactory] = ...) -> Type[Matcher]: ... diff --git a/nonebot/plugins/base.py b/nonebot/plugins/base.py index c937f5c0..bf4e9619 100644 --- a/nonebot/plugins/base.py +++ b/nonebot/plugins/base.py @@ -3,21 +3,20 @@ from functools import reduce from nonebot.rule import to_me from nonebot.plugin import on_command from nonebot.permission import SUPERUSER -from nonebot.typing import Bot, Event, MessageSegment +from nonebot.adapters.cqhttp import Bot, unescape, MessageEvent, Message, MessageSegment say = on_command("say", to_me(), permission=SUPERUSER) @say.handle() -async def say_unescape(bot: Bot, event: Event, state: dict): - Message = event.message.__class__ +async def say_unescape(bot: Bot, event: MessageEvent): def _unescape(message: Message, segment: MessageSegment): - if segment.type == "text": - return message.append(str(segment)) + if segment.is_text(): + return message.append(unescape(str(segment))) return message.append(segment) - message = reduce(_unescape, event.message, Message()) # type: ignore + message = reduce(_unescape, event.get_message(), Message()) # type: ignore await bot.send(message=message, event=event) @@ -25,10 +24,5 @@ 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=event.message, event=event) +async def echo_escape(bot: Bot, event: MessageEvent): + await bot.send(message=event.get_message(), event=event) diff --git a/nonebot/rule.py b/nonebot/rule.py index c58d5874..d2b8f1fd 100644 --- a/nonebot/rule.py +++ b/nonebot/rule.py @@ -12,13 +12,17 @@ import re import asyncio from itertools import product +from typing import Any, Dict, Union, Tuple, Optional, Callable, NoReturn, Awaitable, TYPE_CHECKING from pygtrie import CharTrie from nonebot import get_driver from nonebot.log import logger from nonebot.utils import run_sync -from nonebot.typing import Bot, Any, Dict, Event, Union, Tuple, NoReturn, Optional, Callable, Awaitable, RuleChecker +from nonebot.typing import T_State, T_RuleChecker + +if TYPE_CHECKING: + from nonebot.adapters import Bot, Event class Rule: @@ -39,12 +43,12 @@ class Rule: __slots__ = ("checkers",) def __init__( - self, *checkers: Callable[[Bot, Event, dict], - Awaitable[bool]]) -> None: + self, *checkers: Callable[["Bot", "Event", T_State], + Awaitable[bool]]) -> None: """ :参数: - * ``*checkers: Callable[[Bot, Event, dict], Awaitable[bool]]``: **异步** RuleChecker + * ``*checkers: Callable[[Bot, Event, T_State], Awaitable[bool]]``: **异步** RuleChecker """ self.checkers = set(checkers) @@ -55,10 +59,11 @@ class Rule: :类型: - * ``Set[Callable[[Bot, Event, dict], Awaitable[bool]]]`` + * ``Set[Callable[[Bot, Event, T_State], Awaitable[bool]]]`` """ - async def __call__(self, bot: Bot, event: Event, state: dict) -> bool: + async def __call__(self, bot: "Bot", event: "Event", + state: T_State) -> bool: """ :说明: @@ -68,7 +73,7 @@ class Rule: * ``bot: Bot``: Bot 对象 * ``event: Event``: Event 对象 - * ``state: dict``: 当前 State + * ``state: T_State``: 当前 State :返回: @@ -78,7 +83,7 @@ class Rule: *map(lambda c: c(bot, event, state), self.checkers)) return all(results) - def __and__(self, other: Optional[Union["Rule", RuleChecker]]) -> "Rule": + def __and__(self, other: Optional[Union["Rule", T_RuleChecker]]) -> "Rule": checkers = self.checkers.copy() if other is None: return self @@ -113,9 +118,9 @@ class TrieRule: cls.suffix[suffix[::-1]] = value @classmethod - def get_value(cls, bot: Bot, event: Event, - state: dict) -> Tuple[Dict[str, Any], Dict[str, Any]]: - if event.type != "message": + def get_value(cls, bot: "Bot", event: "Event", + state: T_State) -> Tuple[Dict[str, Any], Dict[str, Any]]: + if event.get_type() != "message": state["_prefix"] = {"raw_command": None, "command": None} state["_suffix"] = {"raw_command": None, "command": None} return { @@ -128,12 +133,14 @@ class TrieRule: prefix = None suffix = None - message = event.message[0] - if message.type == "text": - prefix = cls.prefix.longest_prefix(str(message).lstrip()) - message_r = event.message[-1] - if message_r.type == "text": - suffix = cls.suffix.longest_prefix(str(message_r).rstrip()[::-1]) + message = event.get_message() + message_seg = message[0] + if message_seg.is_text(): + prefix = cls.prefix.longest_prefix(str(message_seg).lstrip()) + message_seg_r = message[-1] + if message_seg_r.is_text(): + suffix = cls.suffix.longest_prefix( + str(message_seg_r).rstrip()[::-1]) state["_prefix"] = { "raw_command": prefix.key, @@ -176,8 +183,11 @@ def startswith(msg: str) -> Rule: * ``msg: str``: 消息开头字符串 """ - async def _startswith(bot: Bot, event: Event, state: dict) -> bool: - return event.plain_text.startswith(msg) + async def _startswith(bot: "Bot", event: "Event", state: T_State) -> bool: + if event.get_type() != "message": + return False + text = event.get_plaintext() + return text.startswith(msg) return Rule(_startswith) @@ -193,8 +203,10 @@ def endswith(msg: str) -> Rule: * ``msg: str``: 消息结尾字符串 """ - async def _endswith(bot: Bot, event: Event, state: dict) -> bool: - return event.plain_text.endswith(msg) + async def _endswith(bot: "Bot", event: "Event", state: T_State) -> bool: + if event.get_type() != "message": + return False + return event.get_plaintext().endswith(msg) return Rule(_endswith) @@ -210,9 +222,11 @@ def keyword(*keywords: str) -> Rule: * ``*keywords: str``: 关键词 """ - async def _keyword(bot: Bot, event: Event, state: dict) -> bool: - return bool(event.plain_text and - any(keyword in event.plain_text for keyword in keywords)) + async def _keyword(bot: "Bot", event: "Event", state: T_State) -> bool: + if event.get_type() != "message": + return False + text = event.get_plaintext() + return bool(text and any(keyword in text for keyword in keywords)) return Rule(_keyword) @@ -256,7 +270,7 @@ def command(*cmds: Union[str, Tuple[str, ...]]) -> Rule: for start, sep in product(command_start, command_sep): TrieRule.add_prefix(f"{start}{sep.join(command)}", command) - async def _command(bot: Bot, event: Event, state: dict) -> bool: + async def _command(bot: "Bot", event: "Event", state: T_State) -> bool: return state["_prefix"]["command"] in commands return Rule(_command) @@ -282,8 +296,10 @@ def regex(regex: str, flags: Union[int, re.RegexFlag] = 0) -> Rule: pattern = re.compile(regex, flags) - async def _regex(bot: Bot, event: Event, state: dict) -> bool: - matched = pattern.search(str(event.message)) + async def _regex(bot: "Bot", event: "Event", state: T_State) -> bool: + if event.get_type() != "message": + return False + matched = pattern.search(str(event.get_message())) if matched: state["_matched"] = matched.group() return True @@ -298,14 +314,14 @@ def to_me() -> Rule: """ :说明: - 通过 ``event.to_me`` 判断消息是否是发送给机器人 + 通过 ``event.is_tome()`` 判断事件是否与机器人有关 :参数: * 无 """ - async def _to_me(bot: Bot, event: Event, state: dict) -> bool: - return bool(event.to_me) + async def _to_me(bot: "Bot", event: "Event", state: T_State) -> bool: + return event.is_tome() return Rule(_to_me) diff --git a/nonebot/typing.py b/nonebot/typing.py index 21a8b0ee..f92d1379 100644 --- a/nonebot/typing.py +++ b/nonebot/typing.py @@ -17,24 +17,19 @@ .. _typing: https://docs.python.org/3/library/typing.html """ +from collections.abc import Callable as BaseCallable +from typing import Any, Dict, Union, TypeVar, Optional, Callable, NoReturn, Awaitable, TYPE_CHECKING -from types import ModuleType -from typing import NoReturn, TYPE_CHECKING -from typing import Any, Set, List, Dict, Type, Tuple, Mapping -from typing import Union, TypeVar, Optional, Iterable, Callable, Awaitable, Generic - -# import some modules needed when checking types if TYPE_CHECKING: - from nonebot.rule import Rule as RuleClass - from nonebot.drivers import BaseDriver, BaseWebSocket - from nonebot.permission import Permission as PermissionClass - from nonebot.adapters import BaseBot, BaseEvent, BaseMessage, BaseMessageSegment - from nonebot.matcher import Matcher as MatcherClass, MatcherGroup as MatcherGroupClass + from nonebot.adapters import Bot, Event + from nonebot.matcher import Matcher + +T_Wrapped = TypeVar("T_Wrapped", bound=BaseCallable) def overrides(InterfaceClass: object): - def overrider(func: Callable) -> Callable: + def overrider(func: T_Wrapped) -> T_Wrapped: assert func.__name__ in dir( InterfaceClass), f"Error method: {func.__name__}" return func @@ -42,134 +37,85 @@ def overrides(InterfaceClass: object): return overrider -Driver = TypeVar("Driver", bound="BaseDriver") +T_State = Dict[Any, Any] """ -:类型: ``BaseDriver`` +:类型: ``Dict[Any, Any]`` :说明: - 所有 Driver 的基类。 + 事件处理状态 State 类型 """ -WebSocket = TypeVar("WebSocket", bound="BaseWebSocket") +T_StateFactory = Callable[["Bot", "Event"], Awaitable[T_State]] """ -:类型: ``BaseWebSocket`` +:类型: ``Callable[[Bot, Event], Awaitable[T_State]]`` :说明: - 所有 WebSocket 的基类。 + 事件处理状态 State 类工厂函数 """ -Bot = TypeVar("Bot", bound="BaseBot") +T_WebSocketConnectionHook = Callable[["Bot"], Awaitable[None]] """ -:类型: ``BaseBot`` +:类型: ``Callable[[Bot], Awaitable[None]]`` :说明: - 所有 Bot 的基类。 + WebSocket 连接建立时执行的函数 """ -Event = TypeVar("Event", bound="BaseEvent") +T_WebSocketDisconnectionHook = Callable[["Bot"], Awaitable[None]] """ -:类型: ``BaseEvent`` +:类型: ``Callable[[Bot], Awaitable[None]]`` :说明: - 所有 Event 的基类。 -""" -Message = TypeVar("Message", bound="BaseMessage") -""" -:类型: ``BaseMessage`` - -:说明: - - 所有 Message 的基类。 -""" -MessageSegment = TypeVar("MessageSegment", bound="BaseMessageSegment") -""" -:类型: ``BaseMessageSegment`` - -:说明: - - 所有 MessageSegment 的基类。 + WebSocket 连接断开时执行的函数 """ -EventPreProcessor = Callable[[Bot, Event, dict], Union[Awaitable[None], - Awaitable[NoReturn]]] +T_EventPreProcessor = Callable[["Bot", "Event", T_State], Awaitable[None]] """ -:类型: ``Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`` +:类型: ``Callable[[Bot, Event, T_State], Awaitable[None]]`` :说明: 事件预处理函数 EventPreProcessor 类型 """ -EventPostProcessor = Callable[[Bot, Event, dict], Union[Awaitable[None], - Awaitable[NoReturn]]] +T_EventPostProcessor = Callable[["Bot", "Event", T_State], Awaitable[None]] """ -:类型: ``Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`` +:类型: ``Callable[[Bot, Event, T_State], Awaitable[None]]`` :说明: 事件预处理函数 EventPostProcessor 类型 """ -RunPreProcessor = Callable[["Matcher", Bot, Event, dict], - Union[Awaitable[None], Awaitable[NoReturn]]] +T_RunPreProcessor = Callable[["Matcher", "Bot", "Event", T_State], + Awaitable[None]] """ -:类型: ``Callable[[Matcher, Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`` +:类型: ``Callable[[Matcher, Bot, Event, T_State], Awaitable[None]]`` :说明: 事件响应器运行前预处理函数 RunPreProcessor 类型 """ -RunPostProcessor = Callable[["Matcher", Optional[Exception], Bot, Event, dict], - Union[Awaitable[None], Awaitable[NoReturn]]] +T_RunPostProcessor = Callable[ + ["Matcher", Optional[Exception], "Bot", "Event", T_State], Awaitable[None]] """ -:类型: ``Callable[[Matcher, Optional[Exception], Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`` +:类型: ``Callable[[Matcher, Optional[Exception], Bot, Event, T_State], Awaitable[None]]`` :说明: 事件响应器运行前预处理函数 RunPostProcessor 类型,第二个参数为运行时产生的错误(如果存在) """ -Matcher = TypeVar("Matcher", bound="MatcherClass") +T_RuleChecker = Callable[["Bot", "Event", T_State], Union[bool, + Awaitable[bool]]] """ -:类型: ``Matcher`` - -:说明: - - Matcher 即响应事件的处理类。通过 Rule 判断是否响应事件,运行 Handler。 -""" -MatcherGroup = TypeVar("MatcherGroup", bound="MatcherGroupClass") -""" -:类型: ``MatcherGroup`` - -:说明: - - MatcherGroup 为 Matcher 的集合。可以共享 Handler。 -""" -Rule = TypeVar("Rule", bound="RuleClass") -""" -:类型: ``Rule`` - -:说明: - - Rule 即判断是否响应事件的处理类。内部存储 RuleChecker ,返回全为 True 则响应事件。 -""" -RuleChecker = Callable[[Bot, Event, dict], Union[bool, Awaitable[bool]]] -""" -:类型: ``Callable[[Bot, Event, dict], Union[bool, Awaitable[bool]]]`` +:类型: ``Callable[[Bot, Event, T_State], Union[bool, Awaitable[bool]]]`` :说明: RuleChecker 即判断是否响应事件的处理函数。 """ -Permission = TypeVar("Permission", bound="PermissionClass") -""" -:类型: ``Permission`` - -:说明: - - Permission 即判断是否响应消息的处理类。内部存储 PermissionChecker ,返回只要有一个 True 则响应消息。 -""" -PermissionChecker = Callable[[Bot, Event], Union[bool, Awaitable[bool]]] +T_PermissionChecker = Callable[["Bot", "Event"], Union[bool, Awaitable[bool]]] """ :类型: ``Callable[[Bot, Event], Union[bool, Awaitable[bool]]]`` @@ -177,19 +123,30 @@ PermissionChecker = Callable[[Bot, Event], Union[bool, Awaitable[bool]]] RuleChecker 即判断是否响应消息的处理函数。 """ -Handler = Callable[[Bot, Event, dict], Union[Awaitable[None], - Awaitable[NoReturn]]] + +T_Handler = Union[Callable[[Any, Any, Any, Any], Union[Awaitable[None], + Awaitable[NoReturn]]], + Callable[[Any, Any, Any], Union[Awaitable[None], + Awaitable[NoReturn]]], + Callable[[Any, Any], Union[Awaitable[None], + Awaitable[NoReturn]]], + Callable[[Any], Union[Awaitable[None], Awaitable[NoReturn]]]] """ -:类型: ``Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`` +:类型: + + * ``Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`` + * ``Callable[[Bot, Event], Union[Awaitable[None], Awaitable[NoReturn]]]`` + * ``Callable[[Bot, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`` + * ``Callable[[Bot], Union[Awaitable[None], Awaitable[NoReturn]]]`` :说明: Handler 即事件的处理函数。 """ -ArgsParser = Callable[[Bot, Event, dict], Union[Awaitable[None], - Awaitable[NoReturn]]] +T_ArgsParser = Callable[["Bot", "Event", T_State], Union[Awaitable[None], + Awaitable[NoReturn]]] """ -:类型: ``Callable[[Bot, Event, dict], Union[Awaitable[None], Awaitable[NoReturn]]]`` +:类型: ``Callable[[Bot, Event, T_State], Union[Awaitable[None], Awaitable[NoReturn]]]`` :说明: diff --git a/nonebot/utils.py b/nonebot/utils.py index 7ef93769..8253d3c7 100644 --- a/nonebot/utils.py +++ b/nonebot/utils.py @@ -3,9 +3,10 @@ import json import asyncio import dataclasses from functools import wraps, partial +from typing import Any, Optional, Callable, Awaitable from nonebot.log import logger -from nonebot.typing import Any, Optional, Callable, Awaitable, overrides +from nonebot.typing import overrides def escape_tag(s: str) -> str: diff --git a/pages/changelog.md b/pages/changelog.md index 2a766f70..68a29608 100644 --- a/pages/changelog.md +++ b/pages/changelog.md @@ -4,6 +4,17 @@ sidebar: auto # 更新日志 +## v2.0.0a8 + +- 修改 typing 类型注释 +- 修改 event 基类接口 +- 修复部分非法 CQ 码被识别导致报错 +- 修复非 text 类型 CQ 码 data 未进行去转义 +- 修复内置插件未进行去转义,修改内置插件为 cqhttp 定制 +- 修复 `load_plugins` 加载不合法的包时出现 `spec` 为 `None` 的问题 +- 出于**CQ 码安全性考虑**,使用 cqhttp 的 `bot.send` 或者 `matcher.send` 时默认对字符串进行转义 +- 移动 cqhttp 相关 `Permission` 至 `nonebot.adapters.cqhttp` 包内 + ## v2.0.0a7 - 修复 cqhttp 检查 to me 时出现 IndexError diff --git a/poetry.lock b/poetry.lock index 6ac05a37..dc0b527f 100644 --- a/poetry.lock +++ b/poetry.lock @@ -11,41 +11,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "arrow" -version = "0.17.0" -description = "Better dates & times for Python" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" - -[package.dependencies] -python-dateutil = ">=2.7.0" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "attrs" -version = "20.3.0" -description = "Classes Without Boilerplate" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" - -[package.extras] -dev = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "zope.interface", "furo", "sphinx", "pre-commit"] -docs = ["furo", "sphinx", "zope.interface"] -tests = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six", "zope.interface"] -tests_no_zope = ["coverage[toml] (>=5.0.2)", "hypothesis", "pympler", "pytest (>=4.3.0)", "six"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "babel" version = "2.9.0" @@ -62,59 +27,9 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "bcrypt" -version = "3.2.0" -description = "Modern password hashing for your software and your servers" -category = "dev" -optional = true -python-versions = ">=3.6" - -[package.dependencies] -cffi = ">=1.1" -six = ">=1.4.1" - -[package.extras] -tests = ["pytest (>=3.2.1,!=3.3.0)"] -typecheck = ["mypy"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "binaryornot" -version = "0.4.4" -description = "Ultra-lightweight pure Python package to check if a file is binary or text." -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -chardet = ">=3.0.2" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "cached-property" -version = "1.5.2" -description = "A decorator for caching properties in classes." -category = "dev" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "certifi" -version = "2020.11.8" +version = "2020.12.5" description = "Python package for providing Mozilla's CA Bundle." category = "main" optional = false @@ -125,29 +40,13 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "cffi" -version = "1.14.4" -description = "Foreign Function Interface for Python calling C code." -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -pycparser = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "chardet" -version = "3.0.4" +version = "4.0.0" description = "Universal encoding detector for Python 2 and 3" category = "dev" optional = false -python-versions = "*" +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" [package.source] type = "legacy" @@ -180,151 +79,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "cookiecutter" -version = "1.7.2" -description = "A command-line utility that creates projects from project templates, e.g. creating a Python package project from a Python package project template." -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" - -[package.dependencies] -binaryornot = ">=0.4.4" -click = ">=7.0" -Jinja2 = "<3.0.0" -jinja2-time = ">=0.2.0" -MarkupSafe = "<2.0.0" -poyo = ">=0.5.0" -python-slugify = ">=4.0.0" -requests = ">=2.23.0" -six = ">=1.10" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "cryptography" -version = "3.2.1" -description = "cryptography is a package which provides cryptographic recipes and primitives to Python developers." -category = "dev" -optional = true -python-versions = ">=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*" - -[package.dependencies] -cffi = ">=1.8,<1.11.3 || >1.11.3" -six = ">=1.4.1" - -[package.extras] -docs = ["sphinx (>=1.6.5,!=1.8.0,!=3.1.0,!=3.1.1)", "sphinx-rtd-theme"] -docstest = ["doc8", "pyenchant (>=1.6.11)", "twine (>=1.12.0)", "sphinxcontrib-spelling (>=4.0.1)"] -pep8test = ["black", "flake8", "flake8-import-order", "pep8-naming"] -ssh = ["bcrypt (>=3.1.5)"] -test = ["pytest (>=3.6.0,!=3.9.0,!=3.9.1,!=3.9.2)", "pretend", "iso8601", "pytz", "hypothesis (>=1.11.4,!=3.79.2)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "distro" -version = "1.5.0" -description = "Distro - an OS platform information API" -category = "dev" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "docker" -version = "4.4.0" -description = "A Python library for the Docker Engine API." -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" - -[package.dependencies] -paramiko = {version = ">=2.4.2", optional = true, markers = "extra == \"ssh\""} -pywin32 = {version = "227", markers = "sys_platform == \"win32\""} -requests = ">=2.14.2,<2.18.0 || >2.18.0" -six = ">=1.4.0" -websocket-client = ">=0.32.0" - -[package.extras] -ssh = ["paramiko (>=2.4.2)"] -tls = ["pyOpenSSL (>=17.5.0)", "cryptography (>=1.3.4)", "idna (>=2.0.0)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "docker-compose" -version = "1.27.4" -description = "Multi-container orchestration for Docker" -category = "dev" -optional = true -python-versions = ">=3.4" - -[package.dependencies] -cached-property = ">=1.2.0,<2" -colorama = {version = ">=0.4,<1", markers = "sys_platform == \"win32\""} -distro = ">=1.5.0,<2" -docker = {version = ">=4.3.1,<5", extras = ["ssh"]} -dockerpty = ">=0.4.1,<1" -docopt = ">=0.6.1,<1" -jsonschema = ">=2.5.1,<4" -python-dotenv = ">=0.13.0,<1" -PyYAML = ">=3.10,<6" -requests = ">=2.20.0,<3" -texttable = ">=0.9.0,<2" -websocket-client = ">=0.32.0,<1" - -[package.extras] -socks = ["PySocks (>=1.5.6,!=1.5.7,<2)"] -tests = ["ddt (>=1.2.2,<2)", "pytest (<6)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "dockerpty" -version = "0.4.1" -description = "Python library to use the pseudo-tty of a docker container" -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -six = ">=1.3.0" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "docopt" -version = "0.6.2" -description = "Pythonic argument parser, that will make you smile" -category = "dev" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "docutils" version = "0.16" @@ -340,21 +94,21 @@ reference = "aliyun" [[package]] name = "fastapi" -version = "0.58.1" +version = "0.63.0" description = "FastAPI framework, high performance, easy to learn, fast to code, ready for production" category = "main" optional = false python-versions = ">=3.6" [package.dependencies] -pydantic = ">=0.32.2,<2.0.0" -starlette = "0.13.4" +pydantic = ">=1.0.0,<2.0.0" +starlette = "0.13.6" [package.extras] -all = ["requests", "aiofiles", "jinja2", "python-multipart", "itsdangerous", "pyyaml", "graphene", "ujson", "orjson", "email-validator", "uvicorn", "async-exit-stack", "async-generator"] -dev = ["pyjwt", "passlib", "autoflake", "flake8", "uvicorn", "graphene"] -doc = ["mkdocs", "mkdocs-material", "markdown-include", "typer", "typer-cli", "pyyaml"] -test = ["pytest (==5.4.3)", "pytest-cov (==2.10.0)", "mypy", "black", "isort", "requests", "email-validator", "sqlalchemy", "peewee", "databases", "orjson", "async-exit-stack", "async-generator", "python-multipart", "aiofiles", "flask"] +all = ["requests (>=2.24.0,<3.0.0)", "aiofiles (>=0.5.0,<0.6.0)", "jinja2 (>=2.11.2,<3.0.0)", "python-multipart (>=0.0.5,<0.0.6)", "itsdangerous (>=1.1.0,<2.0.0)", "pyyaml (>=5.3.1,<6.0.0)", "graphene (>=2.1.8,<3.0.0)", "ujson (>=3.0.0,<4.0.0)", "orjson (>=3.2.1,<4.0.0)", "email_validator (>=1.1.1,<2.0.0)", "uvicorn[standard] (>=0.12.0,<0.14.0)", "async_exit_stack (>=1.0.1,<2.0.0)", "async_generator (>=1.10,<2.0.0)"] +dev = ["python-jose[cryptography] (>=3.1.0,<4.0.0)", "passlib[bcrypt] (>=1.7.2,<2.0.0)", "autoflake (>=1.3.1,<2.0.0)", "flake8 (>=3.8.3,<4.0.0)", "uvicorn[standard] (>=0.12.0,<0.14.0)", "graphene (>=2.1.8,<3.0.0)"] +doc = ["mkdocs (>=1.1.2,<2.0.0)", "mkdocs-material (>=6.1.4,<7.0.0)", "markdown-include (>=0.5.1,<0.6.0)", "mkdocs-markdownextradata-plugin (>=0.1.7,<0.2.0)", "typer-cli (>=0.0.9,<0.0.10)", "pyyaml (>=5.3.1,<6.0.0)"] +test = ["pytest (==5.4.3)", "pytest-cov (==2.10.0)", "pytest-asyncio (>=0.14.0,<0.15.0)", "mypy (==0.790)", "flake8 (>=3.8.3,<4.0.0)", "black (==20.8b1)", "isort (>=5.0.6,<6.0.0)", "requests (>=2.24.0,<3.0.0)", "httpx (>=0.14.0,<0.15.0)", "email_validator (>=1.1.1,<2.0.0)", "sqlalchemy (>=1.3.18,<2.0.0)", "peewee (>=3.13.3,<4.0.0)", "databases[sqlite] (>=0.3.2,<0.4.0)", "orjson (>=3.2.1,<4.0.0)", "async_exit_stack (>=1.0.1,<2.0.0)", "async_generator (>=1.10,<2.0.0)", "python-multipart (>=0.0.5,<0.0.6)", "aiofiles (>=0.5.0,<0.6.0)", "flask (>=1.1.2,<2.0.0)"] [package.source] type = "legacy" @@ -472,26 +226,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "importlib-metadata" -version = "3.1.1" -description = "Read metadata from Python packages" -category = "dev" -optional = true -python-versions = ">=3.6" - -[package.dependencies] -zipp = ">=0.5" - -[package.extras] -docs = ["sphinx", "jaraco.packaging (>=3.2)", "rst.linker (>=1.9)"] -testing = ["pytest (>=3.5,!=3.7.3)", "pytest-checkdocs (>=1.2.3)", "pytest-flake8", "pytest-cov", "jaraco.test (>=3.2.0)", "packaging", "pep517", "pyfakefs", "flufl.flake8", "pytest-black (>=0.3.7)", "pytest-mypy", "importlib-resources (>=1.3)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "jinja2" version = "2.11.2" @@ -511,46 +245,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "jinja2-time" -version = "0.2.0" -description = "Jinja2 Extension for Dates and Times" -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -arrow = "*" -jinja2 = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "jsonschema" -version = "3.2.0" -description = "An implementation of JSON Schema validation for Python" -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -attrs = ">=17.4.0" -importlib-metadata = {version = "*", markers = "python_version < \"3.8\""} -pyrsistent = ">=0.14.0" -six = ">=1.11.0" - -[package.extras] -format = ["idna", "jsonpointer (>1.13)", "rfc3987", "strict-rfc3339", "webcolors"] -format_nongpl = ["idna", "jsonpointer (>1.13)", "webcolors", "rfc3986-validator (>0.1.0)", "rfc3339-validator"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "loguru" version = "0.5.3" @@ -584,31 +278,9 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "nb-cli" -version = "0.2.0" -description = "CLI for nonebot2" -category = "dev" -optional = true -python-versions = ">=3.7,<4.0" - -[package.dependencies] -click = ">=7.1.2,<8.0.0" -colorama = ">=0.4.3,<0.5.0" -cookiecutter = ">=1.7.2,<2.0.0" -docker-compose = ">=1.27.2,<2.0.0" -nonebot2 = ">=2.0.0-alpha.4,<3.0.0" -pyfiglet = ">=0.8.post1,<0.9" -pyinquirer = "1.0.3" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "packaging" -version = "20.7" +version = "20.8" description = "Core utilities for Python packages" category = "dev" optional = false @@ -622,73 +294,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "paramiko" -version = "2.7.2" -description = "SSH2 protocol library" -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -bcrypt = ">=3.1.3" -cryptography = ">=2.5" -pynacl = ">=1.0.1" - -[package.extras] -all = ["pyasn1 (>=0.1.7)", "pynacl (>=1.0.1)", "bcrypt (>=3.1.3)", "invoke (>=1.3)", "gssapi (>=1.4.1)", "pywin32 (>=2.1.8)"] -ed25519 = ["pynacl (>=1.0.1)", "bcrypt (>=3.1.3)"] -gssapi = ["pyasn1 (>=0.1.7)", "gssapi (>=1.4.1)", "pywin32 (>=2.1.8)"] -invoke = ["invoke (>=1.3)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "poyo" -version = "0.5.0" -description = "A lightweight YAML Parser for Python. 🐓" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "prompt-toolkit" -version = "1.0.14" -description = "Library for building powerful interactive command lines in Python" -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -six = ">=1.9.0" -wcwidth = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "pycparser" -version = "2.20" -description = "C parser in Python" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pydantic" version = "1.7.3" @@ -699,6 +304,7 @@ python-versions = ">=3.6" [package.dependencies] python-dotenv = {version = ">=0.10.4", optional = true, markers = "extra == \"dotenv\""} +typing-extensions = {version = ">=3.7.2", optional = true, markers = "extra == \"typing_extensions\""} [package.extras] dotenv = ["python-dotenv (>=0.10.4)"] @@ -712,27 +318,14 @@ reference = "aliyun" [[package]] name = "pydash" -version = "4.9.0" +version = "4.9.2" description = "The kitchen sink of Python utility libraries for doing \"stuff\" in a functional way. Based on the Lo-Dash Javascript library." category = "dev" optional = false python-versions = "*" [package.extras] -dev = ["coverage", "flake8", "mock", "pylint", "pytest", "pytest-cov", "sphinx", "sphinx-rtd-theme", "tox", "twine", "wheel"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "pyfiglet" -version = "0.8.post1" -description = "Pure-python FIGlet implementation" -category = "dev" -optional = true -python-versions = "*" +dev = ["coverage", "docformatter", "flake8", "invoke", "mock", "pylint", "pytest", "pytest-cov", "pytest-flake8", "pytest-pylint", "sphinx", "sphinx-rtd-theme", "tox", "twine", "wheel", "black", "flake8-black", "flake8-bugbear", "flake8-isort", "isort"] [package.source] type = "legacy" @@ -741,7 +334,7 @@ reference = "aliyun" [[package]] name = "pygments" -version = "2.7.2" +version = "2.7.3" description = "Pygments is a syntax highlighting package written in Python." category = "dev" optional = false @@ -765,45 +358,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "pyinquirer" -version = "1.0.3" -description = "A Python module for collection of common interactive command line user interfaces, based on Inquirer.js" -category = "dev" -optional = true -python-versions = "*" - -[package.dependencies] -prompt_toolkit = "1.0.14" -Pygments = ">=2.2.0" -regex = ">=2016.11.21" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "pynacl" -version = "1.4.0" -description = "Python binding to the Networking and Cryptography (NaCl) library" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" - -[package.dependencies] -cffi = ">=1.4.1" -six = "*" - -[package.extras] -docs = ["sphinx (>=1.6.5)", "sphinx-rtd-theme"] -tests = ["pytest (>=3.2.1,!=3.3.0)", "hypothesis (>=3.27.0)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pyparsing" version = "2.4.7" @@ -817,35 +371,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "pyrsistent" -version = "0.17.3" -description = "Persistent/Functional/Immutable data structures" -category = "dev" -optional = true -python-versions = ">=3.5" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "python-dateutil" -version = "2.8.1" -description = "Extensions to the standard Python datetime module" -category = "dev" -optional = true -python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" - -[package.dependencies] -six = ">=1.5" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "python-dotenv" version = "0.15.0" @@ -862,28 +387,9 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "python-slugify" -version = "4.0.1" -description = "A Python Slugify application that handles Unicode" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" - -[package.dependencies] -text-unidecode = ">=1.3" - -[package.extras] -unidecode = ["Unidecode (>=1.1.1)"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "pytz" -version = "2020.4" +version = "2020.5" description = "World timezone definitions, modern and historical" category = "dev" optional = false @@ -894,48 +400,9 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "pywin32" -version = "227" -description = "Python for Window Extensions" -category = "dev" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "pyyaml" -version = "5.3.1" -description = "YAML parser and emitter for Python" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "regex" -version = "2020.11.13" -description = "Alternative regular expression module, to replace re." -category = "dev" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "requests" -version = "2.25.0" +version = "2.25.1" description = "Python HTTP for Humans." category = "dev" optional = false @@ -943,7 +410,7 @@ python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" [package.dependencies] certifi = ">=2017.4.17" -chardet = ">=3.0.2,<4" +chardet = ">=3.0.2,<5" idna = ">=2.5,<3" urllib3 = ">=1.21.1,<1.27" @@ -975,19 +442,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "six" -version = "1.15.0" -description = "Python 2 and 3 compatibility utilities" -category = "dev" -optional = true -python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "sniffio" version = "1.2.0" @@ -1016,7 +470,7 @@ reference = "aliyun" [[package]] name = "sphinx" -version = "3.3.1" +version = "3.4.1" description = "Python documentation generator" category = "dev" optional = false @@ -1042,8 +496,8 @@ sphinxcontrib-serializinghtml = "*" [package.extras] docs = ["sphinxcontrib-websupport"] -lint = ["flake8 (>=3.5.0)", "flake8-import-order", "mypy (>=0.790)", "docutils-stubs"] -test = ["pytest", "pytest-cov", "html5lib", "typed-ast", "cython"] +lint = ["flake8 (>=3.5.0)", "isort", "mypy (>=0.790)", "docutils-stubs"] +test = ["pytest", "pytest-cov", "html5lib", "cython", "typed-ast"] [package.source] type = "legacy" @@ -1175,7 +629,7 @@ reference = "aliyun" [[package]] name = "starlette" -version = "0.13.4" +version = "0.13.6" description = "The little ASGI library that shines." category = "main" optional = false @@ -1190,24 +644,11 @@ url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" [[package]] -name = "text-unidecode" -version = "1.3" -description = "The most basic Text::Unidecode port" -category = "dev" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "texttable" -version = "1.6.3" -description = "module for creating simple ASCII tables" -category = "dev" -optional = true +name = "typing-extensions" +version = "3.7.4.3" +description = "Backported and Experimental Type Hints for Python 3.5+" +category = "main" +optional = false python-versions = "*" [package.source] @@ -1298,35 +739,6 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "wcwidth" -version = "0.2.5" -description = "Measures the displayed width of unicode strings in a terminal" -category = "dev" -optional = true -python-versions = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - -[[package]] -name = "websocket-client" -version = "0.57.0" -description = "WebSocket client for Python. hybi13 is supported." -category = "dev" -optional = true -python-versions = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*" - -[package.dependencies] -six = "*" - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [[package]] name = "websockets" version = "8.1" @@ -1369,105 +781,27 @@ type = "legacy" url = "https://mirrors.aliyun.com/pypi/simple" reference = "aliyun" -[[package]] -name = "zipp" -version = "3.4.0" -description = "Backport of pathlib-compatible object wrapper for zip files" -category = "dev" -optional = true -python-versions = ">=3.6" - -[package.extras] -docs = ["sphinx", "jaraco.packaging (>=3.2)", "rst.linker (>=1.9)"] -testing = ["pytest (>=3.5,!=3.7.3)", "pytest-checkdocs (>=1.2.3)", "pytest-flake8", "pytest-cov", "jaraco.test (>=3.2.0)", "jaraco.itertools", "func-timeout", "pytest-black (>=0.3.7)", "pytest-mypy"] - -[package.source] -type = "legacy" -url = "https://mirrors.aliyun.com/pypi/simple" -reference = "aliyun" - [metadata] lock-version = "1.1" python-versions = "^3.7" -content-hash = "3dfc8b11cbc775c2dca5409212248615b259863864d8a9db247377e273a5eddd" +content-hash = "55439e671ff8c89285f2cf645189c1bf3e3bd53638bbb31ed505727a041d1012" [metadata.files] alabaster = [ {file = "alabaster-0.7.12-py2.py3-none-any.whl", hash = "sha256:446438bdcca0e05bd45ea2de1668c1d9b032e1a9154c2c259092d77031ddd359"}, {file = "alabaster-0.7.12.tar.gz", hash = "sha256:a661d72d58e6ea8a57f7a86e37d86716863ee5e92788398526d58b26a4e4dc02"}, ] -arrow = [ - {file = "arrow-0.17.0-py2.py3-none-any.whl", hash = "sha256:e098abbd9af3665aea81bdd6c869e93af4feb078e98468dd351c383af187aac5"}, - {file = "arrow-0.17.0.tar.gz", hash = "sha256:ff08d10cda1d36c68657d6ad20d74fbea493d980f8b2d45344e00d6ed2bf6ed4"}, -] -attrs = [ - {file = "attrs-20.3.0-py2.py3-none-any.whl", hash = "sha256:31b2eced602aa8423c2aea9c76a724617ed67cf9513173fd3a4f03e3a929c7e6"}, - {file = "attrs-20.3.0.tar.gz", hash = "sha256:832aa3cde19744e49938b91fea06d69ecb9e649c93ba974535d08ad92164f700"}, -] babel = [ {file = "Babel-2.9.0-py2.py3-none-any.whl", hash = "sha256:9d35c22fcc79893c3ecc85ac4a56cde1ecf3f19c540bba0922308a6c06ca6fa5"}, {file = "Babel-2.9.0.tar.gz", hash = "sha256:da031ab54472314f210b0adcff1588ee5d1d1d0ba4dbd07b94dba82bde791e05"}, ] -bcrypt = [ - {file = "bcrypt-3.2.0-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:c95d4cbebffafcdd28bd28bb4e25b31c50f6da605c81ffd9ad8a3d1b2ab7b1b6"}, - {file = "bcrypt-3.2.0-cp36-abi3-manylinux1_x86_64.whl", hash = "sha256:63d4e3ff96188e5898779b6057878fecf3f11cfe6ec3b313ea09955d587ec7a7"}, - {file = "bcrypt-3.2.0-cp36-abi3-manylinux2010_x86_64.whl", hash = "sha256:cd1ea2ff3038509ea95f687256c46b79f5fc382ad0aa3664d200047546d511d1"}, - {file = "bcrypt-3.2.0-cp36-abi3-manylinux2014_aarch64.whl", hash = "sha256:cdcdcb3972027f83fe24a48b1e90ea4b584d35f1cc279d76de6fc4b13376239d"}, - {file = "bcrypt-3.2.0-cp36-abi3-win32.whl", hash = "sha256:a67fb841b35c28a59cebed05fbd3e80eea26e6d75851f0574a9273c80f3e9b55"}, - {file = "bcrypt-3.2.0-cp36-abi3-win_amd64.whl", hash = "sha256:81fec756feff5b6818ea7ab031205e1d323d8943d237303baca2c5f9c7846f34"}, - {file = "bcrypt-3.2.0.tar.gz", hash = "sha256:5b93c1726e50a93a033c36e5ca7fdcd29a5c7395af50a6892f5d9e7c6cfbfb29"}, -] -binaryornot = [ - {file = "binaryornot-0.4.4-py2.py3-none-any.whl", hash = "md5:7a69d00f3c384693c9616c3381c411a3"}, - {file = "binaryornot-0.4.4.tar.gz", hash = "md5:09c0b7f5f3f7c881e2f306780eac7128"}, -] -cached-property = [ - {file = "cached-property-1.5.2.tar.gz", hash = "sha256:9fa5755838eecbb2d234c3aa390bd80fbd3ac6b6869109bfc1b499f7bd89a130"}, - {file = "cached_property-1.5.2-py2.py3-none-any.whl", hash = "sha256:df4f613cf7ad9a588cc381aaf4a512d26265ecebd5eb9e1ba12f1319eb85a6a0"}, -] certifi = [ - {file = "certifi-2020.11.8-py2.py3-none-any.whl", hash = "sha256:1f422849db327d534e3d0c5f02a263458c3955ec0aae4ff09b95f195c59f4edd"}, - {file = "certifi-2020.11.8.tar.gz", hash = "sha256:f05def092c44fbf25834a51509ef6e631dc19765ab8a57b4e7ab85531f0a9cf4"}, -] -cffi = [ - {file = "cffi-1.14.4-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:ebb253464a5d0482b191274f1c8bf00e33f7e0b9c66405fbffc61ed2c839c775"}, - {file = "cffi-1.14.4-cp27-cp27m-manylinux1_i686.whl", hash = "sha256:2c24d61263f511551f740d1a065eb0212db1dbbbbd241db758f5244281590c06"}, - {file = "cffi-1.14.4-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:9f7a31251289b2ab6d4012f6e83e58bc3b96bd151f5b5262467f4bb6b34a7c26"}, - {file = "cffi-1.14.4-cp27-cp27m-win32.whl", hash = "sha256:5cf4be6c304ad0b6602f5c4e90e2f59b47653ac1ed9c662ed379fe48a8f26b0c"}, - {file = "cffi-1.14.4-cp27-cp27m-win_amd64.whl", hash = "sha256:f60567825f791c6f8a592f3c6e3bd93dd2934e3f9dac189308426bd76b00ef3b"}, - {file = "cffi-1.14.4-cp27-cp27mu-manylinux1_i686.whl", hash = "sha256:c6332685306b6417a91b1ff9fae889b3ba65c2292d64bd9245c093b1b284809d"}, - {file = "cffi-1.14.4-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:d9efd8b7a3ef378dd61a1e77367f1924375befc2eba06168b6ebfa903a5e59ca"}, - {file = "cffi-1.14.4-cp35-cp35m-macosx_10_9_x86_64.whl", hash = "sha256:51a8b381b16ddd370178a65360ebe15fbc1c71cf6f584613a7ea08bfad946698"}, - {file = "cffi-1.14.4-cp35-cp35m-manylinux1_i686.whl", hash = "sha256:1d2c4994f515e5b485fd6d3a73d05526aa0fcf248eb135996b088d25dfa1865b"}, - {file = "cffi-1.14.4-cp35-cp35m-manylinux1_x86_64.whl", hash = "sha256:af5c59122a011049aad5dd87424b8e65a80e4a6477419c0c1015f73fb5ea0293"}, - {file = "cffi-1.14.4-cp35-cp35m-win32.whl", hash = "sha256:594234691ac0e9b770aee9fcdb8fa02c22e43e5c619456efd0d6c2bf276f3eb2"}, - {file = "cffi-1.14.4-cp35-cp35m-win_amd64.whl", hash = "sha256:64081b3f8f6f3c3de6191ec89d7dc6c86a8a43911f7ecb422c60e90c70be41c7"}, - {file = "cffi-1.14.4-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:f803eaa94c2fcda012c047e62bc7a51b0bdabda1cad7a92a522694ea2d76e49f"}, - {file = "cffi-1.14.4-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:105abaf8a6075dc96c1fe5ae7aae073f4696f2905fde6aeada4c9d2926752362"}, - {file = "cffi-1.14.4-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:0638c3ae1a0edfb77c6765d487fee624d2b1ee1bdfeffc1f0b58c64d149e7eec"}, - {file = "cffi-1.14.4-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:7c6b1dece89874d9541fc974917b631406233ea0440d0bdfbb8e03bf39a49b3b"}, - {file = "cffi-1.14.4-cp36-cp36m-win32.whl", hash = "sha256:155136b51fd733fa94e1c2ea5211dcd4c8879869008fc811648f16541bf99668"}, - {file = "cffi-1.14.4-cp36-cp36m-win_amd64.whl", hash = "sha256:6bc25fc545a6b3d57b5f8618e59fc13d3a3a68431e8ca5fd4c13241cd70d0009"}, - {file = "cffi-1.14.4-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a7711edca4dcef1a75257b50a2fbfe92a65187c47dab5a0f1b9b332c5919a3fb"}, - {file = "cffi-1.14.4-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:00e28066507bfc3fe865a31f325c8391a1ac2916219340f87dfad602c3e48e5d"}, - {file = "cffi-1.14.4-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:798caa2a2384b1cbe8a2a139d80734c9db54f9cc155c99d7cc92441a23871c03"}, - {file = "cffi-1.14.4-cp37-cp37m-win32.whl", hash = "sha256:00a1ba5e2e95684448de9b89888ccd02c98d512064b4cb987d48f4b40aa0421e"}, - {file = "cffi-1.14.4-cp37-cp37m-win_amd64.whl", hash = "sha256:9cc46bc107224ff5b6d04369e7c595acb700c3613ad7bcf2e2012f62ece80c35"}, - {file = "cffi-1.14.4-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:df5169c4396adc04f9b0a05f13c074df878b6052430e03f50e68adf3a57aa28d"}, - {file = "cffi-1.14.4-cp38-cp38-manylinux1_i686.whl", hash = "sha256:9ffb888f19d54a4d4dfd4b3f29bc2c16aa4972f1c2ab9c4ab09b8ab8685b9c2b"}, - {file = "cffi-1.14.4-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:8d6603078baf4e11edc4168a514c5ce5b3ba6e3e9c374298cb88437957960a53"}, - {file = "cffi-1.14.4-cp38-cp38-win32.whl", hash = "sha256:b4e248d1087abf9f4c10f3c398896c87ce82a9856494a7155823eb45a892395d"}, - {file = "cffi-1.14.4-cp38-cp38-win_amd64.whl", hash = "sha256:ec80dc47f54e6e9a78181ce05feb71a0353854cc26999db963695f950b5fb375"}, - {file = "cffi-1.14.4-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:840793c68105fe031f34d6a086eaea153a0cd5c491cde82a74b420edd0a2b909"}, - {file = "cffi-1.14.4-cp39-cp39-manylinux1_i686.whl", hash = "sha256:b18e0a9ef57d2b41f5c68beefa32317d286c3d6ac0484efd10d6e07491bb95dd"}, - {file = "cffi-1.14.4-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:045d792900a75e8b1e1b0ab6787dd733a8190ffcf80e8c8ceb2fb10a29ff238a"}, - {file = "cffi-1.14.4-cp39-cp39-win32.whl", hash = "sha256:ba4e9e0ae13fc41c6b23299545e5ef73055213e466bd107953e4a013a5ddd7e3"}, - {file = "cffi-1.14.4-cp39-cp39-win_amd64.whl", hash = "sha256:f032b34669220030f905152045dfa27741ce1a6db3324a5bc0b96b6c7420c87b"}, - {file = "cffi-1.14.4.tar.gz", hash = "sha256:1a465cbe98a7fd391d47dce4b8f7e5b921e6cd805ef421d04f5f66ba8f06086c"}, + {file = "certifi-2020.12.5-py2.py3-none-any.whl", hash = "sha256:719a74fb9e33b9bd44cc7f3a8d94bc35e4049deebe19ba7d8e108280cfd59830"}, + {file = "certifi-2020.12.5.tar.gz", hash = "sha256:1a4995114262bffbc2413b159f2a1a480c969de6e6eb13ee966d470af86af59c"}, ] chardet = [ - {file = "chardet-3.0.4-py2.py3-none-any.whl", hash = "md5:0004b00caff7bb543a1d0d0bd0185a03"}, - {file = "chardet-3.0.4.tar.gz", hash = "md5:7dd1ba7f9c77e32351b0a0cfacf4055c"}, + {file = "chardet-4.0.0-py2.py3-none-any.whl", hash = "sha256:f864054d66fd9118f2e67044ac8981a54775ec5b67aed0441892edb553d21da5"}, + {file = "chardet-4.0.0.tar.gz", hash = "sha256:0d6f53a15db4120f2b08c94f11e7d93d2c911ee118b6b30a04ec3ee8310179fa"}, ] click = [ {file = "click-7.1.2-py2.py3-none-any.whl", hash = "sha256:dacca89f4bfadd5de3d7489b7c8a566eee0d3676333fbb50030263894c38c0dc"}, @@ -1477,59 +811,13 @@ colorama = [ {file = "colorama-0.4.4-py2.py3-none-any.whl", hash = "sha256:9f47eda37229f68eee03b24b9748937c7dc3868f906e8ba69fbcbdd3bc5dc3e2"}, {file = "colorama-0.4.4.tar.gz", hash = "sha256:5941b2b48a20143d2267e95b1c2a7603ce057ee39fd88e7329b0c292aa16869b"}, ] -cookiecutter = [ - {file = "cookiecutter-1.7.2-py2.py3-none-any.whl", hash = "sha256:430eb882d028afb6102c084bab6cf41f6559a77ce9b18dc6802e3bc0cc5f4a30"}, - {file = "cookiecutter-1.7.2.tar.gz", hash = "sha256:efb6b2d4780feda8908a873e38f0e61778c23f6a2ea58215723bcceb5b515dac"}, -] -cryptography = [ - {file = "cryptography-3.2.1-cp27-cp27m-macosx_10_10_x86_64.whl", hash = "sha256:6dc59630ecce8c1f558277ceb212c751d6730bd12c80ea96b4ac65637c4f55e7"}, - {file = "cryptography-3.2.1-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:75e8e6684cf0034f6bf2a97095cb95f81537b12b36a8fedf06e73050bb171c2d"}, - {file = "cryptography-3.2.1-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:4e7268a0ca14536fecfdf2b00297d4e407da904718658c1ff1961c713f90fd33"}, - {file = "cryptography-3.2.1-cp27-cp27m-win32.whl", hash = "sha256:7117319b44ed1842c617d0a452383a5a052ec6aa726dfbaffa8b94c910444297"}, - {file = "cryptography-3.2.1-cp27-cp27m-win_amd64.whl", hash = "sha256:a733671100cd26d816eed39507e585c156e4498293a907029969234e5e634bc4"}, - {file = "cryptography-3.2.1-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:a75f306a16d9f9afebfbedc41c8c2351d8e61e818ba6b4c40815e2b5740bb6b8"}, - {file = "cryptography-3.2.1-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:5849d59358547bf789ee7e0d7a9036b2d29e9a4ddf1ce5e06bb45634f995c53e"}, - {file = "cryptography-3.2.1-cp35-abi3-macosx_10_10_x86_64.whl", hash = "sha256:bd717aa029217b8ef94a7d21632a3bb5a4e7218a4513d2521c2a2fd63011e98b"}, - {file = "cryptography-3.2.1-cp35-abi3-manylinux1_x86_64.whl", hash = "sha256:efe15aca4f64f3a7ea0c09c87826490e50ed166ce67368a68f315ea0807a20df"}, - {file = "cryptography-3.2.1-cp35-abi3-manylinux2010_x86_64.whl", hash = "sha256:32434673d8505b42c0de4de86da8c1620651abd24afe91ae0335597683ed1b77"}, - {file = "cryptography-3.2.1-cp35-abi3-manylinux2014_aarch64.whl", hash = "sha256:7b8d9d8d3a9bd240f453342981f765346c87ade811519f98664519696f8e6ab7"}, - {file = "cryptography-3.2.1-cp35-cp35m-win32.whl", hash = "sha256:d3545829ab42a66b84a9aaabf216a4dce7f16dbc76eb69be5c302ed6b8f4a29b"}, - {file = "cryptography-3.2.1-cp35-cp35m-win_amd64.whl", hash = "sha256:a4e27ed0b2504195f855b52052eadcc9795c59909c9d84314c5408687f933fc7"}, - {file = "cryptography-3.2.1-cp36-abi3-win32.whl", hash = "sha256:13b88a0bd044b4eae1ef40e265d006e34dbcde0c2f1e15eb9896501b2d8f6c6f"}, - {file = "cryptography-3.2.1-cp36-abi3-win_amd64.whl", hash = "sha256:07ca431b788249af92764e3be9a488aa1d39a0bc3be313d826bbec690417e538"}, - {file = "cryptography-3.2.1-cp36-cp36m-win32.whl", hash = "sha256:a035a10686532b0587d58a606004aa20ad895c60c4d029afa245802347fab57b"}, - {file = "cryptography-3.2.1-cp36-cp36m-win_amd64.whl", hash = "sha256:d26a2557d8f9122f9bf445fc7034242f4375bd4e95ecda007667540270965b13"}, - {file = "cryptography-3.2.1-cp37-cp37m-win32.whl", hash = "sha256:545a8550782dda68f8cdc75a6e3bf252017aa8f75f19f5a9ca940772fc0cb56e"}, - {file = "cryptography-3.2.1-cp37-cp37m-win_amd64.whl", hash = "sha256:55d0b896631412b6f0c7de56e12eb3e261ac347fbaa5d5e705291a9016e5f8cb"}, - {file = "cryptography-3.2.1-cp38-cp38-win32.whl", hash = "sha256:3cd75a683b15576cfc822c7c5742b3276e50b21a06672dc3a800a2d5da4ecd1b"}, - {file = "cryptography-3.2.1-cp38-cp38-win_amd64.whl", hash = "sha256:d25cecbac20713a7c3bc544372d42d8eafa89799f492a43b79e1dfd650484851"}, - {file = "cryptography-3.2.1.tar.gz", hash = "sha256:d3d5e10be0cf2a12214ddee45c6bd203dab435e3d83b4560c03066eda600bfe3"}, -] -distro = [ - {file = "distro-1.5.0-py2.py3-none-any.whl", hash = "sha256:df74eed763e18d10d0da624258524ae80486432cd17392d9c3d96f5e83cd2799"}, - {file = "distro-1.5.0.tar.gz", hash = "sha256:0e58756ae38fbd8fc3020d54badb8eae17c5b9dcbed388b17bb55b8a5928df92"}, -] -docker = [ - {file = "docker-4.4.0-py2.py3-none-any.whl", hash = "sha256:317e95a48c32de8c1aac92a48066a5b73e218ed096e03758bcdd799a7130a1a1"}, - {file = "docker-4.4.0.tar.gz", hash = "sha256:cffc771d4ea1389fc66bc95cb72d304aa41d1a1563482a9a000fba3a84ed5071"}, -] -docker-compose = [ - {file = "docker-compose-1.27.4.tar.gz", hash = "sha256:5a5690f24c27d4b43dcbe6b3fae91ba680713208e99ee863352b3bae37bcaa83"}, - {file = "docker_compose-1.27.4-py2.py3-none-any.whl", hash = "sha256:84ca2edad226435e3a378ea24ca2ca4e1a77cc7c8de057e2812124c6dcb55147"}, -] -dockerpty = [ - {file = "dockerpty-0.4.1.tar.gz", hash = "md5:028bacb34536f3ee6a2ccd668c27e8e4"}, -] -docopt = [ - {file = "docopt-0.6.2.tar.gz", hash = "md5:4bc74561b37fad5d3e7d037f82a4c3b1"}, -] docutils = [ {file = "docutils-0.16-py2.py3-none-any.whl", hash = "sha256:0c5b78adfbf7762415433f5515cd5c9e762339e23369dbe8000d84a4bf4ab3af"}, {file = "docutils-0.16.tar.gz", hash = "sha256:c2de3a60e9e7d07be26b7f2b00ca0309c207e06c100f9cc2a94931fc75a478fc"}, ] fastapi = [ - {file = "fastapi-0.58.1-py3-none-any.whl", hash = "sha256:d7499761d5ca901cdf5b6b73018d14729593f8ab1ea22d241f82fa574fc406ad"}, - {file = "fastapi-0.58.1.tar.gz", hash = "sha256:92e59b77eef7d6eaa80b16d275adda06b5f33b12d777e3fc5521b2f7f4718e13"}, + {file = "fastapi-0.63.0-py3-none-any.whl", hash = "sha256:98d8ea9591d8512fdadf255d2a8fa56515cdd8624dca4af369da73727409508e"}, + {file = "fastapi-0.63.0.tar.gz", hash = "sha256:63c4592f5ef3edf30afa9a44fa7c6b7ccb20e0d3f68cd9eba07b44d552058dcb"}, ] h11 = [ {file = "h11-0.9.0-py2.py3-none-any.whl", hash = "sha256:4bc6d6a1238b7615b266ada57e0618568066f57dd6fa967d1290ec9309b2f2f1"}, @@ -1569,22 +857,10 @@ imagesize = [ {file = "imagesize-1.2.0-py2.py3-none-any.whl", hash = "sha256:6965f19a6a2039c7d48bca7dba2473069ff854c36ae6f19d2cde309d998228a1"}, {file = "imagesize-1.2.0.tar.gz", hash = "sha256:b1f6b5a4eab1f73479a50fb79fcf729514a900c341d8503d62a62dbc4127a2b1"}, ] -importlib-metadata = [ - {file = "importlib_metadata-3.1.1-py3-none-any.whl", hash = "sha256:6112e21359ef8f344e7178aa5b72dc6e62b38b0d008e6d3cb212c5b84df72013"}, - {file = "importlib_metadata-3.1.1.tar.gz", hash = "sha256:b0c2d3b226157ae4517d9625decf63591461c66b3a808c2666d538946519d170"}, -] jinja2 = [ {file = "Jinja2-2.11.2-py2.py3-none-any.whl", hash = "sha256:f0a4641d3cf955324a89c04f3d94663aa4d638abe8f733ecd3582848e1c37035"}, {file = "Jinja2-2.11.2.tar.gz", hash = "sha256:89aab215427ef59c34ad58735269eb58b1a5808103067f7bb9d5836c651b3bb0"}, ] -jinja2-time = [ - {file = "jinja2-time-0.2.0.tar.gz", hash = "md5:b6ebc4ecac395a18982532f4c2869c06"}, - {file = "jinja2_time-0.2.0-py2.py3-none-any.whl", hash = "md5:d0d553ae5c3e9e7abb79c044acd165c8"}, -] -jsonschema = [ - {file = "jsonschema-3.2.0-py2.py3-none-any.whl", hash = "sha256:4e5b3cf8216f577bee9ce139cbe72eca3ea4f292ec60928ff24758ce626cd163"}, - {file = "jsonschema-3.2.0.tar.gz", hash = "sha256:c8a85b28d377cc7737e46e2d9f2b4f44ee3c0e1deac6bf46ddefc7187d30797a"}, -] loguru = [ {file = "loguru-0.5.3-py3-none-any.whl", hash = "sha256:f8087ac396b5ee5f67c963b495d615ebbceac2796379599820e324419d53667c"}, {file = "loguru-0.5.3.tar.gz", hash = "sha256:b28e72ac7a98be3d28ad28570299a393dfcd32e5e3f6a353dec94675767b6319"}, @@ -1624,30 +900,9 @@ markupsafe = [ {file = "MarkupSafe-1.1.1-cp38-cp38-win_amd64.whl", hash = "sha256:e8313f01ba26fbbe36c7be1966a7b7424942f670f38e666995b88d012765b9be"}, {file = "MarkupSafe-1.1.1.tar.gz", hash = "sha256:29872e92839765e546828bb7754a68c418d927cd064fd4708fab9fe9c8bb116b"}, ] -nb-cli = [ - {file = "nb-cli-0.2.0.tar.gz", hash = "sha256:d53ab571beee259af99a8cb4574ef85b6c1d821549f857eb45c83b3cb4f903a4"}, - {file = "nb_cli-0.2.0-py3-none-any.whl", hash = "sha256:c0975f18bb19da99278ea60c48b668fc6e5fa371b118e8e86d42e989933186ba"}, -] packaging = [ - {file = "packaging-20.7-py2.py3-none-any.whl", hash = "sha256:eb41423378682dadb7166144a4926e443093863024de508ca5c9737d6bc08376"}, - {file = "packaging-20.7.tar.gz", hash = "sha256:05af3bb85d320377db281cf254ab050e1a7ebcbf5410685a9a407e18a1f81236"}, -] -paramiko = [ - {file = "paramiko-2.7.2-py2.py3-none-any.whl", hash = "sha256:4f3e316fef2ac628b05097a637af35685183111d4bc1b5979bd397c2ab7b5898"}, - {file = "paramiko-2.7.2.tar.gz", hash = "sha256:7f36f4ba2c0d81d219f4595e35f70d56cc94f9ac40a6acdf51d6ca210ce65035"}, -] -poyo = [ - {file = "poyo-0.5.0-py2.py3-none-any.whl", hash = "sha256:3e2ca8e33fdc3c411cd101ca395668395dd5dc7ac775b8e809e3def9f9fe041a"}, - {file = "poyo-0.5.0.tar.gz", hash = "sha256:e26956aa780c45f011ca9886f044590e2d8fd8b61db7b1c1cf4e0869f48ed4dd"}, -] -prompt-toolkit = [ - {file = "prompt_toolkit-1.0.14-py2-none-any.whl", hash = "sha256:82c7f8e07d7a0411ff5367a5a8ff520f0112b9179f3e599ee8ad2ad9b943d911"}, - {file = "prompt_toolkit-1.0.14-py3-none-any.whl", hash = "sha256:7281b5199235adaef6980942840c43753e4ab20dfe41338da634fb41c194f9d8"}, - {file = "prompt_toolkit-1.0.14.tar.gz", hash = "sha256:cc66413b1b4b17021675d9f2d15d57e640b06ddfd99bb724c73484126d22622f"}, -] -pycparser = [ - {file = "pycparser-2.20-py2.py3-none-any.whl", hash = "sha256:7582ad22678f0fcd81102833f60ef8d0e57288b6b5fb00323d101be910e35705"}, - {file = "pycparser-2.20.tar.gz", hash = "sha256:2d475327684562c3a96cc71adf7dc8c4f0565175cf86b6d7a404ff4c771f15f0"}, + {file = "packaging-20.8-py2.py3-none-any.whl", hash = "sha256:24e0da08660a87484d1602c30bb4902d74816b6985b93de36926f5bc95741858"}, + {file = "packaging-20.8.tar.gz", hash = "sha256:78598185a7008a470d64526a8059de9aaa449238f280fc9eb6b13ba6c4109093"}, ] pydantic = [ {file = "pydantic-1.7.3-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:c59ea046aea25be14dc22d69c97bee629e6d48d2b2ecb724d7fe8806bf5f61cd"}, @@ -1674,149 +929,36 @@ pydantic = [ {file = "pydantic-1.7.3.tar.gz", hash = "sha256:213125b7e9e64713d16d988d10997dabc6a1f73f3991e1ff8e35ebb1409c7dc9"}, ] pydash = [ - {file = "pydash-4.9.0-py2.py3-none-any.whl", hash = "sha256:a743212a586f92980ee093fdec4a984cb97d38fe6d5dadd3c4eb1de57bc5fb4a"}, - {file = "pydash-4.9.0.tar.gz", hash = "sha256:44f7217669511901bf234628231a8d8fccd89a53c23b54c35759ee0838a67ba7"}, -] -pyfiglet = [ - {file = "pyfiglet-0.8.post1-py2.py3-none-any.whl", hash = "sha256:d555bcea17fbeaf70eaefa48bb119352487e629c9b56f30f383e2c62dd67a01c"}, - {file = "pyfiglet-0.8.post1.tar.gz", hash = "sha256:c6c2321755d09267b438ec7b936825a4910fec696292139e664ca8670e103639"}, + {file = "pydash-4.9.2-py2.py3-none-any.whl", hash = "sha256:dab98145502528369bd05034f6fb2b520297d49f942cfd51dc9cdc2cd47ec368"}, + {file = "pydash-4.9.2.tar.gz", hash = "sha256:11d8f3c92d92a004e042fdb226b10dba28f4e311546b0de89d983e91539d5e55"}, ] pygments = [ - {file = "Pygments-2.7.2-py3-none-any.whl", hash = "sha256:88a0bbcd659fcb9573703957c6b9cff9fab7295e6e76db54c9d00ae42df32773"}, - {file = "Pygments-2.7.2.tar.gz", hash = "sha256:381985fcc551eb9d37c52088a32914e00517e57f4a21609f48141ba08e193fa0"}, + {file = "Pygments-2.7.3-py3-none-any.whl", hash = "sha256:f275b6c0909e5dafd2d6269a656aa90fa58ebf4a74f8fcf9053195d226b24a08"}, + {file = "Pygments-2.7.3.tar.gz", hash = "sha256:ccf3acacf3782cbed4a989426012f1c535c9a90d3a7fc3f16d231b9372d2b716"}, ] pygtrie = [ {file = "pygtrie-2.4.1.tar.gz", hash = "sha256:4367b87d92eaf475107421dce0295a9d4d72156702908c96c430a426b654aee7"}, ] -pyinquirer = [ - {file = "PyInquirer-1.0.3.tar.gz", hash = "sha256:c9a92d68d7727fbd886a7908c08fd9e9773e5dc211bf5cbf836ba90d366dee51"}, -] -pynacl = [ - {file = "PyNaCl-1.4.0-cp27-cp27m-macosx_10_10_x86_64.whl", hash = "sha256:ea6841bc3a76fa4942ce00f3bda7d436fda21e2d91602b9e21b7ca9ecab8f3ff"}, - {file = "PyNaCl-1.4.0-cp27-cp27m-manylinux1_x86_64.whl", hash = "sha256:d452a6746f0a7e11121e64625109bc4468fc3100452817001dbe018bb8b08514"}, - {file = "PyNaCl-1.4.0-cp27-cp27m-win32.whl", hash = "sha256:2fe0fc5a2480361dcaf4e6e7cea00e078fcda07ba45f811b167e3f99e8cff574"}, - {file = "PyNaCl-1.4.0-cp27-cp27m-win_amd64.whl", hash = "sha256:f8851ab9041756003119368c1e6cd0b9c631f46d686b3904b18c0139f4419f80"}, - {file = "PyNaCl-1.4.0-cp27-cp27mu-manylinux1_x86_64.whl", hash = "sha256:7757ae33dae81c300487591c68790dfb5145c7d03324000433d9a2c141f82af7"}, - {file = "PyNaCl-1.4.0-cp35-abi3-macosx_10_10_x86_64.whl", hash = "sha256:757250ddb3bff1eecd7e41e65f7f833a8405fede0194319f87899690624f2122"}, - {file = "PyNaCl-1.4.0-cp35-abi3-manylinux1_x86_64.whl", hash = "sha256:30f9b96db44e09b3304f9ea95079b1b7316b2b4f3744fe3aaecccd95d547063d"}, - {file = "PyNaCl-1.4.0-cp35-abi3-win32.whl", hash = "sha256:4e10569f8cbed81cb7526ae137049759d2a8d57726d52c1a000a3ce366779634"}, - {file = "PyNaCl-1.4.0-cp35-abi3-win_amd64.whl", hash = "sha256:c914f78da4953b33d4685e3cdc7ce63401247a21425c16a39760e282075ac4a6"}, - {file = "PyNaCl-1.4.0-cp35-cp35m-win32.whl", hash = "sha256:06cbb4d9b2c4bd3c8dc0d267416aaed79906e7b33f114ddbf0911969794b1cc4"}, - {file = "PyNaCl-1.4.0-cp35-cp35m-win_amd64.whl", hash = "sha256:511d269ee845037b95c9781aa702f90ccc36036f95d0f31373a6a79bd8242e25"}, - {file = "PyNaCl-1.4.0-cp36-cp36m-win32.whl", hash = "sha256:11335f09060af52c97137d4ac54285bcb7df0cef29014a1a4efe64ac065434c4"}, - {file = "PyNaCl-1.4.0-cp36-cp36m-win_amd64.whl", hash = "sha256:cd401ccbc2a249a47a3a1724c2918fcd04be1f7b54eb2a5a71ff915db0ac51c6"}, - {file = "PyNaCl-1.4.0-cp37-cp37m-win32.whl", hash = "sha256:8122ba5f2a2169ca5da936b2e5a511740ffb73979381b4229d9188f6dcb22f1f"}, - {file = "PyNaCl-1.4.0-cp37-cp37m-win_amd64.whl", hash = "sha256:537a7ccbea22905a0ab36ea58577b39d1fa9b1884869d173b5cf111f006f689f"}, - {file = "PyNaCl-1.4.0-cp38-cp38-win32.whl", hash = "sha256:9c4a7ea4fb81536c1b1f5cc44d54a296f96ae78c1ebd2311bd0b60be45a48d96"}, - {file = "PyNaCl-1.4.0-cp38-cp38-win_amd64.whl", hash = "sha256:7c6092102219f59ff29788860ccb021e80fffd953920c4a8653889c029b2d420"}, - {file = "PyNaCl-1.4.0.tar.gz", hash = "sha256:54e9a2c849c742006516ad56a88f5c74bf2ce92c9f67435187c3c5953b346505"}, -] pyparsing = [ {file = "pyparsing-2.4.7-py2.py3-none-any.whl", hash = "sha256:ef9d7589ef3c200abe66653d3f1ab1033c3c419ae9b9bdb1240a85b024efc88b"}, {file = "pyparsing-2.4.7.tar.gz", hash = "sha256:c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1"}, ] -pyrsistent = [ - {file = "pyrsistent-0.17.3.tar.gz", hash = "sha256:2e636185d9eb976a18a8a8e96efce62f2905fea90041958d8cc2a189756ebf3e"}, -] -python-dateutil = [ - {file = "python-dateutil-2.8.1.tar.gz", hash = "sha256:73ebfe9dbf22e832286dafa60473e4cd239f8592f699aa5adaf10050e6e1823c"}, - {file = "python_dateutil-2.8.1-py2.py3-none-any.whl", hash = "sha256:75bb3f31ea686f1197762692a9ee6a7550b59fc6ca3a1f4b5d7e32fb98e2da2a"}, -] python-dotenv = [ {file = "python-dotenv-0.15.0.tar.gz", hash = "sha256:587825ed60b1711daea4832cf37524dfd404325b7db5e25ebe88c495c9f807a0"}, {file = "python_dotenv-0.15.0-py2.py3-none-any.whl", hash = "sha256:0c8d1b80d1a1e91717ea7d526178e3882732420b03f08afea0406db6402e220e"}, ] -python-slugify = [ - {file = "python-slugify-4.0.1.tar.gz", hash = "sha256:69a517766e00c1268e5bbfc0d010a0a8508de0b18d30ad5a1ff357f8ae724270"}, -] pytz = [ - {file = "pytz-2020.4-py2.py3-none-any.whl", hash = "sha256:5c55e189b682d420be27c6995ba6edce0c0a77dd67bfbe2ae6607134d5851ffd"}, - {file = "pytz-2020.4.tar.gz", hash = "sha256:3e6b7dd2d1e0a59084bcee14a17af60c5c562cdc16d828e8eba2e683d3a7e268"}, -] -pywin32 = [ - {file = "pywin32-227-cp27-cp27m-win32.whl", hash = "sha256:371fcc39416d736401f0274dd64c2302728c9e034808e37381b5e1b22be4a6b0"}, - {file = "pywin32-227-cp27-cp27m-win_amd64.whl", hash = "sha256:4cdad3e84191194ea6d0dd1b1b9bdda574ff563177d2adf2b4efec2a244fa116"}, - {file = "pywin32-227-cp35-cp35m-win32.whl", hash = "sha256:f4c5be1a293bae0076d93c88f37ee8da68136744588bc5e2be2f299a34ceb7aa"}, - {file = "pywin32-227-cp35-cp35m-win_amd64.whl", hash = "sha256:a929a4af626e530383a579431b70e512e736e9588106715215bf685a3ea508d4"}, - {file = "pywin32-227-cp36-cp36m-win32.whl", hash = "sha256:300a2db938e98c3e7e2093e4491439e62287d0d493fe07cce110db070b54c0be"}, - {file = "pywin32-227-cp36-cp36m-win_amd64.whl", hash = "sha256:9b31e009564fb95db160f154e2aa195ed66bcc4c058ed72850d047141b36f3a2"}, - {file = "pywin32-227-cp37-cp37m-win32.whl", hash = "sha256:47a3c7551376a865dd8d095a98deba954a98f326c6fe3c72d8726ca6e6b15507"}, - {file = "pywin32-227-cp37-cp37m-win_amd64.whl", hash = "sha256:31f88a89139cb2adc40f8f0e65ee56a8c585f629974f9e07622ba80199057511"}, - {file = "pywin32-227-cp38-cp38-win32.whl", hash = "sha256:7f18199fbf29ca99dff10e1f09451582ae9e372a892ff03a28528a24d55875bc"}, - {file = "pywin32-227-cp38-cp38-win_amd64.whl", hash = "sha256:7c1ae32c489dc012930787f06244426f8356e129184a02c25aef163917ce158e"}, - {file = "pywin32-227-cp39-cp39-win32.whl", hash = "sha256:c054c52ba46e7eb6b7d7dfae4dbd987a1bb48ee86debe3f245a2884ece46e295"}, - {file = "pywin32-227-cp39-cp39-win_amd64.whl", hash = "sha256:f27cec5e7f588c3d1051651830ecc00294f90728d19c3bf6916e6dba93ea357c"}, -] -pyyaml = [ - {file = "PyYAML-5.3.1-cp27-cp27m-win32.whl", hash = "sha256:74809a57b329d6cc0fdccee6318f44b9b8649961fa73144a98735b0aaf029f1f"}, - {file = "PyYAML-5.3.1-cp27-cp27m-win_amd64.whl", hash = "sha256:240097ff019d7c70a4922b6869d8a86407758333f02203e0fc6ff79c5dcede76"}, - {file = "PyYAML-5.3.1-cp35-cp35m-win32.whl", hash = "sha256:4f4b913ca1a7319b33cfb1369e91e50354d6f07a135f3b901aca02aa95940bd2"}, - {file = "PyYAML-5.3.1-cp35-cp35m-win_amd64.whl", hash = "sha256:cc8955cfbfc7a115fa81d85284ee61147059a753344bc51098f3ccd69b0d7e0c"}, - {file = "PyYAML-5.3.1-cp36-cp36m-win32.whl", hash = "sha256:7739fc0fa8205b3ee8808aea45e968bc90082c10aef6ea95e855e10abf4a37b2"}, - {file = "PyYAML-5.3.1-cp36-cp36m-win_amd64.whl", hash = "sha256:69f00dca373f240f842b2931fb2c7e14ddbacd1397d57157a9b005a6a9942648"}, - {file = "PyYAML-5.3.1-cp37-cp37m-win32.whl", hash = "sha256:d13155f591e6fcc1ec3b30685d50bf0711574e2c0dfffd7644babf8b5102ca1a"}, - {file = "PyYAML-5.3.1-cp37-cp37m-win_amd64.whl", hash = "sha256:73f099454b799e05e5ab51423c7bcf361c58d3206fa7b0d555426b1f4d9a3eaf"}, - {file = "PyYAML-5.3.1-cp38-cp38-win32.whl", hash = "sha256:06a0d7ba600ce0b2d2fe2e78453a470b5a6e000a985dd4a4e54e436cc36b0e97"}, - {file = "PyYAML-5.3.1-cp38-cp38-win_amd64.whl", hash = "sha256:95f71d2af0ff4227885f7a6605c37fd53d3a106fcab511b8860ecca9fcf400ee"}, - {file = "PyYAML-5.3.1-cp39-cp39-win32.whl", hash = "sha256:ad9c67312c84def58f3c04504727ca879cb0013b2517c85a9a253f0cb6380c0a"}, - {file = "PyYAML-5.3.1-cp39-cp39-win_amd64.whl", hash = "sha256:6034f55dab5fea9e53f436aa68fa3ace2634918e8b5994d82f3621c04ff5ed2e"}, - {file = "PyYAML-5.3.1.tar.gz", hash = "sha256:b8eac752c5e14d3eca0e6dd9199cd627518cb5ec06add0de9d32baeee6fe645d"}, -] -regex = [ - {file = "regex-2020.11.13-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:8b882a78c320478b12ff024e81dc7d43c1462aa4a3341c754ee65d857a521f85"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:a63f1a07932c9686d2d416fb295ec2c01ab246e89b4d58e5fa468089cab44b70"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:6e4b08c6f8daca7d8f07c8d24e4331ae7953333dbd09c648ed6ebd24db5a10ee"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:bba349276b126947b014e50ab3316c027cac1495992f10e5682dc677b3dfa0c5"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:56e01daca75eae420bce184edd8bb341c8eebb19dd3bce7266332258f9fb9dd7"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2014_aarch64.whl", hash = "sha256:6a8ce43923c518c24a2579fda49f093f1397dad5d18346211e46f134fc624e31"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2014_i686.whl", hash = "sha256:1ab79fcb02b930de09c76d024d279686ec5d532eb814fd0ed1e0051eb8bd2daa"}, - {file = "regex-2020.11.13-cp36-cp36m-manylinux2014_x86_64.whl", hash = "sha256:9801c4c1d9ae6a70aeb2128e5b4b68c45d4f0af0d1535500884d644fa9b768c6"}, - {file = "regex-2020.11.13-cp36-cp36m-win32.whl", hash = "sha256:49cae022fa13f09be91b2c880e58e14b6da5d10639ed45ca69b85faf039f7a4e"}, - {file = "regex-2020.11.13-cp36-cp36m-win_amd64.whl", hash = "sha256:749078d1eb89484db5f34b4012092ad14b327944ee7f1c4f74d6279a6e4d1884"}, - {file = "regex-2020.11.13-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:b2f4007bff007c96a173e24dcda236e5e83bde4358a557f9ccf5e014439eae4b"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:38c8fd190db64f513fe4e1baa59fed086ae71fa45083b6936b52d34df8f86a88"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:5862975b45d451b6db51c2e654990c1820523a5b07100fc6903e9c86575202a0"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:262c6825b309e6485ec2493ffc7e62a13cf13fb2a8b6d212f72bd53ad34118f1"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:bafb01b4688833e099d79e7efd23f99172f501a15c44f21ea2118681473fdba0"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2014_aarch64.whl", hash = "sha256:e32f5f3d1b1c663af7f9c4c1e72e6ffe9a78c03a31e149259f531e0fed826512"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2014_i686.whl", hash = "sha256:3bddc701bdd1efa0d5264d2649588cbfda549b2899dc8d50417e47a82e1387ba"}, - {file = "regex-2020.11.13-cp37-cp37m-manylinux2014_x86_64.whl", hash = "sha256:02951b7dacb123d8ea6da44fe45ddd084aa6777d4b2454fa0da61d569c6fa538"}, - {file = "regex-2020.11.13-cp37-cp37m-win32.whl", hash = "sha256:0d08e71e70c0237883d0bef12cad5145b84c3705e9c6a588b2a9c7080e5af2a4"}, - {file = "regex-2020.11.13-cp37-cp37m-win_amd64.whl", hash = "sha256:1fa7ee9c2a0e30405e21031d07d7ba8617bc590d391adfc2b7f1e8b99f46f444"}, - {file = "regex-2020.11.13-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:baf378ba6151f6e272824b86a774326f692bc2ef4cc5ce8d5bc76e38c813a55f"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux1_i686.whl", hash = "sha256:e3faaf10a0d1e8e23a9b51d1900b72e1635c2d5b0e1bea1c18022486a8e2e52d"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:2a11a3e90bd9901d70a5b31d7dd85114755a581a5da3fc996abfefa48aee78af"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:d1ebb090a426db66dd80df8ca85adc4abfcbad8a7c2e9a5ec7513ede522e0a8f"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:b2b1a5ddae3677d89b686e5c625fc5547c6e492bd755b520de5332773a8af06b"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2014_aarch64.whl", hash = "sha256:2c99e97d388cd0a8d30f7c514d67887d8021541b875baf09791a3baad48bb4f8"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2014_i686.whl", hash = "sha256:c084582d4215593f2f1d28b65d2a2f3aceff8342aa85afd7be23a9cad74a0de5"}, - {file = "regex-2020.11.13-cp38-cp38-manylinux2014_x86_64.whl", hash = "sha256:a3d748383762e56337c39ab35c6ed4deb88df5326f97a38946ddd19028ecce6b"}, - {file = "regex-2020.11.13-cp38-cp38-win32.whl", hash = "sha256:7913bd25f4ab274ba37bc97ad0e21c31004224ccb02765ad984eef43e04acc6c"}, - {file = "regex-2020.11.13-cp38-cp38-win_amd64.whl", hash = "sha256:6c54ce4b5d61a7129bad5c5dc279e222afd00e721bf92f9ef09e4fae28755683"}, - {file = "regex-2020.11.13-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:1862a9d9194fae76a7aaf0150d5f2a8ec1da89e8b55890b1786b8f88a0f619dc"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux1_i686.whl", hash = "sha256:4902e6aa086cbb224241adbc2f06235927d5cdacffb2425c73e6570e8d862364"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:7a25fcbeae08f96a754b45bdc050e1fb94b95cab046bf56b016c25e9ab127b3e"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:d2d8ce12b7c12c87e41123997ebaf1a5767a5be3ec545f64675388970f415e2e"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:f7d29a6fc4760300f86ae329e3b6ca28ea9c20823df123a2ea8693e967b29917"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2014_aarch64.whl", hash = "sha256:717881211f46de3ab130b58ec0908267961fadc06e44f974466d1887f865bd5b"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2014_i686.whl", hash = "sha256:3128e30d83f2e70b0bed9b2a34e92707d0877e460b402faca908c6667092ada9"}, - {file = "regex-2020.11.13-cp39-cp39-manylinux2014_x86_64.whl", hash = "sha256:8f6a2229e8ad946e36815f2a03386bb8353d4bde368fdf8ca5f0cb97264d3b5c"}, - {file = "regex-2020.11.13-cp39-cp39-win32.whl", hash = "sha256:f8f295db00ef5f8bae530fc39af0b40486ca6068733fb860b42115052206466f"}, - {file = "regex-2020.11.13-cp39-cp39-win_amd64.whl", hash = "sha256:a15f64ae3a027b64496a71ab1f722355e570c3fac5ba2801cafce846bf5af01d"}, - {file = "regex-2020.11.13.tar.gz", hash = "sha256:83d6b356e116ca119db8e7c6fc2983289d87b27b3fac238cfe5dca529d884562"}, + {file = "pytz-2020.5-py2.py3-none-any.whl", hash = "sha256:16962c5fb8db4a8f63a26646d8886e9d769b6c511543557bc84e9569fb9a9cb4"}, + {file = "pytz-2020.5.tar.gz", hash = "sha256:180befebb1927b16f6b57101720075a984c019ac16b1b7575673bea42c6c3da5"}, ] requests = [ - {file = "requests-2.25.0-py2.py3-none-any.whl", hash = "sha256:e786fa28d8c9154e6a4de5d46a1d921b8749f8b74e28bde23768e5e16eece998"}, - {file = "requests-2.25.0.tar.gz", hash = "sha256:7f1a0b932f4a60a1a65caa4263921bb7d9ee911957e0ae4a23a6dd08185ad5f8"}, + {file = "requests-2.25.1-py2.py3-none-any.whl", hash = "sha256:c210084e36a42ae6b9219e00e48287def368a26d03a048ddad7bfee44f75871e"}, + {file = "requests-2.25.1.tar.gz", hash = "sha256:27973dd4a904a4f13b263a19c866c13b92a39ed1c964655f025f3f8d3d75b804"}, ] rfc3986 = [ {file = "rfc3986-1.4.0-py2.py3-none-any.whl", hash = "sha256:af9147e9aceda37c91a05f4deb128d4b4b49d6b199775fd2d2927768abdc8f50"}, {file = "rfc3986-1.4.0.tar.gz", hash = "sha256:112398da31a3344dc25dbf477d8df6cb34f9278a94fee2625d89e4514be8bb9d"}, ] -six = [ - {file = "six-1.15.0-py2.py3-none-any.whl", hash = "sha256:8b74bedcbbbaca38ff6d7491d76f2b06b3592611af620f8426e82dddb04a5ced"}, - {file = "six-1.15.0.tar.gz", hash = "sha256:30639c035cdb23534cd4aa2dd52c3bf48f06e5f4a941509c8bafd8ce11080259"}, -] sniffio = [ {file = "sniffio-1.2.0-py3-none-any.whl", hash = "sha256:471b71698eac1c2112a40ce2752bb2f4a4814c22a54a3eed3676bc0f5ca9f663"}, {file = "sniffio-1.2.0.tar.gz", hash = "sha256:c4666eecec1d3f50960c6bdf61ab7bc350648da6c126e3cf6898d8cd4ddcd3de"}, @@ -1826,8 +968,8 @@ snowballstemmer = [ {file = "snowballstemmer-2.0.0.tar.gz", hash = "sha256:df3bac3df4c2c01363f3dd2cfa78cce2840a79b9f1c2d2de9ce8d31683992f52"}, ] sphinx = [ - {file = "Sphinx-3.3.1-py3-none-any.whl", hash = "sha256:d4e59ad4ea55efbb3c05cde3bfc83bfc14f0c95aa95c3d75346fcce186a47960"}, - {file = "Sphinx-3.3.1.tar.gz", hash = "sha256:1e8d592225447104d1172be415bc2972bd1357e3e12fdc76edf2261105db4300"}, + {file = "Sphinx-3.4.1-py3-none-any.whl", hash = "sha256:aeef652b14629431c82d3fe994ce39ead65b3fe87cf41b9a3714168ff8b83376"}, + {file = "Sphinx-3.4.1.tar.gz", hash = "sha256:e450cb205ff8924611085183bf1353da26802ae73d9251a8fcdf220a8f8712ef"}, ] sphinx-markdown-builder = [] sphinxcontrib-applehelp = [ @@ -1855,16 +997,13 @@ sphinxcontrib-serializinghtml = [ {file = "sphinxcontrib_serializinghtml-1.1.4-py2.py3-none-any.whl", hash = "sha256:f242a81d423f59617a8e5cf16f5d4d74e28ee9a66f9e5b637a18082991db5a9a"}, ] starlette = [ - {file = "starlette-0.13.4-py3-none-any.whl", hash = "sha256:0fb4b38d22945b46acb880fedee7ee143fd6c0542992501be8c45c0ed737dd1a"}, - {file = "starlette-0.13.4.tar.gz", hash = "sha256:04fe51d86fd9a594d9b71356ed322ccde5c9b448fc716ac74155e5821a922f8d"}, + {file = "starlette-0.13.6-py3-none-any.whl", hash = "sha256:bd2ffe5e37fb75d014728511f8e68ebf2c80b0fa3d04ca1479f4dc752ae31ac9"}, + {file = "starlette-0.13.6.tar.gz", hash = "sha256:ebe8ee08d9be96a3c9f31b2cb2a24dbdf845247b745664bd8a3f9bd0c977fdbc"}, ] -text-unidecode = [ - {file = "text-unidecode-1.3.tar.gz", hash = "sha256:bad6603bb14d279193107714b288be206cac565dfa49aa5b105294dd5c4aab93"}, - {file = "text_unidecode-1.3-py2.py3-none-any.whl", hash = "sha256:1311f10e8b895935241623731c2ba64f4c455287888b18189350b67134a822e8"}, -] -texttable = [ - {file = "texttable-1.6.3-py2.py3-none-any.whl", hash = "sha256:f802f2ef8459058736264210f716c757cbf85007a30886d8541aa8c3404f1dda"}, - {file = "texttable-1.6.3.tar.gz", hash = "sha256:ce0faf21aa77d806bbff22b107cc22cce68dc9438f97a2df32c93e9afa4ce436"}, +typing-extensions = [ + {file = "typing_extensions-3.7.4.3-py2-none-any.whl", hash = "sha256:dafc7639cde7f1b6e1acc0f457842a83e722ccca8eef5270af2d74792619a89f"}, + {file = "typing_extensions-3.7.4.3-py3-none-any.whl", hash = "sha256:7cb407020f00f7bfc3cb3e7881628838e69d8f3fcab2f64742a5e76b2f841918"}, + {file = "typing_extensions-3.7.4.3.tar.gz", hash = "sha256:99d4073b617d30288f569d3f13d2bd7548c3a7e4c8de87db09a9d29bb3a4a60c"}, ] unify = [ {file = "unify-0.5.tar.gz", hash = "sha256:8ddce812b2457212b7598fe574c9e6eb3ad69710f445391338270c7f8a71723c"}, @@ -1891,14 +1030,6 @@ uvloop = [ {file = "uvloop-0.14.0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:4315d2ec3ca393dd5bc0b0089d23101276778c304d42faff5dc4579cb6caef09"}, {file = "uvloop-0.14.0.tar.gz", hash = "sha256:123ac9c0c7dd71464f58f1b4ee0bbd81285d96cdda8bc3519281b8973e3a461e"}, ] -wcwidth = [ - {file = "wcwidth-0.2.5-py2.py3-none-any.whl", hash = "sha256:beb4802a9cebb9144e99086eff703a642a13d6a0052920003a230f3294bbe784"}, - {file = "wcwidth-0.2.5.tar.gz", hash = "sha256:c4d647b99872929fdb7bdcaa4fbe7f01413ed3d98077df798530e5b04f116c83"}, -] -websocket-client = [ - {file = "websocket_client-0.57.0-py2.py3-none-any.whl", hash = "sha256:0fc45c961324d79c781bab301359d5a1b00b13ad1b10415a4780229ef71a5549"}, - {file = "websocket_client-0.57.0.tar.gz", hash = "sha256:d735b91d6d1692a6a181f2a8c9e0238e5f6373356f561bb9dc4c7af36f452010"}, -] websockets = [ {file = "websockets-8.1-cp36-cp36m-macosx_10_6_intel.whl", hash = "sha256:3762791ab8b38948f0c4d281c8b2ddfa99b7e510e46bd8dfa942a5fff621068c"}, {file = "websockets-8.1-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:3db87421956f1b0779a7564915875ba774295cc86e81bc671631379371af1170"}, @@ -1931,7 +1062,3 @@ yapf = [ {file = "yapf-0.30.0-py2.py3-none-any.whl", hash = "sha256:3abf61ba67cf603069710d30acbc88cfe565d907e16ad81429ae90ce9651e0c9"}, {file = "yapf-0.30.0.tar.gz", hash = "sha256:3000abee4c28daebad55da6c85f3cd07b8062ce48e2e9943c8da1b9667d48427"}, ] -zipp = [ - {file = "zipp-3.4.0-py3-none-any.whl", hash = "sha256:102c24ef8f171fd729d46599845e95c7ab894a4cf45f5de11a44cc7444fb1108"}, - {file = "zipp-3.4.0.tar.gz", hash = "sha256:ed5eee1974372595f9e416cc7bbeeb12335201d8081ca8a0743c954d4446e5cb"}, -] diff --git a/pyproject.toml b/pyproject.toml index d4fc9677..e69a93e1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "nonebot2" -version = "2.0.0-alpha.7" +version = "2.0.0-alpha.8" description = "An asynchronous python bot framework." authors = ["yanyongyu "] license = "MIT" @@ -27,16 +27,13 @@ python = "^3.7" httpx = "^0.16.1" loguru = "^0.5.1" pygtrie = "^2.4.1" -fastapi = "^0.58.1" +fastapi = "^0.63.0" uvicorn = "^0.11.5" -pydantic = { extras = ["dotenv"], version = "^1.7.2" } +pydantic = {extras = ["dotenv", "typing_extensions"], version = "^1.7.3"} [tool.poetry.dev-dependencies] yapf = "^0.30.0" -sphinx = "^3.3.1" -nb-cli = { version = "^0.2.0", optional = true } -nonebot-plugin-test = { version = "^0.1.0", optional = true } -nonebot-plugin-apscheduler = { version = "^0.1.0", optional = true } +sphinx = "^3.4.1" sphinx-markdown-builder = { git = "https://github.com/nonebot/sphinx-markdown-builder.git" } [[tool.poetry.source]] diff --git a/tests/.env.dev b/tests/.env.dev index 96101fd4..9b69f65a 100644 --- a/tests/.env.dev +++ b/tests/.env.dev @@ -3,7 +3,7 @@ HOST=0.0.0.0 PORT=2333 DEBUG=true -SUPERUSERS=[123123123] +SUPERUSERS=["123123123"] NICKNAME=["bot"] COMMAND_START=["", "/", "#"] diff --git a/tests/test_plugins/test_delete.py b/tests/test_plugins/test_delete.py index bd02cfbc..2c3265d8 100644 --- a/tests/test_plugins/test_delete.py +++ b/tests/test_plugins/test_delete.py @@ -1,23 +1,24 @@ import asyncio from nonebot import on_message +from nonebot.typing import T_State from nonebot.permission import USER -from nonebot.typing import Bot, Event +from nonebot.adapters import Bot, Event -a = on_message(priority=0, permission=USER(123123123), temp=True) +a = on_message(priority=0, permission=USER("123123123"), temp=True) @a.handle() -async def test_a(bot: Bot, event: Event, state: dict): +async def test_a(bot: Bot, event: Event, state: T_State): print("======== A Received ========") print("======== A Running Completed ========") -b = on_message(priority=0, permission=USER(123456789), temp=True) +b = on_message(priority=0, permission=USER("123456789"), temp=True) @b.handle() -async def test_b(bot: Bot, event: Event, state: dict): +async def test_b(bot: Bot, event: Event, state: T_State): print("======== B Received ========") await asyncio.sleep(10) print("======== B Running Completed ========") @@ -27,5 +28,5 @@ c = on_message(priority=0, permission=USER(1111111111)) @c.handle() -async def test_c(bot: Bot, event: Event, state: dict): +async def test_c(bot: Bot, event: Event, state: T_State): print("======== C Received ========") diff --git a/tests/test_plugins/test_ding.py b/tests/test_plugins/test_ding.py new file mode 100644 index 00000000..fca234eb --- /dev/null +++ b/tests/test_plugins/test_ding.py @@ -0,0 +1,160 @@ +from nonebot.rule import to_me +from nonebot.plugin import on_command +from nonebot.adapters.ding import Bot as DingBot, MessageSegment, MessageEvent + +markdown = on_command("markdown", to_me()) + + +@markdown.handle() +async def test_handler(bot: DingBot): + message = MessageSegment.markdown( + "Hello, This is NoneBot", + "#### NoneBot \n> Nonebot 是一款高性能的 Python 机器人框架\n> ![screenshot](https://v2.nonebot.dev/logo.png)\n> [GitHub 仓库地址](https://github.com/nonebot/nonebot2) \n" + ) + await markdown.finish(message) + + +actionCardSingleBtn = on_command("actionCardSingleBtn", to_me()) + + +@actionCardSingleBtn.handle() +async def test_handler(bot: DingBot): + message = MessageSegment.actionCardSingleBtn( + title="打造一间咖啡厅", + text= + "![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \n #### 乔布斯 20 年前想打造的苹果咖啡厅 \n\n Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划", + singleTitle="阅读全文", + singleURL="https://www.dingtalk.com/") + await actionCardSingleBtn.finish(message) + + +actionCard = on_command("actionCard", to_me()) + + +@actionCard.handle() +async def test_handler(bot: DingBot): + message = MessageSegment.raw({ + "msgtype": "actionCard", + "actionCard": { + "title": + "乔布斯 20 年前想打造一间苹果咖啡厅,而它正是 Apple Store 的前身", + "text": + "![screenshot](https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png) \n\n #### 乔布斯 20 年前想打造的苹果咖啡厅 \n\n Apple Store 的设计正从原来满满的科技感走向生活化,而其生活化的走向其实可以追溯到 20 年前苹果一个建立咖啡馆的计划", + "hideAvatar": + "0", + "btnOrientation": + "0", + "btns": [{ + "title": "内容不错", + "actionURL": "https://www.dingtalk.com/" + }, { + "title": "不感兴趣", + "actionURL": "https://www.dingtalk.com/" + }] + } + }) + await actionCard.finish(message) + + +feedCard = on_command("feedCard", to_me()) + + +@feedCard.handle() +async def test_handler(bot: DingBot): + message = MessageSegment.raw({ + "msgtype": "feedCard", + "feedCard": { + "links": [{ + "title": + "时代的火车向前开1", + "messageURL": + "https://www.dingtalk.com/", + "picURL": + "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" + }, { + "title": + "时代的火车向前开2", + "messageURL": + "https://www.dingtalk.com/", + "picURL": + "https://img.alicdn.com/tfs/TB1NwmBEL9TBuNjy1zbXXXpepXa-2400-1218.png" + }] + } + }) + await feedCard.finish(message) + + +atme = on_command("atme", to_me()) + + +@atme.handle() +async def test_handler(bot: DingBot, event: MessageEvent): + message = f"@{event.senderNick} at you" + MessageSegment.atMobiles( + "13800000001") + await atme.finish(message) + + +image = on_command("image", to_me()) + + +@image.handle() +async def test_handler(bot: DingBot, event: MessageEvent): + message = MessageSegment.image( + "https://static-aliyun-doc.oss-accelerate.aliyuncs.com/assets/img/zh-CN/0634199951/p158167.png" + ) + await image.finish(message) + + +textAdd = on_command("t", to_me()) + + +@textAdd.handle() +async def test_handler(bot: DingBot, event: MessageEvent): + message = "第一段消息\n" + MessageSegment.text("asdawefaefa\n") + await textAdd.send(message) + + message = message + MessageSegment.text("第二段消息\n") + await textAdd.send(message) + + message = message + MessageSegment.text( + "\n第三段消息\n") + "adfkasfkhsdkfahskdjasdashdkjasdf" + message = message + MessageSegment.extension({ + "text_type": "code_snippet", + "code_language": "C#" + }) + await textAdd.send(message) + + +code = on_command("code", to_me()) + + +@code.handle() +async def test_handler(bot: DingBot, event: MessageEvent): + raw = MessageSegment.raw({ + "msgtype": "text", + "text": { + "content": 'print("hello world")' + }, + "extension": { + "text_type": "code_snippet", + "code_language": "Python", + } + }) + await code.send(raw) + message = MessageSegment.text("""using System; + +namespace HelloWorld +{ + class Program + { + static void Main(string[] args) + { + Console.WriteLine("Hello World!"); + } + } +}""") + message += MessageSegment.extension({ + "text_type": "code_snippet", + "code_language": "C#" + }) + await code.finish(message) diff --git a/tests/test_plugins/test_group/commands.py b/tests/test_plugins/test_group/commands.py index 52242d32..4d0898b9 100644 --- a/tests/test_plugins/test_group/commands.py +++ b/tests/test_plugins/test_group/commands.py @@ -1,11 +1,10 @@ -from nonebot.typing import Bot, Event -from nonebot.permission import GROUP_OWNER +from nonebot.adapters import Bot, Event from . import cmd -test_1 = cmd.command("1", aliases={"test"}, permission=GROUP_OWNER) +test_1 = cmd.command("1", aliases={"test"}) @test_1.handle() -async def test1(bot: Bot, event: Event, state: dict): - await test_1.finish(event.raw_message) +async def test1(bot: Bot, event: Event): + await test_1.finish(event.get_message()) diff --git a/tests/test_plugins/test_group/matches.py b/tests/test_plugins/test_group/matches.py index 8c3c786b..d33d8dc7 100644 --- a/tests/test_plugins/test_group/matches.py +++ b/tests/test_plugins/test_group/matches.py @@ -1,15 +1,17 @@ -from nonebot.typing import Bot, Event +from nonebot.typing import T_State +from nonebot.adapters import Bot, Event +from nonebot.adapters.cqhttp import HeartbeatMetaEvent from . import match -async def heartbeat(bot: Bot, event: Event, state: dict) -> bool: - return event.detail_type == "heartbeat" +async def heartbeat(bot: Bot, event: Event, state: T_State) -> bool: + return isinstance(event, HeartbeatMetaEvent) test = match.on_metaevent(rule=heartbeat) @test.receive() -async def handle_heartbeat(bot: Bot, event: Event, state: dict): +async def handle_heartbeat(bot: Bot): print("[i] Heartbeat") diff --git a/tests/test_plugins/test_metaevent.py b/tests/test_plugins/test_metaevent.py index 439513b1..e2a160e2 100644 --- a/tests/test_plugins/test_metaevent.py +++ b/tests/test_plugins/test_metaevent.py @@ -1,14 +1,21 @@ -from nonebot.typing import Bot, Event +from nonebot.typing import T_State from nonebot.plugin import on_metaevent +from nonebot.adapters import Bot, Event +from nonebot.adapters.cqhttp import HeartbeatMetaEvent -async def heartbeat(bot: Bot, event: Event, state: dict) -> bool: - return event.detail_type == "heartbeat" +async def heartbeat(bot: Bot, event: Event, state: T_State) -> bool: + return isinstance(event, HeartbeatMetaEvent) -test_matcher = on_metaevent(heartbeat) +async def factory(bot: Bot, event: Event) -> T_State: + return {"factory": True} + + +test_matcher = on_metaevent(heartbeat, state_factory=factory) @test_matcher.receive() -async def handle_heartbeat(bot: Bot, event: Event, state: dict): +async def handle_heartbeat(bot: Bot, event: Event, state: T_State): + print(state) print("[i] Heartbeat") diff --git a/tests/test_plugins/test_package/test_command.py b/tests/test_plugins/test_package/test_command.py index fd85b1d9..3b77fb5e 100644 --- a/tests/test_plugins/test_package/test_command.py +++ b/tests/test_plugins/test_package/test_command.py @@ -1,14 +1,14 @@ from nonebot.rule import to_me -from nonebot.typing import Event +from nonebot.typing import T_State from nonebot.plugin import on_command -from nonebot.adapters.cqhttp import Bot +from nonebot.adapters import Bot, Event test_command = on_command("帮助", to_me()) @test_command.handle() -async def test_handler(bot: Bot, event: Event, state: dict): - args = str(event.message).strip() +async def test_handler(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() print("[!] Command:", state["_prefix"], "Args:", args) if args: state["help"] = args @@ -17,7 +17,7 @@ async def test_handler(bot: Bot, event: Event, state: dict): @test_command.got("help", prompt="你要帮助的命令是?") -async def test_handler(bot: Bot, event: Event, state: dict): +async def test_handler(bot: Bot, event: Event, state: T_State): print("[!] Command 帮助:", state["help"]) if state["help"] not in ["test1", "test2"]: await test_command.reject(f"{state['help']} 不支持,请重新输入!") diff --git a/tests/test_plugins/test_permission.py b/tests/test_plugins/test_permission.py index 23d4e0f5..a7157dff 100644 --- a/tests/test_plugins/test_permission.py +++ b/tests/test_plugins/test_permission.py @@ -1,18 +1,18 @@ from nonebot.rule import to_me -from nonebot.typing import Event +from nonebot.typing import T_State from nonebot.plugin import on_startswith -from nonebot.adapters.cqhttp import Bot -from nonebot.adapters.ding import Bot as DingBot, Event as DingEvent -from nonebot.permission import GROUP_ADMIN +from nonebot.permission import SUPERUSER +from nonebot.adapters.ding import Bot as DingBot +from nonebot.adapters.cqhttp import Bot as CQHTTPBot -test_command = on_startswith("hello", to_me(), permission=GROUP_ADMIN) +test_command = on_startswith("hello", to_me(), permission=SUPERUSER) @test_command.handle() -async def test_handler(bot: Bot, event: Event, state: dict): +async def test_handler(bot: CQHTTPBot): await test_command.finish("cqhttp hello") @test_command.handle() -async def test_handler(bot: DingBot, event: DingEvent, state: dict): +async def test_handler(bot: DingBot): await test_command.finish("ding hello") diff --git a/tests/test_plugins/test_processor.py b/tests/test_plugins/test_processor.py index 8352dbdb..b5aaa298 100644 --- a/tests/test_plugins/test_processor.py +++ b/tests/test_plugins/test_processor.py @@ -1,13 +1,15 @@ -from nonebot.typing import Bot, Event, Matcher +from nonebot.typing import T_State +from nonebot.matcher import Matcher +from nonebot.adapters import Bot, Event from nonebot.message import event_preprocessor, run_preprocessor @event_preprocessor -async def handle(bot: Bot, event: Event, state: dict): +async def handle(bot: Bot, event: Event, state: T_State): state["preprocessed"] = True - print(event) + print(type(event), event) @run_preprocessor -async def run(matcher: Matcher, bot: Bot, event: Event, state: dict): +async def run(matcher: Matcher, bot: Bot, event: Event, state: T_State): print(matcher) diff --git a/tests/test_plugins/test_weather.py b/tests/test_plugins/test_weather.py index 26effa5d..350e8d1d 100644 --- a/tests/test_plugins/test_weather.py +++ b/tests/test_plugins/test_weather.py @@ -1,20 +1,21 @@ from nonebot import on_command from nonebot.rule import to_me -from nonebot.typing import Bot, Event +from nonebot.typing import T_State +from nonebot.adapters import Bot, Event weather = on_command("天气", rule=to_me(), priority=1) @weather.handle() -async def handle_first_receive(bot: Bot, event: Event, state: dict): - args = str(event.message).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 +async def handle_first_receive(bot: Bot, event: Event, state: T_State): + args = str(event.get_message()).strip() # 首次发送命令时跟随的参数,例:/天气 上海,则args为上海 print(f"==={args}===") if args: state["city"] = args # 如果用户发送了参数则直接赋值 @weather.got("city", prompt="你想查询哪个城市的天气呢?") -async def handle_city(bot: Bot, event: Event, state: dict): +async def handle_city(bot: Bot, state: T_State): city = state["city"] if city not in ["上海", "北京"]: await weather.reject("你想查询的城市暂不支持,请重新输入!") diff --git a/tests/test_plugins/test_ws_hook.py b/tests/test_plugins/test_ws_hook.py new file mode 100644 index 00000000..7b5f9b2b --- /dev/null +++ b/tests/test_plugins/test_ws_hook.py @@ -0,0 +1,14 @@ +import nonebot +from nonebot.adapters import Bot + +driver = nonebot.get_driver() + + +@driver.on_bot_connect +async def connect(bot: Bot) -> None: + print("Connect", bot) + + +@driver.on_bot_disconnect +async def disconnect(bot: Bot) -> None: + print("Disconnect", bot)