@linjz/opencode-qqbot 0.3.12 → 0.3.14
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 +12 -7
- package/bin/openqq-setup.mjs +50 -50
- package/bin/openqq.js +47 -47
- package/dist/opencode-qqbot-plugin.js +4 -4
- package/dist/openqq-bot.js +1072 -208
- package/package.json +2 -2
- package/src/_FOLDER.md +19 -19
- package/src/bridge.ts +141 -15
- package/src/commands.ts +554 -554
- package/src/config.ts +118 -121
- package/src/core/bot-launcher.ts +146 -146
- package/src/core/card-approval.ts +146 -146
- package/src/core/context-buffer.ts +78 -78
- package/src/core/delivery.ts +115 -18
- package/src/core/discovery.ts +151 -151
- package/src/core/error-rescue.ts +33 -33
- package/src/core/file-log.ts +45 -45
- package/src/core/form-bridge.ts +388 -72
- package/src/core/form-journal.ts +214 -0
- package/src/core/gateway-state.ts +68 -0
- package/src/core/inbound-dedupe.ts +43 -0
- package/src/core/inflight-journal.ts +170 -22
- package/src/core/instance-lock.ts +28 -1
- package/src/core/linkwatch.ts +195 -195
- package/src/core/message-queue.ts +11 -0
- package/src/core/mirror.ts +182 -182
- package/src/core/outbox.ts +522 -0
- package/src/core/permission.ts +301 -301
- package/src/core/reply-limiter.ts +106 -106
- package/src/core/send-media.ts +90 -90
- package/src/core/util.ts +8 -8
- package/src/index.ts +162 -162
- package/src/opencode/_FOLDER.md +11 -11
- package/src/opencode/client.ts +98 -13
- package/src/opencode/eventstream.ts +138 -138
- package/src/opencode/history.ts +143 -143
- package/src/opencode/mirror.ts +85 -85
- package/src/opencode/sessions.ts +158 -158
- package/src/plugin-entry.ts +112 -112
- package/src/qq/_FOLDER.md +13 -13
- package/src/qq/api.ts +546 -539
- package/src/qq/gateway.ts +69 -20
- package/src/qq/media.ts +219 -219
- package/src/qq/sender.ts +303 -300
- package/src/qq/types.ts +154 -154
- package/tsconfig.json +24 -24
package/src/qq/api.ts
CHANGED
|
@@ -1,539 +1,546 @@
|
|
|
1
|
-
// @input: (none - raw HTTP to QQ Bot REST API)
|
|
2
|
-
// @output: getAccessToken, apiRequest, sendC2CMessage, sendGroupMessage, getGatewayUrl, startBackgroundTokenRefresh
|
|
3
|
-
// @pos: qq层 - QQ Bot REST API 鉴权+请求封装 (Token singleflight + 后台刷新)
|
|
4
|
-
import type { MessageContext } from "./types.js"
|
|
5
|
-
|
|
6
|
-
const API_BASE = "https://api.sgroup.qq.com"
|
|
7
|
-
const TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken"
|
|
8
|
-
// 沙箱模式(QQ_SANDBOX=true):API 底座切沙箱域(QQ 官方文档约定
|
|
9
|
-
// sandbox.api.sgroup.qq.com);token 端点两环境共用 bots.qq.com。
|
|
10
|
-
// 注意:沙箱 bot 在非沙箱场景会被网关以 4914(offline/sandbox-only)拒绝。
|
|
11
|
-
const
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
*
|
|
124
|
-
*/
|
|
125
|
-
export function
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
body.
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
accessToken
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
ctx:
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
const
|
|
421
|
-
|
|
422
|
-
}
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
1
|
+
// @input: (none - raw HTTP to QQ Bot REST API)
|
|
2
|
+
// @output: getAccessToken, apiRequest, sendC2CMessage, sendGroupMessage, getGatewayUrl, startBackgroundTokenRefresh
|
|
3
|
+
// @pos: qq层 - QQ Bot REST API 鉴权+请求封装 (Token singleflight + 后台刷新)
|
|
4
|
+
import type { MessageContext } from "./types.js"
|
|
5
|
+
|
|
6
|
+
const API_BASE = "https://api.sgroup.qq.com"
|
|
7
|
+
const TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken"
|
|
8
|
+
// 沙箱模式(QQ_SANDBOX=true):API 底座切沙箱域(QQ 官方文档约定
|
|
9
|
+
// sandbox.api.sgroup.qq.com);token 端点两环境共用 bots.qq.com。
|
|
10
|
+
// 注意:沙箱 bot 在非沙箱场景会被网关以 4914(offline/sandbox-only)拒绝。
|
|
11
|
+
// ★ P0 修复(2026-11-03,外部复盘核验实证):原 `const API_BASE_EFFECTIVE = …`
|
|
12
|
+
// 在模块加载期求值,而 .env 由 ensureConfig() 在运行时才注入 process.env——
|
|
13
|
+
// 发布包(shell 未预置 QQ_SANDBOX)永远赶不上取值,沙箱开关形同虚设。
|
|
14
|
+
// 改为惰性函数:每次构造请求 URL 时现场读取 env,不再依赖加载顺序。
|
|
15
|
+
const API_BASE_SANDBOX = "https://sandbox.api.sgroup.qq.com"
|
|
16
|
+
|
|
17
|
+
export function apiBase(): string {
|
|
18
|
+
return process.env.QQ_SANDBOX === "true" ? API_BASE_SANDBOX : API_BASE
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
let cachedToken: { token: string; expiresAt: number; appId: string } | null = null
|
|
22
|
+
// Singleflight:防止并发获取 Token 时重复请求
|
|
23
|
+
let tokenFetchPromise: Promise<string> | null = null
|
|
24
|
+
|
|
25
|
+
// 债务D3:日志脱敏——Authorization/cookie/token 头含凭证,打印前掩码
|
|
26
|
+
export function maskHeaders(headers: Record<string, string>): Record<string, string> {
|
|
27
|
+
const out: Record<string, string> = {}
|
|
28
|
+
for (const [k, v] of Object.entries(headers)) {
|
|
29
|
+
out[k] = /authorization|cookie|token|secret/i.test(k) ? "***" : v
|
|
30
|
+
}
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 获取 AccessToken,内置缓存与 singleflight 并发保护。
|
|
36
|
+
* 当多个请求同时发现 Token 过期时,只会发起一次真实刷新请求。
|
|
37
|
+
*/
|
|
38
|
+
export async function getAccessToken(appId: string, clientSecret: string): Promise<string> {
|
|
39
|
+
if (cachedToken && Date.now() < cachedToken.expiresAt - 5 * 60 * 1000 && cachedToken.appId === appId) {
|
|
40
|
+
return cachedToken.token
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (cachedToken && cachedToken.appId !== appId) {
|
|
44
|
+
console.log(`[qqbot-api] appId changed (${cachedToken.appId} → ${appId}), clearing token cache`)
|
|
45
|
+
cachedToken = null
|
|
46
|
+
tokenFetchPromise = null
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (tokenFetchPromise) {
|
|
50
|
+
console.log("[qqbot-api] Token fetch in progress, waiting for existing request...")
|
|
51
|
+
return tokenFetchPromise
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
tokenFetchPromise = (async () => {
|
|
55
|
+
try {
|
|
56
|
+
return await doFetchToken(appId, clientSecret)
|
|
57
|
+
} finally {
|
|
58
|
+
tokenFetchPromise = null
|
|
59
|
+
}
|
|
60
|
+
})()
|
|
61
|
+
|
|
62
|
+
return tokenFetchPromise
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 真正执行 Token 获取的内部函数。
|
|
67
|
+
*/
|
|
68
|
+
async function doFetchToken(appId: string, clientSecret: string): Promise<string> {
|
|
69
|
+
const requestBody = { appId, clientSecret }
|
|
70
|
+
const requestHeaders = { "Content-Type": "application/json" }
|
|
71
|
+
|
|
72
|
+
console.log(`[qqbot-api] >>> POST ${TOKEN_URL}`)
|
|
73
|
+
console.log("[qqbot-api] >>> Headers:", JSON.stringify(maskHeaders(requestHeaders), null, 2))
|
|
74
|
+
console.log("[qqbot-api] >>> Body:", JSON.stringify({ appId, clientSecret: "***" }, null, 2))
|
|
75
|
+
|
|
76
|
+
let response: Response
|
|
77
|
+
try {
|
|
78
|
+
response = await fetch(TOKEN_URL, {
|
|
79
|
+
method: "POST",
|
|
80
|
+
headers: requestHeaders,
|
|
81
|
+
body: JSON.stringify(requestBody),
|
|
82
|
+
})
|
|
83
|
+
} catch (err) {
|
|
84
|
+
console.error("[qqbot-api] <<< Network error:", err)
|
|
85
|
+
throw new Error(`Network error getting access_token: ${err instanceof Error ? err.message : String(err)}`)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const responseHeaders: Record<string, string> = {}
|
|
89
|
+
response.headers.forEach((value, key) => {
|
|
90
|
+
responseHeaders[key] = value
|
|
91
|
+
})
|
|
92
|
+
console.log(`[qqbot-api] <<< Status: ${response.status} ${response.statusText}`)
|
|
93
|
+
console.log("[qqbot-api] <<< Headers:", JSON.stringify(maskHeaders(responseHeaders), null, 2))
|
|
94
|
+
|
|
95
|
+
let data: { access_token?: string; expires_in?: number }
|
|
96
|
+
let rawBody: string
|
|
97
|
+
try {
|
|
98
|
+
rawBody = await response.text()
|
|
99
|
+
const logBody = rawBody.replace(/"access_token"\s*:\s*"[^"]+"/g, '"access_token": "***"')
|
|
100
|
+
console.log("[qqbot-api] <<< Body:", logBody)
|
|
101
|
+
data = JSON.parse(rawBody) as { access_token?: string; expires_in?: number }
|
|
102
|
+
} catch (err) {
|
|
103
|
+
console.error("[qqbot-api] <<< Parse error:", err)
|
|
104
|
+
throw new Error(`Failed to parse access_token response: ${err instanceof Error ? err.message : String(err)}`)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (!data.access_token) {
|
|
108
|
+
throw new Error(`Failed to get access_token: ${JSON.stringify(data)}`)
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
cachedToken = {
|
|
112
|
+
token: data.access_token,
|
|
113
|
+
expiresAt: Date.now() + (data.expires_in ?? 7200) * 1000,
|
|
114
|
+
appId,
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
console.log(`[qqbot-api] Token cached for appId=${appId}, expires at: ${new Date(cachedToken.expiresAt).toISOString()}`)
|
|
118
|
+
return cachedToken.token
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* 清空当前 Token 缓存。
|
|
123
|
+
* 不会中断已经在进行中的刷新请求。
|
|
124
|
+
*/
|
|
125
|
+
export function clearTokenCache(): void {
|
|
126
|
+
cachedToken = null
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* 获取当前 Token 缓存状态,便于监控或启动阶段打印状态。
|
|
131
|
+
*/
|
|
132
|
+
export function getTokenStatus(): { status: "valid" | "expired" | "refreshing" | "none"; expiresAt: number | null } {
|
|
133
|
+
if (tokenFetchPromise) {
|
|
134
|
+
return { status: "refreshing", expiresAt: cachedToken?.expiresAt ?? null }
|
|
135
|
+
}
|
|
136
|
+
if (!cachedToken) {
|
|
137
|
+
return { status: "none", expiresAt: null }
|
|
138
|
+
}
|
|
139
|
+
const isValid = Date.now() < cachedToken.expiresAt - 5 * 60 * 1000
|
|
140
|
+
return { status: isValid ? "valid" : "expired", expiresAt: cachedToken.expiresAt }
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* 生成消息序号,范围固定为 0~65535。
|
|
145
|
+
* 用时间戳低位与随机数混合,避免进程内碰撞。
|
|
146
|
+
*/
|
|
147
|
+
export function getNextMsgSeq(_msgId: string): number {
|
|
148
|
+
const timePart = Date.now() % 100000000
|
|
149
|
+
const random = Math.floor(Math.random() * 65536)
|
|
150
|
+
return (timePart ^ random) % 65536
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const DEFAULT_API_TIMEOUT = 30000
|
|
154
|
+
const FILE_UPLOAD_TIMEOUT = 120000
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* 统一封装 QQ Bot REST 请求。
|
|
158
|
+
* 保留源实现的超时、日志、错误处理和 JSON 解析行为。
|
|
159
|
+
*/
|
|
160
|
+
export async function apiRequest<T = unknown>(
|
|
161
|
+
accessToken: string,
|
|
162
|
+
method: string,
|
|
163
|
+
path: string,
|
|
164
|
+
body?: unknown,
|
|
165
|
+
timeoutMs?: number,
|
|
166
|
+
): Promise<T> {
|
|
167
|
+
const url = `${apiBase()}${path}`
|
|
168
|
+
const headers: Record<string, string> = {
|
|
169
|
+
Authorization: `QQBot ${accessToken}`,
|
|
170
|
+
"Content-Type": "application/json",
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const isFileUpload = path.includes("/files")
|
|
174
|
+
const timeout = timeoutMs ?? (isFileUpload ? FILE_UPLOAD_TIMEOUT : DEFAULT_API_TIMEOUT)
|
|
175
|
+
|
|
176
|
+
console.log(`[qqbot-api] >>> ${method} ${url} (timeout: ${timeout}ms)`)
|
|
177
|
+
console.log("[qqbot-api] >>> Headers:", JSON.stringify(maskHeaders(headers), null, 2))
|
|
178
|
+
if (body) {
|
|
179
|
+
const logBody = { ...(body as Record<string, unknown>) }
|
|
180
|
+
if (typeof logBody.file_data === "string") {
|
|
181
|
+
logBody.file_data = `<base64 ${logBody.file_data.length} chars>`
|
|
182
|
+
}
|
|
183
|
+
console.log("[qqbot-api] >>> Body:", JSON.stringify(logBody, null, 2))
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// O 项(2026-10-30,吸收竞品 opencode-qq-v2 postWithRetry):HTTP 429 限流时
|
|
187
|
+
// 尊重 Retry-After 退避重试(最多再试 2 次,单次等待封顶 30s);其余错误不重试。
|
|
188
|
+
// 429 语义=请求被拒绝未生效,重试无副作用。
|
|
189
|
+
let res: Response | undefined
|
|
190
|
+
for (let attempt = 0; ; attempt++) {
|
|
191
|
+
const controller = new AbortController()
|
|
192
|
+
const timeoutId = setTimeout(() => {
|
|
193
|
+
controller.abort()
|
|
194
|
+
}, timeout)
|
|
195
|
+
|
|
196
|
+
const options: RequestInit = {
|
|
197
|
+
method,
|
|
198
|
+
headers,
|
|
199
|
+
signal: controller.signal,
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
if (body) {
|
|
203
|
+
options.body = JSON.stringify(body)
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
try {
|
|
207
|
+
res = await fetch(url, options)
|
|
208
|
+
} catch (err) {
|
|
209
|
+
clearTimeout(timeoutId)
|
|
210
|
+
if (err instanceof Error && err.name === "AbortError") {
|
|
211
|
+
console.error(`[qqbot-api] <<< Request timeout after ${timeout}ms`)
|
|
212
|
+
throw new Error(`Request timeout [${path}]: exceeded ${timeout}ms`)
|
|
213
|
+
}
|
|
214
|
+
console.error("[qqbot-api] <<< Network error:", err)
|
|
215
|
+
throw new Error(`Network error [${path}]: ${err instanceof Error ? err.message : String(err)}`)
|
|
216
|
+
} finally {
|
|
217
|
+
clearTimeout(timeoutId)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (res.status === 429 && attempt < 2) {
|
|
221
|
+
const retryAfterSec = Number(res.headers.get("Retry-After") ?? "1")
|
|
222
|
+
const waitMs = Math.min(Number.isFinite(retryAfterSec) && retryAfterSec > 0 ? retryAfterSec : 1, 30) * 1000
|
|
223
|
+
console.warn(`[qqbot-api] 429 限流,${waitMs}ms 后重试(第 ${attempt + 1}/2 次): ${path}`)
|
|
224
|
+
await new Promise((r) => setTimeout(r, waitMs))
|
|
225
|
+
continue
|
|
226
|
+
}
|
|
227
|
+
break
|
|
228
|
+
}
|
|
229
|
+
const response = res as Response
|
|
230
|
+
|
|
231
|
+
const responseHeaders: Record<string, string> = {}
|
|
232
|
+
response.headers.forEach((value, key) => {
|
|
233
|
+
responseHeaders[key] = value
|
|
234
|
+
})
|
|
235
|
+
console.log(`[qqbot-api] <<< Status: ${response.status} ${response.statusText}`)
|
|
236
|
+
console.log("[qqbot-api] <<< Headers:", JSON.stringify(maskHeaders(responseHeaders), null, 2))
|
|
237
|
+
|
|
238
|
+
let data: T
|
|
239
|
+
let rawBody: string
|
|
240
|
+
try {
|
|
241
|
+
rawBody = await response.text()
|
|
242
|
+
console.log("[qqbot-api] <<< Body:", rawBody)
|
|
243
|
+
data = JSON.parse(rawBody) as T
|
|
244
|
+
} catch (err) {
|
|
245
|
+
console.error("[qqbot-api] <<< Parse error:", err)
|
|
246
|
+
throw new Error(`Failed to parse response [${path}]: ${err instanceof Error ? err.message : String(err)}`)
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
if (!response.ok) {
|
|
250
|
+
const error = data as { message?: string; code?: number }
|
|
251
|
+
throw new Error(`API Error [${path}]: ${error.message ?? JSON.stringify(data)}`)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
return data
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 获取 WebSocket Gateway 地址。
|
|
259
|
+
*/
|
|
260
|
+
export async function getGatewayUrl(accessToken: string): Promise<string> {
|
|
261
|
+
const data = await apiRequest<{ url: string }>(accessToken, "GET", "/gateway")
|
|
262
|
+
return data.url
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* QQ 发消息成功后的通用响应结构。
|
|
267
|
+
*/
|
|
268
|
+
export interface MessageResponse {
|
|
269
|
+
id: string
|
|
270
|
+
timestamp: number | string
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 构建消息体。
|
|
275
|
+
* markdown=true 时用 msg_type=2(markdown 消息),content 放 markdown 原文;
|
|
276
|
+
* 否则用 msg_type=0(纯文本)。注意: 传 markdown 时 content 字段必须为空。
|
|
277
|
+
* keyboard 仅 markdown 卡片可携带(A 项 2026-10-29,形状对齐 P0 官方 SDK)。
|
|
278
|
+
*/
|
|
279
|
+
export interface KeyboardButton {
|
|
280
|
+
id: string
|
|
281
|
+
render_data: { label: string; visited_label: string; style: number }
|
|
282
|
+
action: {
|
|
283
|
+
type: number
|
|
284
|
+
permission: { type: number; specify_user_ids?: string[] }
|
|
285
|
+
data: string
|
|
286
|
+
click_limit?: number
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export interface InlineKeyboard {
|
|
291
|
+
content: { rows: Array<{ buttons: KeyboardButton[] }> }
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function buildMessageBody(
|
|
295
|
+
content: string,
|
|
296
|
+
msgId: string | undefined,
|
|
297
|
+
msgSeq: number,
|
|
298
|
+
markdown = false,
|
|
299
|
+
keyboard?: InlineKeyboard,
|
|
300
|
+
): Record<string, unknown> {
|
|
301
|
+
const body: Record<string, unknown> = {
|
|
302
|
+
msg_seq: msgSeq,
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (markdown) {
|
|
306
|
+
body.msg_type = 2
|
|
307
|
+
body.markdown = { content }
|
|
308
|
+
} else {
|
|
309
|
+
body.msg_type = 0
|
|
310
|
+
body.content = content
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
if (msgId) {
|
|
314
|
+
body.msg_id = msgId
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (keyboard) {
|
|
318
|
+
body.keyboard = keyboard
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return body
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* 发送 C2C 单聊消息。
|
|
326
|
+
* msgSeq 可选,传入时优先使用,便于上层做分片发送。
|
|
327
|
+
* markdown=true 时以 markdown 消息发送(msg_type=2)。
|
|
328
|
+
*/
|
|
329
|
+
export async function sendC2CMessage(
|
|
330
|
+
accessToken: string,
|
|
331
|
+
openid: string,
|
|
332
|
+
content: string,
|
|
333
|
+
msgId?: string,
|
|
334
|
+
msgSeq?: number,
|
|
335
|
+
markdown = false,
|
|
336
|
+
keyboard?: InlineKeyboard,
|
|
337
|
+
): Promise<MessageResponse> {
|
|
338
|
+
const resolvedMsgSeq = msgSeq ?? (msgId ? getNextMsgSeq(msgId) : 1)
|
|
339
|
+
const body = buildMessageBody(content, msgId, resolvedMsgSeq, markdown, keyboard)
|
|
340
|
+
return apiRequest(accessToken, "POST", `/v2/users/${openid}/messages`, body)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* 发送 C2C 输入状态提示,告诉用户机器人正在输入。
|
|
345
|
+
*/
|
|
346
|
+
export async function sendC2CInputNotify(
|
|
347
|
+
accessToken: string,
|
|
348
|
+
openid: string,
|
|
349
|
+
msgId?: string,
|
|
350
|
+
inputSecond: number = 60,
|
|
351
|
+
): Promise<void> {
|
|
352
|
+
const msgSeq = msgId ? getNextMsgSeq(msgId) : 1
|
|
353
|
+
const body = {
|
|
354
|
+
msg_type: 6,
|
|
355
|
+
input_notify: {
|
|
356
|
+
input_type: 1,
|
|
357
|
+
input_second: inputSecond,
|
|
358
|
+
},
|
|
359
|
+
msg_seq: msgSeq,
|
|
360
|
+
...(msgId ? { msg_id: msgId } : {}),
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
await apiRequest(accessToken, "POST", `/v2/users/${openid}/messages`, body)
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* 发送群聊消息。
|
|
368
|
+
* msgSeq 可选,传入时优先使用,便于上层做分片发送。
|
|
369
|
+
* markdown=true 时以 markdown 消息发送(msg_type=2)。
|
|
370
|
+
*/
|
|
371
|
+
export async function sendGroupMessage(
|
|
372
|
+
accessToken: string,
|
|
373
|
+
groupOpenid: string,
|
|
374
|
+
content: string,
|
|
375
|
+
msgId?: string,
|
|
376
|
+
msgSeq?: number,
|
|
377
|
+
markdown = false,
|
|
378
|
+
keyboard?: InlineKeyboard,
|
|
379
|
+
): Promise<MessageResponse> {
|
|
380
|
+
const resolvedMsgSeq = msgSeq ?? (msgId ? getNextMsgSeq(msgId) : 1)
|
|
381
|
+
const body = buildMessageBody(content, msgId, resolvedMsgSeq, markdown, keyboard)
|
|
382
|
+
return apiRequest(accessToken, "POST", `/v2/groups/${groupOpenid}/messages`, body)
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* 响应按钮互动回调(A 项 2026-10-29,端点对齐 P0 官方 SDK acknowledgeInteraction)。
|
|
387
|
+
* QQ 平台要求收到 INTERACTION_CREATE 后 3 秒内响应,同 id 只能响应一次——
|
|
388
|
+
* 调用方必须先 ack 再执行业务处理。
|
|
389
|
+
*/
|
|
390
|
+
export async function acknowledgeInteraction(accessToken: string, interactionId: string, code = 0): Promise<void> {
|
|
391
|
+
await apiRequest(accessToken, "PUT", `/interactions/${interactionId}`, { code })
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// ── 媒体发送(生态观察缺口 4:bot→QQ 发图/文件,P0 参照 qqbot-nodejs protocol/api/media.ts)──
|
|
395
|
+
export const MediaFileType = { IMAGE: 1, VIDEO: 2, VOICE: 3, FILE: 4 } as const
|
|
396
|
+
|
|
397
|
+
/** 上传媒体到 QQ 拿 file_info(单次上限 20MB;base64 体由调用方给) */
|
|
398
|
+
export async function uploadQQMedia(
|
|
399
|
+
accessToken: string,
|
|
400
|
+
ctx: MessageContext,
|
|
401
|
+
opts: { fileType: number; fileData?: string; url?: string; fileName?: string },
|
|
402
|
+
): Promise<{ file_uuid?: string; file_info: string; ttl?: number }> {
|
|
403
|
+
const isGroup = ctx.type === "group" && ctx.groupId
|
|
404
|
+
const body: Record<string, unknown> = { file_type: opts.fileType, srv_send_msg: false }
|
|
405
|
+
if (opts.url) body.url = opts.url
|
|
406
|
+
else if (opts.fileData) body.file_data = opts.fileData
|
|
407
|
+
if (opts.fileType === MediaFileType.FILE && opts.fileName) body.file_name = opts.fileName
|
|
408
|
+
const path = isGroup ? `/v2/groups/${ctx.groupId}/files` : `/v2/users/${ctx.userId}/files`
|
|
409
|
+
return apiRequest(accessToken, "POST", path, body)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/** 发送媒体消息(msg_type=7,media.file_info 引用上传结果) */
|
|
413
|
+
export async function sendQQMediaMessage(
|
|
414
|
+
accessToken: string,
|
|
415
|
+
ctx: MessageContext,
|
|
416
|
+
fileInfo: string,
|
|
417
|
+
content?: string,
|
|
418
|
+
): Promise<MessageResponse> {
|
|
419
|
+
const isGroup = ctx.type === "group" && ctx.groupId
|
|
420
|
+
const body: Record<string, unknown> = {
|
|
421
|
+
msg_type: 7,
|
|
422
|
+
media: { file_info: fileInfo },
|
|
423
|
+
msg_seq: ctx.msgId ? getNextMsgSeq(ctx.msgId) : 1,
|
|
424
|
+
...(content ? { content } : {}),
|
|
425
|
+
...(ctx.msgId ? { msg_id: ctx.msgId } : {}),
|
|
426
|
+
}
|
|
427
|
+
const path = isGroup ? `/v2/groups/${ctx.groupId}/messages` : `/v2/users/${ctx.userId}/messages`
|
|
428
|
+
return apiRequest(accessToken, "POST", path, body)
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
interface BackgroundTokenRefreshOptions {
|
|
432
|
+
refreshAheadMs?: number
|
|
433
|
+
randomOffsetMs?: number
|
|
434
|
+
minRefreshIntervalMs?: number
|
|
435
|
+
retryDelayMs?: number
|
|
436
|
+
log?: {
|
|
437
|
+
info: (msg: string) => void
|
|
438
|
+
error: (msg: string) => void
|
|
439
|
+
debug?: (msg: string) => void
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
let backgroundRefreshRunning = false
|
|
444
|
+
let backgroundRefreshAbortController: AbortController | null = null
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* 启动后台 Token 刷新循环。
|
|
448
|
+
* 它会在 Token 过期前提前刷新,避免真正发消息时才发现 Token 已失效。
|
|
449
|
+
*/
|
|
450
|
+
export function startBackgroundTokenRefresh(
|
|
451
|
+
appId: string,
|
|
452
|
+
clientSecret: string,
|
|
453
|
+
options?: BackgroundTokenRefreshOptions,
|
|
454
|
+
): void {
|
|
455
|
+
if (backgroundRefreshRunning) {
|
|
456
|
+
console.log("[qqbot-api] Background token refresh already running")
|
|
457
|
+
return
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const {
|
|
461
|
+
refreshAheadMs = 5 * 60 * 1000,
|
|
462
|
+
randomOffsetMs = 30 * 1000,
|
|
463
|
+
minRefreshIntervalMs = 60 * 1000,
|
|
464
|
+
retryDelayMs = 5 * 1000,
|
|
465
|
+
log,
|
|
466
|
+
} = options ?? {}
|
|
467
|
+
|
|
468
|
+
backgroundRefreshRunning = true
|
|
469
|
+
backgroundRefreshAbortController = new AbortController()
|
|
470
|
+
const signal = backgroundRefreshAbortController.signal
|
|
471
|
+
|
|
472
|
+
const refreshLoop = async () => {
|
|
473
|
+
log?.info?.("[qqbot-api] Background token refresh started")
|
|
474
|
+
|
|
475
|
+
while (!signal.aborted) {
|
|
476
|
+
try {
|
|
477
|
+
await getAccessToken(appId, clientSecret)
|
|
478
|
+
|
|
479
|
+
if (cachedToken) {
|
|
480
|
+
const expiresIn = cachedToken.expiresAt - Date.now()
|
|
481
|
+
const randomOffset = Math.random() * randomOffsetMs
|
|
482
|
+
const refreshIn = Math.max(
|
|
483
|
+
expiresIn - refreshAheadMs - randomOffset,
|
|
484
|
+
minRefreshIntervalMs,
|
|
485
|
+
)
|
|
486
|
+
|
|
487
|
+
log?.debug?.(`[qqbot-api] Token valid, next refresh in ${Math.round(refreshIn / 1000)}s`)
|
|
488
|
+
await sleep(refreshIn, signal)
|
|
489
|
+
} else {
|
|
490
|
+
log?.debug?.("[qqbot-api] No cached token, retrying soon")
|
|
491
|
+
await sleep(minRefreshIntervalMs, signal)
|
|
492
|
+
}
|
|
493
|
+
} catch (err) {
|
|
494
|
+
if (signal.aborted) break
|
|
495
|
+
|
|
496
|
+
log?.error?.(`[qqbot-api] Background token refresh failed: ${err}`)
|
|
497
|
+
await sleep(retryDelayMs, signal)
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
backgroundRefreshRunning = false
|
|
502
|
+
log?.info?.("[qqbot-api] Background token refresh stopped")
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
refreshLoop().catch((err) => {
|
|
506
|
+
backgroundRefreshRunning = false
|
|
507
|
+
log?.error?.(`[qqbot-api] Background token refresh crashed: ${err}`)
|
|
508
|
+
})
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/**
|
|
512
|
+
* 停止后台 Token 刷新循环。
|
|
513
|
+
*/
|
|
514
|
+
export function stopBackgroundTokenRefresh(): void {
|
|
515
|
+
if (backgroundRefreshAbortController) {
|
|
516
|
+
backgroundRefreshAbortController.abort()
|
|
517
|
+
backgroundRefreshAbortController = null
|
|
518
|
+
}
|
|
519
|
+
backgroundRefreshRunning = false
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* 可被 AbortSignal 中断的 sleep,供后台刷新循环复用。
|
|
524
|
+
*/
|
|
525
|
+
async function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
526
|
+
return new Promise((resolve, reject) => {
|
|
527
|
+
const timer = setTimeout(() => {
|
|
528
|
+
resolve()
|
|
529
|
+
}, ms)
|
|
530
|
+
|
|
531
|
+
if (signal) {
|
|
532
|
+
if (signal.aborted) {
|
|
533
|
+
clearTimeout(timer)
|
|
534
|
+
reject(new Error("Aborted"))
|
|
535
|
+
return
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
const onAbort = () => {
|
|
539
|
+
clearTimeout(timer)
|
|
540
|
+
reject(new Error("Aborted"))
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
signal.addEventListener("abort", onAbort, { once: true })
|
|
544
|
+
}
|
|
545
|
+
})
|
|
546
|
+
}
|