commands — 命令
注册命令处理器并在本地调度命令执行。
self.commands 提供命令注册与调度能力。注册的命令处理器对应 Manifest 中声明的命令(需声明 commands 权限)。
方法
| 方法 | 说明 |
|---|---|
register(command_id, handler) | 注册命令处理器 |
unregister(command_id) | 注销命令处理器 |
dispose_all() | 清空所有已注册处理器 |
dispatch(command_id, args?, context?) | 调度命令执行(async) |
register(command_id, handler)
注册指定命令的处理器。
self.commands.register("my-plugin.do-thing", self._do_thing)参数:
command_id(str) — 命令 ID,不能为空,否则抛出ValueErrorhandler(callable) — 命令处理器,以关键字参数调用:handler(args=dict, context=dict)
处理器既可以返回普通结果,也可以返回 async def 协程;dispatch 会自动等待协程完成。
unregister(command_id)
注销已注册的命令处理器。未注册的命令 ID 会被静默忽略。
dispose_all()
清空所有已注册的命令处理器。插件卸载时会自动调用。
async dispatch(command_id, args?, context?)
在本地调度命令执行。
result = await self.commands.dispatch(
"my-plugin.do-thing",
args={"value": 42},
context={"trigger": "button"},
)参数:
command_id(str) — 要调度的命令 IDargs(dict, 可选) — 传给处理器的参数,默认{}context(dict, 可选) — 执行上下文,默认{}
当 command_id 没有对应的已注册处理器时,dispatch 会抛出 LookupError。
使用示例
class MyPlugin(UiPlugin):
def on_start(self):
self.commands.register("my-plugin.greet", self._greet)
def on_dispose(self):
self.commands.dispose_all()
async def _greet(self, args, context):
name = args.get("name", "world")
return {"message": f"hello, {name}"}