Files
NeoBot/docs/plugin-development/command-handling.md
K2cr2O1 7880f0f928 docs: 更新文档内容并优化语言风格
重构所有文档内容,使用更简洁直接的语言风格
更新架构、插件开发、部署等核心文档
优化代码示例和图表说明
统一术语和格式规范
2026-01-13 04:09:13 +08:00

91 lines
3.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 指令处理与参数解析
光会 `event.reply()` 只能写玩具。正经的插件,都得和用户传进来的参数打交道。
## 1. 获取原始参数
最简单粗暴的方式,就是直接在处理器函数里声明 `args: str`
```python
from core.managers.command_manager import matcher
from models.events.message import MessageEvent
@matcher.command("echo")
async def handle_echo(event: MessageEvent, args: str):
# 如果用户发送 /echo hello world
# args 的值就是 "hello world"
if not args:
await event.reply("你啥也没说啊。")
else:
await event.reply(f"你说了:{args}")
```
`args` 就是去掉命令本身后,后面跟着的**一整坨字符串**。
## 2. 自动解析参数 (推荐)
一整坨字符串用起来太费劲了,还得自己 `split()`。框架提供了更高级的玩法:**参数自动解析**。
你只需要在函数签名里,用类型提示声明你想要的参数,框架会像 FastAPI 一样,自动帮你解析和注入。
### a. 基础用法
```python
from core.managers.command_manager import matcher
from models.events.message import MessageEvent
@matcher.command("add")
async def handle_add(event: MessageEvent, a: int, b: int):
# 如果用户发送 /add 10 20
# 框架会自动把 "10" 转成整数 10注入给 a
# 把 "20" 转成整数 20注入给 b
result = a + b
await event.reply(f"计算结果是:{result}")
```
**它是怎么工作的?**
框架会按顺序把 `args` 字符串用空格分割,然后尝试把分割后的每一块,转换成你声明的参数类型。
* `/add 10 20` -> `args``"10 20"` -> 分割成 `["10", "20"]`
* 第一块 `"10"` -> 尝试转成 `int` -> 成功,`a = 10`
* 第二块 `"20"` -> 尝试转成 `int` -> 成功,`b = 20`
### b. 处理可选参数和默认值
你可以像普通 Python 函数一样,给参数提供默认值。
```python
from typing import Optional
@matcher.command("greet")
async def handle_greet(event: MessageEvent, name: str, title: Optional[str] = "先生"):
# 例 1: /greet 张三
# name = "张三", title = "先生" (默认值)
# 例 2: /greet 李四 女士
# name = "李四", title = "女士"
await event.reply(f"你好,{name} {title}")
```
### c. 贪婪的最后一个参数
有时候,最后一个参数可能包含空格,比如 `/say hello world`。默认情况下,`hello` 会被解析给第一个参数,`world` 会被解析给第二个。
如果你想让最后一个参数“吃掉”所有剩下的内容,可以用 `...` 作为默认值(这是一个特殊的标记)。
```python
@matcher.command("say")
async def handle_say(event: MessageEvent, target_user: str, content: str = ...):
# 例: /say 张三 早上好,吃了没?
# target_user = "张三"
# content = "早上好,吃了没?"
await event.reply(f"正在对 {target_user} 说:{content}")
```
## 3. 更复杂的解析:依赖注入
如果你的参数不是简单的 `int``str`,或者你需要更复杂的解析逻辑(比如 `@某人`),请参考 `FastAPI` 的依赖注入系统,我们用了同一套逻辑。