1- # 指令系统
1+ # 指令开发
22
33Saltify 提供了一套类型安全的指令构建 DSL,支持参数解析、子指令以及特定上下文的执行逻辑。
44
5- ## 基础指令与参数解析
5+ ## 定义指令
66
7- 你可以为指令定义类型安全的参数,并通过 ` .value ` 快速获取。
7+ 以下是一个简单的指令定义:
88
99``` kotlin
1010client.command(" order" , prefix = " /" ) {
@@ -14,9 +14,8 @@ client.command("order", prefix = "/") {
1414 val note = greedyStringParameter(" note" )
1515
1616 onExecute {
17- respond {
18- text(" Order #${id.value} created\n note:${note.value} " )
19- }
17+ // some logic...
18+ respond(" 订单 #${id.value} 已创建\n Note:${note.value} " )
2019 }
2120
2221 onFailure { error ->
@@ -32,7 +31,7 @@ onFailure 块是**解析**失败的处理,注意这里不是异常,而是指
3231默认情况下,如果不定义这个块,会忽视所有解析错误,并对指令不做回复。
3332
3433> [ !tip]
35- > 与 ` on ` 一样,command 在插件初始化块中也是可以使用的,并且不用手动传 client。
34+ > 与 ` on ` 一样,command 在插件初始化块中也是可以,并且推荐使用的。不需要传 ` client ` 。
3635
3736## 上下文隔离
3837
@@ -41,11 +40,11 @@ onFailure 块是**解析**失败的处理,注意这里不是异常,而是指
4140``` kotlin
4241client.command(" info" ) {
4342 onGroupExecute {
44- respond { text (" 这是群聊专用的信息!" ) }
43+ respond(" 这是群聊专用的信息!" )
4544 }
4645
4746 onPrivateExecute {
48- respond { text (" 这是私聊专用的信息!" ) }
47+ respond(" 这是私聊专用的信息!" )
4948 }
5049
5150 onExecute {
@@ -57,22 +56,50 @@ client.command("info") {
5756> [ !tip]
5857> ` onGroupExecute ` 和 ` onPrivateExecute ` 的优先级** 高于** ` onExecute ` 。如果群聊触发了指令且你定义了 ` onGroupExecute ` ,那么 ` onExecute ` 中的兜底逻辑将** 不会** 被执行。
5958
59+ ## 子指令
60+
61+ 通过 ` subCommand ` 函数,可以方便地定义一个任意嵌套层级的指令树:
62+
63+ ``` kotlin
64+ command(" math" ) {
65+ // /math add <num1> <num2>
66+ subCommand(" add" ) {
67+ val a = parameter<Int >(" a" )
68+ val b = parameter<Int >(" b" )
69+
70+ onExecute {
71+ val result = a.value + b.value
72+ respond(" $result " )
73+ }
74+ }
75+
76+ // /math power <base>
77+ subCommand(" power" ) {
78+ val base = parameter<Int >(" base" )
79+ onExecute {
80+ val value = base.value
81+ respond(" $value 的平方是 ${value * value} " )
82+ }
83+ }
84+ }
85+ ```
86+
6087## 上下文交互
6188
6289在指令执行上下文中,你可以挂起当前协程,等待该用户的下一条回复。
6390
6491``` kotlin
6592client.command(" shutdown" ) {
6693 onExecute {
67- respond { text (" 真的要关机吗?" ) }
94+ respond(" 真的要关机吗?" )
6895
6996 // 等待该用户在同一上下文中发送的下一条消息(默认 30 秒超时)
7097 val replyEvent = awaitNextMessage(timeout = 30 .seconds)
7198
7299 if (replyEvent == null ) {
73- respond { text (" 等待超时" ) }
100+ respond(" 等待超时" )
74101 } else {
75- respond { text (" 你回复了我,但这不重要,无论如何,我都不想关掉我自己!" ) }
102+ respond(" 你回复了我,但这不重要,无论如何,我都不想关掉我自己!" )
76103 }
77104 }
78105}
0 commit comments