mirror of
				https://github.com/nonebot/nonebot2.git
				synced 2025-10-31 06:56:39 +00:00 
			
		
		
		
	📝 Docs: 更新最佳实践的 Alconna 部分 (#2443)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: StarHeartHunt <starheart233@gmail.com>
This commit is contained in:
		| @@ -5,11 +5,14 @@ description: Alconna 命令解析拓展 | ||||
| slug: /best-practice/alconna/ | ||||
| --- | ||||
|  | ||||
| import Tabs from "@theme/Tabs"; | ||||
| import TabItem from "@theme/TabItem"; | ||||
|  | ||||
| # Alconna 插件 | ||||
|  | ||||
| [`nonebot-plugin-alconna`](https://github.com/nonebot/plugin-alconna) 是一类提供了拓展响应规则的插件。 | ||||
| 该插件使用 [Alconna](https://github.com/ArcletProject/Alconna) 作为命令解析器, | ||||
| 是一个简单、灵活、高效的命令参数解析器, 并且不局限于解析命令式字符串。 | ||||
| 是一个简单、灵活、高效的命令参数解析器,并且不局限于解析命令式字符串。 | ||||
|  | ||||
| 该插件提供了一类新的事件响应器辅助函数 `on_alconna`,以及 `AlconnaResult` 等依赖注入函数。 | ||||
|  | ||||
| @@ -31,16 +34,31 @@ slug: /best-practice/alconna/ | ||||
|  | ||||
| 在**项目目录**下执行以下命令: | ||||
|  | ||||
| <Tabs groupId="install"> | ||||
| <TabItem value="cli" label="使用 nb-cli"> | ||||
|  | ||||
| ```shell | ||||
| nb plugin install nonebot-plugin-alconna | ||||
| ``` | ||||
|  | ||||
| 或 | ||||
| </TabItem> | ||||
| <TabItem value="pip" label="使用 pip"> | ||||
|  | ||||
| ```shell | ||||
| pip install nonebot-plugin-alconna | ||||
| ``` | ||||
|  | ||||
| </TabItem> | ||||
|  | ||||
| <TabItem value="pdm" label="使用 pdm"> | ||||
|  | ||||
| ```shell | ||||
| pdm add nonebot-plugin-alconna | ||||
| ``` | ||||
|  | ||||
| </TabItem> | ||||
| </Tabs> | ||||
|  | ||||
| ## 导入插件 | ||||
|  | ||||
| 由于 `nonebot-plugin-alconna` 作为插件,因此需要在使用前对其进行**加载**并**导入**其中的 `on_alconna` 来使用命令拓展。使用 `require` 方法可轻松完成这一过程,可参考 [跨插件访问](../../advanced/requiring.md) 一节进行了解。 | ||||
| @@ -87,7 +105,7 @@ async def got_location(location: str = ArgPlainText()): | ||||
| ```python {5-10,14-16,18-19} | ||||
| from nonebot.rule import to_me | ||||
| from arclet.alconna import Alconna, Args | ||||
| from nonebot_plugin_alconna import Match, AlconnaMatcher, on_alconna | ||||
| from nonebot_plugin_alconna import Match, on_alconna | ||||
|  | ||||
| weather = on_alconna( | ||||
|     Alconna("天气", Args["location?", str]), | ||||
| @@ -98,9 +116,9 @@ weather.shortcut("天气预报", {"command": "天气"}) | ||||
|  | ||||
|  | ||||
| @weather.handle() | ||||
| async def handle_function(matcher: AlconnaMatcher, location: Match[str]): | ||||
| async def handle_function(location: Match[str]): | ||||
|     if location.available: | ||||
|         matcher.set_path_arg("location", location.result) | ||||
|         weather.set_path_arg("location", location.result) | ||||
|  | ||||
| @weather.got_path("location", prompt="请输入地名") | ||||
| async def got_location(location: str): | ||||
|   | ||||
| @@ -6,9 +6,9 @@ description: Alconna 基本介绍 | ||||
| # Alconna 命令解析 | ||||
|  | ||||
| [Alconna](https://github.com/ArcletProject/Alconna) 作为命令解析器, | ||||
| 是一个简单、灵活、高效的命令参数解析器, 并且不局限于解析命令式字符串。 | ||||
| 是一个简单、灵活、高效的命令参数解析器,并且不局限于解析命令式字符串。 | ||||
|  | ||||
| 特点包括: | ||||
| 特点包括: | ||||
|  | ||||
| - 高效 | ||||
| - 直观的命令组件创建方式 | ||||
| @@ -16,10 +16,94 @@ description: Alconna 基本介绍 | ||||
| - 自定义的帮助信息格式 | ||||
| - 多语言支持 | ||||
| - 易用的快捷命令创建与使用 | ||||
| - 可创建命令补全会话, 以实现多轮连续的补全提示 | ||||
| - 可创建命令补全会话,以实现多轮连续的补全提示 | ||||
| - 可嵌套的多级子命令 | ||||
| - 正则匹配支持 | ||||
|  | ||||
| ## 命令示范 | ||||
|  | ||||
| ```python | ||||
| import sys | ||||
| from io import StringIO | ||||
|  | ||||
| from arclet.alconna import Alconna, Args, Field, Option, CommandMeta, MultiVar, Arparma | ||||
| from nepattern import AnyString | ||||
|  | ||||
| alc = Alconna( | ||||
|     "exec", | ||||
|     Args["code", MultiVar(AnyString), Field(completion=lambda: "print(1+1)")] / "\n", | ||||
|     Option("纯文本"), | ||||
|     Option("无输出"), | ||||
|     Option("目标", Args["name", str, "res"]), | ||||
|     meta=CommandMeta("exec python code", example="exec\\nprint(1+1)"), | ||||
| ) | ||||
|  | ||||
| alc.shortcut( | ||||
|     "echo", | ||||
|     {"command": "exec 纯文本\nprint(\\'{*}\\')"}, | ||||
| ) | ||||
|  | ||||
| alc.shortcut( | ||||
|     "sin(\d+)", | ||||
|     {"command": "exec 纯文本\nimport math\nprint(math.sin({0}*math.pi/180))"}, | ||||
| ) | ||||
|  | ||||
|  | ||||
| def exec_code(result: Arparma): | ||||
|     if result.find("纯文本"): | ||||
|         codes = list(result.code) | ||||
|     else: | ||||
|         codes = str(result.origin).split("\n")[1:] | ||||
|     output = result.query[str]("目标.name", "res") | ||||
|     if not codes: | ||||
|         return "" | ||||
|     lcs = {} | ||||
|     _stdout = StringIO() | ||||
|     _to = sys.stdout | ||||
|     sys.stdout = _stdout | ||||
|     try: | ||||
|         exec( | ||||
|             "def rc(__out: str):\n    " | ||||
|             + "    ".join(_code + "\n" for _code in codes) | ||||
|             + "    return locals().get(__out)", | ||||
|             {**globals(), **locals()}, | ||||
|             lcs, | ||||
|         ) | ||||
|         code_res = lcs["rc"](output) | ||||
|         sys.stdout = _to | ||||
|         if result.find("无输出"): | ||||
|             return "" | ||||
|         if code_res is not None: | ||||
|             return f"{output}: {code_res}" | ||||
|         _out = _stdout.getvalue() | ||||
|         return f"输出: {_out}" | ||||
|     except Exception as e: | ||||
|         sys.stdout = _to | ||||
|         return str(e) | ||||
|     finally: | ||||
|         sys.stdout = _to | ||||
|  | ||||
| print(exec_code(alc.parse("echo 1234"))) | ||||
| print(exec_code(alc.parse("sin30"))) | ||||
| print( | ||||
|     exec_code( | ||||
|         alc.parse( | ||||
| """\ | ||||
| exec | ||||
| print( | ||||
|     exec_code( | ||||
|         alc.parse( | ||||
|             "exec\\n" | ||||
|             "import sys;print(sys.version)" | ||||
|         ) | ||||
|     ) | ||||
| ) | ||||
| """ | ||||
|         ) | ||||
|     ) | ||||
| ) | ||||
| ``` | ||||
|  | ||||
| ## 命令编写 | ||||
|  | ||||
| ### 命令头 | ||||
| @@ -115,7 +199,7 @@ alc = Alconna( | ||||
| - `help_text`: 传入该组件的帮助信息 | ||||
| - `dest`: 被指定为解析完成时标注匹配结果的标识符,不传入时默认为选项或子命令的名称 (name) | ||||
| - `requires`: 一段指定顺序的字符串列表,作为唯一的前置序列与命令嵌套替换 | ||||
|   对于命令 `test foo bar baz qux <a:int>` 来讲,因为`foo bar baz` 仅需要判断是否相等, 所以可以这么编写: | ||||
|   对于命令 `test foo bar baz qux <a:int>` 来讲,因为`foo bar baz` 仅需要判断是否相等,所以可以这么编写: | ||||
|  | ||||
|   ```python | ||||
|   Alconna("test", Option("qux", Args["a", int], requires=["foo", "bar", "baz"])) | ||||
| @@ -263,7 +347,7 @@ args = Args["foo", BasePattern("@\d+")] | ||||
|  | ||||
| ### 紧凑命令 | ||||
|  | ||||
| `Alconna`, `Option` 与 `Subcommand` 可以设置 `compact=True` 使得解析命令时允许名称与后随参数之间没有分隔: | ||||
| `Alconna`,`Option` 可以设置 `compact=True` 使得解析命令时允许名称与后随参数之间没有分隔: | ||||
|  | ||||
| ```python | ||||
| from arclet.alconna import Alconna, Option, CommandMeta, Args | ||||
| @@ -390,14 +474,14 @@ class ShortcutArgs(TypedDict): | ||||
|  | ||||
| - `{%X}`: 如 `setu {%0}`,表示此处必须填入快捷指令后随的第 X 个参数。 | ||||
|  | ||||
|   例如,若快捷指令为 `涩图`, 配置为 `{"command": "setu {%0}"}`, 则指令 `涩图 1` 相当于 `setu 1` | ||||
|   例如,若快捷指令为 `涩图`,配置为 `{"command": "setu {%0}"}`,则指令 `涩图 1` 相当于 `setu 1` | ||||
|  | ||||
| - `{*}`: 表示此处填入所有后随参数,并且可以通过 `{*X}` 的方式指定组合参数之间的分隔符。 | ||||
| - `{X}`: 表示此处填入可能的正则匹配的组: | ||||
|   - 若 `command` 中存在匹配组 `(xxx)`,则 `{X}` 表示第 X 个匹配组的内容 | ||||
|   - 若 `command` 中存储匹配组 `(?P<xxx>...)`, 则 `{X}` 表示名字为 X 的匹配结果 | ||||
|   - 若 `command` 中存储匹配组 `(?P<xxx>...)`,则 `{X}` 表示名字为 X 的匹配结果 | ||||
|  | ||||
| 除此之外, 通过内置选项 `--shortcut` 可以动态操作快捷指令。 | ||||
| 除此之外,通过内置选项 `--shortcut` 可以动态操作快捷指令。 | ||||
|  | ||||
| 例如: | ||||
|  | ||||
| @@ -444,17 +528,17 @@ alc.parse("test_fuzy") | ||||
|  | ||||
| `path` 支持如下: | ||||
|  | ||||
| - `main_args`, `options`, ...: 返回对应的属性 | ||||
| - `main_args`,`options`,...: 返回对应的属性 | ||||
| - `args`: 返回 all_matched_args | ||||
| - `main_args.xxx`, `options.xxx`, ...: 返回字典中 `xxx`键对应的值 | ||||
| - `main_args.xxx`,`options.xxx`,...: 返回字典中 `xxx`键对应的值 | ||||
| - `args.xxx`: 返回 all_matched_args 中 `xxx`键对应的值 | ||||
| - `options.foo`, `foo`: 返回选项 `foo` 的解析结果 (OptionResult) | ||||
| - `options.foo.value`, `foo.value`: 返回选项 `foo` 的解析值 | ||||
| - `options.foo.args`, `foo.args`: 返回选项 `foo` 的解析参数字典 | ||||
| - `options.foo.args.bar`, `foo.bar`: 返回选项 `foo` 的参数字典中 `bar` 键对应的值 | ||||
| - `options.foo`,`foo`: 返回选项 `foo` 的解析结果 (OptionResult) | ||||
| - `options.foo.value`,`foo.value`: 返回选项 `foo` 的解析值 | ||||
| - `options.foo.args`,`foo.args`: 返回选项 `foo` 的解析参数字典 | ||||
| - `options.foo.args.bar`,`foo.bar`: 返回选项 `foo` 的参数字典中 `bar` 键对应的值 | ||||
|   ... | ||||
|  | ||||
| 同样, `Arparma["foo.bar"]` 的表现与 `query()` 一致 | ||||
| 同样,`Arparma["foo.bar"]` 的表现与 `query()` 一致 | ||||
|  | ||||
| ## Duplication | ||||
|  | ||||
|   | ||||
| @@ -31,14 +31,7 @@ description: 配置项 | ||||
| - **类型**: `bool` | ||||
| - **默认值**: `False` | ||||
|  | ||||
| 是否全局使用原始消息 (即未经过 to_me 等处理的), 该选项会影响到 Alconna 的匹配行为。 | ||||
|  | ||||
| ## alconna_use_param | ||||
|  | ||||
| - **类型**: `bool` | ||||
| - **默认值**: `True` | ||||
|  | ||||
| 是否使用特制的 Param 提供更好的依赖注入,该选项不会对使用依赖注入函数形式造成影响 | ||||
| 是否全局使用原始消息 (即未经过 to_me 等处理的),该选项会影响到 Alconna 的匹配行为。 | ||||
|  | ||||
| ## alconna_use_command_sep | ||||
|  | ||||
| @@ -52,4 +45,4 @@ description: 配置项 | ||||
| - **类型**: `List[str]` | ||||
| - **默认值**: `[]` | ||||
|  | ||||
| 全局加载的扩展, 路径以 . 分隔, 如 foo.bar.baz:DemoExtension | ||||
| 全局加载的扩展,路径以 . 分隔,如 `foo.bar.baz:DemoExtension` | ||||
|   | ||||
| @@ -9,7 +9,7 @@ description: 响应规则的使用 | ||||
|  | ||||
| ```python | ||||
| from nonebot_plugin_alconna.adapters.onebot12 import Image | ||||
| from nonebot_plugin_alconna import At, AlconnaMatches, on_alconna | ||||
| from nonebot_plugin_alconna import At, on_alconna | ||||
| from arclet.alconna import Args, Option, Alconna, Arparma, MultiVar, Subcommand | ||||
|  | ||||
| alc = Alconna( | ||||
| @@ -27,9 +27,9 @@ rg = on_alconna(alc, auto_send_output=True) | ||||
|  | ||||
|  | ||||
| @rg.handle() | ||||
| async def _(result: Arparma = AlconnaMatches()): | ||||
| async def _(result: Arparma): | ||||
|     if result.find("list"): | ||||
|         img = await gen_role_group_list_image() | ||||
|         img = await ob12_gen_role_group_list_image() | ||||
|         await rg.finish(Image(img)) | ||||
|     if result.find("add"): | ||||
|         group = await create_role_group(result.query[str]("add.name")) | ||||
| @@ -46,10 +46,10 @@ async def _(result: Arparma = AlconnaMatches()): | ||||
| - `command: Alconna | str`: Alconna 命令 | ||||
| - `skip_for_unmatch: bool = True`: 是否在命令不匹配时跳过该响应 | ||||
| - `auto_send_output: bool = False`: 是否自动发送输出信息并跳过响应 | ||||
| - `aliases: set[str | tuple[str, ...]] | None = None`: 命令别名, 作用类似于 `on_command` 中的 aliases | ||||
| - `comp_config: CompConfig | None = None`: 补全会话配置, 不传入则不启用补全会话 | ||||
| - `extensions: list[type[Extension] | Extension] | None = None`: 需要加载的匹配扩展, 可以是扩展类或扩展实例 | ||||
| - `exclude_ext: list[type[Extension] | str] | None = None`: 需要排除的匹配扩展, 可以是扩展类或扩展的id | ||||
| - `aliases: set[str | tuple[str, ...]] | None = None`: 命令别名,作用类似于 `on_command` 中的 aliases | ||||
| - `comp_config: CompConfig | None = None`: 补全会话配置,不传入则不启用补全会话 | ||||
| - `extensions: list[type[Extension] | Extension] | None = None`: 需要加载的匹配扩展,可以是扩展类或扩展实例 | ||||
| - `exclude_ext: list[type[Extension] | str] | None = None`: 需要排除的匹配扩展,可以是扩展类或扩展的 id | ||||
| - `use_origin: bool = False`: 是否使用未经 to_me 等处理过的消息 | ||||
| - `use_cmd_start: bool = False`: 是否使用 COMMAND_START 作为命令前缀 | ||||
| - `use_cmd_sep: bool = False`: 是否使用 COMMAND_SEP 作为命令分隔符 | ||||
| @@ -67,7 +67,7 @@ async def _(result: Arparma = AlconnaMatches()): | ||||
|  | ||||
| ```python | ||||
| from arclet.alconna import Alconna, Option, Args | ||||
| from nonebot_plugin_alconna import on_alconna, AlconnaMatch, Match, AlconnaMatcher, AlconnaArg, UniMessage | ||||
| from nonebot_plugin_alconna import on_alconna, AlconnaMatch, Match, UniMessage | ||||
|  | ||||
| login = on_alconna(Alconna(["/"], "login", Args["password?", str], Option("-r|--recall"))) | ||||
|  | ||||
| @@ -76,11 +76,12 @@ async def login_exit(): | ||||
|     await login.finish("已退出") | ||||
|  | ||||
| @login.assign("password") | ||||
| async def login_handle(matcher: AlconnaMatcher, pw: Match[str] = AlconnaMatch("password")): | ||||
|     matcher.set_path_arg("password", pw.result) | ||||
| async def login_handle(pw: Match[str] = AlconnaMatch("password")): | ||||
|     if pw.available: | ||||
|         login.set_path_arg("password", pw.result) | ||||
|  | ||||
| @login.got_path("password", prompt=UniMessage.template("{:At(user, $event.get_user_id())} 请输入密码")) | ||||
| async def login_got(password: str = AlconnaArg("password")): | ||||
| async def login_got(password: str): | ||||
|     assert password | ||||
|     await login.send("登录成功") | ||||
| ``` | ||||
| @@ -89,50 +90,14 @@ async def login_got(password: str = AlconnaArg("password")): | ||||
|  | ||||
| `Alconna` 的解析结果会放入 `Arparma` 类中,或用户指定的 `Duplication` 类。 | ||||
|  | ||||
| `nonebot_plugin_alconna` 提供了一系列的依赖注入函数,他们包括: | ||||
|  | ||||
| - `AlconnaResult`: `CommandResult` 类型的依赖注入函数 | ||||
| - `AlconnaMatches`: `Arparma` 类型的依赖注入函数 | ||||
| - `AlconnaDuplication`: `Duplication` 类型的依赖注入函数 | ||||
| - `AlconnaMatch`: `Match` 类型的依赖注入函数,其能够额外传入一个 middleware 函数来处理得到的参数 | ||||
| - `AlconnaQuery`: `Query` 类型的依赖注入函数,其能够额外传入一个 middleware 函数来处理得到的参数 | ||||
| - `AlconnaExecResult`: 提供挂载在命令上的 callback 的返回结果 (`Dict[str, Any]`) 的依赖注入函数 | ||||
| - `AlconnaExtension`: 提供指定类型的 `Extension` 的依赖注入函数 | ||||
|  | ||||
| 可以看到,本插件提供了几类额外的模型: | ||||
|  | ||||
| - `CommandResult`: 解析结果,包括了源命令 `source: Alconna` ,解析结果 `result: Arparma`,以及可能的输出信息 `output: str | None` 字段 | ||||
| - `Match`: 匹配项,表示参数是否存在于 `all_matched_args` 内,可用 `Match.available` 判断是否匹配,`Match.result` 获取匹配的值 | ||||
| - `Query`: 查询项,表示参数是否可由 `Arparma.query` 查询并获得结果,可用 `Query.available` 判断是否查询成功,`Query.result` 获取查询结果 | ||||
|  | ||||
| 同时,基于 [`Annotated` 支持](https://github.com/nonebot/nonebot2/pull/1832), 添加了三类注解: | ||||
|  | ||||
| - `AlcMatches`:同 `AlconnaMatches` | ||||
| - `AlcResult`:同 `AlconnaResult` | ||||
| - `AlcExecResult`: 同 `AlconnaExecResult` | ||||
|  | ||||
| 而若设置配置项 **ALCONNA_USE_PARAM** (默认为 True) 为 True,则上述依赖注入的目标参数皆不需要使用依赖注入函数: | ||||
| 而 `AlconnaMatcher` 在原有 Matcher 的基础上拓展了允许的依赖注入: | ||||
|  | ||||
| ```python | ||||
| ... | ||||
| @cmd.handle() | ||||
| async def handle1( | ||||
|     result: CommandResult = AlconnaResult(), | ||||
|     arp: Arparma = AlconnaMatches(), | ||||
|     dup: Duplication = AlconnaDuplication(Duplication), | ||||
|     ext: Extension = AlconnaExtension(Extension), | ||||
|     foo: Match[str] = AlconnaMatch("foo"), | ||||
|     bar: Query[int] = AlconnaQuery("ttt.bar", 0) | ||||
| ): | ||||
|     ... | ||||
|  | ||||
| # ALCONNA_USE_PARAM 为 True 后 | ||||
|  | ||||
| @cmd.handle() | ||||
| async def handle2( | ||||
| async def handle( | ||||
|     result: CommandResult, | ||||
|     arp: Arparma, | ||||
|     dup: Duplication, | ||||
|     dup: Duplication,  # 基类或子类都可以 | ||||
|     ext: Extension, | ||||
|     source: Alconna, | ||||
|     abc: str,  # 类似 Match, 但是若匹配结果不存在对应字段则跳过该 handler | ||||
| @@ -142,7 +107,25 @@ async def handle2( | ||||
|     ... | ||||
| ``` | ||||
|  | ||||
| 该效果对于 `got_path` 下的 Arg 同样有效 | ||||
| 可以看到,本插件提供了几类额外的模型: | ||||
|  | ||||
| - `CommandResult`: 解析结果,包括了源命令 `source: Alconna` ,解析结果 `result: Arparma`,以及可能的输出信息 `output: str | None` 字段 | ||||
| - `Match`: 匹配项,表示参数是否存在于 `all_matched_args` 内,可用 `Match.available` 判断是否匹配,`Match.result` 获取匹配的值 | ||||
| - `Query`: 查询项,表示参数是否可由 `Arparma.query` 查询并获得结果,可用 `Query.available` 判断是否查询成功,`Query.result` 获取查询结果 | ||||
|  | ||||
| :::note | ||||
|  | ||||
| 如果你更喜欢 Depends 式的依赖注入,`nonebot_plugin_alconna` 同时提供了一系列的依赖注入函数,他们包括: | ||||
|  | ||||
| - `AlconnaResult`: `CommandResult` 类型的依赖注入函数 | ||||
| - `AlconnaMatches`: `Arparma` 类型的依赖注入函数 | ||||
| - `AlconnaDuplication`: `Duplication` 类型的依赖注入函数 | ||||
| - `AlconnaMatch`: `Match` 类型的依赖注入函数,其能够额外传入一个 middleware 函数来处理得到的参数 | ||||
| - `AlconnaQuery`: `Query` 类型的依赖注入函数,其能够额外传入一个 middleware 函数来处理得到的参数 | ||||
| - `AlconnaExecResult`: 提供挂载在命令上的 callback 的返回结果 (`Dict[str, Any]`) 的依赖注入函数 | ||||
| - `AlconnaExtension`: 提供指定类型的 `Extension` 的依赖注入函数 | ||||
|  | ||||
| ::: | ||||
|  | ||||
| 实例: | ||||
|  | ||||
| @@ -152,13 +135,7 @@ from nonebot import require | ||||
| require("nonebot_plugin_alconna") | ||||
| ... | ||||
|  | ||||
| from nonebot_plugin_alconna import ( | ||||
|     on_alconna, | ||||
|     Match, | ||||
|     Query, | ||||
|     AlconnaQuery, | ||||
|     AlcResult | ||||
| ) | ||||
| from nonebot_plugin_alconna import on_alconna, Match, Query, AlconnaQuery | ||||
| from arclet.alconna import Alconna, Args, Option, Arparma | ||||
|  | ||||
| test = on_alconna( | ||||
| @@ -177,17 +154,12 @@ async def handle_test1(result: AlcResult): | ||||
|     await test.send(f"maybe output: {result.output}") | ||||
|  | ||||
| @test.handle() | ||||
| async def handle_test2(result: Arparma): | ||||
|     await test.send(f"head result: {result.header_result}") | ||||
|     await test.send(f"args: {result.all_matched_args}") | ||||
|  | ||||
| @test.handle() | ||||
| async def handle_test3(bar: Match[int]): | ||||
| async def handle_test2(bar: Match[int]): | ||||
|     if bar.available: | ||||
|         await test.send(f"foo={bar.result}") | ||||
|  | ||||
| @test.handle() | ||||
| async def handle_test4(qux: Query[bool] = AlconnaQuery("baz.qux", False)): | ||||
| async def handle_test3(qux: Query[bool] = AlconnaQuery("baz.qux", False)): | ||||
|     if qux.available: | ||||
|         await test.send(f"baz.qux={qux.result}") | ||||
| ``` | ||||
| @@ -220,7 +192,7 @@ group.extend(member.target for member in ats) | ||||
| | [飞书](https://github.com/nonebot/adapter-feishu)                   | adapters.feishu                      | | ||||
| | [GitHub](https://github.com/nonebot/adapter-github)                 | adapters.github                      | | ||||
| | [QQ bot](https://github.com/nonebot/adapter-qq)                     | adapters.qq                          | | ||||
| | [QQ 频道bot](https://github.com/nonebot/adapter-qq)                 | adapters.qqguild                     | | ||||
| | [QQ 频道 bot](https://github.com/nonebot/adapter-qq)                | adapters.qqguild                     | | ||||
| | [钉钉](https://github.com/nonebot/adapter-ding)                     | adapters.ding                        | | ||||
| | [Console](https://github.com/nonebot/adapter-console)               | adapters.console                     | | ||||
| | [开黑啦](https://github.com/Tian-que/nonebot-adapter-kaiheila)      | adapters.kook                        | | ||||
| @@ -232,6 +204,7 @@ group.extend(member.target for member in ats) | ||||
| | [Villa](https://github.com/CMHopeSunshine/nonebot-adapter-villa)    | adapters.villa                       | | ||||
| | [Discord](https://github.com/nonebot/adapter-discord)               | adapters.discord                     | | ||||
| | [Red 协议](https://github.com/nonebot/adapter-red)                  | adapters.red                         | | ||||
| | [Satori 协议](https://github.com/nonebot/adapter-satori)            | adapters.satori                      | | ||||
|  | ||||
| ## 条件控制 | ||||
|  | ||||
| @@ -258,6 +231,7 @@ pip = Alconna( | ||||
|  | ||||
| pip_cmd = on_alconna(pip) | ||||
|  | ||||
| # 仅在命令为 `pip install pip` 时响应 | ||||
| @pip_cmd.assign("install.pak", "pip") | ||||
| async def update(res: CommandResult): | ||||
|     ... | ||||
| @@ -267,7 +241,7 @@ async def update(res: CommandResult): | ||||
| async def list_(res: CommandResult): | ||||
|     ... | ||||
|  | ||||
| # 仅在命令为 `pip install` 时响应 | ||||
| # 在命令为 `pip install xxx` 时响应 | ||||
| @pip_cmd.assign("install") | ||||
| async def install(res: CommandResult): | ||||
|     ... | ||||
| @@ -279,28 +253,28 @@ async def install(res: CommandResult): | ||||
| update_cmd = pip_cmd.dispatch("install.pak", "pip") | ||||
|  | ||||
| @update_cmd.handle() | ||||
| async def update(arp: CommandResult = AlconnaResult()): | ||||
| async def update(arp: CommandResult): | ||||
|     ... | ||||
| ``` | ||||
|  | ||||
| 另外,`AlconnaMatcher` 有类似于 `got` 的 `got_path`: | ||||
|  | ||||
| ```python | ||||
| from nonebot_plugin_alconna import At, Match, UniMessage, AlconnaMatcher, on_alconna | ||||
| from nonebot_plugin_alconna import At, Match, UniMessage, on_alconna | ||||
|  | ||||
| test_cmd = on_alconna(Alconna("test", Args["target?", Union[str, At]])) | ||||
|  | ||||
| @test_cmd.handle() | ||||
| async def tt_h(matcher: AlconnaMatcher, target: Match[Union[str, At]]): | ||||
| async def tt_h(target: Match[Union[str, At]]): | ||||
|     if target.available: | ||||
|         matcher.set_path_arg("target", target.result) | ||||
|         test_cmd.set_path_arg("target", target.result) | ||||
|  | ||||
| @test_cmd.got_path("target", prompt="请输入目标") | ||||
| async def tt(target: Union[str, At]): | ||||
|     await test_cmd.send(UniMessage(["ok\n", target])) | ||||
| ``` | ||||
|  | ||||
| `got_path` 与 `assign`, `Match`, `Query` 等地方一样,都需要指明 `path` 参数 (即对应 Arg 验证的路径) | ||||
| `got_path` 与 `assign`,`Match`,`Query` 等地方一样,都需要指明 `path` 参数 (即对应 Arg 验证的路径) | ||||
|  | ||||
| `got_path` 会获取消息的最后一个消息段并转为 path 对应的类型,例如示例中 `target` 对应的 Arg 里要求 str 或 At,则 got 后用户输入的消息只有为 text 或 at 才能进入处理函数。 | ||||
|  | ||||
| @@ -338,7 +312,7 @@ async def tt(target: Union[str, At]): | ||||
| 例如 `LLMExtension` (仅举例): | ||||
|  | ||||
| ```python | ||||
| from nonebot_plugin_alconna import Extension, Alconna, on_alconna | ||||
| from nonebot_plugin_alconna import Extension, Alconna, on_alconna, Interface | ||||
|  | ||||
| class LLMExtension(Extension): | ||||
|     @property | ||||
| @@ -359,6 +333,13 @@ class LLMExtension(Extension): | ||||
|         resp = await self.llm.input(str(receive)) | ||||
|         return receive.__class__(resp.content) | ||||
|  | ||||
|     def before_catch(self, name, annotation, default): | ||||
|         return name == "llm" | ||||
|  | ||||
|     def catch(self, interface: Interface): | ||||
|         if interface.name == "llm": | ||||
|             return self.llm | ||||
|  | ||||
| matcher = on_alconna( | ||||
|     Alconna(...), | ||||
|     extensions=[LLMExtension(LLM)] | ||||
| @@ -366,20 +347,22 @@ matcher = on_alconna( | ||||
| ... | ||||
| ``` | ||||
|  | ||||
| 那么使用了 `LLMExtension` 的响应器便能接受任何能通过 llm 翻译为具体命令的自然语言消息。 | ||||
| 那么使用了 `LLMExtension` 的响应器便能接受任何能通过 llm 翻译为具体命令的自然语言消息,同时可以在响应器中为所有 `llm` 参数注入模型变量 | ||||
|  | ||||
| 目前 `Extension` 的功能有: | ||||
|  | ||||
| - 对于事件的来源适配器或 bot 选择是否接受响应 | ||||
| - 输出信息的自定义转换方法 | ||||
| - 从传入事件中自定义提取消息的方法 | ||||
| - 对于传入的alc对象的追加的自定义处理 | ||||
| - 对传入的消息 (Message 或 UniMessage) 的额外处理 | ||||
| - 对命令解析结果的额外处理 | ||||
| - 对发送的消息 (Message 或 UniMessage) 的额外处理 | ||||
| - 自定义额外的matcher api | ||||
| - `validate`: 对于事件的来源适配器或 bot 选择是否接受响应 | ||||
| - `output_converter`: 输出信息的自定义转换方法 | ||||
| - `message_provider`: 从传入事件中自定义提取消息的方法 | ||||
| - `receive_provider`: 对传入的消息 (Message 或 UniMessage) 的额外处理 | ||||
| - `permission_check`: 命令对消息解析并确认头部匹配(即确认选择响应)时对发送者的权限判断 | ||||
| - `parse_wrapper`: 对命令解析结果的额外处理 | ||||
| - `send_wrapper`: 对发送的消息 (Message 或 UniMessage) 的额外处理 | ||||
| - `before_catch`: 自定义依赖注入的绑定确认函数 | ||||
| - `catch`: 自定义依赖注入处理函数 | ||||
| - `post_init`: 响应器创建后对命令对象的额外除了 | ||||
|  | ||||
| 例如内置的 `DiscordSlashExtension`,其可自动将 Alconna 对象翻译成 slash指令并注册,且将收到的指令交互事件转为指令供命令解析: | ||||
| 例如内置的 `DiscordSlashExtension`,其可自动将 Alconna 对象翻译成 slash 指令并注册,且将收到的指令交互事件转为指令供命令解析: | ||||
|  | ||||
| ```python | ||||
| from nonebot_plugin_alconna import Match, on_alconna | ||||
| @@ -404,3 +387,9 @@ async def add(plugin: Match[str], priority: Match[int]): | ||||
| async def remove(plugin: Match[str], time: Match[int]): | ||||
|     await matcher.finish(f"removed {plugin.result} with {time.result if time.available else -1}") | ||||
| ``` | ||||
|  | ||||
| :::tip | ||||
|  | ||||
| 全局的 Extension 可延迟加载 (即若有全局拓展加载于部分 AlconnaMatcher 之后,这部分响应器会被追加拓展) | ||||
|  | ||||
| ::: | ||||
|   | ||||
| @@ -3,6 +3,9 @@ sidebar_position: 5 | ||||
| description: 通用消息组件 | ||||
| --- | ||||
| 
 | ||||
| import Tabs from "@theme/Tabs"; | ||||
| import TabItem from "@theme/TabItem"; | ||||
| 
 | ||||
| # 通用消息组件 | ||||
| 
 | ||||
| `uniseg` 模块属于 `nonebot-plugin-alconna` 的子插件,其提供了一套通用的消息组件,用于在 `nonebot-plugin-alconna` 下构建通用消息。 | ||||
| @@ -58,9 +61,16 @@ class File(Segment): | ||||
| 
 | ||||
| class Reply(Segment): | ||||
|     """Reply对象,表示一类回复消息""" | ||||
|     origin: Any | ||||
|     id: str | ||||
|     """此处不一定是消息ID,可能是其他ID,如消息序号等""" | ||||
|     msg: Optional[Union[Message, str]] | ||||
|     origin: Optional[Any] | ||||
| 
 | ||||
| class Reference(Segment): | ||||
|     """Reference对象,表示一类引用消息。转发消息 (Forward) 也属于此类""" | ||||
|     id: Optional[str] | ||||
|     """此处不一定是消息ID,可能是其他ID,如消息序号等""" | ||||
|     content: Optional[Union[Message, str, List[Union[RefNode, CustomNode]]]] | ||||
| 
 | ||||
| class Card(Segment): | ||||
| 	type: Literal["xml", "json"] | ||||
| @@ -76,7 +86,12 @@ class Other(Segment): | ||||
| 
 | ||||
| `nonebot-plugin-alconna.uniseg` 同时提供了一个类似于 `Message` 的 `UniMessage` 类型,其元素为经过通用标注转换后的通用消息段。 | ||||
| 
 | ||||
| 你可以通过提供的 `UniversalMessage` 或 `UniMsg` 依赖注入器来获取 `UniMessage`。 | ||||
| 你可以用如下方式获取 `UniMessage` : | ||||
| 
 | ||||
| <Tabs groupId="get_unimsg"> | ||||
| <TabItem value="depend" label="使用依赖注入"> | ||||
| 
 | ||||
| 通过提供的 `UniversalMessage` 或 `UniMsg` 依赖注入器来获取 `UniMessage`。 | ||||
| 
 | ||||
| ```python | ||||
| from nonebot_plugin_alconna.uniseg import UniMsg, At, Reply | ||||
| @@ -93,9 +108,28 @@ async def _(msg: UniMsg): | ||||
|     ... | ||||
| ``` | ||||
| 
 | ||||
| 不仅如此,你还可以通过 `UniMessage` 的 `export` 方法来**跨平台发送消息**。 | ||||
| </TabItem> | ||||
| <TabItem value="method" label="使用 UniMessage.generate"> | ||||
| 
 | ||||
| `UniMessage.export` 会通过传入的 `bot: Bot` 参数读取适配器信息,并使用对应的生成方法把通用消息转为适配器对应的消息序列: | ||||
| 注意,`generate` 方法在响应器以外的地方如果不传入 `event` 与 `bot` 则无法处理 reply。 | ||||
| 
 | ||||
| ```python | ||||
| from nonebot import Message, EventMessage | ||||
| from nonebot_plugin_alconna.uniseg import UniMessage | ||||
| 
 | ||||
| matcher = on_xxx(...) | ||||
| 
 | ||||
| @matcher.handle() | ||||
| async def _(message: Message = EventMessage()): | ||||
|     msg = await UniMessage.generate(message=message) | ||||
| ``` | ||||
| 
 | ||||
| </TabItem> | ||||
| </Tabs> | ||||
| 
 | ||||
| 不仅如此,你还可以通过 `UniMessage` 的 `export` 与 `send` 方法来**跨平台发送消息**。 | ||||
| 
 | ||||
| `UniMessage.export` 会通过传入的 `bot: Bot` 参数,或上下文中的 `Bot` 对象读取适配器信息,并使用对应的生成方法把通用消息转为适配器对应的消息序列 | ||||
| 
 | ||||
| ```python | ||||
| from nonebot import Bot, on_command | ||||
| @@ -104,8 +138,8 @@ from nonebot_plugin_alconna.uniseg import Image, UniMessage | ||||
| test = on_command("test") | ||||
| 
 | ||||
| @test.handle() | ||||
| async def handle_test(bot: Bot): | ||||
|     await test.send(await UniMessage(Image(path="path/to/img")).export(bot)) | ||||
| async def handle_test(): | ||||
|     await test.send(await UniMessage(Image(path="path/to/img")).export()) | ||||
| ``` | ||||
| 
 | ||||
| 而在 `AlconnaMatcher` 下,`got`, `send`, `reject` 等可以发送消息的方法皆支持使用 `UniMessage`,不需要手动调用 export 方法: | ||||
| @@ -127,6 +161,49 @@ async def tt(target: At): | ||||
|     await test_cmd.send(UniMessage([target, "\ndone."])) | ||||
| ``` | ||||
| 
 | ||||
| 除此之外 `UniMessage.send` 方法基于 `UniMessage.export` 并调用各适配器下的发送消息方法,返回一个 `Receipt` 对象,用于修改/撤回消息: | ||||
| 
 | ||||
| ```python | ||||
| from nonebot import Bot, on_command | ||||
| from nonebot_plugin_alconna.uniseg import UniMessage | ||||
| 
 | ||||
| test = on_command("test") | ||||
| 
 | ||||
| @test.handle() | ||||
| async def handle(): | ||||
|     receipt = await UniMessage.text("hello!").send(at_sender=True, reply_to=True) | ||||
|     await receipt.recall(delay=1) | ||||
| ``` | ||||
| 
 | ||||
| :::caution | ||||
| 
 | ||||
| 在响应器以外的地方,`bot` 参数必须手动传入。 | ||||
| 
 | ||||
| ::: | ||||
| 
 | ||||
| ### 构造 | ||||
| 
 | ||||
| 如同 `Message`, `UniMessage` 可以传入单个字符串/消息段,或可迭代的字符串/消息段: | ||||
| 
 | ||||
| ```python | ||||
| from nonebot_plugin_alconna.uniseg import UniMessage, At | ||||
| 
 | ||||
| msg = UniMessage("Hello") | ||||
| msg1 = UniMessage(At("user", "124")) | ||||
| msg2 = UniMessage(["Hello", At("user", "124")]) | ||||
| ``` | ||||
| 
 | ||||
| `UniMessage` 上同时存在便捷方法,令其可以链式地添加消息段: | ||||
| 
 | ||||
| ```python | ||||
| from nonebot_plugin_alconna.uniseg import UniMessage, At, Image | ||||
| 
 | ||||
| msg = UniMessage.text("Hello").at("124").image(path="/path/to/img") | ||||
| assert msg == UniMessage( | ||||
|     ["Hello", At("user", "124"), Image(path="/path/to/img")] | ||||
| ) | ||||
| ``` | ||||
| 
 | ||||
| ### 获取消息纯文本 | ||||
| 
 | ||||
| 类似于 `Message.extract_plain_text()`,用于获取通用消息的纯文本。 | ||||
| @@ -277,7 +354,7 @@ UniMessage(At("user", "123")) | ||||
| 
 | ||||
| 而在 `AlconnaMatcher` 中,{:XXX} 更进一步地提供了获取 `event` 和 `bot` 中的属性的功能 | ||||
| 
 | ||||
| ```python title=在 AlconnaMatcher 中使用通用消息段的拓展控制符 | ||||
| ```python title=在AlconnaMatcher中使用通用消息段的拓展控制符 | ||||
| from arclet.alconna import Alconna, Args | ||||
| from nonebot_plugin_alconna import At, Match, UniMessage, AlconnaMatcher, on_alconna | ||||
| 
 | ||||
| @@ -297,3 +374,57 @@ async def tt(): | ||||
|       UniMessage.template("{:At(user, $event.get_user_id())} 已确认目标为 {target}") | ||||
|     ) | ||||
| ``` | ||||
| 
 | ||||
| 另外也有 `$message_id` 与 `$target` 两个特殊值。 | ||||
| 
 | ||||
| ## 消息发送 | ||||
| 
 | ||||
| 前面提到,通用消息可用 `UniMessage.send` 发送自身: | ||||
| 
 | ||||
| ```python | ||||
| async def send( | ||||
|     self, | ||||
|     target: Union[Event, Target, None] = None, | ||||
|     bot: Optional[Bot] = None, | ||||
|     fallback: bool = True, | ||||
|     at_sender: Union[str, bool] = False, | ||||
|     reply_to: Union[str, bool] = False, | ||||
| ) -> Receipt: | ||||
| ``` | ||||
| 
 | ||||
| 实际上,`UniMessage` 同时提供了获取消息事件 id 与消息发送对象的方法: | ||||
| 
 | ||||
| ```python | ||||
| from nonebot import Event, Bot | ||||
| from nonebot_plugin_alconna.uniseg import UniMessage, Target | ||||
| 
 | ||||
| matcher = on_xxx(...) | ||||
| 
 | ||||
| @matcher.handle() | ||||
| asycn def _(bot: Bot, event: Event): | ||||
|     target: Target = UniMessage.get_target(event, bot) | ||||
|     msg_id: str = UniMessage.get_message_id(event, bot) | ||||
| 
 | ||||
| ``` | ||||
| 
 | ||||
| `send`, `get_target`, `get_message_id` 中与 `event`, `bot` 相关的参数都会尝试从上下文中获取对象。 | ||||
| 
 | ||||
| 其中,`Target`: | ||||
| 
 | ||||
| ```python | ||||
| class Target: | ||||
|     id: str | ||||
|     """目标id;若为群聊则为group_id或者channel_id,若为私聊则为user_id""" | ||||
|     parent_id: str = "" | ||||
|     """父级id;若为频道则为guild_id,其他情况为空字符串""" | ||||
|     channel: bool = False | ||||
|     """是否为频道,仅当目标平台同时支持群聊和频道时有效""" | ||||
|     private: bool = False | ||||
|     """是否为私聊""" | ||||
|     source: str = "" | ||||
|     """可能的事件id""" | ||||
| ``` | ||||
| 
 | ||||
| 是用来描述响应消息时的发送对象。 | ||||
| 
 | ||||
| 同样的,你可以通过依赖注入的方式在响应器中直接获取它们。 | ||||
| @@ -7,7 +7,7 @@ description: 杂项 | ||||
|  | ||||
| ## 特殊装饰器 | ||||
|  | ||||
| `nonebot_plugin_alconna` 提供 了一个 `funcommand` 装饰器, 其用于将一个接受任意参数, | ||||
| `nonebot_plugin_alconna` 提供 了一个 `funcommand` 装饰器,其用于将一个接受任意参数, | ||||
| 返回 `str` 或 `Message` 或 `MessageSegment` 的函数转换为命令响应器。 | ||||
|  | ||||
| ```python | ||||
|   | ||||
		Reference in New Issue
	
	Block a user