### Define Pip Command with Alconna Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md This example demonstrates creating a command parser for 'pip install' with arguments and options using Alconna's core components. ```python from arclet.alconna import Alconna, Args, Subcommand, Option alc = Alconna( "pip", Subcommand( "install", Args["package", str], Option("-r|--requirement", Args["file", str]), Option("-i|--index-url", Args["url", str]), ) ) res = alc.parse("pip install nonebot2 -i URL") print(res) # matched=True, header_match=(origin='pip' result='pip' matched=True groups={}), subcommands={'install': (value=Ellipsis args={'package': 'nonebot2'} options={'index-url': (value=None args={'url': 'URL'})} subcommands={})}, other_args={'package': 'nonebot2', 'url': 'URL'} print(res.all_matched_args) # {'package': 'nonebot2', 'url': 'URL'} ``` -------------------------------- ### Full Import Example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/exports.md Demonstrates how to import all symbols from the nonebot_plugin_alconna library. ```python from nonebot_plugin_alconna import * ``` -------------------------------- ### Assign Method Example Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates the use of the `.assign()` method for handling different command branches based on options or subcommands. This example shows conditional logic for login commands. ```python from nonebot import require require("nonebot_plugin_alconna") from arclet.alconna import Alconna, Option, Args from nonebot_plugin_alconna import on_alconna, AlconnaMatch, Match, UniMessage login = on_alconna(Alconna(["/"], "login", Args["password?", str], Option("-r|--recall"))) # 这里["/"]指命令前缀必须是/ @login.assign("recall") # /login -r async def login_exit(): await login.finish("已退出") @login.assign("password") # /login xxx def login_handle(pw: Match[str] = AlconnaMatch("password")): if pw.available: login.set_path_arg("password", pw.result) ``` -------------------------------- ### Submodule Import Example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/exports.md Illustrates how to import specific submodules from the nonebot_plugin_alconna library. ```python # 导入特定子模块 from nonebot_plugin_alconna import uniseg from nonebot_plugin_alconna import matcher from nonebot_plugin_alconna import params ``` -------------------------------- ### Install Nonebot Plugin Alconna Source: https://github.com/nonebot/plugin-alconna/blob/master/intro.md Install the plugin using pip or nb plugin command. ```shell pip install nonebot-plugin-alconna ``` ```shell nb plugin install nonebot-plugin-alconna ``` -------------------------------- ### Selective Import Example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/exports.md Shows how to import only specific, needed symbols from the nonebot_plugin_alconna library. ```python # 只导入需要的 from nonebot_plugin_alconna import ( on_alconna, UniMessage, Command, ) ``` -------------------------------- ### AlconnaMatcher got() method example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Obtains user input for a specific state key. A prompt message and an argument parser can be provided. ```python from nonebot_plugin_alconna import UniMessage matcher = on_alconna("ask") @matcher.got("name", prompt=UniMessage.text("请输入你的名字")) async def handle_got_name(state: T_State): name = state["name"] await matcher.send(f"你的名字是 {name}") ``` -------------------------------- ### Alconna Default Dependency Injection Example Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates default dependency injection for Alconna's parsing results and matched arguments. This works for standard arguments and `AlconnaMatcher.got_path`. ```python async def handle( result: CommandResult, arp: Arparma, dup: Duplication, source: Alconna, abc: str, # 类似 Match, 但是若匹配结果不存在对应字段则跳过该 handler foo: Match[str], bar: Query[int] = Query("ttt.bar", 0) # Query 仍然需要一个默认值来传递 path 参数 ): ... ``` -------------------------------- ### Simplest Command Example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/INDEX.md This snippet demonstrates how to create the simplest command using `on_alconna`. It registers a command named 'test' and defines a handler to send a confirmation message when the command is received. ```python from nonebot_plugin_alconna import on_alconna test = on_alconna("test") @test.handle() async def handler(): await test.send("收到 test 命令") ``` -------------------------------- ### AlconnaMatcher receive() method example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Receives user interaction on a specific slot. The slot ID can be specified. ```python @matcher.receive("action") async def handle_action(state: T_State): action = state["action"] pass ``` -------------------------------- ### get_bot() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Retrieves a Bot instance. You can specify an adapter name to get a specific Bot, or leave it blank to get the first available Bot. ```APIDOC ## get_bot() ### Description Retrieves a Bot instance. You can specify an adapter name to get a specific Bot, or leave it blank to get the first available Bot. ### Parameters - adapter (str | None): The name of the adapter (if None, returns the first Bot). ### Returns - Bot: The Bot instance. ### Usage Example ```python from nonebot_plugin_alconna import get_bot # Get any Bot bot = get_bot() # Get a specific adapter's Bot onebot_bot = get_bot("onebot11") ``` ``` -------------------------------- ### Dispatch Method Example Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Illustrates the use of the `.dispatch()` method to create separate matchers for subcommands. This allows for distinct handling logic for different parts of a command group. ```python update_cmd = pip_cmd.dispatch("install.pak", "pip") @update_cmd.handle() async def update(arp: CommandResult = AlconnaResult()): ... ``` -------------------------------- ### AlconnaMatcher reject() method example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Rejects the current request and prompts the user for input again. This is useful for re-prompting when input is invalid. ```python @matcher.got("value", prompt="输入一个数字") async def handle_input(state: T_State): try: num = int(state["value"]) except ValueError: await matcher.reject("请输入有效的数字") ``` -------------------------------- ### Get Bot Instance Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Retrieves a Bot instance. Can fetch any available Bot or a specific one by adapter name. ```python from nonebot_plugin_alconna import get_bot # 获取任意 Bot bot = get_bot() # 获取特定适配器的 Bot onebot_bot = get_bot("onebot11") ``` -------------------------------- ### AlconnaMatcher shortcut() method example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Adds a shortcut trigger for a command. This allows users to invoke commands with shorter aliases or with pre-defined arguments. ```python matcher = on_alconna("test ") matcher.shortcut("t", command="test", arguments=["run"]) # 现在输入 "t" 等同于 "test run" ``` -------------------------------- ### Alconna Depends-Style Dependency Injection Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how to use Alconna's dependency injection functions, similar to Depends, for various parsing results and callbacks. Includes examples for `AlconnaMatch` and `Query` with middleware. ```python from nonebot import require require("nonebot_plugin_alconna") from nonebot_plugin_alconna import ( on_alconna, Match, Query, AlconnaMatch, AlcResult ) from arclet.alconna import Alconna, Args, Option, Arparma test = on_alconna( Alconna( "test", Option("foo", Args["bar", int]), Option("baz", Args["qux", bool, False]) ), auto_send_output=True ) @test.handle() async def handle_test1(result: AlcResult): await test.send(f"matched: {result.matched}") 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] = AlconnaMatch("bar")): if bar.available: await test.send(f"foo={bar.result}") @test.handle() async def handle_test4(qux: Query[bool] = Query("baz.qux", False)): if qux.available: await test.send(f"baz.qux={qux.result}") ``` -------------------------------- ### AlconnaMatcher send() method examples Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Sends a message to the user. Supports plain text, UniMessage, and fallback strategies. The `at_sender` and `reply_to` options can be used to customize the message. ```python from nonebot_plugin_alconna import UniMessage @matcher.handle() async def handler(): # 发送纯文本 await matcher.send("Hello") # 发送 UniMessage msg = UniMessage.text("消息").image(path="test.png") receipt = await matcher.send(msg) # 使用降级策略 from nonebot_plugin_alconna import FallbackStrategy await matcher.send(msg, fallback=FallbackStrategy.text) ``` -------------------------------- ### AlconnaMatcher handle() method example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Adds an event handler function to the matcher. Usage is identical to the base Matcher's handle() method. ```python matcher = on_alconna("test") @matcher.handle() async def handle_test(): await matcher.send("响应") ``` -------------------------------- ### Define and Handle Alconna Commands Source: https://github.com/nonebot/plugin-alconna/blob/master/intro.md Define an Alconna command with subcommands and options, then handle the parsed results using on_alconna and AlconnaMatches. This example demonstrates handling 'list' and 'add' subcommands, including image attachments and member mentions. ```python from nonebot.adapters.onebot.v12 import Message from nonebot_plugin_alconna import on_alconna, AlconnaMatches, At from nonebot_plugin_alconna.adapters.onebot12 import Image from arclet.alconna import Alconna, Args, Option, Arparma, Subcommand, MultiVar alc = Alconna( "role-group", Subcommand( "add", Args["name", str], Option("member", Args["target", MultiVar(At)]), ), Option("list"), ) rg = on_alconna(alc, auto_send_output=True) @rg.handle() async def _(result: Arparma = AlconnaMatches()): if result.find("list"): img = await gen_role_group_list_image() await rg.finish(Message([Image(img)])) if result.find("add"): group = await create_role_group(result["add.name"]) if result.find("add.member"): ats: tuple[At] = result["add.member.target"] group.extend(member.target for member in ats) await rg.finish("添加成功") ``` -------------------------------- ### Basic Alconna Command Registration Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Register a basic Alconna command with a handler. This example shows how to define a command that responds to 'Hello!' and optionally processes an '@' mention. ```python from nonebot.adapters.onebot.v12 import Message from nonebot_plugin_alconna import on_alconna, AlconnaMatches, At from nonebot_plugin_alconna.adapters.onebot12 import Image from arclet.alconna import Alconna, Args, Option, Arparma alc = Alconna("Hello!", Option("--spec", Args["target", At])) hello = on_alconna(alc, auto_send_output=True) @hello.handle() async def _(result: Arparma = AlconnaMatches()): if result.find("spec"): target = result.query[At]("spec.target") seed = target.target await hello.finish(Message(Image(await gen_image(seed)))) else: await hello.finish("Hello!") ``` -------------------------------- ### Getting Specific Message Segments Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how to use the 'get' method to retrieve a specified number of segments of a particular type from the message sequence. ```python # 获取指定类型指定个数的消息段 message.get(Text, 1) == UniMessage([Text("test1")]) ``` -------------------------------- ### Create and Apply Custom Namespace Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how to create a custom `Namespace` with specific configurations like prefixes and formatter types, and then apply it to an `Alconna` instance during its creation. ```python ns = Namespace("foo", prefixes=["/"]) alc = Alconna("pip", Subcommand("install", Args["package", str]), namespace=ns) ``` -------------------------------- ### Manage Namespaces with Config Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates how to mount and switch between namespaces using the Alconna config object. This is useful for organizing commands into distinct groups. ```python config.namespaces["foo"] = ns # 将命名空间挂载到 config 上 alc = Alconna("pip", Subcommand("install", Args["package", str]), namespace=config.namespaces["foo"]) # 也是同样可以切换到"foo"命名空间 ``` -------------------------------- ### Create Command Shortcut with Args Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Illustrates creating a shortcut for a command that passes arguments to the original command. The shortcut '涩图(\d+)张' maps to the 'setu' command, extracting the number of images. ```python from arclet.alconna import Alconna, Args alc = Alconna("setu", Args["count", int]) alc.shortcut("涩图(\d+)张", {"args": ["{0}"]}) # 'Alconna::setu 的快捷指令: "涩图(\d+)张" 添加成功' alc.parse("涩图3张").query("count") # 3 ``` -------------------------------- ### List Command Shortcuts via CLI Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how to list all available shortcuts for a command using the `--shortcut list` option. This is useful for inspecting and managing shortcuts dynamically. ```python from arclet.alconna import Alconna, Args alc = Alconna("eval", Args["content", str]) alc.shortcut("echo", {"command": "eval print(\'{*}\')"}) alc.parse("eval --shortcut list") # 'echo' ``` -------------------------------- ### Args Parameter Declaration Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Illustrates how to declare command parameters using Args, showing that keys are not passed as keywords in the command line for positional arguments. ```python from arclet.alconna import Alconna, Args alc = Alconna("test", Args["foo", str]) alc.parse("test --foo abc") # 错误 alc.parse("test abc") # 正确 ``` -------------------------------- ### AlconnaMatcher finish() method example Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Sends a message and terminates the event handling process. This method raises a FinishedException. ```python @matcher.handle() async def handler(): await matcher.finish("处理完毕") ``` -------------------------------- ### Configure Namespace using Context Manager Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates using the `namespace` context manager to temporarily configure namespace settings, such as prefixes, formatter types, and built-in option names, for commands created within the context. ```python with namespace("bar") as np1: np1.prefixes = ["!"] np1.formatter_type = ShellTextFormatter np1.builtin_option_name["help"] = {"帮助", "-h"} ``` -------------------------------- ### Get Message Target Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Retrieves the target of a message event. Use this when you need to identify where a message originated from or where a reply should be directed. ```python async def get_target( bot: Bot | None = None, event: Event | None = None, ) -> Target | None ``` ```python from nonebot_plugin_alconna import on_alconna, get_target from nonebot.internal.matcher import current_bot, current_event matcher = on_alconna("reply") @matcher.handle() async def handle(): bot = current_bot.get() event = current_event.get() target = await get_target(bot, event) if target: await target.send("目标回复") ``` -------------------------------- ### Extract Text from UniMessage Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/unimessage.md Use extract_text() to get the plain text content of a UniMessage. Specify a separator to join text elements. ```python def extract_text(self, sep: str = "") -> str ``` ```python msg = UniMessage([Text("Hello"), Text(" "), Text("World")]) text = msg.extract_text() # "HelloWorld" text = msg.extract_text(sep=" ") # "Hello World" ``` -------------------------------- ### Option for Keyword Arguments Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates using Option to define arguments that should be passed as keywords, allowing for explicit flag-based input like '--foo abc'. ```python from arclet.alconna import Alconna, Args, Option alc = Alconna("test", Option("--foo", Args["foo", str])) ``` -------------------------------- ### AlconnaArg() - Get Single Argument Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/params.md Retrieve a single command argument by its path. This is useful for accessing specific parameters within a command handler. ```python from nonebot_plugin_alconna import on_alconna, AlconnaArg cmd = on_alconna("calc ") @cmd.handle() async def handle( a: int = AlconnaArg("a"), op: str = AlconnaArg("op"), b: int = AlconnaArg("b"), ): if op == "+": result = a + b elif op == "-": result = a - b else: result = 0 await cmd.send(f"{a} {op} {b} = {result}") ``` -------------------------------- ### Create and Manage Command Shortcuts Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates creating, deleting, and binding shortcuts to commands. The 'echo' shortcut is created for the 'eval' command and can be dynamically managed via the command line. ```python from arclet.alconna import Alconna, Args alc = Alconna("eval", Args["content", str]) alc.shortcut("echo", {"command": "eval print(\'{*}\')"}) # 'Alconna::eval 的快捷指令: "echo" 添加成功' alc.shortcut("echo", delete=True) # 删除快捷指令 # 'Alconna::eval 的快捷指令: "echo" 删除成功' @alc.bind() # 绑定一个命令执行器, 若匹配成功则会传入参数, 自动执行命令执行器 def cb(content: str): eval(content, {}, {}) alc.parse('eval print(\"hello world\")') # hello world alc.parse("echo hello world!") # hello world! ``` -------------------------------- ### Apply Media to URL with apply_media_to_url() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Register a function to convert media to a URL. This is useful for custom media handling. ```python @staticmethod async def apply_media_to_url(apply_func: Callable) -> None ``` ```python from nonebot_plugin_alconna import Image async def custom_handler(media): # 处理媒体转 URL return "http://example.com/media/" + media.id Image.apply_media_to_url(custom_handler) ``` -------------------------------- ### custom_handler() - 获取或注册自定义处理函数 Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Gets or registers a custom handler function. This can be used to set up specific processing logic for custom keys or to retrieve existing handlers. ```APIDOC ## custom_handler() ### Description Gets or registers a custom handler function. ### Parameters #### Path Parameters - **key** (str) - Required - The key for the handler. - **handler** (Callable | None) - Optional - The handler function to register. If None, returns the registered handler. ### Returns - **Callable | None** - The registered handler function or None. ### Request Example ```python from nonebot_plugin_alconna import custom_handler # 注册处理器 async def my_handler(data): return await process(data) custom_handler("my_processor", my_handler) # 获取处理器 handler = custom_handler("my_processor") ``` ``` -------------------------------- ### AlconnaDuplication() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/params.md Retrieves a Duplication object, which can be used to manage command duplication behavior. It can be used to get a default Duplication object or a specific subclass instance. ```APIDOC ## AlconnaDuplication() ### Description Retrieves a Duplication object. This function can be used to obtain a default Duplication instance or a specific subclass instance if provided. ### Method `AlconnaDuplication(_t: type[T_Duplication] | None = None) -> Duplication` ### Parameters - `_t` (type[T_Duplication] | None): The specific Duplication type to instantiate. If None, a default Duplication object is returned. ### Return Value - `Duplication`: A Duplication object or an instance of the specified subclass. ### Usage Example ```python from nonebot_plugin_alconna import on_alconna, AlconnaDuplication from arclet.alconna import Duplication cmd = on_alconna("test") # Basic usage @cmd.handle() async def handle(dup: AlconnaDuplication()): print(dup) # Specifying a type class MyDuplication(Duplication): pass @cmd.handle() async def handle(dup: AlconnaDuplication(MyDuplication)): print(dup) ``` ``` -------------------------------- ### Configure Command Completion with Command.build() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/command-and-shortcut.md Configure command completion session settings when building a Command instance. This method allows for fine-grained control over the completion UI and behavior. ```python from nonebot_plugin_alconna import Command, on_alconna # 方法1:通过 Command.build() cmd = Command("search ").build( comp_config={ "tab": "→", "enter": "✓", "timeout": 20, "hide_tabs": False, "lite": False, } ) ``` -------------------------------- ### Path Syntax with '~' Prefix Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how to use the '~' prefix in path arguments to refer to parent paths. This is useful for defining relative paths within nested command structures. ```python pip = Alconna( "pip", Subcommand( "install", Args["pak", str], Option("--upgrade|-U"), Option("--force-reinstall"), ), Subcommand("list", Option("--out-dated")), ) pipcmd = on_alconna(pip) pip_install_cmd = pipcmd.dispatch("install") @pip_install_cmd.assign("~upgrade") async def pip1_u(pak: Query[str] = Query("~pak")): await pip_install_cmd.finish(f"pip upgrading {pak.result}...") ``` -------------------------------- ### Utilize Duplication for Enhanced Auto-completion Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Explains and demonstrates the use of `Duplication` to provide richer auto-completion suggestions, similar to `argparse`'s `Namespace`. It requires defining stub classes for options and subcommands. ```python from arclet.alconna import Alconna, Args, Option, OptionResult, Duplication, SubcommandStub, Subcommand, count class MyDup(Duplication): verbose: OptionResult install: SubcommandStub alc = Alconna( "pip", Subcommand( "install", Args["package", str], Option("-r|--requirement", Args["file", str]), Option("-i|--index-url", Args["url", str]), ), Option("-v|--version"), Option("-v|--verbose", action=count), ) res = alc.parse("pip -v install ...") # 不使用duplication获得的提示较少 print(res.query("install")) # (value=Ellipsis args={'package': '...'} options={} subcommands={}) result = alc.parse("pip -v install ...", duplication=MyDup) print(result.install) ``` -------------------------------- ### got() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Obtains user input for a specific key, optionally with a prompt and argument parser. ```APIDOC ## got() ### Description Obtains user input and stores it in the state under the specified key. It can display a prompt and use a custom parser for the input. ### Method `@classmethod got(cls, key: str, *, prompt: _M | None = None, args_parser: Callable | None = None) -> Callable` ### Parameters - **key** (str): The key in the state to store the user's input. - **prompt** (_M | None): The prompt message to display to the user (can be Text, Message, Segment, UniMessage, etc.). - **args_parser** (Callable | None): A function to parse the user's arguments. ### Usage Example ```python from nonebot_plugin_alconna import UniMessage matcher = on_alconna("ask") @matcher.got("name", prompt=UniMessage.text("请输入你的名字")) async def handle_got_name(state: T_State): name = state["name"] await matcher.send(f"你的名字是 {name}") ``` ``` -------------------------------- ### Define Subcommands with Options and Nested Subcommands Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Illustrates how `Subcommand` components can include their own `Option` and `Subcommand` definitions. Common parameters like `help_text`, `dest`, `requires`, and `default` are supported. ```python Alconna("test", Subcommand("sub", Option("--bar"))) ``` -------------------------------- ### Define Custom Argument Pattern Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Define a custom argument pattern for matching strings that start with '@' followed by digits. This pattern is registered globally for use in argument definitions. ```python args = Args["foo", BasePattern("@\d+")] ``` -------------------------------- ### Get or Register Custom Handler with custom_handler() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Use this function to register a custom handler for a specific key or retrieve an already registered handler. Useful for extending processing logic. ```python @staticmethod def custom_handler( key: str, handler: Callable | None = None ) -> Callable | None ``` ```python from nonebot_plugin_alconna import custom_handler # 注册处理器 async def my_handler(data): return await process(data) custom_handler("my_processor", my_handler) # 获取处理器 handler = custom_handler("my_processor") ``` -------------------------------- ### Configure Command Completion with on_alconna() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/command-and-shortcut.md Configure command completion session settings directly when creating an Alconna matcher. This is useful for setting up command handlers with specific completion behaviors, such as disabling the Tab key. ```python from nonebot_plugin_alconna import Alconna matcher = on_alconna( "filter ", comp_config={ "timeout": 15, "block": True, "disables": {"tab"} # 禁用 Tab 键 } ) ``` -------------------------------- ### Getting Target and Message ID from Event/Bot Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Illustrates how to obtain the target and message ID using helper functions get_target and get_message_id, which can infer details from the event and bot objects. ```python from nonebot import Event, Bot from nonebot_plugin_alconna.uniseg import Target, get_message_id, get_target matcher = on_xxx(...) @matcher.handle() async def _(bot: Bot, event: Event): target: Target = get_target(event, bot) msg_id: str = get_message_id(event, bot) ``` -------------------------------- ### build() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/unimessage.md Builds a UniMessage into a native message object for a specific adapter. ```APIDOC ## build() ### Description Constructs a message object compatible with a specified adapter, using the current UniMessage content. It can optionally use a fallback strategy if direct conversion is not possible. ### Method Signature ```python async def build( self, adapter: str | None = None, bot: Bot | None = None, fallback: bool | FallbackStrategy = False, ) -> Message ``` ### Parameters - **adapter** (str | None) - Optional - The name of the target adapter (e.g., "onebot11"). If None, the current bot's adapter is used. - **bot** (Bot | None) - Optional - The current Bot instance. Required if adapter is not specified and the bot context is not available. - **fallback** (bool | FallbackStrategy) - Optional - Specifies the fallback strategy to use if the message cannot be built directly. Can be a boolean or a `FallbackStrategy` enum value. ### Return Value - **Message** - The adapter-native message object. ### Usage Example ```python msg = UniMessage.text("Hello").image(url="http://example.com/img.png") # Use the current bot to build the message current_msg = await msg.build() # Specify an adapter and fallback strategy from nonebot_plugin_alconna import FallbackStrategy onebot_msg = await msg.build("onebot11", fallback=FallbackStrategy.text) ``` ``` -------------------------------- ### AlconnaDuplication() - Get Duplication Object Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/params.md Use AlconnaDuplication to obtain a Duplication object or its subclass instance. It can be used without arguments for a base Duplication object or with a type argument to specify a custom subclass. ```python from nonebot_plugin_alconna import on_alconna, AlconnaDuplication from arclet.alconna import Duplication cmd = on_alconna("test") # 基础用法 @cmd.handle() async def handle(dup: AlconnaDuplication()): print(dup) # 指定类型 class MyDuplication(Duplication): pass @cmd.handle() async def handle(dup: AlconnaDuplication(MyDuplication)): print(dup) ``` -------------------------------- ### Compact Option with Append Action Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates using `compact=True` with an Option that has an `append` action. This allows multiple compact arguments to be collected into a list. ```python from arclet.alconna import Alconna, Option, Args, append alc = Alconna("gcc", Option("--flag|-F", Args["content", str], action=append, compact=True)) print(alc.parse("gcc -Fabc -Fdef -Fxyz").query[list]("flag.content")) # ['abc', 'def', 'xyz'] ``` -------------------------------- ### Get Message ID Information Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Retrieves detailed message ID information, including bot ID, target ID, message ID, and adapter. Use this to uniquely identify and reference specific messages. ```python async def get_message_id( bot: Bot | None = None, event: Event | None = None, ) -> MessageId | None ``` ```python class MessageId(TypedDict): """消息ID信息 字段: bot_id: str - Bot ID target_id: str - 目标ID message_id: str - 消息ID adapter: str - 适配器名称 """ bot_id: str target_id: str message_id: str adapter: str ``` ```python from nonebot_plugin_alconna import on_alconna, get_message_id from nonebot.internal.matcher import current_bot, current_event cmd = on_alconna("forward") @cmd.handle() async def handle(): bot = current_bot.get() event = current_event.get() msg_id = await get_message_id(bot, event) if msg_id: print(f"消息ID: {msg_id['message_id']}") print(f"Bot: {msg_id['bot_id']}") ``` -------------------------------- ### Set Default Values for Options Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how to set default values for `Option` components. Special `OptionResult` can be used to provide a default value along with a dictionary of arguments. ```python opt1 = Option("--foo", default=False) opt2 = Option("--foo", default=OptionResult(value=False, args={"bar": 1})) ``` -------------------------------- ### receive() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Receives user interaction on a specified slot. ```APIDOC ## receive() ### Description Receives user interaction on a specific slot, allowing for stateful conversations. ### Method `@classmethod receive(cls, id: str = RECEIVE_KEY) -> Callable` ### Parameters - **id** (str): The ID of the receiving slot. Defaults to `RECEIVE_KEY`. ### Usage Example ```python @matcher.receive("action") async def handle_action(state: T_State): action = state["action"] # Process the action pass ``` ``` -------------------------------- ### match_path() - Path Matching Check Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/params.md Create a check function that matches a specific path within the command arguments. Use '$main' to match only the main command or provide a path to match a specific argument or option. ```python from nonebot_plugin_alconna import on_alconna, match_path cmd = on_alconna( "admin [-type type:str]", rule=match_path("type") # 仅当指定 -type 时处理 ) @cmd.handle() async def handle(): pass # 仅当主命令匹配(无子命令) main_cmd = on_alconna( "test", rule=match_path("$main") ) ``` -------------------------------- ### Using UniMessage Templates with At Segments Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Illustrates how to use UniMessage templates with the '{:At(...)}' format specifier to dynamically create At segments. Supports different syntaxes for specifying user and target. ```python UniMessage.template("{:At(user, target)}").format(target="123") ``` ```python UniMessage.template("{:At(type=user, target=id)}").format(id="123") ``` ```python UniMessage.template("{:At(type=user, target=123)}").format() ``` -------------------------------- ### MultiVar and KeyWordVar for Multiple Arguments Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates `MultiVar` for accepting multiple values for a parameter and `KeyWordVar` for keyword-only parameters. They can be combined, and `default` values can be specified. `MultiVar` must precede `KeyWordVar` when used together. ```python args = Args[MultiVar(KeyWordVar(str))] ``` -------------------------------- ### Trigger Auto-Completion Suggestions Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates how to trigger auto-completion suggestions by appending `--comp`, `-cp`, or `?` to the command. This provides users with helpful input recommendations. ```python from arclet.alconna import Alconna, Args, Option alc = Alconna("test", Args["abc", int]) + Option("foo") + Option("bar") alc.parse("test --comp") ''' output 以下是建议的输入: * * --help * -h * -sct * --shortcut * foo * bar ''' ``` -------------------------------- ### Configuration and Management Exports Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/exports.md These symbols are used for configuring the plugin and managing extensions. ```python Config # 插件配置 CompConfig # 补全配置 Extension # 扩展基类 add_global_extension # 添加扩展 ``` -------------------------------- ### Compact Option with Count Action Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how an Option with a `count` action automatically supports `compact` parsing. This is useful for tracking the number of times an option is specified, like verbose flags. ```python from arclet.alconna import Alconna, Option, count alc = Alconna("pp", Option("--verbose|-v", action=count, default=0)) print(alc.parse("pp -vvv").query[int]("verbose.value")) # 3 ``` -------------------------------- ### Using Built-in Type Patterns Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates how to use built-in type patterns like 'str', 'int', 'float', 'bool', 'hex', 'url', 'email', 'ipv4', 'list', 'dict', 'datetime', 'Any', 'AnyString', and 'Number' directly in argument definitions. These patterns are automatically resolved from `nepattern.global_patterns`. ```python args = Args["package", str] ``` -------------------------------- ### video() - Add Video Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/unimessage.md Adds video to the UniMessage. Supports adding from URL, local path, or raw bytes, with parameters similar to image() and audio(). ```APIDOC ## video() - Add Video ### Description Adds video to the UniMessage. Supports adding from URL, local path, or raw bytes, with parameters similar to image() and audio(). ### Method Signature ```python UniMessage.video( id: str | None = None, url: str | None = None, path: str | Path | None = None, raw: bytes | BytesIO | None = None, mimetype: str | None = None, width: int | None = None, height: int | None = None, duration: int | None = None, title: str | None = None, name: str = "video.mp4", ) -> UniMessage ``` ### Parameters - **id** (str | None): Video ID - **url** (str | None): Video URL - **path** (str | Path | None): Local file path - **raw** (bytes | BytesIO | None): Raw binary data - **mimetype** (str | None): MIME type - **width** (int | None): Video width - **height** (int | None): Video height - **duration** (int | None): Video duration (seconds) - **title** (str | None): Title - **name** (str): File name ``` -------------------------------- ### Fetch Image using image_fetch() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/target-and-functions.md Use this function to fetch an image from a given URL. It returns an Image object. ```python async def image_fetch(url: str) -> Image ``` ```python from nonebot_plugin_alconna import on_alconna, image_fetch matcher = on_alconna("fetch ") @matcher.handle() async def handle(url: str): image = await image_fetch(url) await matcher.send(image) ``` -------------------------------- ### Querying Arparma Results by Path Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates the `query` method of `Arparma` for retrieving parsed arguments using a path-like syntax. Paths can refer to main arguments, options, subcommands, and their nested values. ```python result = alc.parse("--foo bar") print(result.options.foo.value) ``` -------------------------------- ### Specify Requires for Command Sequencing Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates the `requires` parameter for `Option` and `Subcommand`, which specifies a list of strings that must match sequentially before the component is activated. This is useful for nested command structures. ```python Alconna("test", Option("qux", Args.a[int], requires=["foo", "bar", "baz"]))) ``` -------------------------------- ### Define Options with Aliases Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Shows how to define `Option` components with multiple aliases. The longest alias is chosen as the option's primary name. Hyphens are not required for option names or aliases. ```python Alconna("test", Option("--foo|-F|--FOO|-f")) ``` -------------------------------- ### Command Creation and Handling Exports Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/exports.md These symbols are used for creating command responders and handling commands. ```python on_alconna # 创建命令响应器 AlconnaMatcher # 响应器基类 Command # 命令构建器 funcommand # 函数装饰器 ``` -------------------------------- ### Using UniMessage Templates with Event/Bot Attributes in AlconnaMatcher Source: https://github.com/nonebot/plugin-alconna/blob/master/docs.md Demonstrates how to use UniMessage templates within AlconnaMatcher to dynamically include attributes from the event or bot objects, such as user IDs. ```python from arclet.alconna import Alconna, Args from nonebot_plugin_alconna import At, Match, UniMessage, AlconnaMatcher, on_alconna test_cmd = on_alconna(Alconna("test", Args["target?", At])) @test_cmd.handle() async def tt_h(matcher: AlconnaMatcher, target: Match[At]): if target.available: matcher.set_path_arg("target", target.result) @test_cmd.got_path( "target", prompt=UniMessage.template("{:At(user, $event.get_user_id())} 请确认目标") ) async def tt(): await test_cmd.send( UniMessage.template("{:At(user, $event.get_user_id())} 已确认目标为 {target}") ) ``` -------------------------------- ### Build Adapter-Specific Message Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/unimessage.md Use build() to convert a UniMessage into a message object native to a specific adapter. You can specify the adapter name, the bot instance, and a fallback strategy. ```python async def build( self, adapter: str | None = None, bot: Bot | None = None, fallback: bool | FallbackStrategy = False, ) -> Message ``` ```python msg = UniMessage.text("Hello").image(url="http://example.com/img.png") # 使用当前 bot 构建 current_msg = await msg.build() # 指定适配器 from nonebot_plugin_alconna import FallbackStrategy onebot_msg = await msg.build("onebot11", fallback=FallbackStrategy.text) ``` -------------------------------- ### file() - Add File Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/unimessage.md Adds a generic file to the UniMessage. Supports adding from URL, local path, or raw bytes, with basic parameters similar to image(). ```APIDOC ## file() - Add File ### Description Adds a generic file to the UniMessage. Supports adding from URL, local path, or raw bytes, with basic parameters similar to image(). ### Method Signature ```python UniMessage.file( id: str | None = None, url: str | None = None, path: str | Path | None = None, raw: bytes | BytesIO | None = None, mimetype: str | None = None, name: str = "file", ) -> UniMessage ``` ### Parameters - **id** (str | None): File ID - **url** (str | None): File URL - **path** (str | Path | None): Local file path - **raw** (bytes | BytesIO | None): Raw binary data - **mimetype** (str | None): MIME type - **name** (str): File name ``` -------------------------------- ### Check() - Create Check Rule Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/params.md Create a check rule using the Check function, which takes a checking function as an argument. The checking function must have the signature `async (event, bot, state, result) -> bool` and determines if the command should proceed. ```python from nonebot_plugin_alconna import on_alconna, Check async def check_admin(event, bot, state, result): # 检查用户是否为管理员 return event.sender.user_id in ADMIN_IDS admin_cmd = on_alconna( "admin ", rule=Check(check_admin) ) @admin_cmd.handle() async def handle_admin(): await admin_cmd.send("管理员命令") ``` -------------------------------- ### Add Video to UniMessage Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/unimessage.md Use the `video` method to add video content to a UniMessage. Supports adding from URL, local path, or raw bytes. Parameters include dimensions, duration, and title. ```python @_method def video( cls_or_self: UniMessage | type[UniMessage], id: str | None = None, url: str | None = None, path: str | Path | None = None, raw: bytes | BytesIO | None = None, mimetype: str | None = None, width: int | None = None, height: int | None = None, duration: int | None = None, title: str | None = None, name: str = "video.mp4", ) -> UniMessage ``` -------------------------------- ### audio() - Add Audio Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/unimessage.md Adds audio to the UniMessage. Supports adding from URL, local path, or raw bytes, with optional metadata like duration, title, and performer. ```APIDOC ## audio() - Add Audio ### Description Adds audio to the UniMessage. Supports adding from URL, local path, or raw bytes, with optional metadata like duration, title, and performer. ### Method Signature ```python UniMessage.audio( id: str | None = None, url: str | None = None, path: str | Path | None = None, raw: bytes | BytesIO | None = None, mimetype: str | None = None, duration: int | None = None, title: str | None = None, performer: str | None = None, name: str = "audio.mp3", ) -> UniMessage ``` ### Parameters - **id** (str | None): Audio ID - **url** (str | None): Audio URL - **path** (str | Path | None): Local file path - **raw** (bytes | BytesIO | None): Raw binary data - **mimetype** (str | None): MIME type - **duration** (int | None): Audio duration (seconds) - **title** (str | None): Title - **performer** (str | None): Performer - **name** (str): File name ``` -------------------------------- ### shortcut() Source: https://github.com/nonebot/plugin-alconna/blob/master/_autodocs/api-reference/matcher.md Adds a shortcut alias for a command. ```APIDOC ## shortcut() ### Description Adds a shortcut or alias for an existing Alconna command, making it easier to invoke. ### Method `@classmethod shortcut( cls, key: str, command: str | None = None, arguments: list[str] | None = None, *, fuzzy: bool = True, prefix: bool = False, humanized: str | None = None, ) -> None` ### Parameters - **key** (str): The trigger word for the shortcut. - **command** (str | None): The name of the command the shortcut maps to. If `None`, it maps to the command associated with the matcher. - **arguments** (list[str] | None): A list of arguments to automatically append when the shortcut is used. - **fuzzy** (bool): Whether to enable fuzzy matching for the shortcut key. Defaults to `True`. - **prefix** (bool): Whether the shortcut should act as a command prefix. Defaults to `False`. - **humanized** (str | None): A human-readable description for the shortcut. ### Usage Example ```python matcher = on_alconna("test ") matcher.shortcut("t", command="test", arguments=["run"]) # Now typing "t" is equivalent to typing "test run" ``` ```