Skip to content

Commit

Permalink
update: 快捷主动回复、指令前缀
Browse files Browse the repository at this point in the history
  • Loading branch information
Soulter committed Aug 10, 2024
1 parent e1547ff commit cbb2f02
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion docs/开发/插件开发.md
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ class HelloWorldPlugin:
await inst.send_msg({"user_id": 905617992}, CommandResult().message("你好")) # 发送消息给qq号为905617992的用户
```
上面的例子使用了异步的方式来实现定时任务。当然可以使用 threading.Thread 来实现,不过不推荐
上面的例子使用了异步的方式来实现定时任务。当然,你也可以使用 threading.Thread 来实现。

### 注册指令 context.register_commands()

Expand All @@ -247,6 +247,8 @@ class HelloWorldPlugin:
- description: str 指令简短描述。
- priority: int 优先级。数字越大,优先级越高。
- handler: callable 指令处理函数。
- use_regex: bool 是否使用正则表达式识别指令。默认为 False。
- ignore_prefix: bool 是否忽略指令前缀。默认为 False。

当用户输入以 `command_name` 开头的指令时,会调用 `handler` 函数。

Expand All @@ -273,6 +275,15 @@ def helloworld(self, message: AstrMessageEvent, context: Context):
self.context.register_commands("helloworld", "world$", "内置测试指令。", 1, self.helloworld, use_regex=True)
```

在 v3.3.8 版本之后,支持忽略指令前缀。

```py
# 忽略指令前缀
self.context.register_commands("helloworld", "haha", "内置测试指令。", 1, self.helloworld, ignore_prefix=True)
```
> 指令前缀指的不是第二个参数,而是类似于 `/` 这样的用户设置的指令前缀。(wake指令)

忽略指令前缀后,用户发送的消息中如果不包含指令前缀,也会被触发指令。

## 指令返回值 CommandResult

Expand All @@ -297,6 +308,17 @@ cmd_result = CommandResult(
)
```

### 关闭或开启文转图

默认情况下,CommandResult() 是否文转图取决于用户 t2i 指令的设置。你可以通过 use_t2i 方法来强行在这个回复中关闭或开启文转图。

```py
CommandResult().message("Hello, World!").use_t2i(False) # 关闭文转图
```

:::tip
AstrBot 触发文转图只会在回复操作(也就是指令处理函数的return)中生效,如果你在插件中主动发送消息,文转图永远不会生效。
:::

## AstrMessageEvent

Expand Down Expand Up @@ -330,6 +352,32 @@ timestamp: int # 消息时间戳

## 主动发送消息

### 快捷主动回复

AstrBot 封装了一个统一的快捷回复方法,可以直接在插件中调用。(>=v3.3.8)

`unified_msg_origin`: 这是一个字符串,用于标识消息来源。它的格式类似 `aiocqhttp:GroupMessage:123456`。其中 `aiocqhttp` 是平台名,`GroupMessage` 是消息类型,`123456` 是群号。

通过保存(因为是字符串,因此也可以持久化保存)这个标识,可以在后续的消息(甚至重启之后),通过指定标识来主动发送消息给对应的消息来源。

此值在 `AstrMessageEvent` 中可以找到。

```py
context.register_commands("sub", "sub", "内置测试指令。", 1, self.sub)
def sub(self, message: AstrMessageEvent, context: Context):
unified_msg_origin = message.unified_msg_origin
# 保存此值 ...
def send(self, context: Context):
# 通过 unified_msg_origin 回复消息
await context.send_message(unified_msg_origin, CommandResult().message("Hello, World!"))
```

有了这个功能,你可以实现一些复杂的插件逻辑,比如订阅、定时任务等。

### 主动发送消息的其他方法

插件可以主动给受支持的平台发送消息。(>=v3.3.3)

采用 context.platforms 获取所有已注册(启用)的平台。
Expand Down

0 comments on commit cbb2f02

Please sign in to comment.