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.
Files changed (55) hide show
  1. package/README.md +10 -3
  2. package/config/bot.example.json +30 -0
  3. package/docs/AI/345/256/277/344/270/273/346/216/245/345/205/245.md +145 -0
  4. package/docs/DSH/346/216/245/345/205/245.md +267 -0
  5. package/docs/OneBot/345/205/274/345/256/271/345/261/202/350/256/276/350/256/241.md +1032 -0
  6. package/docs/images/bot-menu.png +0 -0
  7. package/docs/images/bot-switcher.png +0 -0
  8. package/docs/images/events.png +0 -0
  9. package/docs/images/group-manage.png +0 -0
  10. package/docs/images/logs.png +0 -0
  11. package/docs/images/overview.png +0 -0
  12. package/docs/images/plugin-dash-tab.png +0 -0
  13. package/docs/images/plugins-dash.png +0 -0
  14. package/docs/images/plugins.png +0 -0
  15. package/docs//345/217/221/347/211/210/346/270/205/345/215/225.md +167 -0
  16. package/docs//345/233/236/346/273/232/351/242/204/346/241/210.md +78 -0
  17. package/docs//345/256/230/346/226/271/346/216/245/345/217/243/351/231/220/345/210/266.md +375 -0
  18. package/docs//345/256/277/344/270/273/345/215/217/350/256/256v1.md +402 -0
  19. package/docs//345/270/270/350/247/201/351/227/256/351/242/230.md +559 -0
  20. package/docs//346/217/222/344/273/266/345/215/217/350/256/256.md +521 -0
  21. package/docs//346/217/222/344/273/266/345/274/200/345/217/221/350/247/204/350/214/203.md +1857 -0
  22. package/docs//346/235/203/351/231/220/346/250/241/345/236/213.md +237 -0
  23. package/docs//346/236/266/346/236/204/350/257/264/346/230/216.md +311 -0
  24. package/docs//347/234/237/346/234/272/350/201/224/350/260/203.md +253 -0
  25. package/docs//351/205/215/347/275/256/345/217/202/350/200/203.md +427 -0
  26. package/package.json +4 -3
  27. package/src/api.js +242 -77
  28. package/src/bot.js +93 -2
  29. package/src/config.js +150 -6
  30. package/src/endpoints.js +5 -3
  31. package/src/ext-deps.js +703 -0
  32. package/src/host/dispatch.js +125 -0
  33. package/src/host/index.js +395 -0
  34. package/src/host/media.js +462 -0
  35. package/src/host/methods.js +756 -0
  36. package/src/host/ops.js +462 -0
  37. package/src/host/serialize.js +79 -0
  38. package/src/host/server.js +397 -0
  39. package/src/instance.js +75 -13
  40. package/src/ledger.js +45 -0
  41. package/src/main.js +5 -1
  42. package/src/onebot/actions.js +524 -0
  43. package/src/onebot/capability.js +95 -0
  44. package/src/onebot/ids.js +265 -0
  45. package/src/onebot/index.js +410 -0
  46. package/src/onebot/segments.js +195 -0
  47. package/src/onebot/translate.js +219 -0
  48. package/src/onebot/voice.js +449 -0
  49. package/src/onebot/ws-server.js +270 -0
  50. package/src/plugin/loader.js +9 -0
  51. package/src/plugin/market.js +19 -0
  52. package/src/web/server.js +408 -1
  53. package/web/app.js +613 -0
  54. package/web/index.html +190 -1
  55. package/web/style.css +69 -0
@@ -0,0 +1,265 @@
1
+ /**
2
+ * OneBot ID 映射
3
+ * ===============
4
+ *
5
+ * OneBot 的 `user_id` / `group_id` / `message_id` 都是整数,官方给的是
6
+ * openid(32 位十六进制)和字符串 msg_id。这个模块负责两边换算。
7
+ *
8
+ * 三条规则:
9
+ *
10
+ * 1. **真号优先**:identity 表里有绑定就用真 QQ 号。aurobot 这类客户端
11
+ * 用 `user_id === ownerQQ` 判主人,给合成号等于把主人权限静默关掉。
12
+ * 2. **未绑定给 13 位合成号**:`9_000_000_000_000 + hash`。真 QQ 号最长 12 位,
13
+ * 13 位在数学上撞不上;而且在 JS 安全整数范围内(< 2^53),客户端 `Number()`
14
+ * 不会失真。合成号必须**持久化**,否则重启后同一个人会「换号」。
15
+ * 3. **message_id 计数器必须落盘**。不落盘的话重启后从 1 重新开始,
16
+ * 客户端拿着重启前的 id 调 `delete_msg`,会撤掉**另一条**新消息——
17
+ * 这种错既没法解释也没法撤回。
18
+ */
19
+
20
+ import crypto from 'node:crypto';
21
+ import fs from 'node:fs/promises';
22
+ import path from 'node:path';
23
+ import { writeJsonAtomic, readJsonSafe } from '../fsutil.js';
24
+ import { createLogger } from '../logger.js';
25
+
26
+ const log = createLogger('onebot-ids');
27
+
28
+ /** 合成号起点:13 位、9 开头 */
29
+ const SYNTH_BASE = 9_000_000_000_000;
30
+ const SYNTH_MOD = 1_000_000_000_000;
31
+
32
+ /** 保留多少条消息映射。够 `get_msg` / 引用 / 撤回用即可 */
33
+ const MAX_MSGS = 500;
34
+
35
+ /** 落盘节流:映射变化很频繁,每条都写盘不值当 */
36
+ const SAVE_MS = 1000;
37
+
38
+ export class OneBotIds {
39
+ /**
40
+ * @param {object} p
41
+ * @param {string} p.file `data/bots/<id>/onebot-ids.json`
42
+ * @param {string} p.botId
43
+ * @param {object} p.identity IdentityStore(可空:空则一律用合成号)
44
+ */
45
+ constructor({ file, botId, identity = null }) {
46
+ this.file = file;
47
+ this.botId = botId;
48
+ this.identity = identity;
49
+ this.data = null;
50
+ this.dirty = false;
51
+ this.timer = null;
52
+ /** openid → 合成号(反查用) */
53
+ this.synthUsers = new Map();
54
+ this.synthGroups = new Map();
55
+ /** onebot message_id → {m: 官方 msg_id, i: msgIdx, c: chatId, t: 时间} */
56
+ this.msgs = new Map();
57
+ /** 官方 msg_id → onebot message_id(同一条消息重复推送时复用) */
58
+ this.byOfficial = new Map();
59
+ /** msgIdx → onebot message_id(引用回复用) */
60
+ this.byIdx = new Map();
61
+ }
62
+
63
+ async load() {
64
+ if (this.data) return this;
65
+ this.data = (await readJsonSafe(this.file, (m) => log.error(m))) ?? {};
66
+ this.data.version ??= 1;
67
+ /**
68
+ * 计数器下限取「当前时间秒」。
69
+ *
70
+ * 落盘是 1 秒节流的,进程被 kill 时最后一批 id 会丢;如果重启后从旧值
71
+ * 继续发,客户端拿着重启前的 id 调 `delete_msg` 就会撤掉**另一条**新消息。
72
+ * 用时间戳兜底:只要重启间隔 > 1s,新 id 一定比旧 id 大,旧 id 只会「查不到」。
73
+ */
74
+ this.data.nextId = Math.max(Number(this.data.nextId) || 1, Math.floor(Date.now() / 1000));
75
+ this.data.users ??= {};
76
+ this.data.groups ??= {};
77
+ this.data.msgs ??= [];
78
+
79
+ for (const [openid, id] of Object.entries(this.data.users)) this.synthUsers.set(openid, Number(id));
80
+ for (const [openid, id] of Object.entries(this.data.groups)) this.synthGroups.set(openid, Number(id));
81
+ for (const row of this.data.msgs) {
82
+ if (!Array.isArray(row) || row.length !== 2) continue;
83
+ const [id, v] = row;
84
+ if (!v || typeof v !== 'object') continue;
85
+ this.msgs.set(Number(id), v);
86
+ if (v.m) this.byOfficial.set(String(v.m), Number(id));
87
+ if (v.i) this.byIdx.set(String(v.i), Number(id));
88
+ }
89
+ return this;
90
+ }
91
+
92
+ /* ---------------- 号码 ---------------- */
93
+
94
+ /** 合成号:稳定、13 位、9 开头 */
95
+ #synth(openid, bucket) {
96
+ const hit = bucket.get(openid);
97
+ if (hit) return hit;
98
+ const h = crypto.createHash('sha1').update(String(openid)).digest();
99
+ let n = SYNTH_BASE + (h.readUIntBE(0, 6) % SYNTH_MOD);
100
+ // 理论上可能撞(同一机器人下的两个 openid 截断到同一值),撞了就顺延
101
+ const used = new Set([...bucket.values()]);
102
+ while (used.has(n)) n += 1;
103
+ bucket.set(openid, n);
104
+ this.#touch();
105
+ return n;
106
+ }
107
+
108
+ /** openid → OneBot user_id(真号优先) */
109
+ user(openid) {
110
+ const id = String(openid ?? '');
111
+ if (!id) return 0;
112
+ const uin = this.identity?.uinOf?.(id) ?? '';
113
+ if (uin) return Number(uin);
114
+ return this.#synth(id, this.synthUsers);
115
+ }
116
+
117
+ /** group_openid → OneBot group_id(真号优先) */
118
+ group(groupOpenid) {
119
+ const id = String(groupOpenid ?? '');
120
+ if (!id) return 0;
121
+ const uin = this.identity?.groupUinOf?.(id) ?? '';
122
+ if (uin) return Number(uin);
123
+ return this.#synth(id, this.synthGroups);
124
+ }
125
+
126
+ /** OneBot user_id → openid;找不到返回空串 */
127
+ openidOfUser(id) {
128
+ const n = Number(id);
129
+ if (!Number.isFinite(n) || n <= 0) return '';
130
+ // 合成号段:只可能是我们发出去的,反查表里一定有
131
+ if (n >= SYNTH_BASE) {
132
+ for (const [openid, v] of this.synthUsers) if (v === n) return openid;
133
+ return '';
134
+ }
135
+ return this.identity?.openidOf?.(this.botId, String(n)) ?? '';
136
+ }
137
+
138
+ openidOfGroup(id) {
139
+ const n = Number(id);
140
+ if (!Number.isFinite(n) || n <= 0) return '';
141
+ if (n >= SYNTH_BASE) {
142
+ for (const [openid, v] of this.synthGroups) if (v === n) return openid;
143
+ return '';
144
+ }
145
+ return this.identity?.groupOpenidOf?.(this.botId, String(n)) ?? '';
146
+ }
147
+
148
+ /* ---------------- 消息 ---------------- */
149
+
150
+ /**
151
+ * 给一条入站消息分配(或复用)OneBot message_id。
152
+ *
153
+ * 复用很重要:官方会重复推送同一条消息,客户端拿两个不同 id 会把同一条
154
+ * 当成两条来引用/撤回。
155
+ */
156
+ bindMessage(msg, { noIndex = false } = {}) {
157
+ const official = String(msg?.id ?? '');
158
+ if (official && this.byOfficial.has(official)) return this.byOfficial.get(official);
159
+
160
+ const id = this.data.nextId++;
161
+ /**
162
+ * `noIndex`:只借一个号,不登记映射。
163
+ *
164
+ * 历史回放用的是账本行 id(UUID),不是官方 msg_id;登记进去会让
165
+ * `delete_msg` 拿它去撤一条不相干的消息,还会挤掉 500 条配额里的真映射。
166
+ */
167
+ if (noIndex) {
168
+ this.#touch();
169
+ return id;
170
+ }
171
+ const row = {
172
+ m: official,
173
+ i: String(msg?.msgIdx ?? ''),
174
+ c: String(msg?.chatId ?? ''),
175
+ k: String(msg?.kind ?? ''),
176
+ t: Date.now(),
177
+ };
178
+ this.msgs.set(id, row);
179
+ if (official) this.byOfficial.set(official, id);
180
+ if (row.i) this.byIdx.set(row.i, id);
181
+
182
+ // 超上限就丢最老的(Map 保持插入顺序)
183
+ while (this.msgs.size > MAX_MSGS) {
184
+ const [oldId, old] = this.msgs.entries().next().value;
185
+ this.msgs.delete(oldId);
186
+ if (old?.m) this.byOfficial.delete(String(old.m));
187
+ if (old?.i) this.byIdx.delete(String(old.i));
188
+ }
189
+ this.#touch();
190
+ return id;
191
+ }
192
+
193
+ /** OneBot message_id → {m: 官方 msg_id, i: msgIdx, c: chatId, k: kind, t} */
194
+ getMessage(id) {
195
+ return this.msgs.get(Number(id)) ?? null;
196
+ }
197
+
198
+ /**
199
+ * 给「机器人自己发出去的消息」也分配一个 id。
200
+ *
201
+ * 客户端随后会拿它 `delete_msg` / `get_msg`;不登记的话撤回永远失败。
202
+ * 官方没有 msgIdx(那是入站消息才有的引用索引),所以 `i` 留空。
203
+ */
204
+ bindSent({ officialId, chatId, kind }) {
205
+ const official = String(officialId ?? '');
206
+ if (official && this.byOfficial.has(official)) return this.byOfficial.get(official);
207
+
208
+ const id = this.data.nextId++;
209
+ const row = { m: official, i: '', c: String(chatId ?? ''), k: String(kind ?? ''), t: Date.now() };
210
+ this.msgs.set(id, row);
211
+ if (official) this.byOfficial.set(official, id);
212
+ while (this.msgs.size > MAX_MSGS) {
213
+ const [oldId, old] = this.msgs.entries().next().value;
214
+ this.msgs.delete(oldId);
215
+ if (old?.m) this.byOfficial.delete(String(old.m));
216
+ if (old?.i) this.byIdx.delete(String(old.i));
217
+ }
218
+ this.#touch();
219
+ return id;
220
+ }
221
+
222
+ /** 引用用:msgIdx → OneBot message_id(查不到返回 0) */
223
+ messageIdOfIdx(msgIdx) {
224
+ const i = String(msgIdx ?? '');
225
+ if (!i) return 0;
226
+ return this.byIdx.get(i) ?? 0;
227
+ }
228
+
229
+ /* ---------------- 落盘 ---------------- */
230
+
231
+ #touch() {
232
+ this.dirty = true;
233
+ if (this.timer) return;
234
+ this.timer = setTimeout(() => this.flush(), SAVE_MS);
235
+ this.timer.unref?.();
236
+ }
237
+
238
+ async flush() {
239
+ if (this.timer) {
240
+ clearTimeout(this.timer);
241
+ this.timer = null;
242
+ }
243
+ if (!this.dirty || !this.data) return;
244
+ this.dirty = false;
245
+ const out = {
246
+ version: 1,
247
+ nextId: this.data.nextId,
248
+ users: Object.fromEntries(this.synthUsers),
249
+ groups: Object.fromEntries(this.synthGroups),
250
+ // 只留最近 MAX_MSGS 条,别让文件无限长
251
+ msgs: [...this.msgs.entries()].slice(-MAX_MSGS),
252
+ };
253
+ try {
254
+ await fs.mkdir(path.dirname(this.file), { recursive: true });
255
+ await writeJsonAtomic(this.file, out);
256
+ } catch (e) {
257
+ log.warn(`ID 映射落盘失败(不影响本次运行):${e.message}`);
258
+ }
259
+ }
260
+
261
+ /** 状态快照:面板显示「有多少人/群在用合成号」 */
262
+ stats() {
263
+ return { synthUsers: this.synthUsers.size, synthGroups: this.synthGroups.size, msgs: this.msgs.size };
264
+ }
265
+ }
@@ -0,0 +1,410 @@
1
+ /**
2
+ * OneBot v11 兼容层(对外协议,后端仍是官方接口)
3
+ * ==============================================
4
+ *
5
+ * 生命周期:
6
+ *
7
+ * runtime.start() ──> bridge.start()
8
+ * ├─ 缺 ws 依赖 → state='missing-deps',不监听(不抛)
9
+ * ├─ 没开开关 → state='disabled'
10
+ * └─ 正常 → 监听、推送事件、接 action
11
+ *
12
+ * 和内核的接口只有三个:
13
+ * `onMessage(msg)` 每条入站消息(含全量群消息)
14
+ * `onEvent(name, d)` 非消息事件(入群、加好友…)
15
+ * `exclusive` 告诉 bot.js「这条别进插件管线了」
16
+ *
17
+ * 事件只推给客户端,**不参与插件管线**(exclusive 模式)。
18
+ */
19
+
20
+ import crypto from 'node:crypto';
21
+ import fs from 'node:fs/promises';
22
+ import path from 'node:path';
23
+ import { ROOT, DIRS } from '../paths.js';
24
+ import { createLogger } from '../logger.js';
25
+ import * as deps from '../ext-deps.js';
26
+ import { OneBotIds } from './ids.js';
27
+ import { createActions } from './actions.js';
28
+ import { buildCapability, summarize } from './capability.js';
29
+ import { createOneBotServer } from './ws-server.js';
30
+ import { toMessageEvent, toNotice, lifecycleEvent, heartbeatEvent } from './translate.js';
31
+
32
+ const log = createLogger('onebot');
33
+
34
+ /** 自动分配端口的基准与范围:6700–6799 */
35
+ const PORT_BASE = 6700;
36
+ const PORT_SPAN = 100;
37
+ /** 端口被占时最多顺延几次 */
38
+ const PORT_TRIES = 20;
39
+ /** 心跳间隔(与 translate 里的 interval 一致) */
40
+ const HEARTBEAT_MS = 25_000;
41
+
42
+ /** botId → 稳定端口(加一只鸟不会让别的鸟换端口) */
43
+ function portOf(botId) {
44
+ const h = crypto.createHash('sha1').update(String(botId)).digest();
45
+ return PORT_BASE + (h.readUInt16BE(0) % PORT_SPAN);
46
+ }
47
+
48
+ export class OneBotBridge {
49
+ /**
50
+ * @param {object} p
51
+ * @param {object} p.runtime BotRuntime
52
+ * @param {object} p.cfg 该机器人的 `onebot` 配置
53
+ * @param {string} p.botId
54
+ * @param {object} p.identity IdentityStore
55
+ */
56
+ constructor({ runtime, cfg, botId, identity }) {
57
+ this.runtime = runtime;
58
+ this.cfg = cfg ?? {};
59
+ this.botId = botId;
60
+ this.identity = identity;
61
+ this.ids = null;
62
+ this.server = null;
63
+ this.actions = null;
64
+ this.heartbeat = null;
65
+ this.state = 'stopped';
66
+ this.error = '';
67
+ this.port = 0;
68
+ this.lastEventAt = 0;
69
+ this.counters = { ok: 0, fail: 0 };
70
+ this.selfUin = 0;
71
+ this.selfOpenid = '';
72
+ this.silkOk = false;
73
+ /** chatId(openid) → {msgId, at}:被动回复窗口用 */
74
+ this.lastInbound = new Map();
75
+ /** 见过非 @ 的群消息(= 平台「接收所有消息」确实开着) */
76
+ this.sawUnaddressedGroup = false;
77
+ this.pkgVersion = '';
78
+ /** start/stop 串行化:连点两次「保存」不能起两个监听 */
79
+ this.chain = Promise.resolve();
80
+ }
81
+
82
+ /**
83
+ * 串行执行:所有 start / stop / reconfigure 排队。
84
+ *
85
+ * 不做这一步的后果很具体:面板连点保存 → 两次 reconfigure 并发 →
86
+ * 两个 `start()` 各自 `stop()` 再监听,后一个撞 EADDRINUSE 顺延到 6701
87
+ * 并覆盖 `this.server`,**旧监听没人关**、心跳 interval 也漏一个。
88
+ * 表现是「端口漂移 + 客户端连不上 + 关不掉」。
89
+ */
90
+ #enqueue(fn) {
91
+ const run = this.chain.then(fn, fn);
92
+ this.chain = run.then(
93
+ () => undefined,
94
+ () => undefined,
95
+ );
96
+ return run;
97
+ }
98
+
99
+ start() {
100
+ return this.#enqueue(() => this.#startNow());
101
+ }
102
+
103
+ stop() {
104
+ return this.#enqueue(() => this.#stopNow());
105
+ }
106
+
107
+ /** 配置热更新:先停再起(端口/开关都可能变) */
108
+ reconfigure(next) {
109
+ this.cfg = next ?? {};
110
+ return this.#enqueue(() => this.#startNow());
111
+ }
112
+
113
+ /** bot.js 用它决定「这条消息还要不要进插件管线」 */
114
+ get exclusive() {
115
+ return Boolean(this.cfg.enabled) && this.cfg.mode === 'exclusive' && this.state === 'running';
116
+ }
117
+
118
+ async #version() {
119
+ if (this.pkgVersion) return this.pkgVersion;
120
+ try {
121
+ const p = JSON.parse(await fs.readFile(path.join(ROOT, 'package.json'), 'utf8'));
122
+ this.pkgVersion = String(p.version ?? '');
123
+ } catch {
124
+ this.pkgVersion = '';
125
+ }
126
+ return this.pkgVersion;
127
+ }
128
+
129
+ /** 已装且可用?不可用返回原因 */
130
+ async #requireWs() {
131
+ const st = await deps.status();
132
+ if (!st.packages.ws?.resolvable) return '缺依赖 ws';
133
+ return '';
134
+ }
135
+
136
+ async #startNow() {
137
+ await this.#stopNow();
138
+ this.error = '';
139
+
140
+ if (!this.cfg.enabled) {
141
+ this.state = 'disabled';
142
+ return this;
143
+ }
144
+
145
+ const missing = await this.#requireWs();
146
+ if (missing) {
147
+ this.state = 'missing-deps';
148
+ this.error = `${missing}:到面板「外接」页点『一键安装 ws』`;
149
+ log.info(`兼容模式未就绪:${this.error}`);
150
+ return this;
151
+ }
152
+
153
+ this.selfUin = Number(this.cfg.selfUin) || 0;
154
+ if (!this.selfUin) {
155
+ this.state = 'error';
156
+ this.error = '没填机器人 QQ 号(selfUin)';
157
+ return this;
158
+ }
159
+ /**
160
+ * 没 token 不监听。`ws-server` 里空 token 是「不校验」,
161
+ * 在这里拦一道,免得配置被手改成空串就变成一个人人可连的后门。
162
+ */
163
+ if (!String(this.cfg.token ?? '').trim()) {
164
+ this.state = 'error';
165
+ this.error = '没设 access token(面板「外接」页点『生成』)';
166
+ return this;
167
+ }
168
+ this.selfOpenid = this.identity?.openidOf?.(this.botId, String(this.selfUin)) ?? '';
169
+
170
+ this.ids = new OneBotIds({
171
+ file: path.join(DIRS.data, 'bots', this.botId, 'onebot-ids.json'),
172
+ botId: this.botId,
173
+ identity: this.identity,
174
+ });
175
+ await this.ids.load();
176
+ await this.#version();
177
+
178
+ // 依赖装好才加载:`ws` 在 `data/deps/onebot/node_modules`,ESM 静态 import 找不到它
179
+ const wsMod = await deps.load('ws');
180
+ if (!wsMod?.WebSocketServer) {
181
+ this.state = 'missing-deps';
182
+ this.error = 'ws 加载失败(面板「外接」页可重装)';
183
+ return this;
184
+ }
185
+ const depState = await deps.status();
186
+ const silkOk = Boolean(depState.packages['silk-wasm']?.resolvable);
187
+ const silkMod = silkOk ? await deps.load('silk-wasm') : null;
188
+ this.silkOk = Boolean(silkMod);
189
+
190
+ this.actions = createActions({
191
+ /**
192
+ * **传真的 runtime,不要 `{...runtime}`**。
193
+ *
194
+ * `online` / `groupName()` 都在原型上,展开会丢掉——表现是
195
+ * 「永远判定离线」「群名永远是空」,而且不会报错。
196
+ */
197
+ runtime: this.runtime,
198
+ version: this.pkgVersion,
199
+ ids: this.ids,
200
+ selfUin: this.selfUin,
201
+ botName: this.runtime.cfg?.name ?? '',
202
+ getPassive: (chatId) => this.#passive(chatId),
203
+ emit: (evt) => this.server?.broadcast(evt),
204
+ // `voice: 'reject'` 是「装了也不发」,面板上那个开关得真生效
205
+ /** 首次发语音会自动装 silk-wasm,所以这个判断要能看到「刚装上」的模块 */
206
+ silkReady: () => Boolean(silkMod || deps.cached('silk-wasm')) && this.cfg.voice !== 'reject',
207
+ silk: silkMod,
208
+ historyLimit: Math.min(Math.max(Number(this.cfg.historyCache) || 0, 0), 200),
209
+ });
210
+
211
+ const wanted = Number(this.cfg.port) || portOf(this.botId);
212
+ let lastErr = null;
213
+ for (let i = 0; i < PORT_TRIES; i++) {
214
+ const p = wanted + i;
215
+ const srv = createOneBotServer({
216
+ host: this.cfg.host || '127.0.0.1',
217
+ port: p,
218
+ token: String(this.cfg.token ?? ''),
219
+ http: this.cfg.http !== false,
220
+ ws: wsMod,
221
+ maxConnections: Number(this.cfg.maxConnections) || 4,
222
+ onAction: async (action, params) => {
223
+ try {
224
+ const r = await this.actions(action, params);
225
+ this.counters.ok += 1;
226
+ return r;
227
+ } catch (e) {
228
+ this.counters.fail += 1;
229
+ throw e;
230
+ }
231
+ },
232
+ onConnect: (ws) => {
233
+ try {
234
+ ws.send(JSON.stringify(lifecycleEvent(this.selfUin, 'connect')));
235
+ } catch {
236
+ // 连接刚断,忽略
237
+ }
238
+ },
239
+ });
240
+ try {
241
+ this.port = await srv.start();
242
+ this.server = srv;
243
+ break;
244
+ } catch (e) {
245
+ lastErr = e;
246
+ await srv.stop().catch(() => {});
247
+ if (e?.code !== 'EADDRINUSE') break;
248
+ }
249
+ }
250
+
251
+ if (!this.server) {
252
+ this.state = 'error';
253
+ this.error = `端口 ${wanted} 起不来:${lastErr?.message ?? '未知原因'}`;
254
+ log.error(this.error);
255
+ return this;
256
+ }
257
+
258
+ this.state = 'running';
259
+ this.heartbeat = setInterval(() => {
260
+ if (!this.server) return;
261
+ this.server.broadcast(heartbeatEvent(this.selfUin, HEARTBEAT_MS));
262
+ }, HEARTBEAT_MS);
263
+ this.heartbeat.unref?.();
264
+
265
+ log.info(
266
+ `兼容模式已监听 ${this.cfg.host || '127.0.0.1'}:${this.port}` +
267
+ `(${this.cfg.mode}${this.cfg.http !== false ? ' + HTTP' : ''})`,
268
+ );
269
+ /**
270
+ * `forwardAll` 的承诺是「群里说什么都推给客户端」,但上游只在下发了
271
+ * 才能推。没有 `1 << 30`(全量群消息)时,非 @ 的群消息根本到不了框架,
272
+ * 客户端那边看起来就是「群聊没消息」——2026-11-13 就是这么被误判成 bug 的。
273
+ *
274
+ * 只在 OneBot 启用时打一次,不按消息刷屏。
275
+ */
276
+ if (this.cfg.forwardAll !== false) {
277
+ log.info(
278
+ '群聊默认只下发 @ 机器人的消息;要让普通群聊也进客户端,'
279
+ + '到 q.qq.com 给机器人开「接收所有消息」(平台开关,不是 intents 位)',
280
+ );
281
+ }
282
+ return this;
283
+ }
284
+
285
+ async #stopNow() {
286
+ if (this.heartbeat) {
287
+ clearInterval(this.heartbeat);
288
+ this.heartbeat = null;
289
+ }
290
+ if (this.server) {
291
+ await this.server.stop().catch((e) => log.warn(`关监听失败:${e.message}`));
292
+ this.server = null;
293
+ }
294
+ if (this.ids) await this.ids.flush().catch(() => {});
295
+ if (this.state === 'running') this.state = 'stopped';
296
+ // 端口已经没了,别再让面板显示一个「正在监听」的数字
297
+ this.port = 0;
298
+ return this;
299
+ }
300
+
301
+ /** 被动回复窗口:取该会话最近一条入站消息(窗口与次数由 outbound 判,这里只给数据) */
302
+ #passive(chatId) {
303
+ const hit = this.lastInbound.get(chatId);
304
+ if (!hit) return null;
305
+ return { msgId: hit.msgId, at: hit.at };
306
+ }
307
+
308
+ /** 这条消息是不是机器人自己发的(全量模式下平台可能回推) */
309
+ #isSelf(msg) {
310
+ if (this.selfOpenid && msg.userId === this.selfOpenid) return true;
311
+ // 认不出自己时保守一点:过滤所有 bot,避免自激循环
312
+ if (!this.selfOpenid && msg.raw?.author?.bot === true) return true;
313
+ return false;
314
+ }
315
+
316
+ /** bot.js 在每条入站消息上调用 */
317
+ onMessage(msg) {
318
+ if (this.state !== 'running' || !this.ids) return;
319
+ if (!msg?.chatId) return;
320
+ if (this.#isSelf(msg)) return;
321
+ // 全量模式下 `forwardAll=false` 只推「跟机器人有关」的
322
+ if (this.cfg.forwardAll === false && !msg.addressed) return;
323
+ /**
324
+ * `unboundPolicy: 'block'`:没绑 QQ 号的人/群直接不推。
325
+ *
326
+ * 默认是 `warn`(给合成号 + 面板告警),因为「路人说话」不该凭空消失;
327
+ * `block` 是给强一致场景的选项——宁可客户端看不见,也不要看到一串
328
+ * 永远对不上真人的 13 位号。
329
+ */
330
+ if (this.cfg.unboundPolicy === 'block') {
331
+ const uin = this.identity?.uinOf?.(msg.userId) ?? '';
332
+ const guin = msg.kind === 'group' ? (this.identity?.groupUinOf?.(msg.groupId) ?? '') : 'x';
333
+ if (!uin || !guin) return;
334
+ }
335
+
336
+ /**
337
+ * 非 @ 的群消息能到这儿,就证明平台侧「接收所有消息」开着。
338
+ * 面板据此区分「全量已开」和「只收到过 @ 的」,不用猜 intents 位。
339
+ */
340
+ if (msg.kind === 'group' && !msg.addressed) this.sawUnaddressedGroup = true;
341
+
342
+ this.lastInbound.set(msg.chatId, { msgId: msg.id, at: msg.receivedAt || Date.now() });
343
+ if (this.lastInbound.size > 500) {
344
+ const first = this.lastInbound.keys().next().value;
345
+ this.lastInbound.delete(first);
346
+ }
347
+
348
+ try {
349
+ const evt = toMessageEvent({ msg, ids: this.ids, selfUin: this.selfUin });
350
+ this.server?.broadcast(evt);
351
+ this.lastEventAt = Date.now();
352
+ } catch (e) {
353
+ log.warn(`事件翻译失败(已跳过):${e.message}`);
354
+ }
355
+ }
356
+
357
+ /** bot.js 在非消息事件上调用 */
358
+ onEvent(eventName, d) {
359
+ if (this.state !== 'running' || !this.ids) return;
360
+ try {
361
+ const evt = toNotice(eventName, d, { ids: this.ids, selfUin: this.selfUin });
362
+ if (!evt) return;
363
+ this.server?.broadcast(evt);
364
+ this.lastEventAt = Date.now();
365
+ } catch (e) {
366
+ log.warn(`通知翻译失败(${eventName}):${e.message}`);
367
+ }
368
+ }
369
+
370
+ /** 面板用:能力表(支持 / 降级 / 不支持 + 原因) */
371
+ capability() {
372
+ const list = buildCapability({
373
+ implemented: this.actions?.names ?? [],
374
+ hasSilk: this.silkOk || Boolean(deps.cached('silk-wasm')),
375
+ });
376
+ return { list, summary: summarize(list) };
377
+ }
378
+
379
+ /** 面板用 */
380
+ snapshot() {
381
+ /**
382
+ * 上游能推什么,直接决定客户端能看到什么。
383
+ *
384
+ * 全量群消息(`GROUP_MESSAGE_CREATE` 里非 @ 的那些)**不是靠 intents 位**
385
+ * 决定的,而是开放平台的「接收所有消息」开关:开了,同一个
386
+ * `GROUP_AND_C2C_EVENT` 订阅就会把这些消息一起下发;没开,框架根本收不到,
387
+ * OneBot 这边再怎么配也转不出去(2026-11-13 的「收不到群聊消息」就是这个)。
388
+ *
389
+ * 配置里查不到那个开关,所以只能给「经验证据」:见过至少一条非 @ 的群消息,
390
+ * 就说明它确实开着;从来没见过的,面板提示去看一眼开关,而不是断言没开。
391
+ */
392
+ const intents = Number(this.runtime?.cfg?.intents) || 0;
393
+ return {
394
+ state: this.state,
395
+ upstream: { intents, groupAll: this.sawUnaddressedGroup },
396
+ error: this.error,
397
+ host: this.cfg.host || '127.0.0.1',
398
+ port: this.port || 0,
399
+ connections: this.server?.connections ?? 0,
400
+ lastEventAt: this.lastEventAt,
401
+ actions: { ...this.counters },
402
+ ids: this.ids?.stats?.() ?? { synthUsers: 0, synthGroups: 0, msgs: 0 },
403
+ selfOpenidBound: Boolean(this.selfOpenid),
404
+ exclusive: this.exclusive,
405
+ /** 机器人本体有没有上线:没上线时客户端能连上但发不出去,必须显式告诉面板 */
406
+ online: Boolean(this.runtime.online),
407
+ botError: String(this.runtime.lastError ?? ''),
408
+ };
409
+ }
410
+ }