@yangfan1998/dsh-qqbot-plus 0.0.0-stage → 0.1.0

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 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,235 @@
1
- # Temporary Holding Version
1
+ # @yangfan1998/dsh-qqbot-plus
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **One-install QQ bot bundle for DeepSeek Harness.**
4
+
5
+ `@yangfan1998/dsh-qqbot-plus` mounts the [`@zaofan/dsh-qqbot`](https://www.npmjs.com/package/@zaofan/dsh-qqbot) gateway together with three optional tools:
6
+
7
+ - `qqbot_describe_image` — image understanding / OCR via an image-capable model
8
+ - `tts_speak` — Edge TTS voice messages (mp3)
9
+ - `bili_read` / `bili_search` / `bili_hot` / `bili_frames` — Bilibili video, danmaku, comments and thumbnail understanding
10
+
11
+ It is a **bundle**, not a fork of the QQ gateway. The gateway remains `@zaofan/dsh-qqbot` and can be upgraded independently.
12
+
13
+ > Status: `0.1.0` · not yet published to npm. Build a local tarball with `npm pack`.
14
+
15
+ ---
16
+
17
+ ## Requirements
18
+
19
+ | Item | Requirement |
20
+ |---|---|
21
+ | Node.js | `>= 22.13` |
22
+ | DeepSeek Harness | `>= 0.2.1-alpha.2` |
23
+ | QQ bot | AppID + AppSecret from QQ Open Platform |
24
+ | LLM route | An image-capable model for `qqbot_describe_image` (default `zhipu/aliyun/qwen3-vl-plus`) |
25
+ | TTS (optional) | `edge-tts` executable on `PATH`, or set `tts.bin` |
26
+ | Bilibili (optional) | No key required for public data; `BILIBILI_SESSDATA` unlocks subtitles |
27
+
28
+ ---
29
+
30
+ ## Install
31
+
32
+ ### Local tarball (works today, no npm account needed)
33
+
34
+ ```bash
35
+ cd /path/to/dsh-qqbot-plus
36
+ npm pack
37
+ # produces yangfan1998-dsh-qqbot-plus-0.1.0.tgz
38
+
39
+ dsh plugin --profile <your-profile> add ./yangfan1998-dsh-qqbot-plus-0.1.0.tgz
40
+ ```
41
+
42
+ If pnpm reports `ERR_PNPM_IGNORED_BUILDS` (the QQ gateway pulls `onnxruntime-node` / `protobufjs`):
43
+
44
+ ```bash
45
+ cd ~/.dsh/profiles/<your-profile>
46
+ pnpm approve-builds --all
47
+ ```
48
+
49
+ Then add the bundle to the profile's `package.json` (the plugin manager does not
50
+ auto-append bundle packages in all DSH versions):
51
+
52
+ ```json
53
+ {
54
+ "dsh": {
55
+ "profile": {
56
+ "bundles": [
57
+ "@deepseek-ai/dsh-base",
58
+ "@deepseek-ai/dsh-web-app",
59
+ "@yangfan1998/dsh-qqbot-plus"
60
+ ]
61
+ }
62
+ }
63
+ }
64
+ ```
65
+
66
+ Verify the composed tree before booting:
67
+
68
+ ```bash
69
+ dsh --profile <your-profile> --dump-config | grep -A3 'id: im-qqbot'
70
+ dsh --profile <your-profile> --dump-config | grep -A3 'id: qqbot-plus'
71
+ ```
72
+
73
+ ### npm (after publishing)
74
+
75
+ ```bash
76
+ dsh plugin --profile <your-profile> add @yangfan1998/dsh-qqbot-plus
77
+ ```
78
+
79
+ > Use a **fresh profile**. The bundle patch inserts an `im-qqbot` row; if you already installed `@zaofan/dsh-qqbot` in that profile, you will get a duplicate `im-qqbot` and the patch will not activate.
80
+ >
81
+ > For an existing gateway, **do not add this package to `dsh.profile.bundles`**. Install the package, then copy the `- insert:` block from [`cordis.tools-only.yml`](./cordis.tools-only.yml) into the profile's own `cordis.patch.yml`.
82
+
83
+ ---
84
+
85
+ ## Configure credentials
86
+
87
+ The bundle patch uses `__FROM_ENV__` for `appId` / `appSecret`. Either:
88
+
89
+ ### Option A — environment variables
90
+
91
+ ```bash
92
+ export QQBOT_APPID=1905977275
93
+ export QQBOT_APP_SECRET=your-secret
94
+ ```
95
+
96
+ ### Option B — literal values in the profile patch
97
+
98
+ Edit the `im-qqbot` row in your profile's `cordis.patch.yml`:
99
+
100
+ ```yaml
101
+ - id: im-qqbot
102
+ name: '@zaofan/dsh-qqbot'
103
+ config:
104
+ appId: '1905977275'
105
+ appSecret: 'your-secret'
106
+ ```
107
+
108
+ Never commit real secrets. The QQ bot must also have the group-message permission enabled by the group owner if you want non-@ group messages.
109
+
110
+ ---
111
+
112
+ ## Tool configuration
113
+
114
+ The bundle's `cordis.patch.yml` ships safe defaults. Override them in the `qqbot-plus` row:
115
+
116
+ ```yaml
117
+ - id: qqbot-plus
118
+ name: @yangfan1998/dsh-qqbot-plus
119
+ config:
120
+ vision:
121
+ provider: zhipu
122
+ model: aliyun/qwen3-vl-plus
123
+ maxTokens: 1024
124
+ tts:
125
+ bin: edge-tts
126
+ voice: zh-CN-XiaoyiNeural
127
+ rate: '+5%'
128
+ pitch: '+12Hz'
129
+ maxChars: 500
130
+ bilibili:
131
+ timeoutMs: 20000
132
+ danmakuLimit: 25
133
+ commentLimit: 10
134
+ replyLimit: 5
135
+ ```
136
+
137
+ ### Vision
138
+
139
+ Any route whose model accepts `image` input works. The model must be available in your `llm-pi-ai` (or other LLM plugin) provider config. If the model is missing, `qqbot_describe_image` disables itself and the rest of the bundle keeps running.
140
+
141
+ ### TTS
142
+
143
+ `tts_speak` shells out to `edge-tts` and writes an mp3 under `downloads/tts` by default.
144
+
145
+ ```bash
146
+ python3 -m pip install edge-tts
147
+ # or point at an existing venv:
148
+ # tts.bin: /path/to/venv/bin/edge-tts
149
+ ```
150
+
151
+ If `edge-tts` is unavailable, the tool returns a clear error; it does not crash the plugin.
152
+
153
+ ### Bilibili
154
+
155
+ Public video metadata, danmaku and comments work without a cookie. Subtitles often require login:
156
+
157
+ ```bash
158
+ export BILIBILI_SESSDATA=your-sessdata
159
+ ```
160
+
161
+ Bilibili can rate-limit anonymous requests; the tool throttles requests and caches the anonymous `buvid3` cookie.
162
+
163
+ ---
164
+
165
+ ## Tools
166
+
167
+ | Tool | Purpose |
168
+ |---|---|
169
+ | `qqbot_describe_image` | Inspect one local image or URL; OCR, tables, screenshots, photos |
170
+ | `tts_speak` | Generate a short mp3 with Edge TTS; send it with `send_media(kind="voice")` |
171
+ | `bili_read` | Metadata, danmaku, hot comments (nested), optional subtitles |
172
+ | `bili_search` | Search Bilibili by title/keyword; returns BV ids with match scores |
173
+ | `bili_hot` | Bilibili trending list |
174
+ | `bili_frames` | Thumbnail sprite sheet → vision model summary; low-resolution, do not treat as factual |
175
+
176
+ ---
177
+
178
+ ## Optional extensions
179
+
180
+ The package ships two `{dataRoot}/.qqbot-extensions` extensions:
181
+
182
+ - `extensions/inbound/bili-card-url.mjs` — extracts a Bilibili URL from a QQ mini-program card's raw payload. It intentionally only accepts URLs, never bare `BV...` substrings (QQ message ids can contain false BVs).
183
+ - `extensions/outbound/abs-image-paths.mjs` — rewrites relative markdown image paths to absolute paths before QQ upload.
184
+
185
+ Copy them into the QQ bot's data root:
186
+
187
+ ```bash
188
+ DATA_ROOT="/path/to/qqbot/data-root" # usually <im-qqbot.cwd>/dshqqbot
189
+ PKG_DIR="$(node -e "console.log(require.resolve('@yangfan1998/dsh-qqbot-plus'))" | xargs dirname)"
190
+
191
+ mkdir -p "$DATA_ROOT/.qqbot-extensions/inbound" "$DATA_ROOT/.qqbot-extensions/outbound"
192
+ cp "$PKG_DIR/extensions/inbound/bili-card-url.mjs" "$DATA_ROOT/.qqbot-extensions/inbound/"
193
+ cp "$PKG_DIR/extensions/outbound/abs-image-paths.mjs" "$DATA_ROOT/.qqbot-extensions/outbound/"
194
+ ```
195
+
196
+ `abs-image-paths` resolves relative paths against `process.cwd()`; set `QQBOT_CWD` if your host cwd differs from `im-qqbot.cwd`.
197
+
198
+ ---
199
+
200
+ ## What is NOT included
201
+
202
+ - No QQ AppID / AppSecret / API keys / cookies
203
+ - No persona or group prompt (bring your own)
204
+ - No sticker/meme image packs (third-party art licensing)
205
+ - No web settings page; configure via `cordis.patch.yml` or env
206
+ - No `launchd` / systemd unit; deployment is up to you
207
+
208
+ ---
209
+
210
+ ## Security notes
211
+
212
+ - The Bilibili tool makes outbound HTTPS requests to `bilibili.com`, `b23.tv` and `api.bilibili.com`.
213
+ - The vision tool downloads only `http(s)` images you pass it; it does not scan arbitrary files.
214
+ - `tts_speak` executes the configured `edge-tts` binary with text as an argument. Do not point `tts.bin` at an untrusted script.
215
+ - This package does not bundle credentials. Run it with a dedicated QQ bot account.
216
+
217
+ ---
218
+
219
+ ## Publishing checklist
220
+
221
+ - [ ] `npm pack` and install the tarball into a fresh test profile
222
+ - [ ] verify `im-qqbot` + `qqbot-plus` both activate
223
+ - [ ] verify `qqbot_describe_image` with a real image
224
+ - [ ] verify `tts_speak` with `edge-tts`
225
+ - [ ] verify `bili_read` with a public BV
226
+ - [ ] replace the placeholder version/author/repository in `package.json`
227
+ - [ ] `npm publish` (needs an npm account)
228
+ - [ ] push to your own GitHub repository (do not reuse another account's credentials)
229
+ - [ ] add the `dsh-plugin` topic and submit to the DSH plugin market
230
+
231
+ ---
232
+
233
+ ## License
234
+
235
+ MIT. See [LICENSE](./LICENSE).
@@ -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
+ * 模型经常写 ![alt](downloads/xx.jpg),会被当成普通文本,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 `![${alt}](${path.resolve(CWD, clean)})`
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,56 @@
1
1
  {
2
2
  "name": "@yangfan1998/dsh-qqbot-plus",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ }
@@ -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(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&#x27;/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
+ }
@@ -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
+ }