匹配 `shell_like` 形式的消息命令。 根据配置里提供的 {ref}``command_start` `, {ref}``command_sep` ` 判断消息是否为命令。 可以通过 {ref}`nonebot.params.Command` 获取匹配成功的命令 (例: `("test",)`), 通过 {ref}`nonebot.params.RawCommand` 获取匹配成功的原始命令文本
(
*cmds: str | tuple[str, ...], parser: ArgumentParser | None = None
)
| 587 | |
| 588 | |
| 589 | def shell_command( |
| 590 | *cmds: str | tuple[str, ...], parser: ArgumentParser | None = None |
| 591 | ) -> Rule: |
| 592 | """匹配 `shell_like` 形式的消息命令。 |
| 593 | |
| 594 | 根据配置里提供的 {ref}``command_start` <nonebot.config.Config.command_start>`, |
| 595 | {ref}``command_sep` <nonebot.config.Config.command_sep>` 判断消息是否为命令。 |
| 596 | |
| 597 | 可以通过 {ref}`nonebot.params.Command` 获取匹配成功的命令 |
| 598 | (例: `("test",)`), |
| 599 | 通过 {ref}`nonebot.params.RawCommand` 获取匹配成功的原始命令文本 |
| 600 | (例: `"/test"`), |
| 601 | 通过 {ref}`nonebot.params.ShellCommandArgv` 获取解析前的参数列表 |
| 602 | (例: `["arg", "-h"]`), |
| 603 | 通过 {ref}`nonebot.params.ShellCommandArgs` 获取解析后的参数字典 |
| 604 | (例: `{"arg": "arg", "h": True}`)。 |
| 605 | |
| 606 | :::caution 警告 |
| 607 | 如果参数解析失败,则通过 {ref}`nonebot.params.ShellCommandArgs` |
| 608 | 获取的将是 {ref}`nonebot.exception.ParserExit` 异常。 |
| 609 | ::: |
| 610 | |
| 611 | 参数: |
| 612 | cmds: 命令文本或命令元组 |
| 613 | parser: {ref}`nonebot.rule.ArgumentParser` 对象 |
| 614 | |
| 615 | 用法: |
| 616 | 使用默认 `command_start`, `command_sep` 配置,更多示例参考 |
| 617 | [argparse](https://docs.python.org/3/library/argparse.html) 标准库文档。 |
| 618 | |
| 619 | ```python |
| 620 | from nonebot.rule import ArgumentParser |
| 621 | |
| 622 | parser = ArgumentParser() |
| 623 | parser.add_argument("-a", action="store_true") |
| 624 | |
| 625 | rule = shell_command("ls", parser=parser) |
| 626 | ``` |
| 627 | |
| 628 | :::tip 提示 |
| 629 | 命令内容与后续消息间无需空格! |
| 630 | ::: |
| 631 | """ |
| 632 | if parser is not None and not isinstance(parser, ArgumentParser): |
| 633 | raise TypeError("`parser` must be an instance of nonebot.rule.ArgumentParser") |
| 634 | |
| 635 | config = get_driver().config |
| 636 | command_start = config.command_start |
| 637 | command_sep = config.command_sep |
| 638 | commands: list[tuple[str, ...]] = [] |
| 639 | for command in cmds: |
| 640 | if isinstance(command, str): |
| 641 | command = (command,) |
| 642 | |
| 643 | commands.append(command) |
| 644 | |
| 645 | if len(command) == 1: |
| 646 | for start in command_start: |