@sliverp/qqbot 1.3.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.
Files changed (78) hide show
  1. package/README.md +231 -0
  2. package/clawdbot.plugin.json +16 -0
  3. package/dist/index.d.ts +17 -0
  4. package/dist/index.js +22 -0
  5. package/dist/src/api.d.ts +194 -0
  6. package/dist/src/api.js +555 -0
  7. package/dist/src/channel.d.ts +3 -0
  8. package/dist/src/channel.js +146 -0
  9. package/dist/src/config.d.ts +25 -0
  10. package/dist/src/config.js +148 -0
  11. package/dist/src/gateway.d.ts +17 -0
  12. package/dist/src/gateway.js +722 -0
  13. package/dist/src/image-server.d.ts +62 -0
  14. package/dist/src/image-server.js +401 -0
  15. package/dist/src/known-users.d.ts +100 -0
  16. package/dist/src/known-users.js +264 -0
  17. package/dist/src/onboarding.d.ts +10 -0
  18. package/dist/src/onboarding.js +190 -0
  19. package/dist/src/outbound.d.ts +149 -0
  20. package/dist/src/outbound.js +476 -0
  21. package/dist/src/proactive.d.ts +170 -0
  22. package/dist/src/proactive.js +398 -0
  23. package/dist/src/runtime.d.ts +3 -0
  24. package/dist/src/runtime.js +10 -0
  25. package/dist/src/session-store.d.ts +49 -0
  26. package/dist/src/session-store.js +242 -0
  27. package/dist/src/types.d.ts +116 -0
  28. package/dist/src/types.js +1 -0
  29. package/dist/src/utils/image-size.d.ts +51 -0
  30. package/dist/src/utils/image-size.js +234 -0
  31. package/dist/src/utils/payload.d.ts +112 -0
  32. package/dist/src/utils/payload.js +186 -0
  33. package/index.ts +27 -0
  34. package/moltbot.plugin.json +16 -0
  35. package/node_modules/ws/LICENSE +20 -0
  36. package/node_modules/ws/README.md +548 -0
  37. package/node_modules/ws/browser.js +8 -0
  38. package/node_modules/ws/index.js +13 -0
  39. package/node_modules/ws/lib/buffer-util.js +131 -0
  40. package/node_modules/ws/lib/constants.js +19 -0
  41. package/node_modules/ws/lib/event-target.js +292 -0
  42. package/node_modules/ws/lib/extension.js +203 -0
  43. package/node_modules/ws/lib/limiter.js +55 -0
  44. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  45. package/node_modules/ws/lib/receiver.js +706 -0
  46. package/node_modules/ws/lib/sender.js +602 -0
  47. package/node_modules/ws/lib/stream.js +161 -0
  48. package/node_modules/ws/lib/subprotocol.js +62 -0
  49. package/node_modules/ws/lib/validation.js +152 -0
  50. package/node_modules/ws/lib/websocket-server.js +554 -0
  51. package/node_modules/ws/lib/websocket.js +1393 -0
  52. package/node_modules/ws/package.json +69 -0
  53. package/node_modules/ws/wrapper.mjs +8 -0
  54. package/openclaw.plugin.json +16 -0
  55. package/package.json +38 -0
  56. package/qqbot-1.3.0.tgz +0 -0
  57. package/scripts/proactive-api-server.ts +346 -0
  58. package/scripts/send-proactive.ts +273 -0
  59. package/scripts/upgrade.sh +106 -0
  60. package/skills/qqbot-cron/SKILL.md +490 -0
  61. package/skills/qqbot-media/SKILL.md +138 -0
  62. package/src/api.ts +752 -0
  63. package/src/channel.ts +303 -0
  64. package/src/config.ts +172 -0
  65. package/src/gateway.ts +1588 -0
  66. package/src/image-server.ts +474 -0
  67. package/src/known-users.ts +358 -0
  68. package/src/onboarding.ts +254 -0
  69. package/src/openclaw-plugin-sdk.d.ts +483 -0
  70. package/src/outbound.ts +571 -0
  71. package/src/proactive.ts +528 -0
  72. package/src/runtime.ts +14 -0
  73. package/src/session-store.ts +292 -0
  74. package/src/types.ts +123 -0
  75. package/src/utils/image-size.ts +266 -0
  76. package/src/utils/payload.ts +265 -0
  77. package/tsconfig.json +16 -0
  78. package/upgrade-and-run.sh +89 -0
package/src/gateway.ts ADDED
@@ -0,0 +1,1588 @@
1
+ import WebSocket from "ws";
2
+ import path from "node:path";
3
+ import * as fs from "node:fs";
4
+ import type { ResolvedQQBotAccount, WSPayload, C2CMessageEvent, GuildMessageEvent, GroupMessageEvent } from "./types.js";
5
+ import { getAccessToken, getGatewayUrl, sendC2CMessage, sendChannelMessage, sendGroupMessage, clearTokenCache, sendC2CImageMessage, sendGroupImageMessage, initApiConfig, startBackgroundTokenRefresh, stopBackgroundTokenRefresh } from "./api.js";
6
+ import { loadSession, saveSession, clearSession, type SessionState } from "./session-store.js";
7
+ import { recordKnownUser, flushKnownUsers } from "./known-users.js";
8
+ import { getQQBotRuntime } from "./runtime.js";
9
+ import { startImageServer, isImageServerRunning, downloadFile, type ImageServerConfig } from "./image-server.js";
10
+ import { getImageSize, formatQQBotMarkdownImage, hasQQBotImageSize, DEFAULT_IMAGE_SIZE } from "./utils/image-size.js";
11
+ import { parseQQBotPayload, encodePayloadForCron, isCronReminderPayload, isMediaPayload, type CronReminderPayload, type MediaPayload } from "./utils/payload.js";
12
+
13
+ // QQ Bot intents - 按权限级别分组
14
+ const INTENTS = {
15
+ // 基础权限(默认有)
16
+ GUILDS: 1 << 0, // 频道相关
17
+ GUILD_MEMBERS: 1 << 1, // 频道成员
18
+ PUBLIC_GUILD_MESSAGES: 1 << 30, // 频道公开消息(公域)
19
+ // 需要申请的权限
20
+ DIRECT_MESSAGE: 1 << 12, // 频道私信
21
+ GROUP_AND_C2C: 1 << 25, // 群聊和 C2C 私聊(需申请)
22
+ };
23
+
24
+ // 权限级别:从高到低依次尝试
25
+ const INTENT_LEVELS = [
26
+ // Level 0: 完整权限(群聊 + 私信 + 频道)
27
+ {
28
+ name: "full",
29
+ intents: INTENTS.PUBLIC_GUILD_MESSAGES | INTENTS.DIRECT_MESSAGE | INTENTS.GROUP_AND_C2C,
30
+ description: "群聊+私信+频道",
31
+ },
32
+ // Level 1: 群聊 + 频道(无私信)
33
+ {
34
+ name: "group+channel",
35
+ intents: INTENTS.PUBLIC_GUILD_MESSAGES | INTENTS.GROUP_AND_C2C,
36
+ description: "群聊+频道",
37
+ },
38
+ // Level 2: 仅频道(基础权限)
39
+ {
40
+ name: "channel-only",
41
+ intents: INTENTS.PUBLIC_GUILD_MESSAGES | INTENTS.GUILD_MEMBERS,
42
+ description: "仅频道消息",
43
+ },
44
+ ];
45
+
46
+ // 重连配置
47
+ const RECONNECT_DELAYS = [1000, 2000, 5000, 10000, 30000, 60000]; // 递增延迟
48
+ const RATE_LIMIT_DELAY = 60000; // 遇到频率限制时等待 60 秒
49
+ const MAX_RECONNECT_ATTEMPTS = 100;
50
+ const MAX_QUICK_DISCONNECT_COUNT = 3; // 连续快速断开次数阈值
51
+ const QUICK_DISCONNECT_THRESHOLD = 5000; // 5秒内断开视为快速断开
52
+
53
+ // 图床服务器配置(可通过环境变量覆盖)
54
+ const IMAGE_SERVER_PORT = parseInt(process.env.QQBOT_IMAGE_SERVER_PORT || "18765", 10);
55
+ // 使用绝对路径,确保文件保存和读取使用同一目录
56
+ const IMAGE_SERVER_DIR = process.env.QQBOT_IMAGE_SERVER_DIR || path.join(process.env.HOME || "/home/ubuntu", "clawd", "qqbot-images");
57
+
58
+ // 消息队列配置(异步处理,防止阻塞心跳)
59
+ const MESSAGE_QUEUE_SIZE = 1000; // 最大队列长度
60
+ const MESSAGE_QUEUE_WARN_THRESHOLD = 800; // 队列告警阈值
61
+
62
+ // ============ 消息回复限流器 ============
63
+ // 同一 message_id 1小时内最多回复 4 次,超过1小时需降级为主动消息
64
+ const MESSAGE_REPLY_LIMIT = 4;
65
+ const MESSAGE_REPLY_TTL = 60 * 60 * 1000; // 1小时
66
+
67
+ interface MessageReplyRecord {
68
+ count: number;
69
+ firstReplyAt: number;
70
+ }
71
+
72
+ const messageReplyTracker = new Map<string, MessageReplyRecord>();
73
+
74
+ /**
75
+ * 检查是否可以回复该消息(限流检查)
76
+ * @param messageId 消息ID
77
+ * @returns { allowed: boolean, remaining: number } allowed=是否允许回复,remaining=剩余次数
78
+ */
79
+ function checkMessageReplyLimit(messageId: string): { allowed: boolean; remaining: number } {
80
+ const now = Date.now();
81
+ const record = messageReplyTracker.get(messageId);
82
+
83
+ // 清理过期记录(定期清理,避免内存泄漏)
84
+ if (messageReplyTracker.size > 10000) {
85
+ for (const [id, rec] of messageReplyTracker) {
86
+ if (now - rec.firstReplyAt > MESSAGE_REPLY_TTL) {
87
+ messageReplyTracker.delete(id);
88
+ }
89
+ }
90
+ }
91
+
92
+ if (!record) {
93
+ return { allowed: true, remaining: MESSAGE_REPLY_LIMIT };
94
+ }
95
+
96
+ // 检查是否过期
97
+ if (now - record.firstReplyAt > MESSAGE_REPLY_TTL) {
98
+ messageReplyTracker.delete(messageId);
99
+ return { allowed: true, remaining: MESSAGE_REPLY_LIMIT };
100
+ }
101
+
102
+ // 检查是否超过限制
103
+ const remaining = MESSAGE_REPLY_LIMIT - record.count;
104
+ return { allowed: remaining > 0, remaining: Math.max(0, remaining) };
105
+ }
106
+
107
+ /**
108
+ * 记录一次消息回复
109
+ * @param messageId 消息ID
110
+ */
111
+ function recordMessageReply(messageId: string): void {
112
+ const now = Date.now();
113
+ const record = messageReplyTracker.get(messageId);
114
+
115
+ if (!record) {
116
+ messageReplyTracker.set(messageId, { count: 1, firstReplyAt: now });
117
+ } else {
118
+ // 检查是否过期,过期则重新计数
119
+ if (now - record.firstReplyAt > MESSAGE_REPLY_TTL) {
120
+ messageReplyTracker.set(messageId, { count: 1, firstReplyAt: now });
121
+ } else {
122
+ record.count++;
123
+ }
124
+ }
125
+ }
126
+
127
+ // ============ 内部标记过滤 ============
128
+
129
+ /**
130
+ * 过滤内部标记(如 [[reply_to: xxx]])
131
+ * 这些标记可能被 AI 错误地学习并输出,需要在发送前移除
132
+ */
133
+ function filterInternalMarkers(text: string): string {
134
+ if (!text) return text;
135
+
136
+ // 过滤 [[xxx: yyy]] 格式的内部标记
137
+ // 例如: [[reply_to: ROBOT1.0_kbc...]]
138
+ let result = text.replace(/\[\[[a-z_]+:\s*[^\]]*\]\]/gi, "");
139
+
140
+ // 清理可能产生的多余空行
141
+ result = result.replace(/\n{3,}/g, "\n\n").trim();
142
+
143
+ return result;
144
+ }
145
+
146
+ export interface GatewayContext {
147
+ account: ResolvedQQBotAccount;
148
+ abortSignal: AbortSignal;
149
+ cfg: unknown;
150
+ onReady?: (data: unknown) => void;
151
+ onError?: (error: Error) => void;
152
+ log?: {
153
+ info: (msg: string) => void;
154
+ error: (msg: string) => void;
155
+ debug?: (msg: string) => void;
156
+ };
157
+ }
158
+
159
+ /**
160
+ * 消息队列项类型(用于异步处理消息,防止阻塞心跳)
161
+ */
162
+ interface QueuedMessage {
163
+ type: "c2c" | "guild" | "dm" | "group";
164
+ senderId: string;
165
+ senderName?: string;
166
+ content: string;
167
+ messageId: string;
168
+ timestamp: string;
169
+ channelId?: string;
170
+ guildId?: string;
171
+ groupOpenid?: string;
172
+ attachments?: Array<{ content_type: string; url: string; filename?: string }>;
173
+ }
174
+
175
+ /**
176
+ * 启动图床服务器
177
+ */
178
+ async function ensureImageServer(log?: GatewayContext["log"], publicBaseUrl?: string): Promise<string | null> {
179
+ if (isImageServerRunning()) {
180
+ return publicBaseUrl || `http://0.0.0.0:${IMAGE_SERVER_PORT}`;
181
+ }
182
+
183
+ try {
184
+ const config: Partial<ImageServerConfig> = {
185
+ port: IMAGE_SERVER_PORT,
186
+ storageDir: IMAGE_SERVER_DIR,
187
+ // 使用用户配置的公网地址,而不是 0.0.0.0
188
+ baseUrl: publicBaseUrl || `http://0.0.0.0:${IMAGE_SERVER_PORT}`,
189
+ ttlSeconds: 3600, // 1 小时过期
190
+ };
191
+ await startImageServer(config);
192
+ log?.info(`[qqbot] Image server started on port ${IMAGE_SERVER_PORT}, baseUrl: ${config.baseUrl}`);
193
+ return config.baseUrl!;
194
+ } catch (err) {
195
+ log?.error(`[qqbot] Failed to start image server: ${err}`);
196
+ return null;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * 启动 Gateway WebSocket 连接(带自动重连)
202
+ * 支持流式消息发送
203
+ */
204
+ export async function startGateway(ctx: GatewayContext): Promise<void> {
205
+ const { account, abortSignal, cfg, onReady, onError, log } = ctx;
206
+
207
+ if (!account.appId || !account.clientSecret) {
208
+ throw new Error("QQBot not configured (missing appId or clientSecret)");
209
+ }
210
+
211
+ // 初始化 API 配置(markdown 支持)
212
+ initApiConfig({
213
+ markdownSupport: account.markdownSupport,
214
+ });
215
+ log?.info(`[qqbot:${account.accountId}] API config: markdownSupport=${account.markdownSupport === true}`);
216
+
217
+ // 如果配置了公网 URL,启动图床服务器
218
+ let imageServerBaseUrl: string | null = null;
219
+ if (account.imageServerBaseUrl) {
220
+ // 使用用户配置的公网地址作为 baseUrl
221
+ await ensureImageServer(log, account.imageServerBaseUrl);
222
+ imageServerBaseUrl = account.imageServerBaseUrl;
223
+ log?.info(`[qqbot:${account.accountId}] Image server enabled with URL: ${imageServerBaseUrl}`);
224
+ } else {
225
+ log?.info(`[qqbot:${account.accountId}] Image server disabled (no imageServerBaseUrl configured)`);
226
+ }
227
+
228
+ let reconnectAttempts = 0;
229
+ let isAborted = false;
230
+ let currentWs: WebSocket | null = null;
231
+ let heartbeatInterval: ReturnType<typeof setInterval> | null = null;
232
+ let sessionId: string | null = null;
233
+ let lastSeq: number | null = null;
234
+ let lastConnectTime: number = 0; // 上次连接成功的时间
235
+ let quickDisconnectCount = 0; // 连续快速断开次数
236
+ let isConnecting = false; // 防止并发连接
237
+ let reconnectTimer: ReturnType<typeof setTimeout> | null = null; // 重连定时器
238
+ let shouldRefreshToken = false; // 下次连接是否需要刷新 token
239
+ let intentLevelIndex = 0; // 当前尝试的权限级别索引
240
+ let lastSuccessfulIntentLevel = -1; // 上次成功的权限级别
241
+
242
+ // ============ P1-2: 尝试从持久化存储恢复 Session ============
243
+ const savedSession = loadSession(account.accountId);
244
+ if (savedSession) {
245
+ sessionId = savedSession.sessionId;
246
+ lastSeq = savedSession.lastSeq;
247
+ intentLevelIndex = savedSession.intentLevelIndex;
248
+ lastSuccessfulIntentLevel = savedSession.intentLevelIndex;
249
+ log?.info(`[qqbot:${account.accountId}] Restored session from storage: sessionId=${sessionId}, lastSeq=${lastSeq}, intentLevel=${intentLevelIndex}`);
250
+ }
251
+
252
+ // ============ 消息队列(异步处理,防止阻塞心跳) ============
253
+ const messageQueue: QueuedMessage[] = [];
254
+ let messageProcessorRunning = false;
255
+ let messagesProcessed = 0; // 统计已处理消息数
256
+
257
+ /**
258
+ * 将消息加入队列(非阻塞)
259
+ */
260
+ const enqueueMessage = (msg: QueuedMessage): void => {
261
+ if (messageQueue.length >= MESSAGE_QUEUE_SIZE) {
262
+ // 队列满了,丢弃最旧的消息
263
+ const dropped = messageQueue.shift();
264
+ log?.error(`[qqbot:${account.accountId}] Message queue full, dropping oldest message from ${dropped?.senderId}`);
265
+ }
266
+ if (messageQueue.length >= MESSAGE_QUEUE_WARN_THRESHOLD) {
267
+ log?.info(`[qqbot:${account.accountId}] Message queue size: ${messageQueue.length}/${MESSAGE_QUEUE_SIZE}`);
268
+ }
269
+ messageQueue.push(msg);
270
+ log?.debug?.(`[qqbot:${account.accountId}] Message enqueued, queue size: ${messageQueue.length}`);
271
+ };
272
+
273
+ /**
274
+ * 启动消息处理循环(独立于 WS 消息循环)
275
+ */
276
+ const startMessageProcessor = (handleMessageFn: (msg: QueuedMessage) => Promise<void>): void => {
277
+ if (messageProcessorRunning) return;
278
+ messageProcessorRunning = true;
279
+
280
+ const processLoop = async () => {
281
+ while (!isAborted) {
282
+ if (messageQueue.length === 0) {
283
+ // 队列为空,等待一小段时间
284
+ await new Promise(resolve => setTimeout(resolve, 50));
285
+ continue;
286
+ }
287
+
288
+ const msg = messageQueue.shift()!;
289
+ try {
290
+ await handleMessageFn(msg);
291
+ messagesProcessed++;
292
+ } catch (err) {
293
+ // 捕获处理异常,防止影响队列循环
294
+ log?.error(`[qqbot:${account.accountId}] Message processor error: ${err}`);
295
+ }
296
+ }
297
+ messageProcessorRunning = false;
298
+ log?.info(`[qqbot:${account.accountId}] Message processor stopped`);
299
+ };
300
+
301
+ // 异步启动,不阻塞调用者
302
+ processLoop().catch(err => {
303
+ log?.error(`[qqbot:${account.accountId}] Message processor crashed: ${err}`);
304
+ messageProcessorRunning = false;
305
+ });
306
+
307
+ log?.info(`[qqbot:${account.accountId}] Message processor started`);
308
+ };
309
+
310
+ abortSignal.addEventListener("abort", () => {
311
+ isAborted = true;
312
+ if (reconnectTimer) {
313
+ clearTimeout(reconnectTimer);
314
+ reconnectTimer = null;
315
+ }
316
+ cleanup();
317
+ // P1-1: 停止后台 Token 刷新
318
+ stopBackgroundTokenRefresh();
319
+ // P1-3: 保存已知用户数据
320
+ flushKnownUsers();
321
+ });
322
+
323
+ const cleanup = () => {
324
+ if (heartbeatInterval) {
325
+ clearInterval(heartbeatInterval);
326
+ heartbeatInterval = null;
327
+ }
328
+ if (currentWs && (currentWs.readyState === WebSocket.OPEN || currentWs.readyState === WebSocket.CONNECTING)) {
329
+ currentWs.close();
330
+ }
331
+ currentWs = null;
332
+ };
333
+
334
+ const getReconnectDelay = () => {
335
+ const idx = Math.min(reconnectAttempts, RECONNECT_DELAYS.length - 1);
336
+ return RECONNECT_DELAYS[idx];
337
+ };
338
+
339
+ const scheduleReconnect = (customDelay?: number) => {
340
+ if (isAborted || reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) {
341
+ log?.error(`[qqbot:${account.accountId}] Max reconnect attempts reached or aborted`);
342
+ return;
343
+ }
344
+
345
+ // 取消已有的重连定时器
346
+ if (reconnectTimer) {
347
+ clearTimeout(reconnectTimer);
348
+ reconnectTimer = null;
349
+ }
350
+
351
+ const delay = customDelay ?? getReconnectDelay();
352
+ reconnectAttempts++;
353
+ log?.info(`[qqbot:${account.accountId}] Reconnecting in ${delay}ms (attempt ${reconnectAttempts})`);
354
+
355
+ reconnectTimer = setTimeout(() => {
356
+ reconnectTimer = null;
357
+ if (!isAborted) {
358
+ connect();
359
+ }
360
+ }, delay);
361
+ };
362
+
363
+ const connect = async () => {
364
+ // 防止并发连接
365
+ if (isConnecting) {
366
+ log?.debug?.(`[qqbot:${account.accountId}] Already connecting, skip`);
367
+ return;
368
+ }
369
+ isConnecting = true;
370
+
371
+ try {
372
+ cleanup();
373
+
374
+ // 如果标记了需要刷新 token,则清除缓存
375
+ if (shouldRefreshToken) {
376
+ log?.info(`[qqbot:${account.accountId}] Refreshing token...`);
377
+ clearTokenCache();
378
+ shouldRefreshToken = false;
379
+ }
380
+
381
+ const accessToken = await getAccessToken(account.appId, account.clientSecret);
382
+ const gatewayUrl = await getGatewayUrl(accessToken);
383
+
384
+ log?.info(`[qqbot:${account.accountId}] Connecting to ${gatewayUrl}`);
385
+
386
+ const ws = new WebSocket(gatewayUrl);
387
+ currentWs = ws;
388
+
389
+ const pluginRuntime = getQQBotRuntime();
390
+
391
+ // 处理收到的消息
392
+ const handleMessage = async (event: {
393
+ type: "c2c" | "guild" | "dm" | "group";
394
+ senderId: string;
395
+ senderName?: string;
396
+ content: string;
397
+ messageId: string;
398
+ timestamp: string;
399
+ channelId?: string;
400
+ guildId?: string;
401
+ groupOpenid?: string;
402
+ attachments?: Array<{ content_type: string; url: string; filename?: string }>;
403
+ }) => {
404
+ log?.info(`[qqbot:${account.accountId}] Processing message from ${event.senderId}: ${event.content}`);
405
+ if (event.attachments?.length) {
406
+ log?.info(`[qqbot:${account.accountId}] Attachments: ${event.attachments.length}`);
407
+ }
408
+
409
+ pluginRuntime.channel.activity.record({
410
+ channel: "qqbot",
411
+ accountId: account.accountId,
412
+ direction: "inbound",
413
+ });
414
+
415
+ const isGroup = event.type === "guild" || event.type === "group";
416
+ const peerId = event.type === "guild" ? `channel:${event.channelId}`
417
+ : event.type === "group" ? `group:${event.groupOpenid}`
418
+ : event.senderId;
419
+
420
+ const route = pluginRuntime.channel.routing.resolveAgentRoute({
421
+ cfg,
422
+ channel: "qqbot",
423
+ accountId: account.accountId,
424
+ peer: {
425
+ kind: isGroup ? "group" : "dm",
426
+ id: peerId,
427
+ },
428
+ });
429
+
430
+ const envelopeOptions = pluginRuntime.channel.reply.resolveEnvelopeFormatOptions(cfg);
431
+
432
+ // 组装消息体,添加系统提示词
433
+ let builtinPrompt = "";
434
+
435
+ // ============ 用户标识信息(用于定时提醒和主动消息) ============
436
+ const isGroupChat = event.type === "group";
437
+ const targetAddress = isGroupChat ? `group:${event.groupOpenid}` : event.senderId;
438
+
439
+ builtinPrompt += `
440
+ 【当前用户信息】
441
+ - 用户 openid: ${event.senderId}
442
+ - 用户昵称: ${event.senderName || "未知"}
443
+ - 消息类型: ${isGroupChat ? "群聊" : "私聊"}
444
+ - 当前消息 message_id: ${event.messageId}${isGroupChat ? `
445
+ - 群组 group_openid: ${event.groupOpenid}` : ""}
446
+
447
+ 【定时提醒能力】
448
+ 你可以帮助用户设置定时提醒。使用exec工具来来运行bash命令 openclaw cron 命令而不是直接使用 "cron" 工具:
449
+
450
+ 示例:5分钟后提醒用户喝水
451
+ \`\`\`bash
452
+ openclaw cron add \\
453
+ --name "提醒喝水-${event.senderName || "用户"}" \\
454
+ --at "5m" \\
455
+ --session isolated \\
456
+ --message "💧 该喝水啦!" \\
457
+ --deliver \\
458
+ --channel qqbot \\
459
+ --to "${targetAddress}" \\
460
+ --delete-after-run
461
+ \`\`\`
462
+
463
+ 关键参数说明:
464
+ - \`--to\`: 目标地址(当前用户: ${targetAddress})
465
+ - \`--at\`: 一次性定时任务的触发时间
466
+ - 相对时间格式:数字+单位,如 \`5m\`(5分钟)、\`1h\`(1小时)、\`2d\`(2天)【注意:不要加 + 号】
467
+ - 绝对时间格式:ISO 8601 带时区,如 \`2026-02-01T14:00:00+08:00\`
468
+ - \`--cron\`: 周期性任务(如 \`0 8 * * *\` 每天早上8点)
469
+ - \`--tz "Asia/Shanghai"\`: 周期任务务必设置时区
470
+ - \`--delete-after-run\`: 一次性任务必须添加此参数
471
+ - \`--message\`: 消息内容(必填,不能为空!这是定时提醒触发时直接发送给用户的内容)
472
+ - \`--session isolated\` 独立会话任务
473
+
474
+ ⚠️ 重要注意事项:
475
+ 1. --at 参数格式:相对时间用 \`5m\`、\`1h\` 等(不要加 + 号!);绝对时间用完整 ISO 格式
476
+ 2. --message 参数必须有实际内容,不能为空字符串
477
+ 3. cron add 命令不支持 --reply-to 参数,定时提醒只能作为主动消息发送`;
478
+
479
+ // 🎯 发送图片功能:使用 <qqimg> 标签发送本地或网络图片
480
+ // 系统会自动将本地文件转换为 Base64 发送,不需要图床服务器
481
+ builtinPrompt += `
482
+
483
+ 【发送图片】
484
+ 你可以直接发送图片给用户!使用 <qqimg> 标签包裹图片路径:
485
+
486
+ <qqimg>图片路径</qqimg>
487
+
488
+ 示例:
489
+ - <qqimg>/Users/xxx/images/photo.jpg</qqimg> (本地文件)
490
+ - <qqimg>https://example.com/image.png</qqimg> (网络图片)
491
+
492
+ ⚠️ 注意:
493
+ - 必须使用 <qqimg>路径</qqimg> 格式
494
+ - 本地路径必须是绝对路径,支持 png、jpg、jpeg、gif、webp 格式
495
+ - 图片文件/URL 必须有效,否则发送失败`;
496
+
497
+ const systemPrompts = [builtinPrompt];
498
+ if (account.systemPrompt) {
499
+ systemPrompts.push(account.systemPrompt);
500
+ }
501
+
502
+ // 处理附件(图片等)- 下载到本地供 clawdbot 访问
503
+ let attachmentInfo = "";
504
+ const imageUrls: string[] = [];
505
+ // 存到 clawdbot 工作目录下的 downloads 文件夹
506
+ const downloadDir = path.join(process.env.HOME || "/home/ubuntu", "clawd", "downloads");
507
+
508
+ if (event.attachments?.length) {
509
+ // ============ 接收图片的自然语言描述生成 ============
510
+ // 根据需求 4:将图片信息转换为自然语言描述,便于 AI 理解
511
+ const imageDescriptions: string[] = [];
512
+ const otherAttachments: string[] = [];
513
+
514
+ for (const att of event.attachments) {
515
+ // 下载附件到本地,使用原始文件名
516
+ const localPath = await downloadFile(att.url, downloadDir, att.filename);
517
+ if (localPath) {
518
+ if (att.content_type?.startsWith("image/")) {
519
+ imageUrls.push(localPath);
520
+
521
+ // 构建自然语言描述(根据需求 4.2)
522
+ const format = att.content_type?.split("/")[1] || "未知格式";
523
+ const timestamp = new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" });
524
+
525
+ imageDescriptions.push(`
526
+ 用户发送了一张图片:
527
+ - 图片地址:${localPath}
528
+ - 图片格式:${format}
529
+ - 消息ID:${event.messageId}
530
+ - 发送时间:${timestamp}
531
+
532
+ 请根据图片内容进行回复。`);
533
+ } else {
534
+ otherAttachments.push(`[附件: ${localPath}]`);
535
+ }
536
+ log?.info(`[qqbot:${account.accountId}] Downloaded attachment to: ${localPath}`);
537
+ } else {
538
+ // 下载失败,提供原始 URL 作为后备
539
+ log?.error(`[qqbot:${account.accountId}] Failed to download attachment: ${att.url}`);
540
+ if (att.content_type?.startsWith("image/")) {
541
+ imageUrls.push(att.url);
542
+
543
+ // 下载失败时的自然语言描述
544
+ const format = att.content_type?.split("/")[1] || "未知格式";
545
+ const timestamp = new Date().toLocaleString("zh-CN", { timeZone: "Asia/Shanghai" });
546
+
547
+ imageDescriptions.push(`
548
+ 用户发送了一张图片(下载失败,使用原始URL):
549
+ - 图片地址:${att.url}
550
+ - 图片格式:${format}
551
+ - 消息ID:${event.messageId}
552
+ - 发送时间:${timestamp}
553
+
554
+ 请根据图片内容进行回复。`);
555
+ } else {
556
+ otherAttachments.push(`[附件: ${att.filename ?? att.content_type}] (下载失败)`);
557
+ }
558
+ }
559
+ }
560
+
561
+ // 组合附件信息:先图片描述,后其他附件
562
+ if (imageDescriptions.length > 0) {
563
+ attachmentInfo += "\n" + imageDescriptions.join("\n");
564
+ }
565
+ if (otherAttachments.length > 0) {
566
+ attachmentInfo += "\n" + otherAttachments.join("\n");
567
+ }
568
+ }
569
+
570
+ const userContent = event.content + attachmentInfo;
571
+ const messageBody = `【系统提示】\n${systemPrompts.join("\n")}\n\n【用户输入】\n${userContent}`;
572
+
573
+ const body = pluginRuntime.channel.reply.formatInboundEnvelope({
574
+ channel: "QQBot",
575
+ from: event.senderName ?? event.senderId,
576
+ timestamp: new Date(event.timestamp).getTime(),
577
+ body: messageBody,
578
+ chatType: isGroup ? "group" : "direct",
579
+ sender: {
580
+ id: event.senderId,
581
+ name: event.senderName,
582
+ },
583
+ envelope: envelopeOptions,
584
+ // 传递图片 URL 列表
585
+ ...(imageUrls.length > 0 ? { imageUrls } : {}),
586
+ });
587
+
588
+ const fromAddress = event.type === "guild" ? `qqbot:channel:${event.channelId}`
589
+ : event.type === "group" ? `qqbot:group:${event.groupOpenid}`
590
+ : `qqbot:c2c:${event.senderId}`;
591
+ const toAddress = fromAddress;
592
+
593
+ const ctxPayload = pluginRuntime.channel.reply.finalizeInboundContext({
594
+ Body: body,
595
+ RawBody: event.content,
596
+ CommandBody: event.content,
597
+ From: fromAddress,
598
+ To: toAddress,
599
+ SessionKey: route.sessionKey,
600
+ AccountId: route.accountId,
601
+ ChatType: isGroup ? "group" : "direct",
602
+ SenderId: event.senderId,
603
+ SenderName: event.senderName,
604
+ Provider: "qqbot",
605
+ Surface: "qqbot",
606
+ MessageSid: event.messageId,
607
+ Timestamp: new Date(event.timestamp).getTime(),
608
+ OriginatingChannel: "qqbot",
609
+ OriginatingTo: toAddress,
610
+ QQChannelId: event.channelId,
611
+ QQGuildId: event.guildId,
612
+ QQGroupOpenid: event.groupOpenid,
613
+ });
614
+
615
+ // 发送消息的辅助函数,带 token 过期重试
616
+ const sendWithTokenRetry = async (sendFn: (token: string) => Promise<unknown>) => {
617
+ try {
618
+ const token = await getAccessToken(account.appId, account.clientSecret);
619
+ await sendFn(token);
620
+ } catch (err) {
621
+ const errMsg = String(err);
622
+ // 如果是 token 相关错误,清除缓存重试一次
623
+ if (errMsg.includes("401") || errMsg.includes("token") || errMsg.includes("access_token")) {
624
+ log?.info(`[qqbot:${account.accountId}] Token may be expired, refreshing...`);
625
+ clearTokenCache();
626
+ const newToken = await getAccessToken(account.appId, account.clientSecret);
627
+ await sendFn(newToken);
628
+ } else {
629
+ throw err;
630
+ }
631
+ }
632
+ };
633
+
634
+ // 发送错误提示的辅助函数
635
+ const sendErrorMessage = async (errorText: string) => {
636
+ try {
637
+ await sendWithTokenRetry(async (token) => {
638
+ if (event.type === "c2c") {
639
+ await sendC2CMessage(token, event.senderId, errorText, event.messageId);
640
+ } else if (event.type === "group" && event.groupOpenid) {
641
+ await sendGroupMessage(token, event.groupOpenid, errorText, event.messageId);
642
+ } else if (event.channelId) {
643
+ await sendChannelMessage(token, event.channelId, errorText, event.messageId);
644
+ }
645
+ });
646
+ } catch (sendErr) {
647
+ log?.error(`[qqbot:${account.accountId}] Failed to send error message: ${sendErr}`);
648
+ }
649
+ };
650
+
651
+ try {
652
+ const messagesConfig = pluginRuntime.channel.reply.resolveEffectiveMessagesConfig(cfg, route.agentId);
653
+
654
+ // 追踪是否有响应
655
+ let hasResponse = false;
656
+ const responseTimeout = 60000; // 60秒超时(1分钟)
657
+ let timeoutId: ReturnType<typeof setTimeout> | null = null;
658
+
659
+ const timeoutPromise = new Promise<void>((_, reject) => {
660
+ timeoutId = setTimeout(() => {
661
+ if (!hasResponse) {
662
+ reject(new Error("Response timeout"));
663
+ }
664
+ }, responseTimeout);
665
+ });
666
+
667
+ // ============ 消息发送目标 ============
668
+ // 确定发送目标
669
+ const targetTo = event.type === "c2c" ? event.senderId
670
+ : event.type === "group" ? `group:${event.groupOpenid}`
671
+ : `channel:${event.channelId}`;
672
+
673
+ const dispatchPromise = pluginRuntime.channel.reply.dispatchReplyWithBufferedBlockDispatcher({
674
+ ctx: ctxPayload,
675
+ cfg,
676
+ dispatcherOptions: {
677
+ responsePrefix: messagesConfig.responsePrefix,
678
+ deliver: async (payload: { text?: string; mediaUrls?: string[]; mediaUrl?: string }, info: { kind: string }) => {
679
+ hasResponse = true;
680
+ if (timeoutId) {
681
+ clearTimeout(timeoutId);
682
+ timeoutId = null;
683
+ }
684
+
685
+ log?.info(`[qqbot:${account.accountId}] deliver called, kind: ${info.kind}, payload keys: ${Object.keys(payload).join(", ")}`);
686
+
687
+ let replyText = payload.text ?? "";
688
+
689
+ // ============ 简单图片标签解析 ============
690
+ // 支持 <qqimg>路径</qqimg> 或 <qqimg>路径</img> 格式发送图片
691
+ // 这是比 QQBOT_PAYLOAD JSON 更简单的方式,适合大模型能力较弱的情况
692
+ // 注意:正则限制内容不能包含 < 和 >,避免误匹配 `<qqimg>` 这种反引号内的说明文字
693
+ // 🔧 支持两种闭合方式:</qqimg> 和 </img>(AI 可能输出不同格式)
694
+ const qqimgRegex = /<qqimg>([^<>]+)<\/(?:qqimg|img)>/gi;
695
+ const qqimgMatches = [...replyText.matchAll(qqimgRegex)];
696
+
697
+ if (qqimgMatches.length > 0) {
698
+ log?.info(`[qqbot:${account.accountId}] Detected ${qqimgMatches.length} <qqimg> tag(s)`);
699
+
700
+ // 构建发送队列:根据内容在原文中的实际位置顺序发送
701
+ // type: 'text' | 'image', content: 文本内容或图片路径
702
+ const sendQueue: Array<{ type: "text" | "image"; content: string }> = [];
703
+
704
+ let lastIndex = 0;
705
+ // 使用新的正则来获取带索引的匹配结果(支持 </qqimg> 和 </img> 两种闭合方式)
706
+ const qqimgRegexWithIndex = /<qqimg>([^<>]+)<\/(?:qqimg|img)>/gi;
707
+ let match;
708
+
709
+ while ((match = qqimgRegexWithIndex.exec(replyText)) !== null) {
710
+ // 添加标签前的文本
711
+ const textBefore = replyText.slice(lastIndex, match.index).replace(/\n{3,}/g, "\n\n").trim();
712
+ if (textBefore) {
713
+ sendQueue.push({ type: "text", content: filterInternalMarkers(textBefore) });
714
+ }
715
+
716
+ // 添加图片
717
+ const imagePath = match[1]?.trim();
718
+ if (imagePath) {
719
+ sendQueue.push({ type: "image", content: imagePath });
720
+ log?.info(`[qqbot:${account.accountId}] Found image path in <qqimg>: ${imagePath}`);
721
+ }
722
+
723
+ lastIndex = match.index + match[0].length;
724
+ }
725
+
726
+ // 添加最后一个标签后的文本
727
+ const textAfter = replyText.slice(lastIndex).replace(/\n{3,}/g, "\n\n").trim();
728
+ if (textAfter) {
729
+ sendQueue.push({ type: "text", content: filterInternalMarkers(textAfter) });
730
+ }
731
+
732
+ log?.info(`[qqbot:${account.accountId}] Send queue: ${sendQueue.map(item => item.type).join(" -> ")}`);
733
+
734
+ // 按顺序发送
735
+ for (const item of sendQueue) {
736
+ if (item.type === "text") {
737
+ // 发送文本
738
+ try {
739
+ await sendWithTokenRetry(async (token) => {
740
+ if (event.type === "c2c") {
741
+ await sendC2CMessage(token, event.senderId, item.content, event.messageId);
742
+ } else if (event.type === "group" && event.groupOpenid) {
743
+ await sendGroupMessage(token, event.groupOpenid, item.content, event.messageId);
744
+ } else if (event.channelId) {
745
+ await sendChannelMessage(token, event.channelId, item.content, event.messageId);
746
+ }
747
+ });
748
+ log?.info(`[qqbot:${account.accountId}] Sent text: ${item.content.slice(0, 50)}...`);
749
+ } catch (err) {
750
+ log?.error(`[qqbot:${account.accountId}] Failed to send text: ${err}`);
751
+ }
752
+ } else if (item.type === "image") {
753
+ // 发送图片
754
+ const imagePath = item.content;
755
+ try {
756
+ let imageUrl = imagePath;
757
+
758
+ // 判断是本地文件还是 URL
759
+ const isLocalPath = imagePath.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(imagePath);
760
+ const isHttpUrl = imagePath.startsWith("http://") || imagePath.startsWith("https://");
761
+
762
+ if (isLocalPath) {
763
+ // 本地文件:转换为 Base64 Data URL
764
+ if (!fs.existsSync(imagePath)) {
765
+ log?.error(`[qqbot:${account.accountId}] Image file not found: ${imagePath}`);
766
+ await sendErrorMessage(`图片文件不存在: ${imagePath}`);
767
+ continue;
768
+ }
769
+
770
+ const fileBuffer = fs.readFileSync(imagePath);
771
+ const base64Data = fileBuffer.toString("base64");
772
+ const ext = path.extname(imagePath).toLowerCase();
773
+ const mimeTypes: Record<string, string> = {
774
+ ".jpg": "image/jpeg",
775
+ ".jpeg": "image/jpeg",
776
+ ".png": "image/png",
777
+ ".gif": "image/gif",
778
+ ".webp": "image/webp",
779
+ ".bmp": "image/bmp",
780
+ };
781
+ const mimeType = mimeTypes[ext];
782
+ if (!mimeType) {
783
+ log?.error(`[qqbot:${account.accountId}] Unsupported image format: ${ext}`);
784
+ await sendErrorMessage(`不支持的图片格式: ${ext}`);
785
+ continue;
786
+ }
787
+ imageUrl = `data:${mimeType};base64,${base64Data}`;
788
+ log?.info(`[qqbot:${account.accountId}] Converted local image to Base64 (size: ${fileBuffer.length} bytes)`);
789
+ } else if (!isHttpUrl) {
790
+ log?.error(`[qqbot:${account.accountId}] Invalid image path (not local or URL): ${imagePath}`);
791
+ continue;
792
+ }
793
+
794
+ // 发送图片
795
+ await sendWithTokenRetry(async (token) => {
796
+ if (event.type === "c2c") {
797
+ await sendC2CImageMessage(token, event.senderId, imageUrl, event.messageId);
798
+ } else if (event.type === "group" && event.groupOpenid) {
799
+ await sendGroupImageMessage(token, event.groupOpenid, imageUrl, event.messageId);
800
+ } else if (event.channelId) {
801
+ // 频道使用 Markdown 格式(如果是公网 URL)
802
+ if (isHttpUrl) {
803
+ await sendChannelMessage(token, event.channelId, `![](${imagePath})`, event.messageId);
804
+ } else {
805
+ // 频道不支持富媒体 Base64
806
+ log?.info(`[qqbot:${account.accountId}] Channel does not support rich media for local images`);
807
+ }
808
+ }
809
+ });
810
+ log?.info(`[qqbot:${account.accountId}] Sent image via <qqimg> tag: ${imagePath.slice(0, 60)}...`);
811
+ } catch (err) {
812
+ log?.error(`[qqbot:${account.accountId}] Failed to send image from <qqimg>: ${err}`);
813
+ await sendErrorMessage(`发送图片失败: ${err}`);
814
+ }
815
+ }
816
+ }
817
+
818
+ // 记录活动并返回
819
+ pluginRuntime.channel.activity.record({
820
+ channel: "qqbot",
821
+ accountId: account.accountId,
822
+ direction: "outbound",
823
+ });
824
+ return;
825
+ }
826
+
827
+ // ============ 结构化载荷检测与分发 ============
828
+ // 优先检测 QQBOT_PAYLOAD: 前缀,如果是结构化载荷则分发到对应处理器
829
+ const payloadResult = parseQQBotPayload(replyText);
830
+
831
+ if (payloadResult.isPayload) {
832
+ if (payloadResult.error) {
833
+ // 载荷解析失败,发送错误提示
834
+ log?.error(`[qqbot:${account.accountId}] Payload parse error: ${payloadResult.error}`);
835
+ await sendErrorMessage(`[QQBot] 载荷解析失败: ${payloadResult.error}`);
836
+ return;
837
+ }
838
+
839
+ if (payloadResult.payload) {
840
+ const parsedPayload = payloadResult.payload;
841
+ log?.info(`[qqbot:${account.accountId}] Detected structured payload, type: ${parsedPayload.type}`);
842
+
843
+ // 根据 type 分发到对应处理器
844
+ if (isCronReminderPayload(parsedPayload)) {
845
+ // ============ 定时提醒载荷处理 ============
846
+ log?.info(`[qqbot:${account.accountId}] Processing cron_reminder payload`);
847
+
848
+ // 将载荷编码为 Base64,构建 cron add 命令
849
+ const cronMessage = encodePayloadForCron(parsedPayload);
850
+
851
+ // 向用户确认提醒已设置(通过正常消息发送)
852
+ const confirmText = `⏰ 提醒已设置,将在指定时间发送: "${parsedPayload.content}"`;
853
+ try {
854
+ await sendWithTokenRetry(async (token) => {
855
+ if (event.type === "c2c") {
856
+ await sendC2CMessage(token, event.senderId, confirmText, event.messageId);
857
+ } else if (event.type === "group" && event.groupOpenid) {
858
+ await sendGroupMessage(token, event.groupOpenid, confirmText, event.messageId);
859
+ } else if (event.channelId) {
860
+ await sendChannelMessage(token, event.channelId, confirmText, event.messageId);
861
+ }
862
+ });
863
+ log?.info(`[qqbot:${account.accountId}] Cron reminder confirmation sent, cronMessage: ${cronMessage}`);
864
+ } catch (err) {
865
+ log?.error(`[qqbot:${account.accountId}] Failed to send cron confirmation: ${err}`);
866
+ }
867
+
868
+ // 记录活动并返回(cron add 命令需要由 AI 执行,这里只处理载荷)
869
+ pluginRuntime.channel.activity.record({
870
+ channel: "qqbot",
871
+ accountId: account.accountId,
872
+ direction: "outbound",
873
+ });
874
+ return;
875
+ } else if (isMediaPayload(parsedPayload)) {
876
+ // ============ 媒体消息载荷处理 ============
877
+ log?.info(`[qqbot:${account.accountId}] Processing media payload, mediaType: ${parsedPayload.mediaType}`);
878
+
879
+ if (parsedPayload.mediaType === "image") {
880
+ // 处理图片发送
881
+ let imageUrl = parsedPayload.path;
882
+
883
+ // 如果是本地文件,转换为 Base64 Data URL
884
+ if (parsedPayload.source === "file") {
885
+ try {
886
+ if (!fs.existsSync(imageUrl)) {
887
+ await sendErrorMessage(`[QQBot] 图片文件不存在: ${imageUrl}`);
888
+ return;
889
+ }
890
+ const fileBuffer = fs.readFileSync(imageUrl);
891
+ const base64Data = fileBuffer.toString("base64");
892
+ const ext = path.extname(imageUrl).toLowerCase();
893
+ const mimeTypes: Record<string, string> = {
894
+ ".jpg": "image/jpeg",
895
+ ".jpeg": "image/jpeg",
896
+ ".png": "image/png",
897
+ ".gif": "image/gif",
898
+ ".webp": "image/webp",
899
+ ".bmp": "image/bmp",
900
+ };
901
+ const mimeType = mimeTypes[ext];
902
+ if (!mimeType) {
903
+ await sendErrorMessage(`[QQBot] 不支持的图片格式: ${ext}`);
904
+ return;
905
+ }
906
+ imageUrl = `data:${mimeType};base64,${base64Data}`;
907
+ log?.info(`[qqbot:${account.accountId}] Converted local image to Base64 (size: ${fileBuffer.length} bytes)`);
908
+ } catch (readErr) {
909
+ log?.error(`[qqbot:${account.accountId}] Failed to read local image: ${readErr}`);
910
+ await sendErrorMessage(`[QQBot] 读取图片文件失败: ${readErr}`);
911
+ return;
912
+ }
913
+ }
914
+
915
+ // 发送图片
916
+ try {
917
+ await sendWithTokenRetry(async (token) => {
918
+ if (event.type === "c2c") {
919
+ await sendC2CImageMessage(token, event.senderId, imageUrl, event.messageId);
920
+ } else if (event.type === "group" && event.groupOpenid) {
921
+ await sendGroupImageMessage(token, event.groupOpenid, imageUrl, event.messageId);
922
+ } else if (event.channelId) {
923
+ // 频道使用 Markdown 格式
924
+ await sendChannelMessage(token, event.channelId, `![](${parsedPayload.path})`, event.messageId);
925
+ }
926
+ });
927
+ log?.info(`[qqbot:${account.accountId}] Sent image via media payload`);
928
+
929
+ // 如果有描述文本,单独发送
930
+ if (parsedPayload.caption) {
931
+ await sendWithTokenRetry(async (token) => {
932
+ if (event.type === "c2c") {
933
+ await sendC2CMessage(token, event.senderId, parsedPayload.caption!, event.messageId);
934
+ } else if (event.type === "group" && event.groupOpenid) {
935
+ await sendGroupMessage(token, event.groupOpenid, parsedPayload.caption!, event.messageId);
936
+ } else if (event.channelId) {
937
+ await sendChannelMessage(token, event.channelId, parsedPayload.caption!, event.messageId);
938
+ }
939
+ });
940
+ }
941
+ } catch (err) {
942
+ log?.error(`[qqbot:${account.accountId}] Failed to send image: ${err}`);
943
+ await sendErrorMessage(`[QQBot] 发送图片失败: ${err}`);
944
+ }
945
+ } else if (parsedPayload.mediaType === "audio") {
946
+ // 音频发送暂不支持
947
+ log?.info(`[qqbot:${account.accountId}] Audio sending not yet implemented`);
948
+ await sendErrorMessage(`[QQBot] 音频发送功能暂未实现,敬请期待~`);
949
+ } else if (parsedPayload.mediaType === "video") {
950
+ // 视频发送暂不支持
951
+ log?.info(`[qqbot:${account.accountId}] Video sending not supported`);
952
+ await sendErrorMessage(`[QQBot] 视频发送功能暂不支持`);
953
+ } else {
954
+ log?.error(`[qqbot:${account.accountId}] Unknown media type: ${(parsedPayload as MediaPayload).mediaType}`);
955
+ await sendErrorMessage(`[QQBot] 不支持的媒体类型: ${(parsedPayload as MediaPayload).mediaType}`);
956
+ }
957
+
958
+ // 记录活动并返回
959
+ pluginRuntime.channel.activity.record({
960
+ channel: "qqbot",
961
+ accountId: account.accountId,
962
+ direction: "outbound",
963
+ });
964
+ return;
965
+ } else {
966
+ // 未知的载荷类型
967
+ log?.error(`[qqbot:${account.accountId}] Unknown payload type: ${(parsedPayload as any).type}`);
968
+ await sendErrorMessage(`[QQBot] 不支持的载荷类型: ${(parsedPayload as any).type}`);
969
+ return;
970
+ }
971
+ }
972
+ }
973
+
974
+ // ============ 非结构化消息:简化处理 ============
975
+ // 📝 设计原则:JSON payload (QQBOT_PAYLOAD) 是发送本地图片的唯一方式
976
+ // 非结构化消息只处理:公网 URL (http/https) 和 Base64 Data URL
977
+ const imageUrls: string[] = [];
978
+
979
+ /**
980
+ * 检查并收集图片 URL(仅支持公网 URL 和 Base64 Data URL)
981
+ * ⚠️ 本地文件路径必须使用 QQBOT_PAYLOAD JSON 格式发送
982
+ */
983
+ const collectImageUrl = (url: string | undefined | null): boolean => {
984
+ if (!url) return false;
985
+
986
+ const isHttpUrl = url.startsWith("http://") || url.startsWith("https://");
987
+ const isDataUrl = url.startsWith("data:image/");
988
+
989
+ if (isHttpUrl || isDataUrl) {
990
+ if (!imageUrls.includes(url)) {
991
+ imageUrls.push(url);
992
+ if (isDataUrl) {
993
+ log?.info(`[qqbot:${account.accountId}] Collected Base64 image (length: ${url.length})`);
994
+ } else {
995
+ log?.info(`[qqbot:${account.accountId}] Collected media URL: ${url.slice(0, 80)}...`);
996
+ }
997
+ }
998
+ return true;
999
+ }
1000
+
1001
+ // ⚠️ 本地文件路径不再在此处处理,应使用 <qqimg> 标签
1002
+ const isLocalPath = url.startsWith("/") || /^[a-zA-Z]:[\\/]/.test(url);
1003
+ if (isLocalPath) {
1004
+ log?.info(`[qqbot:${account.accountId}] 💡 Local path detected in non-structured message (not sending): ${url}`);
1005
+ log?.info(`[qqbot:${account.accountId}] 💡 Hint: Use <qqimg>${url}</qqimg> tag to send local images`);
1006
+ }
1007
+ return false;
1008
+ };
1009
+
1010
+ // 处理 mediaUrls 和 mediaUrl 字段
1011
+ if (payload.mediaUrls?.length) {
1012
+ for (const url of payload.mediaUrls) {
1013
+ collectImageUrl(url);
1014
+ }
1015
+ }
1016
+ if (payload.mediaUrl) {
1017
+ collectImageUrl(payload.mediaUrl);
1018
+ }
1019
+
1020
+ // 提取文本中的图片格式(仅处理公网 URL)
1021
+ // 📝 设计:本地路径必须使用 QQBOT_PAYLOAD JSON 格式发送
1022
+ const mdImageRegex = /!\[([^\]]*)\]\(([^)]+)\)/gi;
1023
+ const mdMatches = [...replyText.matchAll(mdImageRegex)];
1024
+ for (const match of mdMatches) {
1025
+ const url = match[2]?.trim();
1026
+ if (url && !imageUrls.includes(url)) {
1027
+ if (url.startsWith('http://') || url.startsWith('https://')) {
1028
+ // 公网 URL:收集并处理
1029
+ imageUrls.push(url);
1030
+ log?.info(`[qqbot:${account.accountId}] Extracted HTTP image from markdown: ${url.slice(0, 80)}...`);
1031
+ } else if (/^\/?(?:Users|home|tmp|var|private|[A-Z]:)/i.test(url)) {
1032
+ // 本地路径:记录日志提示,但不发送
1033
+ log?.info(`[qqbot:${account.accountId}] ⚠️ Local path in markdown (not sending): ${url}`);
1034
+ log?.info(`[qqbot:${account.accountId}] 💡 Use <qqimg>${url}</qqimg> tag to send local images`);
1035
+ }
1036
+ }
1037
+ }
1038
+
1039
+ // 提取裸 URL 图片(公网 URL)
1040
+ const bareUrlRegex = /(?<![(\["'])(https?:\/\/[^\s)"'<>]+\.(?:png|jpg|jpeg|gif|webp)(?:\?[^\s"'<>]*)?)/gi;
1041
+ const bareUrlMatches = [...replyText.matchAll(bareUrlRegex)];
1042
+ for (const match of bareUrlMatches) {
1043
+ const url = match[1];
1044
+ if (url && !imageUrls.includes(url)) {
1045
+ imageUrls.push(url);
1046
+ log?.info(`[qqbot:${account.accountId}] Extracted bare image URL: ${url.slice(0, 80)}...`);
1047
+ }
1048
+ }
1049
+
1050
+ // 判断是否使用 markdown 模式
1051
+ const useMarkdown = account.markdownSupport === true;
1052
+ log?.info(`[qqbot:${account.accountId}] Markdown mode: ${useMarkdown}, images: ${imageUrls.length}`);
1053
+
1054
+ let textWithoutImages = replyText;
1055
+
1056
+ // 🎯 过滤内部标记(如 [[reply_to: xxx]])
1057
+ // 这些标记可能被 AI 错误地学习并输出
1058
+ textWithoutImages = filterInternalMarkers(textWithoutImages);
1059
+
1060
+ // 根据模式处理图片
1061
+ if (useMarkdown) {
1062
+ // ============ Markdown 模式 ============
1063
+ // 🎯 关键改动:区分公网 URL 和本地文件/Base64
1064
+ // - 公网 URL (http/https) → 使用 Markdown 图片格式 ![#宽px #高px](url)
1065
+ // - 本地文件/Base64 (data:image/...) → 使用富媒体 API 发送
1066
+
1067
+ // 分离图片:公网 URL vs Base64/本地文件
1068
+ const httpImageUrls: string[] = []; // 公网 URL,用于 Markdown 嵌入
1069
+ const base64ImageUrls: string[] = []; // Base64,用于富媒体 API
1070
+
1071
+ for (const url of imageUrls) {
1072
+ if (url.startsWith("data:image/")) {
1073
+ base64ImageUrls.push(url);
1074
+ } else if (url.startsWith("http://") || url.startsWith("https://")) {
1075
+ httpImageUrls.push(url);
1076
+ }
1077
+ }
1078
+
1079
+ log?.info(`[qqbot:${account.accountId}] Image classification: httpUrls=${httpImageUrls.length}, base64=${base64ImageUrls.length}`);
1080
+
1081
+ // 🔹 第一步:通过富媒体 API 发送 Base64 图片(本地文件已转换为 Base64)
1082
+ if (base64ImageUrls.length > 0) {
1083
+ log?.info(`[qqbot:${account.accountId}] Sending ${base64ImageUrls.length} image(s) via Rich Media API...`);
1084
+ for (const imageUrl of base64ImageUrls) {
1085
+ try {
1086
+ await sendWithTokenRetry(async (token) => {
1087
+ if (event.type === "c2c") {
1088
+ await sendC2CImageMessage(token, event.senderId, imageUrl, event.messageId);
1089
+ } else if (event.type === "group" && event.groupOpenid) {
1090
+ await sendGroupImageMessage(token, event.groupOpenid, imageUrl, event.messageId);
1091
+ } else if (event.channelId) {
1092
+ // 频道暂不支持富媒体,跳过
1093
+ log?.info(`[qqbot:${account.accountId}] Channel does not support rich media, skipping Base64 image`);
1094
+ }
1095
+ });
1096
+ log?.info(`[qqbot:${account.accountId}] Sent Base64 image via Rich Media API (size: ${imageUrl.length} chars)`);
1097
+ } catch (imgErr) {
1098
+ log?.error(`[qqbot:${account.accountId}] Failed to send Base64 image via Rich Media API: ${imgErr}`);
1099
+ }
1100
+ }
1101
+ }
1102
+
1103
+ // 🔹 第二步:处理文本和公网 URL 图片
1104
+ // 记录已存在于文本中的 markdown 图片 URL
1105
+ const existingMdUrls = new Set(mdMatches.map(m => m[2]));
1106
+
1107
+ // 需要追加的公网图片(从 mediaUrl/mediaUrls 来的,且不在文本中)
1108
+ const imagesToAppend: string[] = [];
1109
+
1110
+ // 处理需要追加的公网 URL 图片:获取尺寸并格式化
1111
+ for (const url of httpImageUrls) {
1112
+ if (!existingMdUrls.has(url)) {
1113
+ // 这个 URL 不在文本的 markdown 格式中,需要追加
1114
+ try {
1115
+ const size = await getImageSize(url);
1116
+ const mdImage = formatQQBotMarkdownImage(url, size);
1117
+ imagesToAppend.push(mdImage);
1118
+ log?.info(`[qqbot:${account.accountId}] Formatted HTTP image: ${size ? `${size.width}x${size.height}` : 'default size'} - ${url.slice(0, 60)}...`);
1119
+ } catch (err) {
1120
+ log?.info(`[qqbot:${account.accountId}] Failed to get image size, using default: ${err}`);
1121
+ const mdImage = formatQQBotMarkdownImage(url, null);
1122
+ imagesToAppend.push(mdImage);
1123
+ }
1124
+ }
1125
+ }
1126
+
1127
+ // 处理文本中已有的 markdown 图片:补充公网 URL 的尺寸信息
1128
+ // 📝 本地路径不再特殊处理(保留在文本中),因为不通过非结构化消息发送
1129
+ for (const match of mdMatches) {
1130
+ const fullMatch = match[0]; // ![alt](url)
1131
+ const imgUrl = match[2]; // url 部分
1132
+
1133
+ // 只处理公网 URL,补充尺寸信息
1134
+ const isHttpUrl = imgUrl.startsWith('http://') || imgUrl.startsWith('https://');
1135
+ if (isHttpUrl && !hasQQBotImageSize(fullMatch)) {
1136
+ try {
1137
+ const size = await getImageSize(imgUrl);
1138
+ const newMdImage = formatQQBotMarkdownImage(imgUrl, size);
1139
+ textWithoutImages = textWithoutImages.replace(fullMatch, newMdImage);
1140
+ log?.info(`[qqbot:${account.accountId}] Updated image with size: ${size ? `${size.width}x${size.height}` : 'default'} - ${imgUrl.slice(0, 60)}...`);
1141
+ } catch (err) {
1142
+ log?.info(`[qqbot:${account.accountId}] Failed to get image size for existing md, using default: ${err}`);
1143
+ const newMdImage = formatQQBotMarkdownImage(imgUrl, null);
1144
+ textWithoutImages = textWithoutImages.replace(fullMatch, newMdImage);
1145
+ }
1146
+ }
1147
+ }
1148
+
1149
+ // 从文本中移除裸 URL 图片(已转换为 markdown 格式)
1150
+ for (const match of bareUrlMatches) {
1151
+ textWithoutImages = textWithoutImages.replace(match[0], "").trim();
1152
+ }
1153
+
1154
+ // 追加需要添加的公网图片到文本末尾
1155
+ if (imagesToAppend.length > 0) {
1156
+ textWithoutImages = textWithoutImages.trim();
1157
+ if (textWithoutImages) {
1158
+ textWithoutImages += "\n\n" + imagesToAppend.join("\n");
1159
+ } else {
1160
+ textWithoutImages = imagesToAppend.join("\n");
1161
+ }
1162
+ }
1163
+
1164
+ // 🔹 第三步:发送带公网图片的 markdown 消息
1165
+ if (textWithoutImages.trim()) {
1166
+ try {
1167
+ await sendWithTokenRetry(async (token) => {
1168
+ if (event.type === "c2c") {
1169
+ await sendC2CMessage(token, event.senderId, textWithoutImages, event.messageId);
1170
+ } else if (event.type === "group" && event.groupOpenid) {
1171
+ await sendGroupMessage(token, event.groupOpenid, textWithoutImages, event.messageId);
1172
+ } else if (event.channelId) {
1173
+ await sendChannelMessage(token, event.channelId, textWithoutImages, event.messageId);
1174
+ }
1175
+ });
1176
+ log?.info(`[qqbot:${account.accountId}] Sent markdown message with ${httpImageUrls.length} HTTP images (${event.type})`);
1177
+ } catch (err) {
1178
+ log?.error(`[qqbot:${account.accountId}] Failed to send markdown message: ${err}`);
1179
+ }
1180
+ }
1181
+ } else {
1182
+ // ============ 普通文本模式:使用富媒体 API 发送图片 ============
1183
+ // 从文本中移除所有图片相关内容
1184
+ for (const match of mdMatches) {
1185
+ textWithoutImages = textWithoutImages.replace(match[0], "").trim();
1186
+ }
1187
+ for (const match of bareUrlMatches) {
1188
+ textWithoutImages = textWithoutImages.replace(match[0], "").trim();
1189
+ }
1190
+
1191
+ try {
1192
+ // 发送图片(通过富媒体 API)
1193
+ for (const imageUrl of imageUrls) {
1194
+ try {
1195
+ await sendWithTokenRetry(async (token) => {
1196
+ if (event.type === "c2c") {
1197
+ await sendC2CImageMessage(token, event.senderId, imageUrl, event.messageId);
1198
+ } else if (event.type === "group" && event.groupOpenid) {
1199
+ await sendGroupImageMessage(token, event.groupOpenid, imageUrl, event.messageId);
1200
+ } else if (event.channelId) {
1201
+ // 频道暂不支持富媒体,发送文本 URL
1202
+ await sendChannelMessage(token, event.channelId, imageUrl, event.messageId);
1203
+ }
1204
+ });
1205
+ log?.info(`[qqbot:${account.accountId}] Sent image via media API: ${imageUrl.slice(0, 80)}...`);
1206
+ } catch (imgErr) {
1207
+ log?.error(`[qqbot:${account.accountId}] Failed to send image: ${imgErr}`);
1208
+ }
1209
+ }
1210
+
1211
+ // 发送文本消息
1212
+ if (textWithoutImages.trim()) {
1213
+ await sendWithTokenRetry(async (token) => {
1214
+ if (event.type === "c2c") {
1215
+ await sendC2CMessage(token, event.senderId, textWithoutImages, event.messageId);
1216
+ } else if (event.type === "group" && event.groupOpenid) {
1217
+ await sendGroupMessage(token, event.groupOpenid, textWithoutImages, event.messageId);
1218
+ } else if (event.channelId) {
1219
+ await sendChannelMessage(token, event.channelId, textWithoutImages, event.messageId);
1220
+ }
1221
+ });
1222
+ log?.info(`[qqbot:${account.accountId}] Sent text reply (${event.type})`);
1223
+ }
1224
+ } catch (err) {
1225
+ log?.error(`[qqbot:${account.accountId}] Send failed: ${err}`);
1226
+ }
1227
+ }
1228
+
1229
+ pluginRuntime.channel.activity.record({
1230
+ channel: "qqbot",
1231
+ accountId: account.accountId,
1232
+ direction: "outbound",
1233
+ });
1234
+ },
1235
+ onError: async (err: unknown) => {
1236
+ log?.error(`[qqbot:${account.accountId}] Dispatch error: ${err}`);
1237
+ hasResponse = true;
1238
+ if (timeoutId) {
1239
+ clearTimeout(timeoutId);
1240
+ timeoutId = null;
1241
+ }
1242
+
1243
+ // 发送错误提示给用户,显示完整错误信息
1244
+ const errMsg = String(err);
1245
+ if (errMsg.includes("401") || errMsg.includes("key") || errMsg.includes("auth")) {
1246
+ await sendErrorMessage("[ClawdBot] 大模型 API Key 可能无效,请检查配置");
1247
+ } else {
1248
+ // 显示完整错误信息,截取前 500 字符
1249
+ await sendErrorMessage(`[ClawdBot] 出错: ${errMsg.slice(0, 500)}`);
1250
+ }
1251
+ },
1252
+ },
1253
+ replyOptions: {},
1254
+ });
1255
+
1256
+ // 等待分发完成或超时
1257
+ try {
1258
+ await Promise.race([dispatchPromise, timeoutPromise]);
1259
+ } catch (err) {
1260
+ if (timeoutId) {
1261
+ clearTimeout(timeoutId);
1262
+ }
1263
+ if (!hasResponse) {
1264
+ log?.error(`[qqbot:${account.accountId}] No response within timeout`);
1265
+ await sendErrorMessage("QQ已经收到了你的请求并转交给了Openclaw,任务可能比较复杂,正在处理中...");
1266
+ }
1267
+ }
1268
+ } catch (err) {
1269
+ log?.error(`[qqbot:${account.accountId}] Message processing failed: ${err}`);
1270
+ await sendErrorMessage(`[ClawdBot] 处理失败: ${String(err).slice(0, 500)}`);
1271
+ }
1272
+ };
1273
+
1274
+ ws.on("open", () => {
1275
+ log?.info(`[qqbot:${account.accountId}] WebSocket connected`);
1276
+ isConnecting = false; // 连接完成,释放锁
1277
+ reconnectAttempts = 0; // 连接成功,重置重试计数
1278
+ lastConnectTime = Date.now(); // 记录连接时间
1279
+ // 启动消息处理器(异步处理,防止阻塞心跳)
1280
+ startMessageProcessor(handleMessage);
1281
+ // P1-1: 启动后台 Token 刷新
1282
+ startBackgroundTokenRefresh(account.appId, account.clientSecret, {
1283
+ log: log as { info: (msg: string) => void; error: (msg: string) => void; debug?: (msg: string) => void },
1284
+ });
1285
+ });
1286
+
1287
+ ws.on("message", async (data) => {
1288
+ try {
1289
+ const rawData = data.toString();
1290
+ const payload = JSON.parse(rawData) as WSPayload;
1291
+ const { op, d, s, t } = payload;
1292
+
1293
+ if (s) {
1294
+ lastSeq = s;
1295
+ // P1-2: 更新持久化存储中的 lastSeq(节流保存)
1296
+ if (sessionId) {
1297
+ saveSession({
1298
+ sessionId,
1299
+ lastSeq,
1300
+ lastConnectedAt: lastConnectTime,
1301
+ intentLevelIndex: lastSuccessfulIntentLevel >= 0 ? lastSuccessfulIntentLevel : intentLevelIndex,
1302
+ accountId: account.accountId,
1303
+ savedAt: Date.now(),
1304
+ });
1305
+ }
1306
+ }
1307
+
1308
+ log?.debug?.(`[qqbot:${account.accountId}] Received op=${op} t=${t}`);
1309
+
1310
+ switch (op) {
1311
+ case 10: // Hello
1312
+ log?.info(`[qqbot:${account.accountId}] Hello received`);
1313
+
1314
+ // 如果有 session_id,尝试 Resume
1315
+ if (sessionId && lastSeq !== null) {
1316
+ log?.info(`[qqbot:${account.accountId}] Attempting to resume session ${sessionId}`);
1317
+ ws.send(JSON.stringify({
1318
+ op: 6, // Resume
1319
+ d: {
1320
+ token: `QQBot ${accessToken}`,
1321
+ session_id: sessionId,
1322
+ seq: lastSeq,
1323
+ },
1324
+ }));
1325
+ } else {
1326
+ // 新连接,发送 Identify
1327
+ // 如果有上次成功的级别,直接使用;否则从当前级别开始尝试
1328
+ const levelToUse = lastSuccessfulIntentLevel >= 0 ? lastSuccessfulIntentLevel : intentLevelIndex;
1329
+ const intentLevel = INTENT_LEVELS[Math.min(levelToUse, INTENT_LEVELS.length - 1)];
1330
+ log?.info(`[qqbot:${account.accountId}] Sending identify with intents: ${intentLevel.intents} (${intentLevel.description})`);
1331
+ ws.send(JSON.stringify({
1332
+ op: 2,
1333
+ d: {
1334
+ token: `QQBot ${accessToken}`,
1335
+ intents: intentLevel.intents,
1336
+ shard: [0, 1],
1337
+ },
1338
+ }));
1339
+ }
1340
+
1341
+ // 启动心跳
1342
+ const interval = (d as { heartbeat_interval: number }).heartbeat_interval;
1343
+ if (heartbeatInterval) clearInterval(heartbeatInterval);
1344
+ heartbeatInterval = setInterval(() => {
1345
+ if (ws.readyState === WebSocket.OPEN) {
1346
+ ws.send(JSON.stringify({ op: 1, d: lastSeq }));
1347
+ log?.debug?.(`[qqbot:${account.accountId}] Heartbeat sent`);
1348
+ }
1349
+ }, interval);
1350
+ break;
1351
+
1352
+ case 0: // Dispatch
1353
+ if (t === "READY") {
1354
+ const readyData = d as { session_id: string };
1355
+ sessionId = readyData.session_id;
1356
+ // 记录成功的权限级别
1357
+ lastSuccessfulIntentLevel = intentLevelIndex;
1358
+ const successLevel = INTENT_LEVELS[intentLevelIndex];
1359
+ log?.info(`[qqbot:${account.accountId}] Ready with ${successLevel.description}, session: ${sessionId}`);
1360
+ // P1-2: 保存新的 Session 状态
1361
+ saveSession({
1362
+ sessionId,
1363
+ lastSeq,
1364
+ lastConnectedAt: Date.now(),
1365
+ intentLevelIndex,
1366
+ accountId: account.accountId,
1367
+ savedAt: Date.now(),
1368
+ });
1369
+ onReady?.(d);
1370
+ } else if (t === "RESUMED") {
1371
+ log?.info(`[qqbot:${account.accountId}] Session resumed`);
1372
+ // P1-2: 更新 Session 连接时间
1373
+ if (sessionId) {
1374
+ saveSession({
1375
+ sessionId,
1376
+ lastSeq,
1377
+ lastConnectedAt: Date.now(),
1378
+ intentLevelIndex: lastSuccessfulIntentLevel >= 0 ? lastSuccessfulIntentLevel : intentLevelIndex,
1379
+ accountId: account.accountId,
1380
+ savedAt: Date.now(),
1381
+ });
1382
+ }
1383
+ } else if (t === "C2C_MESSAGE_CREATE") {
1384
+ const event = d as C2CMessageEvent;
1385
+ // P1-3: 记录已知用户
1386
+ recordKnownUser({
1387
+ openid: event.author.user_openid,
1388
+ type: "c2c",
1389
+ accountId: account.accountId,
1390
+ });
1391
+ // 使用消息队列异步处理,防止阻塞心跳
1392
+ enqueueMessage({
1393
+ type: "c2c",
1394
+ senderId: event.author.user_openid,
1395
+ content: event.content,
1396
+ messageId: event.id,
1397
+ timestamp: event.timestamp,
1398
+ attachments: event.attachments,
1399
+ });
1400
+ } else if (t === "AT_MESSAGE_CREATE") {
1401
+ const event = d as GuildMessageEvent;
1402
+ // P1-3: 记录已知用户(频道用户)
1403
+ recordKnownUser({
1404
+ openid: event.author.id,
1405
+ type: "c2c", // 频道用户按 c2c 类型存储
1406
+ nickname: event.author.username,
1407
+ accountId: account.accountId,
1408
+ });
1409
+ enqueueMessage({
1410
+ type: "guild",
1411
+ senderId: event.author.id,
1412
+ senderName: event.author.username,
1413
+ content: event.content,
1414
+ messageId: event.id,
1415
+ timestamp: event.timestamp,
1416
+ channelId: event.channel_id,
1417
+ guildId: event.guild_id,
1418
+ attachments: event.attachments,
1419
+ });
1420
+ } else if (t === "DIRECT_MESSAGE_CREATE") {
1421
+ const event = d as GuildMessageEvent;
1422
+ // P1-3: 记录已知用户(频道私信用户)
1423
+ recordKnownUser({
1424
+ openid: event.author.id,
1425
+ type: "c2c",
1426
+ nickname: event.author.username,
1427
+ accountId: account.accountId,
1428
+ });
1429
+ enqueueMessage({
1430
+ type: "dm",
1431
+ senderId: event.author.id,
1432
+ senderName: event.author.username,
1433
+ content: event.content,
1434
+ messageId: event.id,
1435
+ timestamp: event.timestamp,
1436
+ guildId: event.guild_id,
1437
+ attachments: event.attachments,
1438
+ });
1439
+ } else if (t === "GROUP_AT_MESSAGE_CREATE") {
1440
+ const event = d as GroupMessageEvent;
1441
+ // P1-3: 记录已知用户(群组用户)
1442
+ recordKnownUser({
1443
+ openid: event.author.member_openid,
1444
+ type: "group",
1445
+ groupOpenid: event.group_openid,
1446
+ accountId: account.accountId,
1447
+ });
1448
+ enqueueMessage({
1449
+ type: "group",
1450
+ senderId: event.author.member_openid,
1451
+ content: event.content,
1452
+ messageId: event.id,
1453
+ timestamp: event.timestamp,
1454
+ groupOpenid: event.group_openid,
1455
+ attachments: event.attachments,
1456
+ });
1457
+ }
1458
+ break;
1459
+
1460
+ case 11: // Heartbeat ACK
1461
+ log?.debug?.(`[qqbot:${account.accountId}] Heartbeat ACK`);
1462
+ break;
1463
+
1464
+ case 7: // Reconnect
1465
+ log?.info(`[qqbot:${account.accountId}] Server requested reconnect`);
1466
+ cleanup();
1467
+ scheduleReconnect();
1468
+ break;
1469
+
1470
+ case 9: // Invalid Session
1471
+ const canResume = d as boolean;
1472
+ const currentLevel = INTENT_LEVELS[intentLevelIndex];
1473
+ log?.error(`[qqbot:${account.accountId}] Invalid session (${currentLevel.description}), can resume: ${canResume}, raw: ${rawData}`);
1474
+
1475
+ if (!canResume) {
1476
+ sessionId = null;
1477
+ lastSeq = null;
1478
+ // P1-2: 清除持久化的 Session
1479
+ clearSession(account.accountId);
1480
+
1481
+ // 尝试降级到下一个权限级别
1482
+ if (intentLevelIndex < INTENT_LEVELS.length - 1) {
1483
+ intentLevelIndex++;
1484
+ const nextLevel = INTENT_LEVELS[intentLevelIndex];
1485
+ log?.info(`[qqbot:${account.accountId}] Downgrading intents to: ${nextLevel.description}`);
1486
+ } else {
1487
+ // 已经是最低权限级别了
1488
+ log?.error(`[qqbot:${account.accountId}] All intent levels failed. Please check AppID/Secret.`);
1489
+ shouldRefreshToken = true;
1490
+ }
1491
+ }
1492
+ cleanup();
1493
+ // Invalid Session 后等待一段时间再重连
1494
+ scheduleReconnect(3000);
1495
+ break;
1496
+ }
1497
+ } catch (err) {
1498
+ log?.error(`[qqbot:${account.accountId}] Message parse error: ${err}`);
1499
+ }
1500
+ });
1501
+
1502
+ ws.on("close", (code, reason) => {
1503
+ log?.info(`[qqbot:${account.accountId}] WebSocket closed: ${code} ${reason.toString()}`);
1504
+ isConnecting = false; // 释放锁
1505
+
1506
+ // 根据错误码处理
1507
+ // 4009: 可以重新发起 resume
1508
+ // 4900-4913: 内部错误,需要重新 identify
1509
+ // 4914: 机器人已下架
1510
+ // 4915: 机器人已封禁
1511
+ if (code === 4914 || code === 4915) {
1512
+ log?.error(`[qqbot:${account.accountId}] Bot is ${code === 4914 ? "offline/sandbox-only" : "banned"}. Please contact QQ platform.`);
1513
+ cleanup();
1514
+ // 不重连,直接退出
1515
+ return;
1516
+ }
1517
+
1518
+ if (code === 4009) {
1519
+ // 4009 可以尝试 resume,保留 session
1520
+ log?.info(`[qqbot:${account.accountId}] Error 4009, will try resume`);
1521
+ shouldRefreshToken = true;
1522
+ } else if (code >= 4900 && code <= 4913) {
1523
+ // 4900-4913 内部错误,清除 session 重新 identify
1524
+ log?.info(`[qqbot:${account.accountId}] Internal error (${code}), will re-identify`);
1525
+ sessionId = null;
1526
+ lastSeq = null;
1527
+ shouldRefreshToken = true;
1528
+ }
1529
+
1530
+ // 检测是否是快速断开(连接后很快就断了)
1531
+ const connectionDuration = Date.now() - lastConnectTime;
1532
+ if (connectionDuration < QUICK_DISCONNECT_THRESHOLD && lastConnectTime > 0) {
1533
+ quickDisconnectCount++;
1534
+ log?.info(`[qqbot:${account.accountId}] Quick disconnect detected (${connectionDuration}ms), count: ${quickDisconnectCount}`);
1535
+
1536
+ // 如果连续快速断开超过阈值,等待更长时间
1537
+ if (quickDisconnectCount >= MAX_QUICK_DISCONNECT_COUNT) {
1538
+ log?.error(`[qqbot:${account.accountId}] Too many quick disconnects. This may indicate a permission issue.`);
1539
+ log?.error(`[qqbot:${account.accountId}] Please check: 1) AppID/Secret correct 2) Bot permissions on QQ Open Platform`);
1540
+ quickDisconnectCount = 0;
1541
+ cleanup();
1542
+ // 快速断开太多次,等待更长时间再重连
1543
+ if (!isAborted && code !== 1000) {
1544
+ scheduleReconnect(RATE_LIMIT_DELAY);
1545
+ }
1546
+ return;
1547
+ }
1548
+ } else {
1549
+ // 连接持续时间够长,重置计数
1550
+ quickDisconnectCount = 0;
1551
+ }
1552
+
1553
+ cleanup();
1554
+
1555
+ // 非正常关闭则重连
1556
+ if (!isAborted && code !== 1000) {
1557
+ scheduleReconnect();
1558
+ }
1559
+ });
1560
+
1561
+ ws.on("error", (err) => {
1562
+ log?.error(`[qqbot:${account.accountId}] WebSocket error: ${err.message}`);
1563
+ onError?.(err);
1564
+ });
1565
+
1566
+ } catch (err) {
1567
+ isConnecting = false; // 释放锁
1568
+ const errMsg = String(err);
1569
+ log?.error(`[qqbot:${account.accountId}] Connection failed: ${err}`);
1570
+
1571
+ // 如果是频率限制错误,等待更长时间
1572
+ if (errMsg.includes("Too many requests") || errMsg.includes("100001")) {
1573
+ log?.info(`[qqbot:${account.accountId}] Rate limited, waiting ${RATE_LIMIT_DELAY}ms before retry`);
1574
+ scheduleReconnect(RATE_LIMIT_DELAY);
1575
+ } else {
1576
+ scheduleReconnect();
1577
+ }
1578
+ }
1579
+ };
1580
+
1581
+ // 开始连接
1582
+ await connect();
1583
+
1584
+ // 等待 abort 信号
1585
+ return new Promise((resolve) => {
1586
+ abortSignal.addEventListener("abort", () => resolve());
1587
+ });
1588
+ }