qq-bot-roost 1.0.13 → 1.0.15
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/README.md +10 -3
- package/config/bot.example.json +30 -0
- package/docs/AI/345/256/277/344/270/273/346/216/245/345/205/245.md +145 -0
- package/docs/DSH/346/216/245/345/205/245.md +267 -0
- package/docs/OneBot/345/205/274/345/256/271/345/261/202/350/256/276/350/256/241.md +1032 -0
- package/docs/images/bot-menu.png +0 -0
- package/docs/images/bot-switcher.png +0 -0
- package/docs/images/events.png +0 -0
- package/docs/images/group-manage.png +0 -0
- package/docs/images/logs.png +0 -0
- package/docs/images/overview.png +0 -0
- package/docs/images/plugin-dash-tab.png +0 -0
- package/docs/images/plugins-dash.png +0 -0
- package/docs/images/plugins.png +0 -0
- package/docs//345/217/221/347/211/210/346/270/205/345/215/225.md +167 -0
- package/docs//345/233/236/346/273/232/351/242/204/346/241/210.md +78 -0
- package/docs//345/256/230/346/226/271/346/216/245/345/217/243/351/231/220/345/210/266.md +375 -0
- package/docs//345/256/277/344/270/273/345/215/217/350/256/256v1.md +402 -0
- package/docs//345/270/270/350/247/201/351/227/256/351/242/230.md +559 -0
- package/docs//346/217/222/344/273/266/345/215/217/350/256/256.md +521 -0
- package/docs//346/217/222/344/273/266/345/274/200/345/217/221/350/247/204/350/214/203.md +1857 -0
- package/docs//346/235/203/351/231/220/346/250/241/345/236/213.md +237 -0
- package/docs//346/236/266/346/236/204/350/257/264/346/230/216.md +311 -0
- package/docs//347/234/237/346/234/272/350/201/224/350/260/203.md +253 -0
- package/docs//351/205/215/347/275/256/345/217/202/350/200/203.md +427 -0
- package/package.json +4 -3
- package/src/api.js +242 -77
- package/src/bot.js +93 -2
- package/src/config.js +150 -6
- package/src/endpoints.js +5 -3
- package/src/ext-deps.js +703 -0
- package/src/host/dispatch.js +125 -0
- package/src/host/index.js +395 -0
- package/src/host/media.js +462 -0
- package/src/host/methods.js +756 -0
- package/src/host/ops.js +462 -0
- package/src/host/serialize.js +79 -0
- package/src/host/server.js +397 -0
- package/src/instance.js +75 -13
- package/src/ledger.js +45 -0
- package/src/main.js +5 -1
- package/src/onebot/actions.js +524 -0
- package/src/onebot/capability.js +95 -0
- package/src/onebot/ids.js +265 -0
- package/src/onebot/index.js +410 -0
- package/src/onebot/segments.js +195 -0
- package/src/onebot/translate.js +219 -0
- package/src/onebot/voice.js +449 -0
- package/src/onebot/ws-server.js +270 -0
- package/src/plugin/loader.js +9 -0
- package/src/plugin/market.js +19 -0
- package/src/web/server.js +408 -1
- package/web/app.js +613 -0
- package/web/index.html +190 -1
- package/web/style.css +69 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "qq-bot-roost",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.15",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "栖 Roost:零依赖的 QQ 官方机器人框架,填 AppID/AppSecret 即连,插件可写任意语言",
|
|
6
6
|
"license": "AGPL-3.0-only",
|
|
@@ -29,9 +29,9 @@
|
|
|
29
29
|
"start": "node src/main.js",
|
|
30
30
|
"mock": "node src/main.js --mock",
|
|
31
31
|
"check": "node src/main.js --check",
|
|
32
|
-
"test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs",
|
|
32
|
+
"test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/web-token-echo.mjs",
|
|
33
33
|
"test:e2e": "node test/e2e.mjs",
|
|
34
|
-
"test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs",
|
|
34
|
+
"test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/web-token-echo.mjs",
|
|
35
35
|
"check:secrets": "node scripts/check-secrets.mjs",
|
|
36
36
|
"create": "node scripts/create-plugin.mjs",
|
|
37
37
|
"test:plugin": "node scripts/test-plugin.mjs",
|
|
@@ -50,6 +50,7 @@
|
|
|
50
50
|
"web",
|
|
51
51
|
"sdk",
|
|
52
52
|
"types",
|
|
53
|
+
"docs",
|
|
53
54
|
"config/*.example.json",
|
|
54
55
|
"README.md",
|
|
55
56
|
"LICENSE"
|
package/src/api.js
CHANGED
|
@@ -8,6 +8,15 @@ const enc = (v) => encodeURIComponent(String(v ?? ''));
|
|
|
8
8
|
|
|
9
9
|
/** 本进程创建、尚未删除的 Markdown 素材 id(崩溃后靠它认领孤儿) */
|
|
10
10
|
const OWN_MEDIA_FILE = path.join(DIRS.data, 'media-images-own.json');
|
|
11
|
+
/**
|
|
12
|
+
* 宿主协议显式 `retain` 的素材单独存一份:不参与孤儿回收。
|
|
13
|
+
* 刻意不碰 OWN_MEDIA_FILE 的数组格式——reply-auto 的回归测试钉着它,
|
|
14
|
+
* 老用户升级后也不需要做格式迁移。
|
|
15
|
+
*/
|
|
16
|
+
const KEPT_MEDIA_FILE = path.join(DIRS.data, 'media-images-kept.json');
|
|
17
|
+
|
|
18
|
+
/** 官方给的单机器人素材配额,查询接口的 total 与它同一口径 */
|
|
19
|
+
export const MEDIA_IMAGE_QUOTA = 100;
|
|
11
20
|
|
|
12
21
|
|
|
13
22
|
const log = createLogger('api');
|
|
@@ -192,6 +201,61 @@ const MEDIA_TTL = 2 * 86400_000;
|
|
|
192
201
|
* QQ 开放平台 HTTP API 封装。
|
|
193
202
|
* 鉴权头固定为 "QQBot {access_token}"。
|
|
194
203
|
*/
|
|
204
|
+
/**
|
|
205
|
+
* 哪些网络错误可以**安全重试**:连接根本没建起来的那几种。
|
|
206
|
+
*
|
|
207
|
+
* `fetch` 失败时只给一句 `fetch failed`,真原因在 `e.cause.code` 里。分类的
|
|
208
|
+
* 依据是「请求有没有可能已经到服务端」:
|
|
209
|
+
*
|
|
210
|
+
* · 连不上(ECONNREFUSED / ENOTFOUND / EAI_AGAIN / 连接超时 / 网络不可达)
|
|
211
|
+
* → 一定没发出去,重试不会造成第二条消息。
|
|
212
|
+
* · 连接被重置(ECONNRESET/EPIPE)、读超时 → **可能已经发出去了**,重试就是
|
|
213
|
+
* 双发。官方被动回复每发一次占一个新的 `msg_seq`,群里会真的出现两条。
|
|
214
|
+
*
|
|
215
|
+
* 抽成纯函数是为了能单测:这条规则错了后果是群里刷重复消息,比少发一条更糟。
|
|
216
|
+
*
|
|
217
|
+
* @param {string} code
|
|
218
|
+
*/
|
|
219
|
+
export function isSafeToRetryNetworkError(code) {
|
|
220
|
+
return new Set([
|
|
221
|
+
'ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN',
|
|
222
|
+
'UND_ERR_CONNECT_TIMEOUT', 'EHOSTUNREACH', 'ENETUNREACH',
|
|
223
|
+
]).has(String(code ?? ''));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* 取网络错误的机器码(`ECONNRESET` 这类)。取不到返回空串。
|
|
228
|
+
*
|
|
229
|
+
* `cause` 可能是 `AggregateError`(多地址并发连接失败时的常见形状),
|
|
230
|
+
* 那时候真正的码在 `cause.errors[]` 里。
|
|
231
|
+
*
|
|
232
|
+
* @param {any} e
|
|
233
|
+
*/
|
|
234
|
+
export function networkCodeOf(e) {
|
|
235
|
+
const cause = e?.cause;
|
|
236
|
+
return String(
|
|
237
|
+
cause?.code
|
|
238
|
+
|| cause?.errno
|
|
239
|
+
|| (Array.isArray(cause?.errors) ? cause.errors.find((x) => x?.code)?.code : '')
|
|
240
|
+
|| '',
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* 把网络错误变成一句能排障的话。
|
|
246
|
+
*
|
|
247
|
+
* 以前只留 `e.message`,日志里全是「网络错误 POST /v2/...: fetch failed」——
|
|
248
|
+
* 断连、DNS、超时看起来一模一样,只能猜。现在带上 `cause.code`。
|
|
249
|
+
*
|
|
250
|
+
* @param {any} e
|
|
251
|
+
*/
|
|
252
|
+
export function networkReasonOf(e) {
|
|
253
|
+
if (e?.name === 'TimeoutError') return '请求超时(15s)';
|
|
254
|
+
const code = networkCodeOf(e);
|
|
255
|
+
const msg = String(e?.message ?? e ?? '未知错误');
|
|
256
|
+
return code ? `${msg}(${code})` : msg;
|
|
257
|
+
}
|
|
258
|
+
|
|
195
259
|
export class QQApi {
|
|
196
260
|
constructor({ tokenManager, baseUrl, metrics = null }) {
|
|
197
261
|
this.tokens = tokenManager;
|
|
@@ -218,11 +282,15 @@ export class QQApi {
|
|
|
218
282
|
/**
|
|
219
283
|
* Markdown 素材图床里**本进程自己上传**的 image_id。
|
|
220
284
|
*
|
|
221
|
-
*
|
|
222
|
-
*
|
|
223
|
-
* 这三个端点已标 `internal:true`,不再进 `/api/qq/call` 白名单。
|
|
285
|
+
* 素材库是机器人级共享的,删除时默认只认这个集合里的 id,避免误删其它插件的素材。
|
|
286
|
+
* 发完即删,正常情况集合是空的。这三个端点已标 `internal:true`,不进 `/api/qq/call` 白名单。
|
|
224
287
|
*/
|
|
225
288
|
this._ownMediaImages = new Set();
|
|
289
|
+
/**
|
|
290
|
+
* 宿主协议显式 `retain` 的素材:要跨消息复用 `qqbot-media://` 引用,
|
|
291
|
+
* 既不能发完即删,也不能被重启后的孤儿回收清掉。仍允许显式删除。
|
|
292
|
+
*/
|
|
293
|
+
this._keptMediaImages = new Set();
|
|
226
294
|
/** 孤儿素材认领,一个进程只做一次 */
|
|
227
295
|
this._mediaReclaimDone = false;
|
|
228
296
|
}
|
|
@@ -245,7 +313,27 @@ export class QQApi {
|
|
|
245
313
|
});
|
|
246
314
|
} catch (e) {
|
|
247
315
|
this.metrics?.bump('errors');
|
|
248
|
-
|
|
316
|
+
/**
|
|
317
|
+
* 网络错误要带上**根因**。`fetch` 抛出来的永远是一句 `fetch failed`,
|
|
318
|
+
* 真正的原因藏在 `e.cause` 里(`ECONNRESET` / `ENOTFOUND` /
|
|
319
|
+
* `UND_ERR_CONNECT_TIMEOUT`…)。只记 message 的话,日志里全是
|
|
320
|
+
* 「网络错误 POST /v2/...: fetch failed」,看不出是断连、DNS 还是超时,
|
|
321
|
+
* 只能靠猜——2026-11-13 排查「发不出去」时就被这一行卡住过。
|
|
322
|
+
*/
|
|
323
|
+
const code = networkCodeOf(e);
|
|
324
|
+
const reason = networkReasonOf(e);
|
|
325
|
+
/**
|
|
326
|
+
* 只有「连接根本没建起来」才敢重试:那时请求一定没到服务端,重试不可能
|
|
327
|
+
* 变成两条消息。`ECONNRESET` / `EPIPE` 属于「可能已经发出去、响应丢了」,
|
|
328
|
+
* 一律不重试——官方被动回复每次都会占一个新的 `msg_seq`,重发就是双发。
|
|
329
|
+
*
|
|
330
|
+
* 这类失败最常见的原因是本机代理 / TUN 抖了一下:连上失败、下一次就好了,
|
|
331
|
+
* 所以补一次重试的收益很高。
|
|
332
|
+
*/
|
|
333
|
+
if (!retried && isSafeToRetryNetworkError(code)) {
|
|
334
|
+
log.warn(`连接没建起来,重试一次:${method} ${path}(${code})`);
|
|
335
|
+
return this.#request(method, path, body, { retried: true, headers });
|
|
336
|
+
}
|
|
249
337
|
throw new Error(`网络错误 ${method} ${path}: ${reason}`);
|
|
250
338
|
}
|
|
251
339
|
|
|
@@ -683,15 +771,30 @@ export class QQApi {
|
|
|
683
771
|
try {
|
|
684
772
|
await fs.mkdir(path.dirname(OWN_MEDIA_FILE), { recursive: true });
|
|
685
773
|
await fs.writeFile(OWN_MEDIA_FILE, JSON.stringify([...this._ownMediaImages]), 'utf8');
|
|
774
|
+
await fs.writeFile(KEPT_MEDIA_FILE, JSON.stringify([...this._keptMediaImages]), 'utf8');
|
|
686
775
|
} catch (e) {
|
|
687
776
|
log.warn(`Markdown 素材归属记录写失败(不影响本次发送): ${e.message}`);
|
|
688
777
|
}
|
|
689
778
|
}
|
|
690
779
|
|
|
691
|
-
/**
|
|
780
|
+
/**
|
|
781
|
+
* 进程内只跑一次:认领上次崩溃留下的孤儿素材并删除,同时加载保留清单。
|
|
782
|
+
* 保留清单只读不删——否则宿主缓存的 qqbot-media:// 引用会在框架重启后静默失效。
|
|
783
|
+
*/
|
|
692
784
|
async #reclaimOrphanMediaImages() {
|
|
693
785
|
if (this._mediaReclaimDone) return;
|
|
694
786
|
this._mediaReclaimDone = true;
|
|
787
|
+
try {
|
|
788
|
+
const kept = JSON.parse(await fs.readFile(KEPT_MEDIA_FILE, 'utf8'));
|
|
789
|
+
if (Array.isArray(kept)) {
|
|
790
|
+
for (const raw of kept) {
|
|
791
|
+
const id = String(raw ?? '');
|
|
792
|
+
if (id) this._keptMediaImages.add(id);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
} catch {
|
|
796
|
+
// 没有记录文件 / 内容损坏,都当空清单
|
|
797
|
+
}
|
|
695
798
|
let ids;
|
|
696
799
|
try {
|
|
697
800
|
ids = JSON.parse(await fs.readFile(OWN_MEDIA_FILE, 'utf8'));
|
|
@@ -713,6 +816,35 @@ export class QQApi {
|
|
|
713
816
|
await this.#persistOwnMedia();
|
|
714
817
|
}
|
|
715
818
|
|
|
819
|
+
/**
|
|
820
|
+
* GET /v2/media-images?cursor={next_cursor}
|
|
821
|
+
*
|
|
822
|
+
* 官方的机器人级素材清单,按上传时间倒序。用它看剩余配额(上限 100 张)、
|
|
823
|
+
* 找可复用的 qqbot-media:// 引用、定位要删除的 image_id。
|
|
824
|
+
* 返回字段统一转 camelCase;`previewUrl` 是短时效预签名链接,别持久化。
|
|
825
|
+
*/
|
|
826
|
+
async listMediaImages({ cursor = '' } = {}) {
|
|
827
|
+
const q = new URLSearchParams();
|
|
828
|
+
const c = String(cursor ?? '').trim();
|
|
829
|
+
if (c) q.set('cursor', c);
|
|
830
|
+
const suffix = q.toString();
|
|
831
|
+
const r = await this.#request('GET', `/v2/media-images${suffix ? `?${suffix}` : ''}`);
|
|
832
|
+
const images = (Array.isArray(r?.images) ? r.images : []).map((it) => ({
|
|
833
|
+
imageId: String(it?.image_id ?? ''),
|
|
834
|
+
url: String(it?.url ?? ''),
|
|
835
|
+
fileName: String(it?.file_name ?? ''),
|
|
836
|
+
previewUrl: String(it?.preview_url ?? ''),
|
|
837
|
+
createdAt: Number(it?.created_at) || 0,
|
|
838
|
+
expiresAt: Number(it?.expires_at) || 0,
|
|
839
|
+
}));
|
|
840
|
+
return {
|
|
841
|
+
images,
|
|
842
|
+
nextCursor: String(r?.next_cursor ?? ''),
|
|
843
|
+
total: Number(r?.total) || 0,
|
|
844
|
+
quota: MEDIA_IMAGE_QUOTA,
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
|
|
716
848
|
/** POST /v2/media-images/prepare */
|
|
717
849
|
prepareMediaImage({ fileName, fileSize, contentType, md5, sha1 } = {}) {
|
|
718
850
|
return this.#request('POST', '/v2/media-images/prepare', {
|
|
@@ -724,15 +856,24 @@ export class QQApi {
|
|
|
724
856
|
});
|
|
725
857
|
}
|
|
726
858
|
|
|
727
|
-
/**
|
|
728
|
-
|
|
859
|
+
/**
|
|
860
|
+
* POST /v2/media-images/complete;md5 取 COS 的 ETag(去引号)。
|
|
861
|
+
* `retain:true` 的素材归到 kept(跨消息复用),其余归 own(发完即删)。
|
|
862
|
+
*/
|
|
863
|
+
async completeMediaImage({ uploadId, md5 } = {}, { retain = false } = {}) {
|
|
729
864
|
const r = await this.#request('POST', '/v2/media-images/complete', {
|
|
730
865
|
upload_id: String(uploadId ?? ''),
|
|
731
866
|
md5: String(md5 ?? ''),
|
|
732
867
|
});
|
|
733
|
-
// 凡经本 QQApi 创建的素材都算「自己人」,记下来供 finally 清理
|
|
868
|
+
// 凡经本 QQApi 创建的素材都算「自己人」,记下来供 finally 清理 / 配额管理
|
|
734
869
|
if (r?.image_id) {
|
|
735
|
-
|
|
870
|
+
const id = String(r.image_id);
|
|
871
|
+
if (retain) {
|
|
872
|
+
this._keptMediaImages.add(id);
|
|
873
|
+
this._ownMediaImages.delete(id);
|
|
874
|
+
} else {
|
|
875
|
+
this._ownMediaImages.add(id);
|
|
876
|
+
}
|
|
736
877
|
await this.#persistOwnMedia();
|
|
737
878
|
}
|
|
738
879
|
return r;
|
|
@@ -742,95 +883,61 @@ export class QQApi {
|
|
|
742
883
|
* DELETE /v2/media-images/{image_id}/delete
|
|
743
884
|
*
|
|
744
885
|
* 删除后引用立即失效,但**已发出的消息不受影响**(平台发送时已转存副本)。
|
|
745
|
-
*
|
|
746
|
-
*
|
|
886
|
+
* 默认只接受本进程创建(own / kept)的 image_id,避免误删其它插件的素材。
|
|
887
|
+
*
|
|
888
|
+
* `allowUnowned` 是给「清理机器人级配额」用的受控入口:调用方必须先用
|
|
889
|
+
* `listMediaImages()` 确认 id 确实属于本机器人,且是用户显式确认的删除。
|
|
890
|
+
* 宿主协议 `media.image.delete` 会先查列表再传它,面板路径不给这个开关。
|
|
747
891
|
*/
|
|
748
|
-
async deleteMediaImage(imageId) {
|
|
892
|
+
async deleteMediaImage(imageId, { allowUnowned = false } = {}) {
|
|
749
893
|
const id = String(imageId ?? '');
|
|
750
894
|
if (!id) throw new Error('deleteMediaImage 需要 image_id');
|
|
751
|
-
|
|
895
|
+
const known = this._ownMediaImages.has(id) || this._keptMediaImages.has(id);
|
|
896
|
+
if (!known && !allowUnowned) {
|
|
752
897
|
throw new Error(`拒绝删除非本进程上传的素材 ${id}(素材库是机器人级共享,可能属于其它插件)`);
|
|
753
898
|
}
|
|
754
899
|
const r = await this.#request('DELETE', `/v2/media-images/${enc(id)}/delete`);
|
|
755
900
|
this._ownMediaImages.delete(id);
|
|
901
|
+
this._keptMediaImages.delete(id);
|
|
756
902
|
await this.#persistOwnMedia();
|
|
757
903
|
return r;
|
|
758
904
|
}
|
|
759
905
|
|
|
760
906
|
/**
|
|
761
|
-
*
|
|
762
|
-
*
|
|
763
|
-
* **预检前置**:大小 >10MB / 扩展名不在白名单 / 文件头与扩展名不符,
|
|
764
|
-
* 都在本地判掉并带 `reason`,跳过 prepare/PUT/complete 三次网络请求。
|
|
765
|
-
* 这是「图片过大」这条最高频降级场景的专用快路径。
|
|
907
|
+
* 把**图片字节**上传成 Markdown 可用的 `qqbot-media://` 引用。
|
|
766
908
|
*
|
|
767
|
-
*
|
|
768
|
-
*
|
|
909
|
+
* 三个本地预检都在这一层:>10MB / 扩展名不在白名单 / 文件头与扩展名不符。
|
|
910
|
+
* 官方只校验「扩展名 ↔ content_type」、不校验实际内容,坏图会一路成功到发消息
|
|
911
|
+
* 才失败(注意事项第 5 条)。跨进程调用尤其要在这里挡住:宿主给的 fileName
|
|
912
|
+
* 决定 content_type,随便落成 .png 会让 jpeg/gif/webp 被 COS 或 40035001 拒。
|
|
769
913
|
*
|
|
770
|
-
* @param {
|
|
771
|
-
* @
|
|
914
|
+
* @param {Buffer} buf 图片原始字节
|
|
915
|
+
* @param {{fileName?:string, retain?:boolean}} opts
|
|
772
916
|
*/
|
|
773
|
-
async
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
if (!p) {
|
|
778
|
-
const e = new Error('uploadMarkdownImage 需要本地文件路径');
|
|
917
|
+
async #pushMarkdownImageBytes(buf, { fileName = '', retain = false } = {}) {
|
|
918
|
+
const name = String(fileName ?? '').split(/[\\/]/).pop() || 'image.png';
|
|
919
|
+
if (!Buffer.isBuffer(buf) || !buf.length) {
|
|
920
|
+
const e = new Error('uploadMarkdownImage 需要非空图片字节');
|
|
779
921
|
e.reason = 'outside';
|
|
780
922
|
throw e;
|
|
781
923
|
}
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
try {
|
|
786
|
-
const st = await fs.stat(p);
|
|
787
|
-
if (st.size > MEDIA_IMAGE_MAX) {
|
|
788
|
-
const e = new Error(`${p} 有 ${(st.size / 1024 / 1024).toFixed(1)}MB,超过 Markdown 素材 10MB 上限`);
|
|
789
|
-
e.reason = 'oversize';
|
|
790
|
-
throw e;
|
|
791
|
-
}
|
|
792
|
-
// 只读 16 字节判断真实格式,别为了预检把 10MB 整包读进来两遍
|
|
793
|
-
const fh = await fs.open(p, 'r');
|
|
794
|
-
let head;
|
|
795
|
-
try {
|
|
796
|
-
const b = Buffer.alloc(16);
|
|
797
|
-
const { bytesRead } = await fh.read(b, 0, 16, 0);
|
|
798
|
-
head = b.subarray(0, bytesRead);
|
|
799
|
-
} finally {
|
|
800
|
-
await fh.close();
|
|
801
|
-
}
|
|
802
|
-
const fmt = inspectImageFormat(head, p);
|
|
803
|
-
if (!fmt.ok) {
|
|
804
|
-
const e = new Error(fmt.detail);
|
|
805
|
-
e.reason = fmt.reason;
|
|
806
|
-
throw e;
|
|
807
|
-
}
|
|
808
|
-
contentType = fmt.contentType;
|
|
809
|
-
buf = await fs.readFile(p);
|
|
810
|
-
if (buf.length > MEDIA_IMAGE_MAX) {
|
|
811
|
-
const e = new Error(`${p} 读取后超过 10MB 上限`);
|
|
812
|
-
e.reason = 'oversize';
|
|
813
|
-
throw e;
|
|
814
|
-
}
|
|
815
|
-
} catch (e) {
|
|
816
|
-
if (!e.reason) {
|
|
817
|
-
e.reason = /ENOENT|EACCES|EPERM|ENOTDIR/.test(`${e?.code ?? ''} ${e?.message ?? ''}`)
|
|
818
|
-
? 'outside'
|
|
819
|
-
: 'internal';
|
|
820
|
-
}
|
|
924
|
+
if (buf.length > MEDIA_IMAGE_MAX) {
|
|
925
|
+
const e = new Error(`图片有 ${(buf.length / 1024 / 1024).toFixed(1)}MB,超过 Markdown 素材 10MB 上限`);
|
|
926
|
+
e.reason = 'oversize';
|
|
821
927
|
throw e;
|
|
822
928
|
}
|
|
823
|
-
|
|
824
|
-
|
|
929
|
+
const fmt = inspectImageFormat(buf.subarray(0, 16), name);
|
|
930
|
+
if (!fmt.ok) {
|
|
931
|
+
const e = new Error(fmt.detail);
|
|
932
|
+
e.reason = fmt.reason;
|
|
933
|
+
throw e;
|
|
934
|
+
}
|
|
935
|
+
const contentType = fmt.contentType;
|
|
825
936
|
const md5 = crypto.createHash('md5').update(buf).digest('hex');
|
|
826
937
|
const sha1 = crypto.createHash('sha1').update(buf).digest('hex');
|
|
827
938
|
|
|
828
939
|
const prep = await this.prepareMediaImage({
|
|
829
|
-
fileName,
|
|
830
|
-
fileSize: buf.length,
|
|
831
|
-
contentType,
|
|
832
|
-
md5,
|
|
833
|
-
sha1,
|
|
940
|
+
fileName: name, fileSize: buf.length, contentType, md5, sha1,
|
|
834
941
|
});
|
|
835
942
|
const uploadId = prep?.upload_id;
|
|
836
943
|
const presignedUrl = prep?.presigned_url;
|
|
@@ -841,21 +948,79 @@ export class QQApi {
|
|
|
841
948
|
}
|
|
842
949
|
|
|
843
950
|
const etag = await this.#putPart(presignedUrl, buf, 60_000, contentType);
|
|
844
|
-
const done = await this.completeMediaImage({ uploadId, md5: etagToMd5(etag, md5) });
|
|
951
|
+
const done = await this.completeMediaImage({ uploadId, md5: etagToMd5(etag, md5) }, { retain });
|
|
845
952
|
if (!done?.image_id || !done?.url) {
|
|
846
953
|
const e = new Error('media-images/complete 未返回 image_id / url');
|
|
847
954
|
e.reason = 'internal';
|
|
848
955
|
throw e;
|
|
849
956
|
}
|
|
850
|
-
this._ownMediaImages.add(String(done.image_id));
|
|
851
957
|
return {
|
|
852
958
|
imageId: String(done.image_id),
|
|
853
959
|
url: String(done.url),
|
|
854
960
|
ttl: done.ttl,
|
|
855
|
-
|
|
961
|
+
previewUrl: String(done.preview_url ?? ''),
|
|
962
|
+
fileName: name,
|
|
963
|
+
retained: Boolean(retain),
|
|
856
964
|
};
|
|
857
965
|
}
|
|
858
966
|
|
|
967
|
+
/**
|
|
968
|
+
* 跨进程入口:宿主协议 / 外部调用方手上的是字节,不是框架本机的路径。
|
|
969
|
+
* `retain:true` 的素材不会被孤儿回收清掉,用完请调 `deleteMediaImage()` 释放配额。
|
|
970
|
+
*
|
|
971
|
+
* @returns {Promise<{imageId:string,url:string,ttl:number,previewUrl:string,fileName:string,retained:boolean}>}
|
|
972
|
+
*/
|
|
973
|
+
async uploadMarkdownImageBytes(buf, { fileName = '', retain = false } = {}) {
|
|
974
|
+
await this.#reclaimOrphanMediaImages();
|
|
975
|
+
try {
|
|
976
|
+
return await this.#pushMarkdownImageBytes(buf, { fileName, retain });
|
|
977
|
+
} catch (e) {
|
|
978
|
+
if (!e.reason) e.reason = 'internal';
|
|
979
|
+
throw e;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
/**
|
|
984
|
+
* 把一张**本地**图上传成 Markdown 可用的 `qqbot-media://` 引用。
|
|
985
|
+
* 框架不校验路径所属目录:调用方是可信的插件代码,路径由它把关。
|
|
986
|
+
* 保留原有的 `reason` 分类(outside / oversize / bad_format / internal),
|
|
987
|
+
* `message.js` 的 replyAuto 靠它决定降级文案。
|
|
988
|
+
*
|
|
989
|
+
* @param {string} filePath 本地文件路径(绝对或 cwd 相对)
|
|
990
|
+
*/
|
|
991
|
+
async uploadMarkdownImage(filePath) {
|
|
992
|
+
await this.#reclaimOrphanMediaImages();
|
|
993
|
+
const p = String(filePath ?? '');
|
|
994
|
+
if (!p) {
|
|
995
|
+
const e = new Error('uploadMarkdownImage 需要本地文件路径');
|
|
996
|
+
e.reason = 'outside';
|
|
997
|
+
throw e;
|
|
998
|
+
}
|
|
999
|
+
let buf;
|
|
1000
|
+
try {
|
|
1001
|
+
const st = await fs.stat(p);
|
|
1002
|
+
if (st.size > MEDIA_IMAGE_MAX) {
|
|
1003
|
+
const e = new Error(`${p} 有 ${(st.size / 1024 / 1024).toFixed(1)}MB,超过 Markdown 素材 10MB 上限`);
|
|
1004
|
+
e.reason = 'oversize';
|
|
1005
|
+
throw e;
|
|
1006
|
+
}
|
|
1007
|
+
buf = await fs.readFile(p);
|
|
1008
|
+
} catch (e) {
|
|
1009
|
+
if (!e.reason) {
|
|
1010
|
+
e.reason = /ENOENT|EACCES|EPERM|ENOTDIR/.test(`${e?.code ?? ''} ${e?.message ?? ''}`)
|
|
1011
|
+
? 'outside'
|
|
1012
|
+
: 'internal';
|
|
1013
|
+
}
|
|
1014
|
+
throw e;
|
|
1015
|
+
}
|
|
1016
|
+
try {
|
|
1017
|
+
return await this.#pushMarkdownImageBytes(buf, { fileName: p.split(/[\\/]/).pop() });
|
|
1018
|
+
} catch (e) {
|
|
1019
|
+
if (!e.reason) e.reason = 'internal';
|
|
1020
|
+
throw e;
|
|
1021
|
+
}
|
|
1022
|
+
}
|
|
1023
|
+
|
|
859
1024
|
/* ---------------- 撤回 ---------------- */
|
|
860
1025
|
|
|
861
1026
|
/**
|
package/src/bot.js
CHANGED
|
@@ -21,6 +21,8 @@ import { createLedger } from './ledger.js';
|
|
|
21
21
|
import { createGate } from './gate.js';
|
|
22
22
|
import { createDeliveryLedger } from './delivery.js';
|
|
23
23
|
import { sharedIdentity } from './identity.js';
|
|
24
|
+
import { OneBotBridge } from './onebot/index.js';
|
|
25
|
+
import { HostBridge } from './host/index.js';
|
|
24
26
|
|
|
25
27
|
/**
|
|
26
28
|
* 一个机器人的完整运行时。
|
|
@@ -132,6 +134,28 @@ export class BotRuntime {
|
|
|
132
134
|
this.session = null;
|
|
133
135
|
this.pipeline = null;
|
|
134
136
|
this.plugins = null;
|
|
137
|
+
/**
|
|
138
|
+
* OneBot v11 兼容层(对外协议,后端仍是官方接口)。
|
|
139
|
+
*
|
|
140
|
+
* 这里只**构造**,不启动——`start()` 里等 api / outbound / identity 都就绪
|
|
141
|
+
* 再 `onebot.start()`。缺 `ws` 依赖时它自己是 `missing-deps` 状态,
|
|
142
|
+
* 不影响机器人本体。
|
|
143
|
+
*/
|
|
144
|
+
this.onebot = new OneBotBridge({
|
|
145
|
+
runtime: this,
|
|
146
|
+
cfg: cfg.onebot ?? {},
|
|
147
|
+
botId: this.id,
|
|
148
|
+
identity: this.identity,
|
|
149
|
+
});
|
|
150
|
+
/**
|
|
151
|
+
* 宿主协议 v1(roost-host/1):框架自己的能力总线,和 OneBot 并列。
|
|
152
|
+
* 同样只构造不启动,缺 `ws` / 没 token 都只是这一层不可用。
|
|
153
|
+
*/
|
|
154
|
+
this.host = new HostBridge({
|
|
155
|
+
runtime: this,
|
|
156
|
+
cfg: cfg.host ?? {},
|
|
157
|
+
botId: this.id,
|
|
158
|
+
});
|
|
135
159
|
|
|
136
160
|
this.state = 'idle'; // idle | starting | online | offline | stopped | error
|
|
137
161
|
this.lastError = '';
|
|
@@ -197,6 +221,20 @@ export class BotRuntime {
|
|
|
197
221
|
quotaFile: this.paths.quota,
|
|
198
222
|
});
|
|
199
223
|
|
|
224
|
+
/**
|
|
225
|
+
* OneBot 兼容层在这里起(api / outbound / identity 都就绪了)。
|
|
226
|
+
*
|
|
227
|
+
* 失败**不拦启动**:缺 `ws` 依赖、端口被占、token 没填,都只是这一层不可用,
|
|
228
|
+
* 机器人本体和插件照常跑。错误挂在 `onebot.error` 上,面板能看见。
|
|
229
|
+
*/
|
|
230
|
+
await this.onebot.start().catch((e) => {
|
|
231
|
+
this.log.warn(`OneBot 兼容层启动失败(不影响机器人本体):${e.message}`);
|
|
232
|
+
});
|
|
233
|
+
/** 同理:外接协议失败不许拖垮机器人本体,错误挂在 host.error 上面板能看见 */
|
|
234
|
+
await this.host.start().catch((e) => {
|
|
235
|
+
this.log.warn(`宿主协议启动失败(不影响机器人本体):${e.message}`);
|
|
236
|
+
});
|
|
237
|
+
|
|
200
238
|
// 群管内邀开关:api 层有自己的副本,配置变了由面板接口同步过来。
|
|
201
239
|
// mock 的 api 也实现了同名方法,一起同步,方便本地验证插件的群管逻辑
|
|
202
240
|
this.api.setGroupInvited?.(cfg.groupManage?.invited);
|
|
@@ -664,6 +702,9 @@ export class BotRuntime {
|
|
|
664
702
|
this.webhook?.unregister(this.cfg.appId);
|
|
665
703
|
} catch {}
|
|
666
704
|
this.session?.clear();
|
|
705
|
+
// 先关两个对外出口:端口要尽快释放,客户端重连时不该打到一个正在退出的进程上
|
|
706
|
+
await this.host?.stop().catch(() => {});
|
|
707
|
+
await this.onebot?.stop().catch(() => {});
|
|
667
708
|
await this.plugins?.shutdown().catch(() => {});
|
|
668
709
|
await this.outbound?.flush().catch(() => {});
|
|
669
710
|
await this.groups?.flush().catch(() => {});
|
|
@@ -801,6 +842,16 @@ export class BotRuntime {
|
|
|
801
842
|
});
|
|
802
843
|
|
|
803
844
|
const meta = EVENTS[eventName] ?? null;
|
|
845
|
+
|
|
846
|
+
/**
|
|
847
|
+
* OneBot 兼容层:非消息事件(入群、退群、加好友…)。
|
|
848
|
+
*
|
|
849
|
+
* 放在插件监听器之前——客户端看到的状态应该是最新的,和可达性更新
|
|
850
|
+
* 同一条理由。它自己吞异常,不会影响插件。
|
|
851
|
+
*/
|
|
852
|
+
this.onebot?.onEvent(eventName, d);
|
|
853
|
+
/** 宿主协议:事件名与 data 原样带出去,不猜结构、不翻译 */
|
|
854
|
+
this.host?.onEvent(eventName, d);
|
|
804
855
|
for (const l of registry.listeners.get(eventName) ?? []) {
|
|
805
856
|
// 事件里的群:有 group_openid 就按群开关过滤,没有(如私聊事件)就放行
|
|
806
857
|
if (d?.group_openid && !pluginAllowedIn(cfg.plugins, d.group_openid, l.pluginId)) continue;
|
|
@@ -887,6 +938,16 @@ export class BotRuntime {
|
|
|
887
938
|
*/
|
|
888
939
|
try {
|
|
889
940
|
this.onMessage?.(msg);
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* OneBot 兼容层收消息。
|
|
944
|
+
*
|
|
945
|
+
* 传的是**完整 msg**(含 uin / msgIdx / attachments),不走 message-bus——
|
|
946
|
+
* 那条通道的 payload 是对外契约,故意脱敏过,拿不到 ID 映射要的东西。
|
|
947
|
+
*/
|
|
948
|
+
this.onebot?.onMessage(msg);
|
|
949
|
+
/** 宿主协议:传完整 msg(原生结构),它自己挑字段 */
|
|
950
|
+
this.host?.onMessage(msg);
|
|
890
951
|
} catch (e) {
|
|
891
952
|
this.log.warn(`消息广播失败: ${e.message}`);
|
|
892
953
|
}
|
|
@@ -914,6 +975,23 @@ export class BotRuntime {
|
|
|
914
975
|
|
|
915
976
|
if (msg.mentioned || msg.isCommand) session.markAddressed(msg.chatId);
|
|
916
977
|
|
|
978
|
+
/**
|
|
979
|
+
* 兼容模式「独占」:**插件**不再回话,但**内核命令照常工作**。
|
|
980
|
+
*
|
|
981
|
+
* 为什么不能直接 `return`(第一版就是这么写的,被主人指出来):
|
|
982
|
+
* `绑定qq` / `绑定群号` / `绑定成员` 这些是**内核命令**(pluginId `__core`),
|
|
983
|
+
* 而 OneBot 的 ID 映射要靠绑定表才能给真 QQ 号。独占模式一刀切掉管线,
|
|
984
|
+
* 用户就再也绑不了号——于是所有人在客户端里永远是一串 13 位合成号,
|
|
985
|
+
* 主人权限、群号都对不上。这是个死循环,必须在管线里解决而不是绕过它。
|
|
986
|
+
*
|
|
987
|
+
* 所以这里**不提前 return**,只打一个标记:
|
|
988
|
+
* - 管线照跑(去重 / 白名单 / 限流 / 暂停闸都还在,别的地方也别想绕过)
|
|
989
|
+
* - 命令只放 `__core`,插件命令静默忽略
|
|
990
|
+
* - 插件监听器整段跳过
|
|
991
|
+
*/
|
|
992
|
+
const coreOnly = Boolean(this.onebot?.exclusive);
|
|
993
|
+
if (coreOnly) msg.coreOnly = true;
|
|
994
|
+
|
|
917
995
|
const commandEntry = msg.isCommand ? registry.commands.get(msg.command) ?? null : null;
|
|
918
996
|
const passed = await pipeline.run({ msg, cfg, commandEntry });
|
|
919
997
|
if (!passed) return;
|
|
@@ -939,6 +1017,16 @@ export class BotRuntime {
|
|
|
939
1017
|
this.#rememberPerson(msg);
|
|
940
1018
|
|
|
941
1019
|
if (msg.isCommand && commandEntry) {
|
|
1020
|
+
/**
|
|
1021
|
+
* 独占模式下插件命令一律静默忽略(不提示「没有这个命令」):
|
|
1022
|
+
* 客户端已经接管了这些能力,群里再冒一句提示只是噪音。
|
|
1023
|
+
* `__core` 是内核命令(绑定 / 管理 / help),必须留着——
|
|
1024
|
+
* 否则 OneBot 的 ID 映射永远拿不到真 QQ 号。
|
|
1025
|
+
*/
|
|
1026
|
+
if (coreOnly && commandEntry.pluginId !== '__core') {
|
|
1027
|
+
this.metrics.bump('ignored');
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
942
1030
|
/**
|
|
943
1031
|
* 分群插件开关:这个群没启用这个插件就不执行。
|
|
944
1032
|
*
|
|
@@ -1021,13 +1109,16 @@ export class BotRuntime {
|
|
|
1021
1109
|
return;
|
|
1022
1110
|
}
|
|
1023
1111
|
|
|
1024
|
-
if (session.deliver(msg)) return;
|
|
1112
|
+
if (!coreOnly && session.deliver(msg)) return;
|
|
1025
1113
|
|
|
1026
|
-
if (msg.isCommand) {
|
|
1114
|
+
if (msg.isCommand && !coreOnly) {
|
|
1027
1115
|
const P = cfg.commandPrefix || '/';
|
|
1028
1116
|
return msg.reply(`没有这个命令:${P}${msg.command}\n发 ${P}help 查看全部命令`).catch(() => {});
|
|
1029
1117
|
}
|
|
1030
1118
|
|
|
1119
|
+
/** 独占模式:插件监听器整段跳过(内核命令上面已经处理完) */
|
|
1120
|
+
if (coreOnly) return;
|
|
1121
|
+
|
|
1031
1122
|
let handled = false;
|
|
1032
1123
|
for (const evt of ['message', eventName]) {
|
|
1033
1124
|
/**
|