@yangfan1998/dsh-qqbot-plus 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +239 -2
- package/cordis.patch.yml +55 -0
- package/cordis.tools-only.yml +22 -0
- package/extensions/README.md +20 -0
- package/extensions/inbound/bili-card-url.mjs +66 -0
- package/extensions/outbound/abs-image-paths.mjs +31 -0
- package/index.js +34 -0
- package/package.json +62 -4
- package/tools/bilibili.js +472 -0
- package/tools/tts.js +99 -0
- package/tools/vision.js +158 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 dsh-qqbot-plus contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,240 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @yangfan1998/dsh-qqbot-plus
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**DeepSeek Harness 的 QQ 机器人整合包:装一次,带网关、识图、语音和 B 站工具。**
|
|
4
|
+
|
|
5
|
+
`@yangfan1998/dsh-qqbot-plus` 会挂载 [`@zaofan/dsh-qqbot`](https://www.npmjs.com/package/@zaofan/dsh-qqbot) 网关,并额外提供:
|
|
6
|
+
|
|
7
|
+
- `qqbot_describe_image` — 图片理解 / OCR
|
|
8
|
+
- `tts_speak` — Edge TTS 语音(mp3)
|
|
9
|
+
- `bili_read` / `bili_search` / `bili_hot` / `bili_frames` — B 站视频、弹幕、评论、缩略图理解
|
|
10
|
+
|
|
11
|
+
它是 **bundle**,不是 QQ 网关的 fork。网关仍然是 `@zaofan/dsh-qqbot`,可以独立升级。
|
|
12
|
+
|
|
13
|
+
> 当前版本:`0.1.0`。已发布到 npm;本地也可以 `npm pack` 后安装。
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## 环境要求
|
|
18
|
+
|
|
19
|
+
| 项目 | 要求 |
|
|
20
|
+
|---|---|
|
|
21
|
+
| Node.js | `>= 22.13` |
|
|
22
|
+
| DeepSeek Harness | `>= 0.2.1-alpha.2` |
|
|
23
|
+
| QQ 机器人 | QQ 开放平台的 AppID + AppSecret |
|
|
24
|
+
| 识图模型 | 支持图片输入的 LLM 路由(默认 `zhipu/aliyun/qwen3-vl-plus`) |
|
|
25
|
+
| TTS(可选) | `edge-tts` 可执行文件在 `PATH`,或配置 `tts.bin` |
|
|
26
|
+
| B 站(可选) | 公开数据不需要 Key;`BILIBILI_SESSDATA` 可解锁字幕 |
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## 安装
|
|
31
|
+
|
|
32
|
+
### 方式一:从 npm 安装(推荐)
|
|
33
|
+
|
|
34
|
+
```bash
|
|
35
|
+
dsh plugin --profile <你的profile> add @yangfan1998/dsh-qqbot-plus
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
如果 pnpm 报 `ERR_PNPM_IGNORED_BUILDS`(QQ 网关依赖的 `onnxruntime-node` / `protobufjs`):
|
|
39
|
+
|
|
40
|
+
```bash
|
|
41
|
+
cd ~/.dsh/profiles/<你的profile>
|
|
42
|
+
pnpm approve-builds --all
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
然后把这个 bundle 加进 profile 的 `package.json`(部分 DSH 版本的插件管理器不会自动追加):
|
|
46
|
+
|
|
47
|
+
```json
|
|
48
|
+
{
|
|
49
|
+
"dsh": {
|
|
50
|
+
"profile": {
|
|
51
|
+
"bundles": [
|
|
52
|
+
"@deepseek-ai/dsh-base",
|
|
53
|
+
"@deepseek-ai/dsh-web-app",
|
|
54
|
+
"@yangfan1998/dsh-qqbot-plus"
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
启动前先确认组合树:
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
dsh --profile <你的profile> --dump-config | grep -A3 'id: im-qqbot'
|
|
65
|
+
dsh --profile <你的profile> --dump-config | grep -A3 'id: qqbot-plus'
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### 方式二:从本地 tarball 安装
|
|
69
|
+
|
|
70
|
+
```bash
|
|
71
|
+
cd /path/to/dsh-qqbot-plus
|
|
72
|
+
npm pack
|
|
73
|
+
# 生成 yangfan1998-dsh-qqbot-plus-0.1.0.tgz
|
|
74
|
+
|
|
75
|
+
dsh plugin --profile <你的profile> add ./yangfan1998-dsh-qqbot-plus-0.1.0.tgz
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
### 方式三:已经有 QQ 网关的 profile
|
|
79
|
+
|
|
80
|
+
这个包默认会插入 `im-qqbot`。如果你已经装了 `@zaofan/dsh-qqbot`,**不要**把本包加入 `dsh.profile.bundles`,否则会出现重复的 `im-qqbot`。
|
|
81
|
+
|
|
82
|
+
改为:安装本包后,把 [`cordis.tools-only.yml`](./cordis.tools-only.yml) 里的 `- insert:` 段复制到你 profile 自己的 `cordis.patch.yml`。
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
## 配置凭据
|
|
87
|
+
|
|
88
|
+
bundle 的 `cordis.patch.yml` 使用 `__FROM_ENV__` 读取 `appId` / `appSecret`。
|
|
89
|
+
|
|
90
|
+
### 方式 A:环境变量
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
export QQBOT_APPID=1905977275
|
|
94
|
+
export QQBOT_APP_SECRET=你的secret
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 方式 B:直接写 profile patch
|
|
98
|
+
|
|
99
|
+
编辑 profile 的 `cordis.patch.yml` 里的 `im-qqbot` 行:
|
|
100
|
+
|
|
101
|
+
```yaml
|
|
102
|
+
- id: im-qqbot
|
|
103
|
+
name: '@zaofan/dsh-qqbot'
|
|
104
|
+
config:
|
|
105
|
+
appId: '1905977275'
|
|
106
|
+
appSecret: '你的secret'
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
不要把真实密钥提交到 Git。
|
|
110
|
+
|
|
111
|
+
如果想让机器人接收非 @ 的群消息,群主还需要在 QQ 机器人资料页开启“接收群消息/通知”。
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## 工具配置
|
|
116
|
+
|
|
117
|
+
bundle 自带安全默认值。覆盖时改 `qqbot-plus` 行:
|
|
118
|
+
|
|
119
|
+
```yaml
|
|
120
|
+
- id: qqbot-plus
|
|
121
|
+
name: '@yangfan1998/dsh-qqbot-plus'
|
|
122
|
+
config:
|
|
123
|
+
vision:
|
|
124
|
+
provider: zhipu
|
|
125
|
+
model: aliyun/qwen3-vl-plus
|
|
126
|
+
maxTokens: 1024
|
|
127
|
+
tts:
|
|
128
|
+
bin: edge-tts
|
|
129
|
+
voice: zh-CN-XiaoyiNeural
|
|
130
|
+
rate: '+5%'
|
|
131
|
+
pitch: '+12Hz'
|
|
132
|
+
maxChars: 500
|
|
133
|
+
bilibili:
|
|
134
|
+
timeoutMs: 20000
|
|
135
|
+
danmakuLimit: 25
|
|
136
|
+
commentLimit: 10
|
|
137
|
+
replyLimit: 5
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
### 识图
|
|
141
|
+
|
|
142
|
+
只要你的 LLM 路由里有支持 `image` 输入的模型即可。模型必须在 `llm-pi-ai`(或其他 LLM 插件)的 provider 配置里存在。
|
|
143
|
+
|
|
144
|
+
模型不可用时,`qqbot_describe_image` 会自动禁用;不会拖垮整个插件。
|
|
145
|
+
|
|
146
|
+
### 语音
|
|
147
|
+
|
|
148
|
+
`tts_speak` 调用外部 `edge-tts`,默认把 mp3 写到 `downloads/tts`。
|
|
149
|
+
|
|
150
|
+
```bash
|
|
151
|
+
python3 -m pip install edge-tts
|
|
152
|
+
# 或者指向已有 venv:
|
|
153
|
+
# tts.bin: /path/to/venv/bin/edge-tts
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
`edge-tts` 不可用时,工具会返回明确错误,不会让插件崩溃。
|
|
157
|
+
|
|
158
|
+
### B 站
|
|
159
|
+
|
|
160
|
+
公开视频的元数据、弹幕、评论不需要 Cookie;字幕通常需要登录:
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
export BILIBILI_SESSDATA=你的SESSDATA
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
B 站会限流匿名请求;工具内部做了节流,并缓存匿名 `buvid3` Cookie。
|
|
167
|
+
|
|
168
|
+
---
|
|
169
|
+
|
|
170
|
+
## 工具列表
|
|
171
|
+
|
|
172
|
+
| 工具 | 用途 |
|
|
173
|
+
|---|---|
|
|
174
|
+
| `qqbot_describe_image` | 看一张本地图片或 URL;OCR、表格、截图、照片 |
|
|
175
|
+
| `tts_speak` | 用 Edge TTS 生成短语音 mp3;再用 `send_media(kind="voice")` 发出 |
|
|
176
|
+
| `bili_read` | 视频元数据、弹幕、热评(含楼中楼)、可选字幕 |
|
|
177
|
+
| `bili_search` | 按标题/关键词搜 B 站,返回 BV 和匹配度 |
|
|
178
|
+
| `bili_hot` | B 站热门榜 |
|
|
179
|
+
| `bili_frames` | 视频缩略图拼图 → 视觉模型概述;分辨率低,不要当事实 |
|
|
180
|
+
|
|
181
|
+
---
|
|
182
|
+
|
|
183
|
+
## 可选扩展
|
|
184
|
+
|
|
185
|
+
包内带了两个 `{dataRoot}/.qqbot-extensions` 扩展:
|
|
186
|
+
|
|
187
|
+
- `extensions/inbound/bili-card-url.mjs` — 从 QQ 小程序卡片的 raw 数据里提取 B 站 URL。只接受 URL,不接受裸 `BV...`,因为 QQ message id 里可能刚好包含假 BV。
|
|
188
|
+
- `extensions/outbound/abs-image-paths.mjs` — 发图前把 markdown 里的相对图片路径改成绝对路径。
|
|
189
|
+
|
|
190
|
+
复制到 QQ 机器人的数据根:
|
|
191
|
+
|
|
192
|
+
```bash
|
|
193
|
+
DATA_ROOT="/path/to/qqbot/data-root" # 通常是 <im-qqbot.cwd>/dshqqbot
|
|
194
|
+
PKG_DIR="$(node -e "console.log(require.resolve('@yangfan1998/dsh-qqbot-plus'))" | xargs dirname)"
|
|
195
|
+
|
|
196
|
+
mkdir -p "$DATA_ROOT/.qqbot-extensions/inbound" "$DATA_ROOT/.qqbot-extensions/outbound"
|
|
197
|
+
cp "$PKG_DIR/extensions/inbound/bili-card-url.mjs" "$DATA_ROOT/.qqbot-extensions/inbound/"
|
|
198
|
+
cp "$PKG_DIR/extensions/outbound/abs-image-paths.mjs" "$DATA_ROOT/.qqbot-extensions/outbound/"
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
`abs-image-paths` 默认用 `process.cwd()` 解析相对路径;如果宿主 cwd 和 `im-qqbot.cwd` 不一致,设置 `QQBOT_CWD`。
|
|
202
|
+
|
|
203
|
+
---
|
|
204
|
+
|
|
205
|
+
## 不包含什么
|
|
206
|
+
|
|
207
|
+
- 不包含 QQ AppID / AppSecret / API Key / Cookie
|
|
208
|
+
- 不包含人设或群守则(自带你的)
|
|
209
|
+
- 不包含表情包图库(第三方素材授权问题)
|
|
210
|
+
- 不包含 Web 设置页;通过 `cordis.patch.yml` 或环境变量配置
|
|
211
|
+
- 不包含 `launchd` / systemd 服务文件;部署方式由你决定
|
|
212
|
+
|
|
213
|
+
---
|
|
214
|
+
|
|
215
|
+
## 安全说明
|
|
216
|
+
|
|
217
|
+
- B 站工具会访问 `bilibili.com`、`b23.tv` 和 `api.bilibili.com`。
|
|
218
|
+
- 识图工具只下载你传入的 `http(s)` 图片,不扫描任意文件。
|
|
219
|
+
- `tts_speak` 会用配置的 `edge-tts` 可执行文件执行文本参数;不要把 `tts.bin` 指向不可信脚本。
|
|
220
|
+
- 本包不内置任何凭据。建议用专门的 QQ 机器人账号运行。
|
|
221
|
+
|
|
222
|
+
---
|
|
223
|
+
|
|
224
|
+
## 发布检查
|
|
225
|
+
|
|
226
|
+
- [ ] `npm pack` 后在全新测试 profile 安装
|
|
227
|
+
- [ ] 确认 `im-qqbot` + `qqbot-plus` 都激活
|
|
228
|
+
- [ ] 用真实图片验证 `qqbot_describe_image`
|
|
229
|
+
- [ ] 用 `edge-tts` 验证 `tts_speak`
|
|
230
|
+
- [ ] 用公开 BV 验证 `bili_read`
|
|
231
|
+
- [ ] 更新 `package.json` 里的版本/作者/仓库
|
|
232
|
+
- [ ] `npm publish`(需要 npm 账号和 2FA)
|
|
233
|
+
- [ ] 推到自己的 GitHub 仓库(不要复用别人的凭据)
|
|
234
|
+
- [ ] 加 `dsh-plugin` topic,提交到 DSH 插件市场
|
|
235
|
+
|
|
236
|
+
---
|
|
237
|
+
|
|
238
|
+
## 许可证
|
|
239
|
+
|
|
240
|
+
MIT,见 [LICENSE](./LICENSE)。
|
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# dsh-qqbot-plus bundle patch
|
|
2
|
+
#
|
|
3
|
+
# Mounts the QQ gateway from @zaofan/dsh-qqbot and the tools shipped by this
|
|
4
|
+
# package. Intended for a FRESH profile: if you already installed
|
|
5
|
+
# @zaofan/dsh-qqbot, do not apply this patch twice (duplicate `im-qqbot`).
|
|
6
|
+
#
|
|
7
|
+
# Credentials: either set QQBOT_APPID / QQBOT_SECRET in the environment, or
|
|
8
|
+
# replace __FROM_ENV__ below with literal strings. Never commit real secrets.
|
|
9
|
+
- insert:
|
|
10
|
+
- id: im-qqbot
|
|
11
|
+
name: '@zaofan/dsh-qqbot'
|
|
12
|
+
config:
|
|
13
|
+
appId: __FROM_ENV__
|
|
14
|
+
appSecret: __FROM_ENV__
|
|
15
|
+
requireMention: false
|
|
16
|
+
textChunkLimit: 4500
|
|
17
|
+
sessionIdleTimeout: 1800000
|
|
18
|
+
maxQueue: 20
|
|
19
|
+
processingTimeoutMs: 120000
|
|
20
|
+
historyLimit: 10
|
|
21
|
+
access:
|
|
22
|
+
c2cMode: open
|
|
23
|
+
c2cAllow: []
|
|
24
|
+
groupMode: open
|
|
25
|
+
groupAllow: []
|
|
26
|
+
behavior:
|
|
27
|
+
freeIntervalSec: 120
|
|
28
|
+
mentionIntervalSec: 0
|
|
29
|
+
directIntervalSec: 0
|
|
30
|
+
debounce:
|
|
31
|
+
enabled: true
|
|
32
|
+
silenceSec: 5
|
|
33
|
+
maxMsgs: 10
|
|
34
|
+
mentionDelayed: false
|
|
35
|
+
busySendMode: queue
|
|
36
|
+
debug: false
|
|
37
|
+
|
|
38
|
+
- id: qqbot-plus
|
|
39
|
+
name: '@yangfan1998/dsh-qqbot-plus'
|
|
40
|
+
config:
|
|
41
|
+
vision:
|
|
42
|
+
provider: zhipu
|
|
43
|
+
model: aliyun/qwen3-vl-plus
|
|
44
|
+
maxTokens: 1024
|
|
45
|
+
tts:
|
|
46
|
+
bin: edge-tts
|
|
47
|
+
voice: zh-CN-XiaoyiNeural
|
|
48
|
+
rate: '+5%'
|
|
49
|
+
pitch: '+12Hz'
|
|
50
|
+
maxChars: 500
|
|
51
|
+
bilibili:
|
|
52
|
+
timeoutMs: 20000
|
|
53
|
+
danmakuLimit: 25
|
|
54
|
+
commentLimit: 10
|
|
55
|
+
replyLimit: 5
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# Tools-only overlay for profiles that ALREADY mount @zaofan/dsh-qqbot.
|
|
2
|
+
# Do NOT add this package to dsh.profile.bundles in that case; copy the
|
|
3
|
+
# `- insert:` block below into the profile's own cordis.patch.yml instead.
|
|
4
|
+
- insert:
|
|
5
|
+
- id: qqbot-plus
|
|
6
|
+
name: '@yangfan1998/dsh-qqbot-plus'
|
|
7
|
+
config:
|
|
8
|
+
vision:
|
|
9
|
+
provider: zhipu
|
|
10
|
+
model: aliyun/qwen3-vl-plus
|
|
11
|
+
maxTokens: 1024
|
|
12
|
+
tts:
|
|
13
|
+
bin: edge-tts
|
|
14
|
+
voice: zh-CN-XiaoyiNeural
|
|
15
|
+
rate: '+5%'
|
|
16
|
+
pitch: '+12Hz'
|
|
17
|
+
maxChars: 500
|
|
18
|
+
bilibili:
|
|
19
|
+
timeoutMs: 20000
|
|
20
|
+
danmakuLimit: 25
|
|
21
|
+
commentLimit: 10
|
|
22
|
+
replyLimit: 5
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# Optional QQ bot extensions
|
|
2
|
+
|
|
3
|
+
These files are **not loaded by the npm package automatically**. Copy them into
|
|
4
|
+
the QQ bot's data root:
|
|
5
|
+
|
|
6
|
+
```text
|
|
7
|
+
{dataRoot}/.qqbot-extensions/inbound/bili-card-url.mjs
|
|
8
|
+
{dataRoot}/.qqbot-extensions/outbound/abs-image-paths.mjs
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`dataRoot` is the QQ bot's data directory (usually `<im-qqbot.cwd>/dshqqbot`).
|
|
12
|
+
|
|
13
|
+
- `bili-card-url.mjs`: reads a Bilibili URL out of a QQ mini-program card's raw
|
|
14
|
+
payload. It only accepts `bilibili.com` / `b23.tv` URLs, never bare `BV...`
|
|
15
|
+
substrings, because QQ message IDs can contain false BVs.
|
|
16
|
+
- `abs-image-paths.mjs`: rewrites relative markdown image paths to absolute
|
|
17
|
+
paths so the QQ uploader can find them. It resolves against `process.cwd()`;
|
|
18
|
+
set `QQBOT_CWD` when the host cwd differs from `im-qqbot.cwd`.
|
|
19
|
+
|
|
20
|
+
Reload extensions with `/tools-reload` (or restart the bot).
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* bili-card-url.mjs — 从 QQ 的 B 站分享卡片 raw 事件里挖出视频链接。
|
|
3
|
+
*
|
|
4
|
+
* ⚠️ 只认 B 站 URL,不再从任意字符串里抠 BV:
|
|
5
|
+
* QQ 的 message id(ROBOT1.0_...)里可能正好包含 "BVxxxxxxxxxx" 子串,
|
|
6
|
+
* 之前会把 message id 里的假 BV 当成视频号(实测 BVHglOfewpT0 → -400)。
|
|
7
|
+
* 卡片没有 URL 时交给 bili_search 按标题搜。
|
|
8
|
+
*/
|
|
9
|
+
import { appendFileSync } from 'node:fs'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
|
|
12
|
+
export const name = 'bili-card-url'
|
|
13
|
+
|
|
14
|
+
const BILI_URL_RE = /https?:\/\/[^\s"'<>\\]*(?:bilibili\.com|b23\.tv)[^\s"'<>\\]*/i
|
|
15
|
+
|
|
16
|
+
function collect(value, out, depth = 0) {
|
|
17
|
+
if (depth > 8 || value == null) return
|
|
18
|
+
if (typeof value === 'string') {
|
|
19
|
+
const url = value.match(BILI_URL_RE)?.[0]
|
|
20
|
+
if (url) out.urls.add(url)
|
|
21
|
+
return
|
|
22
|
+
}
|
|
23
|
+
if (Array.isArray(value)) {
|
|
24
|
+
for (const v of value) collect(v, out, depth + 1)
|
|
25
|
+
return
|
|
26
|
+
}
|
|
27
|
+
if (typeof value === 'object') {
|
|
28
|
+
for (const v of Object.values(value)) {
|
|
29
|
+
if (typeof v === 'object' || typeof v === 'string') collect(v, out, depth + 1)
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function diag(ctx, payload) {
|
|
35
|
+
try {
|
|
36
|
+
const root = String(ctx.dataRoot || '')
|
|
37
|
+
if (!root) return
|
|
38
|
+
appendFileSync(join(root, 'bili-card-diag.log'), new Date().toISOString() + ' ' + JSON.stringify(payload) + '\n')
|
|
39
|
+
} catch { /* ignore */ }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export async function onInbound(ctx, next) {
|
|
43
|
+
try {
|
|
44
|
+
const text = String(ctx.text || '')
|
|
45
|
+
const isCard = /卡片消息|哔哩哔哩/i.test(text)
|
|
46
|
+
const already = BILI_URL_RE.test(text)
|
|
47
|
+
if (isCard || /哔哩哔哩|bilibili|b23\.tv|BV[0-9A-Za-z]{10}/i.test(text)) {
|
|
48
|
+
const out = { urls: new Set() }
|
|
49
|
+
collect(ctx.message?.raw, out)
|
|
50
|
+
collect(ctx.message?.msgElements, out)
|
|
51
|
+
collect(ctx.message?.arkData, out)
|
|
52
|
+
if (out.urls.size) {
|
|
53
|
+
diag(ctx, { found: [...out.urls], hadLink: already })
|
|
54
|
+
if (!already) {
|
|
55
|
+
const link = [...out.urls][0]
|
|
56
|
+
ctx.rewrite({ text: `${text}\n[系统提取] B站视频链接: ${link}`, reason: 'bili-card-url' })
|
|
57
|
+
}
|
|
58
|
+
} else if (isCard) {
|
|
59
|
+
const raw = ctx.message?.raw
|
|
60
|
+
const keys = raw && typeof raw === 'object' ? Object.keys(raw) : []
|
|
61
|
+
diag(ctx, { found: [], hadLink: already, rawKeys: keys.slice(0, 40) })
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
} catch { /* 绝不影响入站 */ }
|
|
65
|
+
return next()
|
|
66
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 出站扩展:把 markdown 图片里的“相对路径”改成绝对路径。
|
|
3
|
+
* 背景:QQ 插件只上传绝对路径(/...、file://...、C:/...)的本地图;
|
|
4
|
+
* 模型经常写 ,会被当成普通文本,QQ 只显示 [alt]。
|
|
5
|
+
*
|
|
6
|
+
* 只改本地相对路径,http(s)/qqbot-media/data/file/绝对路径原样放过。
|
|
7
|
+
*/
|
|
8
|
+
import path from 'node:path'
|
|
9
|
+
|
|
10
|
+
export const name = 'abs-image-paths'
|
|
11
|
+
|
|
12
|
+
// Resolve relative image paths against the bot's current working directory.
|
|
13
|
+
// Prefer ctx.cwd when the host exposes it; QQBOT_CWD is the explicit override.
|
|
14
|
+
|
|
15
|
+
export async function onOutbound(ctx, next) {
|
|
16
|
+
const CWD = process.env.QQBOT_CWD || (typeof ctx?.cwd === 'string' ? ctx.cwd : process.cwd())
|
|
17
|
+
const text = String(ctx?.text ?? '')
|
|
18
|
+
if (!text.includes('![')) return next()
|
|
19
|
+
|
|
20
|
+
const out = text.replace(
|
|
21
|
+
/!\[([^\]]*)\]\(\s*<?((?!https?:|qqbot-media:|data:|file:|\/|[A-Za-z]:[\\/])[^)\n]+?)>?\s*\)/g,
|
|
22
|
+
(whole, alt, src) => {
|
|
23
|
+
const clean = String(src).trim()
|
|
24
|
+
if (!clean) return whole
|
|
25
|
+
return `})`
|
|
26
|
+
},
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
if (out !== text) ctx.rewrite(out)
|
|
30
|
+
return next()
|
|
31
|
+
}
|
package/index.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-qqbot-plus — one-install bundle for the QQ bot.
|
|
3
|
+
*
|
|
4
|
+
* Mounts three optional tools on the host:
|
|
5
|
+
* - qqbot_describe_image (vision, needs an image-capable model)
|
|
6
|
+
* - tts_speak (Edge TTS, needs the `edge-tts` executable)
|
|
7
|
+
* - bili_read / bili_search / bili_hot / bili_frames
|
|
8
|
+
*
|
|
9
|
+
* The QQ gateway itself is provided by @zaofan/dsh-qqbot and is mounted by
|
|
10
|
+
* cordis.patch.yml. Each tool fails soft: a missing model/executable only
|
|
11
|
+
* disables that tool, it never takes down the gateway.
|
|
12
|
+
*/
|
|
13
|
+
import { apply as applyVision } from './tools/vision.js'
|
|
14
|
+
import { apply as applyTts } from './tools/tts.js'
|
|
15
|
+
import { apply as applyBilibili } from './tools/bilibili.js'
|
|
16
|
+
|
|
17
|
+
export const name = 'dsh-qqbot-plus'
|
|
18
|
+
export const inject = ['tools']
|
|
19
|
+
|
|
20
|
+
export function apply(ctx, config = {}) {
|
|
21
|
+
const cfg = config && typeof config === 'object' ? config : {}
|
|
22
|
+
const tools = [
|
|
23
|
+
['vision', applyVision, cfg.vision],
|
|
24
|
+
['tts', applyTts, cfg.tts],
|
|
25
|
+
['bilibili', applyBilibili, cfg.bilibili],
|
|
26
|
+
]
|
|
27
|
+
for (const [key, fn, sub] of tools) {
|
|
28
|
+
try {
|
|
29
|
+
fn(ctx, sub && typeof sub === 'object' ? sub : {})
|
|
30
|
+
} catch (error) {
|
|
31
|
+
ctx.logger?.warn?.(`[dsh-qqbot-plus] ${key} tool failed to mount: ${error instanceof Error ? error.message : String(error)}`)
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yangfan1998/dsh-qqbot-plus",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "One-install DeepSeek Harness QQ bot bundle: @zaofan/dsh-qqbot gateway plus vision, Edge TTS and Bilibili reading tools.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"exports": {
|
|
8
|
+
".": "./index.js"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"index.js",
|
|
12
|
+
"tools/**/*.js",
|
|
13
|
+
"extensions/**/*.mjs",
|
|
14
|
+
"extensions/README.md",
|
|
15
|
+
"cordis.patch.yml",
|
|
16
|
+
"README.md",
|
|
17
|
+
"LICENSE",
|
|
18
|
+
"cordis.tools-only.yml"
|
|
19
|
+
],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"check": "node --check index.js && node --check tools/vision.js && node --check tools/tts.js && node --check tools/bilibili.js && node --check extensions/inbound/bili-card-url.mjs && node --check extensions/outbound/abs-image-paths.mjs",
|
|
22
|
+
"pack:dry": "npm pack --dry-run",
|
|
23
|
+
"pack": "npm pack"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"dsh-plugin",
|
|
27
|
+
"deepseek-harness",
|
|
28
|
+
"qqbot",
|
|
29
|
+
"qq",
|
|
30
|
+
"vision",
|
|
31
|
+
"tts",
|
|
32
|
+
"bilibili"
|
|
33
|
+
],
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=22.13.0"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@zaofan/dsh-qqbot": "^1.10.46"
|
|
40
|
+
},
|
|
41
|
+
"peerDependencies": {
|
|
42
|
+
"@deepseek-ai/dsh-llm": "*"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
},
|
|
47
|
+
"dsh": {
|
|
48
|
+
"manifestVersion": 1,
|
|
49
|
+
"bundle": {
|
|
50
|
+
"patch": "./cordis.patch.yml"
|
|
51
|
+
},
|
|
52
|
+
"engines": {
|
|
53
|
+
"dsh": ">=0.2.1-alpha.2"
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"repository": {
|
|
57
|
+
"type": "git",
|
|
58
|
+
"url": "git+https://github.com/FanFFF/dsh-qqbot-plus.git"
|
|
59
|
+
},
|
|
60
|
+
"homepage": "https://github.com/FanFFF/dsh-qqbot-plus#readme",
|
|
61
|
+
"bugs": {
|
|
62
|
+
"url": "https://github.com/FanFFF/dsh-qqbot-plus/issues"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-qqbot-plus/bilibili — 读 B 站视频:
|
|
3
|
+
* bili_read 元数据 / 弹幕(短视频全量)/ 热评(含楼中楼)/ 字幕(需 SESSDATA)
|
|
4
|
+
* bili_frames 视频缩略图拼图 → 视觉模型概述画面
|
|
5
|
+
* bili_hot B 站热门榜(自己刷 B 站用)
|
|
6
|
+
*/
|
|
7
|
+
import { setTimeout as sleep } from 'node:timers/promises'
|
|
8
|
+
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
9
|
+
|
|
10
|
+
export const name = 'dsh-qqbot-plus:bilibili'
|
|
11
|
+
export const inject = ['tools']
|
|
12
|
+
|
|
13
|
+
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0 Safari/537.36'
|
|
14
|
+
const REF = 'https://www.bilibili.com/'
|
|
15
|
+
const BV_RE = /BV[0-9A-Za-z]{10}/
|
|
16
|
+
const AV_RE = /av(\d+)/i
|
|
17
|
+
const B23_RE = /https?:\/\/b23\.tv\/[A-Za-z0-9]+/i
|
|
18
|
+
let lastRequestAt = 0
|
|
19
|
+
let buvidCookie = ''
|
|
20
|
+
|
|
21
|
+
async function throttle(ms = 400) {
|
|
22
|
+
const wait = lastRequestAt + ms - Date.now()
|
|
23
|
+
if (wait > 0) await sleep(wait)
|
|
24
|
+
lastRequestAt = Date.now()
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function headers(extra = {}) {
|
|
28
|
+
const h = {
|
|
29
|
+
'user-agent': UA,
|
|
30
|
+
referer: REF,
|
|
31
|
+
accept: 'application/json, text/plain, */*',
|
|
32
|
+
'accept-language': 'zh-CN,zh;q=0.9',
|
|
33
|
+
...extra,
|
|
34
|
+
}
|
|
35
|
+
const sess = process.env.BILIBILI_SESSDATA || ''
|
|
36
|
+
const cookies = []
|
|
37
|
+
if (sess) cookies.push(`SESSDATA=${sess}`)
|
|
38
|
+
if (buvidCookie) cookies.push(buvidCookie)
|
|
39
|
+
if (cookies.length) h.cookie = cookies.join('; ')
|
|
40
|
+
return h
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function ensureBuvid(timeoutMs) {
|
|
44
|
+
if (buvidCookie) return
|
|
45
|
+
try {
|
|
46
|
+
await throttle()
|
|
47
|
+
const res = await fetch('https://www.bilibili.com/', { headers: headers(), redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
|
|
48
|
+
const cookies = typeof res.headers.getSetCookie === 'function' ? res.headers.getSetCookie() : []
|
|
49
|
+
const hit = cookies.find(c => String(c).startsWith('buvid3='))
|
|
50
|
+
if (hit) buvidCookie = String(hit).split(';')[0]
|
|
51
|
+
} catch { /* 没 cookie 也继续试 */ }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function fetchJson(url, timeoutMs) {
|
|
55
|
+
await throttle()
|
|
56
|
+
const res = await fetch(url, { headers: headers(), redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
|
|
57
|
+
if (!res.ok) throw new Error(`B站接口 HTTP ${res.status}`)
|
|
58
|
+
const data = await res.json()
|
|
59
|
+
if (typeof data?.code !== 'number') throw new Error('B站接口返回非 JSON 信封')
|
|
60
|
+
if (data.code !== 0) throw new Error(`B站接口错误 ${data.code}: ${data.message || ''}`)
|
|
61
|
+
return data.data
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function fetchText(url, timeoutMs) {
|
|
65
|
+
await throttle()
|
|
66
|
+
const res = await fetch(url, { headers: headers({ accept: 'application/xml,text/xml,*/*' }), redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
|
|
67
|
+
if (!res.ok) throw new Error(`B站接口 HTTP ${res.status}`)
|
|
68
|
+
return await res.text()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function decodeXml(s) {
|
|
72
|
+
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/'/g, "'")
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function fmtDuration(sec) {
|
|
76
|
+
const n = Number(sec) || 0
|
|
77
|
+
const h = Math.floor(n / 3600), m = Math.floor((n % 3600) / 60), s = n % 60
|
|
78
|
+
return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}` : `${m}:${String(s).padStart(2, '0')}`
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function fmtDate(ts) {
|
|
82
|
+
try { return new Date(Number(ts) * 1000).toISOString().slice(0, 10) } catch { return '' }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function fmtCount(n) {
|
|
86
|
+
const v = Number(n) || 0
|
|
87
|
+
if (v >= 100000000) return (v / 100000000).toFixed(1) + '亿'
|
|
88
|
+
if (v >= 10000) return (v / 10000).toFixed(1) + '万'
|
|
89
|
+
return String(v)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function resolveTarget(input, timeoutMs) {
|
|
93
|
+
let s = String(input ?? '').trim()
|
|
94
|
+
if (!s) throw new Error('请给 B 站视频链接、BV 号或 av 号')
|
|
95
|
+
if (/^b23\.tv\//i.test(s)) s = 'https://' + s
|
|
96
|
+
const short = s.match(B23_RE)?.[0]
|
|
97
|
+
if (short) {
|
|
98
|
+
await throttle()
|
|
99
|
+
const res = await fetch(short, { headers: headers(), redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
|
|
100
|
+
s = res.url || s
|
|
101
|
+
}
|
|
102
|
+
const bv = s.match(BV_RE)?.[0]
|
|
103
|
+
const av = s.match(AV_RE)?.[1]
|
|
104
|
+
if (bv) return { kind: 'bvid', id: bv }
|
|
105
|
+
if (av) return { kind: 'aid', id: String(av) }
|
|
106
|
+
throw new Error('没能从输入里找到 BV 号 / av 号 / B 站视频链接')
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function getVideo(target, timeoutMs) {
|
|
110
|
+
const q = target.kind === 'bvid' ? `bvid=${encodeURIComponent(target.id)}` : `aid=${encodeURIComponent(target.id)}`
|
|
111
|
+
return await fetchJson(`https://api.bilibili.com/x/web-interface/view?${q}`, timeoutMs)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function normText(s) {
|
|
115
|
+
return String(s ?? '').replace(/[\s\p{P}\p{S}]/gu, '').toLowerCase()
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function titleScore(query, title) {
|
|
119
|
+
const a = normText(query), b = normText(title)
|
|
120
|
+
if (!a || !b) return 0
|
|
121
|
+
if (b.includes(a) || a.includes(b)) return 1
|
|
122
|
+
const grams = new Set()
|
|
123
|
+
for (let i = 0; i < a.length - 1; i += 2) grams.add(a.slice(i, i + 2))
|
|
124
|
+
if (grams.size === 0) return 0
|
|
125
|
+
let hit = 0
|
|
126
|
+
for (const g of grams) if (b.includes(g)) hit += 1
|
|
127
|
+
return hit / grams.size
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async function searchBili(keyword, limit, timeoutMs) {
|
|
131
|
+
const q = String(keyword ?? '').trim()
|
|
132
|
+
if (!q) throw new Error('bili_search: keyword 不能为空')
|
|
133
|
+
await ensureBuvid(timeoutMs)
|
|
134
|
+
const html = await fetchText('https://search.bilibili.com/all?keyword=' + encodeURIComponent(q), timeoutMs)
|
|
135
|
+
const seen = new Set()
|
|
136
|
+
const bvs = []
|
|
137
|
+
for (const m of html.matchAll(/href="([^"]*?\/video\/(BV[0-9A-Za-z]{10})[^"]*)"/g)) {
|
|
138
|
+
const bv = m[2]
|
|
139
|
+
if (!bv || seen.has(bv)) continue
|
|
140
|
+
seen.add(bv)
|
|
141
|
+
bvs.push(bv)
|
|
142
|
+
}
|
|
143
|
+
if (bvs.length === 0) return []
|
|
144
|
+
const candidates = bvs.slice(0, Math.min(Math.max(limit + 4, 6), 12))
|
|
145
|
+
const rows = []
|
|
146
|
+
for (const bv of candidates) {
|
|
147
|
+
try {
|
|
148
|
+
const v = await getVideo({ kind: 'bvid', id: bv }, timeoutMs)
|
|
149
|
+
rows.push({ bvid: bv, title: v.title, up: v.owner?.name ?? '', view: Number(v.stat?.view) || 0, score: titleScore(q, v.title) })
|
|
150
|
+
} catch { /* 单个失败跳过 */ }
|
|
151
|
+
}
|
|
152
|
+
rows.sort((a, b) => b.score - a.score || b.view - a.view)
|
|
153
|
+
return rows.slice(0, limit)
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function pickPage(video, target) {
|
|
157
|
+
const pages = Array.isArray(video.pages) ? video.pages : []
|
|
158
|
+
const p = Number(target.page) || 1
|
|
159
|
+
const page = pages[p - 1] || pages[0]
|
|
160
|
+
return { cid: page?.cid ?? video.cid, page: page?.page ?? 1, part: page?.part ?? '' }
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function getDanmaku(cid, limit, mode, timeoutMs) {
|
|
164
|
+
const xml = await fetchText(`https://api.bilibili.com/x/v1/dm/list.so?oid=${encodeURIComponent(cid)}`, timeoutMs)
|
|
165
|
+
const items = []
|
|
166
|
+
const re = /<d p="([^"]*)">([\s\S]*?)<\/d>/g
|
|
167
|
+
let m
|
|
168
|
+
while ((m = re.exec(xml)) !== null) {
|
|
169
|
+
const text = decodeXml(m[2]).trim()
|
|
170
|
+
if (text) items.push({ text, p: m[1] })
|
|
171
|
+
if (items.length >= 4000) break
|
|
172
|
+
}
|
|
173
|
+
const counts = new Map()
|
|
174
|
+
for (const it of items) counts.set(it.text, (counts.get(it.text) || 0) + 1)
|
|
175
|
+
const wanted = Math.min(Math.max(Number(limit) || 25, 1), 50)
|
|
176
|
+
const top = [...counts.entries()].sort((a, b) => b[1] - a[1]).slice(0, wanted)
|
|
177
|
+
const recent = items.slice(-Math.min(10, wanted)).map(x => x.text)
|
|
178
|
+
const full = mode === 'full' || (mode !== 'sample' && items.length <= 300) ? items.map(x => x.text) : undefined
|
|
179
|
+
return { total: items.length, top: top.map(([text, count]) => ({ text, count })), recent, full, mode: full ? 'full' : 'sample' }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function getComments(aid, limit, replyLimit, timeoutMs) {
|
|
183
|
+
const data = await fetchJson(`https://api.bilibili.com/x/v2/reply?type=1&oid=${encodeURIComponent(aid)}&sort=2&ps=${Math.min(limit, 50)}&pn=1`, timeoutMs)
|
|
184
|
+
const all = [...(data.top_replies || []), ...(data.replies || [])]
|
|
185
|
+
const seen = new Set()
|
|
186
|
+
const list = []
|
|
187
|
+
for (const r of all) {
|
|
188
|
+
const id = String(r.rpid ?? '')
|
|
189
|
+
if (id && seen.has(id)) continue
|
|
190
|
+
if (id) seen.add(id)
|
|
191
|
+
const item = {
|
|
192
|
+
user: r.member?.uname ?? '',
|
|
193
|
+
text: r.content?.message ?? '',
|
|
194
|
+
like: Number(r.like) || 0,
|
|
195
|
+
replies: Number(r.rcount) || 0,
|
|
196
|
+
nested: [],
|
|
197
|
+
}
|
|
198
|
+
if (replyLimit > 0 && Number(r.rcount) > 0) {
|
|
199
|
+
try {
|
|
200
|
+
const sub = await fetchJson(`https://api.bilibili.com/x/v2/reply/reply?type=1&oid=${encodeURIComponent(aid)}&root=${encodeURIComponent(id)}&ps=${Math.min(replyLimit, 10)}&pn=1`, timeoutMs)
|
|
201
|
+
item.nested = (sub.replies || []).slice(0, replyLimit).map(x => ({
|
|
202
|
+
user: x.member?.uname ?? '',
|
|
203
|
+
text: x.content?.message ?? '',
|
|
204
|
+
like: Number(x.like) || 0,
|
|
205
|
+
}))
|
|
206
|
+
} catch { /* 楼中楼失败不影响主楼 */ }
|
|
207
|
+
}
|
|
208
|
+
list.push(item)
|
|
209
|
+
}
|
|
210
|
+
list.sort((a, b) => b.like - a.like)
|
|
211
|
+
return { total: Number(data.page?.count) || list.length, list: list.slice(0, limit) }
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
async function getSubtitles(aid, cid, lang, maxChars, timeoutMs) {
|
|
215
|
+
const data = await fetchJson(`https://api.bilibili.com/x/player/v2?aid=${encodeURIComponent(aid)}&cid=${encodeURIComponent(cid)}`, timeoutMs)
|
|
216
|
+
const tracks = data.subtitle?.subtitles || []
|
|
217
|
+
if (!tracks.length) {
|
|
218
|
+
return { available: false, reason: '没有可访问的字幕轨(可能视频没字幕,或需要登录 BILIBILI_SESSDATA)' }
|
|
219
|
+
}
|
|
220
|
+
const track = tracks.find(t => String(t.lan || '').toLowerCase() === String(lang || 'zh-CN').toLowerCase()) || tracks[0]
|
|
221
|
+
let url = String(track.subtitle_url || '')
|
|
222
|
+
if (url.startsWith('//')) url = 'https:' + url
|
|
223
|
+
if (!url) return { available: false, reason: '字幕轨没有下载地址' }
|
|
224
|
+
await throttle()
|
|
225
|
+
const res = await fetch(url, { headers: headers({ accept: 'application/json,*/*' }), redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) })
|
|
226
|
+
if (!res.ok) return { available: false, reason: `字幕下载 HTTP ${res.status}` }
|
|
227
|
+
const body = await res.json()
|
|
228
|
+
const lines = (body.body || []).map(x => String(x.content ?? '').trim()).filter(Boolean)
|
|
229
|
+
let text = lines.join('\n')
|
|
230
|
+
let truncated = false
|
|
231
|
+
if (text.length > maxChars) { text = text.slice(0, maxChars); truncated = true }
|
|
232
|
+
return { available: true, language: track.lan_doc || track.lan || '', text, truncated, lines: lines.length }
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async function getVideoShot(aid, cid, timeoutMs) {
|
|
236
|
+
const data = await fetchJson(`https://api.bilibili.com/x/player/videoshot?aid=${encodeURIComponent(aid)}&cid=${encodeURIComponent(cid)}&index=1`, timeoutMs)
|
|
237
|
+
const images = (data.image || []).map(u => String(u).startsWith('//') ? 'https:' + u : String(u))
|
|
238
|
+
return { images, xLen: data.img_x_len, yLen: data.img_y_len, xSize: data.img_x_size, ySize: data.img_y_size }
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function renderRead(video, page, danmaku, comments, subtitles, include) {
|
|
242
|
+
const d = video
|
|
243
|
+
const out = []
|
|
244
|
+
out.push(`【视频】${d.title}`)
|
|
245
|
+
out.push(`BV: ${d.bvid} AV: ${d.aid} 分P: ${page.page}${page.part ? ` ${page.part}` : ''} 时长: ${fmtDuration(d.duration)} 发布: ${fmtDate(d.pubdate)}`)
|
|
246
|
+
out.push(`UP: ${d.owner?.name ?? ''} 分区: ${d.tname || d.tname_v2 || ''}`)
|
|
247
|
+
out.push(`播放: ${fmtCount(d.stat?.view)} 弹幕: ${fmtCount(d.stat?.danmaku)} 评论: ${fmtCount(d.stat?.reply)} 点赞: ${fmtCount(d.stat?.like)} 投币: ${fmtCount(d.stat?.coin)} 收藏: ${fmtCount(d.stat?.favorite)} 分享: ${fmtCount(d.stat?.share)}`)
|
|
248
|
+
if (d.desc) out.push(`简介: ${String(d.desc).trim().slice(0, 900)}`)
|
|
249
|
+
if (Array.isArray(d.pages) && d.pages.length > 1) {
|
|
250
|
+
out.push(`分P: ${d.pages.slice(0, 10).map(p => `P${p.page} ${p.part || ''}`).join(' | ')}${d.pages.length > 10 ? ' ...' : ''}`)
|
|
251
|
+
}
|
|
252
|
+
if (include.includes('danmaku') && danmaku) {
|
|
253
|
+
out.push('', `【弹幕】共 ${danmaku.total} 条(${danmaku.mode === 'full' ? '全量' : '样本'})`)
|
|
254
|
+
if (danmaku.full) {
|
|
255
|
+
out.push(danmaku.full.join(' | ').slice(0, 9000))
|
|
256
|
+
} else {
|
|
257
|
+
out.push('高频: ' + (danmaku.top.map(x => `${x.text}${x.count > 1 ? `×${x.count}` : ''}`).join(' | ') || '(无)'))
|
|
258
|
+
if (danmaku.recent.length) out.push('近期: ' + danmaku.recent.join(' | '))
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
if (include.includes('comments') && comments) {
|
|
262
|
+
out.push('', `【热评】共 ${fmtCount(comments.total)} 条,取前 ${comments.list.length} 条(含楼中楼样本)`)
|
|
263
|
+
for (const c of comments.list) {
|
|
264
|
+
const t = String(c.text).replace(/\s+/g, ' ').slice(0, 220)
|
|
265
|
+
out.push(`- ${c.user}(👍${fmtCount(c.like)}): ${t}`)
|
|
266
|
+
for (const n of c.nested || []) {
|
|
267
|
+
out.push(` ↳ ${n.user}(👍${fmtCount(n.like)}): ${String(n.text).replace(/\s+/g, ' ').slice(0, 160)}`)
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (include.includes('subtitles') && subtitles) {
|
|
272
|
+
out.push('', '【字幕】')
|
|
273
|
+
if (subtitles.available) {
|
|
274
|
+
out.push(`(${subtitles.language || '字幕'},${subtitles.lines} 行${subtitles.truncated ? ',已截断' : ''})`)
|
|
275
|
+
out.push(subtitles.text)
|
|
276
|
+
} else {
|
|
277
|
+
out.push(subtitles.reason)
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return out.join('\n').slice(0, 18000)
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
function finishError(finish) {
|
|
284
|
+
if (finish?.kind === 'error' || finish?.kind === 'aborted') return new Error(finish.failure?.message || 'vision call failed')
|
|
285
|
+
return undefined
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
export function apply(ctx, config = {}) {
|
|
289
|
+
const tools = ctx.get('tools')
|
|
290
|
+
if (!tools?.register) {
|
|
291
|
+
ctx.logger?.warn('[dsh-qqbot-plus/bilibili] tools 服务不可用,工具未注册')
|
|
292
|
+
return
|
|
293
|
+
}
|
|
294
|
+
const llm = ctx.get('llm')
|
|
295
|
+
const attachments = ctx.get('attachments')
|
|
296
|
+
const canVision = !!llm?.stream && !!attachments?.saveImage
|
|
297
|
+
const cfg = {
|
|
298
|
+
timeoutMs: Number(config.timeoutMs ?? 20000),
|
|
299
|
+
danmakuLimit: Number(config.danmakuLimit ?? 25),
|
|
300
|
+
commentLimit: Number(config.commentLimit ?? 10),
|
|
301
|
+
replyLimit: Number(config.replyLimit ?? 5),
|
|
302
|
+
subtitleLang: String(config.subtitleLang ?? 'zh-CN'),
|
|
303
|
+
subtitleMaxChars: Number(config.subtitleMaxChars ?? 8000),
|
|
304
|
+
visionProvider: String(config.visionProvider ?? 'zhipu'),
|
|
305
|
+
visionModel: String(config.visionModel ?? 'aliyun/qwen3-vl-plus'),
|
|
306
|
+
visionMaxTokens: Number(config.visionMaxTokens ?? 1024),
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const readTool = {
|
|
310
|
+
name: 'bili_read',
|
|
311
|
+
description: 'Read a Bilibili video by URL, b23.tv short link, BV id or av id. Returns metadata, danmaku (full for short videos), hot comments with nested replies, and subtitles when available. Use this whenever a QQ message shares a Bilibili video, then join the discussion based on the returned content. If subtitles are unavailable and you need the visual content, call bili_frames.',
|
|
312
|
+
parameters: {
|
|
313
|
+
type: 'object',
|
|
314
|
+
properties: {
|
|
315
|
+
target: { type: 'string', description: 'Bilibili video URL, b23.tv short link, BV id or av id.' },
|
|
316
|
+
include: {
|
|
317
|
+
type: 'array',
|
|
318
|
+
items: { type: 'string', enum: ['video', 'danmaku', 'comments', 'subtitles'] },
|
|
319
|
+
description: 'Sections to include. Default: video, danmaku, comments. Add subtitles when the video has a public subtitle track.',
|
|
320
|
+
},
|
|
321
|
+
danmaku_mode: { type: 'string', enum: ['auto', 'full', 'sample'], description: 'auto=full when <=300 danmaku, else sample; full/sample force one mode.' },
|
|
322
|
+
danmaku_limit: { type: 'integer', description: 'Sample size for high-frequency danmaku (default 25, max 50).' },
|
|
323
|
+
comment_limit: { type: 'integer', description: 'Top-level comments (default 10, max 30).' },
|
|
324
|
+
reply_limit: { type: 'integer', description: 'Nested replies per top comment (default 5, max 10; 0=off).' },
|
|
325
|
+
subtitle_lang: { type: 'string', description: 'Preferred subtitle language, default zh-CN.' },
|
|
326
|
+
},
|
|
327
|
+
required: ['target'],
|
|
328
|
+
additionalProperties: false,
|
|
329
|
+
},
|
|
330
|
+
output: {
|
|
331
|
+
schema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false },
|
|
332
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
333
|
+
},
|
|
334
|
+
async execute(args) {
|
|
335
|
+
const include = Array.isArray(args.include) && args.include.length ? args.include : ['video', 'danmaku', 'comments']
|
|
336
|
+
const target = await resolveTarget(args.target, cfg.timeoutMs)
|
|
337
|
+
let video
|
|
338
|
+
try {
|
|
339
|
+
video = await getVideo(target, cfg.timeoutMs)
|
|
340
|
+
} catch (e) {
|
|
341
|
+
const msg = e instanceof Error ? e.message : String(e)
|
|
342
|
+
if (/-400|-404|请求错误/.test(msg)) {
|
|
343
|
+
return { text: `这个视频号无效或不存在:${args.target}\n如果它来自 QQ 卡片,请改用 bili_search 按卡片标题搜索(不要用 message id 里的 BV 片段)。` }
|
|
344
|
+
}
|
|
345
|
+
throw e
|
|
346
|
+
}
|
|
347
|
+
const page = pickPage(video, target)
|
|
348
|
+
let danmaku, comments, subtitles
|
|
349
|
+
if (include.includes('danmaku')) {
|
|
350
|
+
danmaku = await getDanmaku(page.cid, args.danmaku_limit || cfg.danmakuLimit, args.danmaku_mode || 'auto', cfg.timeoutMs)
|
|
351
|
+
.catch(e => ({ total: 0, top: [], recent: [], error: e.message }))
|
|
352
|
+
}
|
|
353
|
+
if (include.includes('comments')) {
|
|
354
|
+
comments = await getComments(video.aid, Math.min(Number(args.comment_limit) || cfg.commentLimit, 30), Math.min(Number(args.reply_limit) ?? cfg.replyLimit, 10), cfg.timeoutMs)
|
|
355
|
+
.catch(e => ({ total: 0, list: [], error: e.message }))
|
|
356
|
+
}
|
|
357
|
+
if (include.includes('subtitles')) {
|
|
358
|
+
subtitles = await getSubtitles(video.aid, page.cid, args.subtitle_lang || cfg.subtitleLang, cfg.subtitleMaxChars, cfg.timeoutMs)
|
|
359
|
+
.catch(e => ({ available: false, reason: e.message }))
|
|
360
|
+
}
|
|
361
|
+
return { text: renderRead(video, page, danmaku, comments, subtitles, include) }
|
|
362
|
+
},
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const framesTool = {
|
|
366
|
+
name: 'bili_frames',
|
|
367
|
+
description: 'Fetch Bilibili video snapshot sprites (a grid of frames) and ask the vision model to describe the visuals. Use this when subtitles are unavailable but you need to know what happens on screen, who appears, or what text is shown. Read-only; no video download.',
|
|
368
|
+
parameters: {
|
|
369
|
+
type: 'object',
|
|
370
|
+
properties: {
|
|
371
|
+
target: { type: 'string', description: 'Bilibili video URL, b23.tv short link, BV id or av id.' },
|
|
372
|
+
prompt: { type: 'string', description: 'What to look for in the frames (default: overview of scenes/people/on-screen text).' },
|
|
373
|
+
},
|
|
374
|
+
required: ['target'],
|
|
375
|
+
additionalProperties: false,
|
|
376
|
+
},
|
|
377
|
+
output: {
|
|
378
|
+
schema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false },
|
|
379
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
380
|
+
},
|
|
381
|
+
async execute(args, exec) {
|
|
382
|
+
if (!canVision) return { text: '当前宿主没有 llm/attachments 服务,无法调用视觉模型。' }
|
|
383
|
+
const target = await resolveTarget(args.target, cfg.timeoutMs)
|
|
384
|
+
const video = await getVideo(target, cfg.timeoutMs)
|
|
385
|
+
const page = pickPage(video, target)
|
|
386
|
+
const shot = await getVideoShot(video.aid, page.cid, cfg.timeoutMs)
|
|
387
|
+
if (!shot.images.length) return { text: '这个视频没有可用的缩略图拼图(videoshot 为空)。' }
|
|
388
|
+
await throttle()
|
|
389
|
+
const res = await fetch(shot.images[0], { headers: headers({ accept: 'image/jpeg,image/*,*/*' }), redirect: 'follow', signal: AbortSignal.timeout(cfg.timeoutMs) })
|
|
390
|
+
if (!res.ok) return { text: `缩略图下载失败 HTTP ${res.status}` }
|
|
391
|
+
const buf = Buffer.from(await res.arrayBuffer())
|
|
392
|
+
if (buf.length > 8 * 1024 * 1024) return { text: '缩略图拼图过大,已跳过。' }
|
|
393
|
+
const ref = await attachments.saveImage({ data: new Uint8Array(buf), mediaType: 'image/jpeg', name: 'bili-videoshot.jpg' })
|
|
394
|
+
const prompt = String(args.prompt || '这是 B 站视频的低分辨率缩略图拼图,按时间顺序排列(可能为 10x10 网格)。只描述你能明确看到的画面/人物/场景/大块文字;看不清的名单、比分、具体数字一律说“看不清”,不要猜。不要逐格复述。')
|
|
395
|
+
const message = createUserMessage({
|
|
396
|
+
content: [{ type: 'image', attachment: ref }, { type: 'text', text: prompt }],
|
|
397
|
+
source: { kind: 'plugin', plugin: 'dsh-qqbot-plus' },
|
|
398
|
+
})
|
|
399
|
+
const assembler = new BlockAssembler()
|
|
400
|
+
for await (const chunk of llm.stream({ provider: cfg.visionProvider, model: cfg.visionModel, messages: [message], maxTokens: cfg.visionMaxTokens, signal: exec.signal })) {
|
|
401
|
+
assembler.push(chunk)
|
|
402
|
+
}
|
|
403
|
+
const err = finishError(assembler.finish)
|
|
404
|
+
if (err) throw err
|
|
405
|
+
const text = assembler.blocks().filter(b => b.type === 'text').map(b => b.text).join(' ').trim()
|
|
406
|
+
return { text: '【注意】以下是低分辨率缩略图拼图的视觉概述,画面文字/比分/名单可能看不清,不要当作事实。\n\n' + (text || '视觉模型没有返回文字。') }
|
|
407
|
+
},
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const searchTool = {
|
|
411
|
+
name: 'bili_search',
|
|
412
|
+
description: 'Search Bilibili videos by keyword or a card title, and return matching BV ids with titles/UP/play counts. Use this when a QQ Bilibili share card has no URL/BV: pass the card title here, then call bili_read on the best match. Only returns public search results.',
|
|
413
|
+
parameters: {
|
|
414
|
+
type: 'object',
|
|
415
|
+
properties: {
|
|
416
|
+
keyword: { type: 'string', description: 'Search keywords or the card title.' },
|
|
417
|
+
limit: { type: 'integer', description: 'How many matches to return (default 5, max 10).' },
|
|
418
|
+
},
|
|
419
|
+
required: ['keyword'],
|
|
420
|
+
additionalProperties: false,
|
|
421
|
+
},
|
|
422
|
+
output: {
|
|
423
|
+
schema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false },
|
|
424
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
425
|
+
},
|
|
426
|
+
async execute(args) {
|
|
427
|
+
const limit = Math.min(Math.max(Number(args.limit) || 5, 1), 10)
|
|
428
|
+
const rows = await searchBili(args.keyword, limit, cfg.timeoutMs)
|
|
429
|
+
if (!rows.length) return { text: `【B站搜索】${args.keyword}\n没搜到匹配视频。` }
|
|
430
|
+
const lines = [`【B站搜索】${args.keyword}`]
|
|
431
|
+
for (const [i, r] of rows.entries()) {
|
|
432
|
+
lines.push(`${i + 1}. ${r.title} | ${r.bvid} | UP ${r.up} | 播放 ${fmtCount(r.view)} | 匹配 ${(r.score * 100).toFixed(0)}%`)
|
|
433
|
+
}
|
|
434
|
+
if (rows[0].score < 0.6) lines.push('', '匹配度偏低:建议用卡片标题里更完整的片段(保留“第几集/节目名/关键词”)再搜一次。')
|
|
435
|
+
return { text: lines.join('\n') }
|
|
436
|
+
},
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
const hotTool = {
|
|
440
|
+
name: 'bili_hot',
|
|
441
|
+
description: 'Read the current Bilibili trending/ranking list (rid=0, all). Useful when the user wants you to browse Bilibili for something worth sharing. Returns title, BV, UP and stats.',
|
|
442
|
+
parameters: {
|
|
443
|
+
type: 'object',
|
|
444
|
+
properties: { limit: { type: 'integer', description: 'How many videos (default 10, max 20).' } },
|
|
445
|
+
required: [],
|
|
446
|
+
additionalProperties: false,
|
|
447
|
+
},
|
|
448
|
+
output: {
|
|
449
|
+
schema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'], additionalProperties: false },
|
|
450
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
451
|
+
},
|
|
452
|
+
async execute(args) {
|
|
453
|
+
const limit = Math.min(Math.max(Number(args.limit) || 10, 1), 20)
|
|
454
|
+
const data = await fetchJson('https://api.bilibili.com/x/web-interface/ranking/v2?rid=0&type=all', cfg.timeoutMs)
|
|
455
|
+
const list = (data.list || []).slice(0, limit)
|
|
456
|
+
const lines = [`【B站热门榜】取前 ${list.length} 条`]
|
|
457
|
+
for (const v of list) {
|
|
458
|
+
lines.push(`- ${v.title} | ${v.bvid} | UP ${v.owner?.name ?? ''} | 播放 ${fmtCount(v.stat?.view)} | 弹幕 ${fmtCount(v.stat?.danmaku)} | ${fmtDuration(v.duration)}`)
|
|
459
|
+
}
|
|
460
|
+
return { text: lines.join('\n') }
|
|
461
|
+
},
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
tools.register(readTool)
|
|
465
|
+
if (canVision) tools.register(framesTool)
|
|
466
|
+
tools.register(searchTool)
|
|
467
|
+
tools.register(hotTool)
|
|
468
|
+
console.log(`[dsh-qqbot-plus/bilibili] bili_read / bili_search / bili_hot${canVision ? ' / bili_frames' : ''} 已注册`)
|
|
469
|
+
ctx.logger?.info('[dsh-qqbot-plus/bilibili] bili_read / bili_hot 已注册')
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
export { resolveTarget, getVideo, getDanmaku, getComments, getSubtitles, getVideoShot, searchBili, fetchJson }
|
package/tools/tts.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-qqbot-plus/tts — 用 edge-tts(微软神经语音)生成语音文件。
|
|
3
|
+
* 只负责生成 mp3 并返回绝对路径;发送由 fork 的 send_media(kind=voice) 完成。
|
|
4
|
+
*/
|
|
5
|
+
import { execFile } from 'node:child_process'
|
|
6
|
+
import { mkdir, stat } from 'node:fs/promises'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
|
|
10
|
+
export const name = 'dsh-qqbot-plus:tts'
|
|
11
|
+
export const inject = ['tools']
|
|
12
|
+
|
|
13
|
+
const TOOL_NAME = 'tts_speak'
|
|
14
|
+
|
|
15
|
+
function run(cmd, args, timeoutMs) {
|
|
16
|
+
return new Promise((resolve, reject) => {
|
|
17
|
+
execFile(cmd, args, { timeout: timeoutMs, maxBuffer: 1024 * 1024 }, (error, stdout, stderr) => {
|
|
18
|
+
if (error) {
|
|
19
|
+
reject(new Error(`tts_speak: ${error.message}${stderr ? ` | ${String(stderr).slice(0, 300)}` : ''}`))
|
|
20
|
+
return
|
|
21
|
+
}
|
|
22
|
+
resolve({ stdout: String(stdout), stderr: String(stderr) })
|
|
23
|
+
})
|
|
24
|
+
})
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function apply(ctx, config = {}) {
|
|
28
|
+
const tools = ctx.get('tools')
|
|
29
|
+
if (!tools?.register) {
|
|
30
|
+
ctx.logger?.warn('[dsh-qqbot-plus/tts] tools 服务不可用,工具未注册')
|
|
31
|
+
return
|
|
32
|
+
}
|
|
33
|
+
const cfg = {
|
|
34
|
+
edgeTts: String(config.edgeTts ?? process.env.EDGE_TTS_BIN ?? 'edge-tts'),
|
|
35
|
+
outDir: String(config.outDir ?? join(process.cwd(), 'downloads', 'tts')),
|
|
36
|
+
voice: String(config.voice ?? 'zh-CN-XiaoyiNeural'),
|
|
37
|
+
rate: String(config.rate ?? '+5%'),
|
|
38
|
+
pitch: String(config.pitch ?? '+12Hz'),
|
|
39
|
+
maxChars: Number(config.maxChars ?? 500),
|
|
40
|
+
timeoutMs: Number(config.timeoutMs ?? 60000),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const definition = {
|
|
44
|
+
name: TOOL_NAME,
|
|
45
|
+
description: 'Synthesize a short Chinese voice message with Microsoft Edge neural TTS and return the absolute mp3 path. '
|
|
46
|
+
+ 'Use this whenever the user asks for a voice message / 语音 / 声音. Then send it with '
|
|
47
|
+
+ 'send_media({ kind: "voice", source: <returned path> }). Do NOT use macOS `say` — it sounds robotic.',
|
|
48
|
+
parameters: {
|
|
49
|
+
type: 'object',
|
|
50
|
+
properties: {
|
|
51
|
+
text: { type: 'string', description: 'Text to speak. Keep it short (1-3 sentences).' },
|
|
52
|
+
voice: { type: 'string', description: 'Optional edge-tts voice id. Default zh-CN-XiaoyiNeural (lively/sweet).' },
|
|
53
|
+
rate: { type: 'string', description: 'Optional rate, e.g. "+5%". Default from config.' },
|
|
54
|
+
pitch: { type: 'string', description: 'Optional pitch, e.g. "+12Hz". Default from config.' },
|
|
55
|
+
},
|
|
56
|
+
required: ['text'],
|
|
57
|
+
additionalProperties: false,
|
|
58
|
+
},
|
|
59
|
+
output: {
|
|
60
|
+
schema: {
|
|
61
|
+
type: 'object',
|
|
62
|
+
properties: {
|
|
63
|
+
path: { type: 'string' },
|
|
64
|
+
voice: { type: 'string' },
|
|
65
|
+
bytes: { type: 'integer' },
|
|
66
|
+
},
|
|
67
|
+
required: ['path', 'voice', 'bytes'],
|
|
68
|
+
additionalProperties: false,
|
|
69
|
+
},
|
|
70
|
+
render: (_args, value) => [{ type: 'text', text: `语音文件已生成: ${value.path}` }],
|
|
71
|
+
},
|
|
72
|
+
async execute(args, exec) {
|
|
73
|
+
const text = String(args.text ?? '').trim()
|
|
74
|
+
if (!text) throw new Error('tts_speak: `text` must be non-empty')
|
|
75
|
+
if ([...text].length > cfg.maxChars) {
|
|
76
|
+
throw new Error(`tts_speak: text too long (${[...text].length} > ${cfg.maxChars})`)
|
|
77
|
+
}
|
|
78
|
+
const voice = String(args.voice ?? cfg.voice)
|
|
79
|
+
const rate = String(args.rate ?? cfg.rate)
|
|
80
|
+
const pitch = String(args.pitch ?? cfg.pitch)
|
|
81
|
+
await mkdir(cfg.outDir, { recursive: true })
|
|
82
|
+
const out = join(cfg.outDir, `tts-${Date.now()}-${randomUUID().slice(0, 8)}.mp3`)
|
|
83
|
+
await run(cfg.edgeTts, [
|
|
84
|
+
'--voice', voice,
|
|
85
|
+
`--rate=${rate}`,
|
|
86
|
+
`--pitch=${pitch}`,
|
|
87
|
+
'--text', text,
|
|
88
|
+
'--write-media', out,
|
|
89
|
+
], cfg.timeoutMs)
|
|
90
|
+
const info = await stat(out)
|
|
91
|
+
if (!info.isFile() || info.size === 0) throw new Error('tts_speak: edge-tts produced no file')
|
|
92
|
+
return { path: out, voice, bytes: info.size }
|
|
93
|
+
},
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
tools.register(definition)
|
|
97
|
+
console.log(`[dsh-qqbot-plus/tts] ${TOOL_NAME} 已注册 (edge-tts, default ${cfg.voice})`)
|
|
98
|
+
ctx.logger?.info(`[dsh-qqbot-plus/tts] ${TOOL_NAME} 已注册 (default ${cfg.voice})`)
|
|
99
|
+
}
|
package/tools/vision.js
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-qqbot-plus/vision — 独立识图工具
|
|
3
|
+
*
|
|
4
|
+
* 主模型可以保持 deepseek(纯文本);遇到图片时调用本工具,
|
|
5
|
+
* 工具内部用 qwen3-vl-plus 看图并把结果作为文本返回。
|
|
6
|
+
*/
|
|
7
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
8
|
+
import { basename } from 'node:path'
|
|
9
|
+
import { BlockAssembler, createUserMessage } from '@deepseek-ai/dsh-llm'
|
|
10
|
+
|
|
11
|
+
export const name = 'dsh-qqbot-plus:vision'
|
|
12
|
+
export const inject = ['tools', 'llm', 'attachments']
|
|
13
|
+
|
|
14
|
+
const TOOL_NAME = 'qqbot_describe_image'
|
|
15
|
+
|
|
16
|
+
function sniffImageMediaType(bytes) {
|
|
17
|
+
if (bytes.length < 12) return null
|
|
18
|
+
if (bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return 'image/png'
|
|
19
|
+
if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return 'image/jpeg'
|
|
20
|
+
if (bytes[0] === 0x47 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x38) return 'image/gif'
|
|
21
|
+
if (bytes[0] === 0x52 && bytes[1] === 0x49 && bytes[2] === 0x46 && bytes[3] === 0x46
|
|
22
|
+
&& bytes[8] === 0x57 && bytes[9] === 0x45 && bytes[10] === 0x42 && bytes[11] === 0x50) return 'image/webp'
|
|
23
|
+
return null
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
async function loadImageBytes(image, maxBytes, signal) {
|
|
27
|
+
let data
|
|
28
|
+
if (/^https?:\/\//i.test(image)) {
|
|
29
|
+
const resp = await fetch(image, { signal, redirect: 'error' })
|
|
30
|
+
if (!resp.ok) throw new Error(`${TOOL_NAME}: download failed (HTTP ${resp.status})`)
|
|
31
|
+
const buf = Buffer.from(await resp.arrayBuffer())
|
|
32
|
+
if (buf.length > maxBytes) throw new Error(`${TOOL_NAME}: image too large (${buf.length} bytes)`)
|
|
33
|
+
data = new Uint8Array(buf)
|
|
34
|
+
} else {
|
|
35
|
+
const info = await stat(image).catch(() => null)
|
|
36
|
+
if (!info?.isFile()) throw new Error(`${TOOL_NAME}: image file not found: ${image}`)
|
|
37
|
+
if (info.size > maxBytes) throw new Error(`${TOOL_NAME}: image too large (${info.size} bytes)`)
|
|
38
|
+
data = new Uint8Array(await readFile(image))
|
|
39
|
+
}
|
|
40
|
+
const mediaType = sniffImageMediaType(data)
|
|
41
|
+
if (mediaType === null) throw new Error(`${TOOL_NAME}: unrecognized image format (png/jpeg/gif/webp only)`)
|
|
42
|
+
return { data, mediaType }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function finishError(finish) {
|
|
46
|
+
switch (finish.kind) {
|
|
47
|
+
case 'error':
|
|
48
|
+
case 'aborted':
|
|
49
|
+
return new Error(finish.failure.message)
|
|
50
|
+
default:
|
|
51
|
+
return undefined
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function callVision(llm, vision, prompt, imageRef, signal) {
|
|
56
|
+
const message = createUserMessage({
|
|
57
|
+
content: [
|
|
58
|
+
{ type: 'image', attachment: imageRef },
|
|
59
|
+
{ type: 'text', text: prompt },
|
|
60
|
+
],
|
|
61
|
+
source: { kind: 'plugin', plugin: 'dsh-qqbot-plus' },
|
|
62
|
+
})
|
|
63
|
+
const assembler = new BlockAssembler()
|
|
64
|
+
for await (const chunk of llm.stream({
|
|
65
|
+
provider: vision.provider,
|
|
66
|
+
model: vision.model,
|
|
67
|
+
messages: [message],
|
|
68
|
+
maxTokens: vision.maxTokens,
|
|
69
|
+
signal,
|
|
70
|
+
})) {
|
|
71
|
+
assembler.push(chunk)
|
|
72
|
+
}
|
|
73
|
+
const terminalError = finishError(assembler.finish)
|
|
74
|
+
if (terminalError !== undefined) throw terminalError
|
|
75
|
+
const text = assembler.blocks()
|
|
76
|
+
.filter((block) => block.type === 'text')
|
|
77
|
+
.map((block) => block.text)
|
|
78
|
+
.join(' ')
|
|
79
|
+
.trim()
|
|
80
|
+
if (text.length === 0) throw new Error(`${TOOL_NAME}: vision model returned no text`)
|
|
81
|
+
return text
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function apply(ctx, config = {}) {
|
|
85
|
+
const vision = {
|
|
86
|
+
provider: String(config.provider ?? 'zhipu'),
|
|
87
|
+
model: String(config.model ?? 'aliyun/qwen3-vl-plus'),
|
|
88
|
+
maxBytes: Number(config.maxBytes ?? 10 * 1024 * 1024),
|
|
89
|
+
maxTokens: Number(config.maxTokens ?? 1024),
|
|
90
|
+
defaultPrompt: String(config.defaultPrompt ?? '描述这张图片的内容;如果有文字,逐字转录;如果是截图,说明界面和关键信息。'),
|
|
91
|
+
timeoutMs: Number(config.timeoutMs ?? 120000),
|
|
92
|
+
}
|
|
93
|
+
const tools = ctx.get('tools')
|
|
94
|
+
const llm = ctx.get('llm')
|
|
95
|
+
const attachments = ctx.get('attachments')
|
|
96
|
+
if (!tools?.register || !llm?.stream || !attachments?.saveImage) {
|
|
97
|
+
ctx.logger?.warn(`[dsh-qqbot-plus/vision] tools/llm/attachments 不可用,工具未注册`)
|
|
98
|
+
return
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const definition = {
|
|
102
|
+
name: TOOL_NAME,
|
|
103
|
+
description: 'Inspect one image and return the text the user needs. The image is a local absolute path '
|
|
104
|
+
+ '(downloaded by the QQ bot) or an http(s) URL. Use this when the user references an image, '
|
|
105
|
+
+ 'or when a task needs OCR, chart/diagram reading, screenshot or UI analysis, translation of '
|
|
106
|
+
+ 'image text, or photo understanding. Always pass an explicit `prompt` with a precise '
|
|
107
|
+
+ 'instruction (e.g. "transcribe all text", "extract the table as CSV", "translate the text '
|
|
108
|
+
+ 'into Chinese") instead of relying on the generic default.',
|
|
109
|
+
parameters: {
|
|
110
|
+
type: 'object',
|
|
111
|
+
properties: {
|
|
112
|
+
image: {
|
|
113
|
+
type: 'string',
|
|
114
|
+
description: 'Absolute path to a local image file, or an http(s) URL of the image.',
|
|
115
|
+
},
|
|
116
|
+
prompt: {
|
|
117
|
+
type: 'string',
|
|
118
|
+
description: 'Your precise instruction for the vision model about this image.',
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
required: ['image'],
|
|
122
|
+
additionalProperties: false,
|
|
123
|
+
},
|
|
124
|
+
output: {
|
|
125
|
+
schema: {
|
|
126
|
+
type: 'object',
|
|
127
|
+
properties: {
|
|
128
|
+
text: { type: 'string' },
|
|
129
|
+
model: { type: 'string' },
|
|
130
|
+
image: { type: 'string' },
|
|
131
|
+
mimeType: { type: 'string', enum: ['image/png', 'image/jpeg', 'image/gif', 'image/webp'] },
|
|
132
|
+
bytes: { type: 'integer' },
|
|
133
|
+
},
|
|
134
|
+
required: ['text', 'model', 'image', 'mimeType', 'bytes'],
|
|
135
|
+
additionalProperties: false,
|
|
136
|
+
},
|
|
137
|
+
render: (_args, value) => [{ type: 'text', text: value.text }],
|
|
138
|
+
},
|
|
139
|
+
async execute(args, exec) {
|
|
140
|
+
const { image, prompt } = args
|
|
141
|
+
if (typeof image !== 'string' || image.length === 0) {
|
|
142
|
+
throw new Error(`${TOOL_NAME}: \`image\` must be a non-empty string`)
|
|
143
|
+
}
|
|
144
|
+
const loaded = await loadImageBytes(image, vision.maxBytes, exec.signal)
|
|
145
|
+
const ref = await attachments.saveImage({
|
|
146
|
+
data: loaded.data,
|
|
147
|
+
mediaType: loaded.mediaType,
|
|
148
|
+
name: /^https?:\/\//i.test(image) ? undefined : basename(image),
|
|
149
|
+
})
|
|
150
|
+
const text = await callVision(llm, vision, prompt ?? vision.defaultPrompt, ref, exec.signal)
|
|
151
|
+
return { text, model: vision.model, image, mimeType: loaded.mediaType, bytes: loaded.data.length }
|
|
152
|
+
},
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
tools.register(definition)
|
|
156
|
+
console.log(`[dsh-qqbot-plus/vision] ${TOOL_NAME} 已注册 (${vision.provider}/${vision.model})`)
|
|
157
|
+
ctx.logger?.info(`[dsh-qqbot-plus/vision] ${TOOL_NAME} 已注册 (${vision.provider}/${vision.model})`)
|
|
158
|
+
}
|