@ryantest/openclaw-qqbot 0.0.1

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 (197) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +483 -0
  3. package/README.zh.md +478 -0
  4. package/bin/qqbot-cli.js +243 -0
  5. package/clawdbot.plugin.json +16 -0
  6. package/dist/index.d.ts +17 -0
  7. package/dist/index.js +26 -0
  8. package/dist/src/admin-resolver.d.ts +27 -0
  9. package/dist/src/admin-resolver.js +122 -0
  10. package/dist/src/api.d.ts +156 -0
  11. package/dist/src/api.js +599 -0
  12. package/dist/src/channel.d.ts +11 -0
  13. package/dist/src/channel.js +354 -0
  14. package/dist/src/config.d.ts +25 -0
  15. package/dist/src/config.js +161 -0
  16. package/dist/src/credential-backup.d.ts +31 -0
  17. package/dist/src/credential-backup.js +66 -0
  18. package/dist/src/gateway.d.ts +18 -0
  19. package/dist/src/gateway.js +1265 -0
  20. package/dist/src/image-server.d.ts +68 -0
  21. package/dist/src/image-server.js +462 -0
  22. package/dist/src/inbound-attachments.d.ts +58 -0
  23. package/dist/src/inbound-attachments.js +234 -0
  24. package/dist/src/known-users.d.ts +100 -0
  25. package/dist/src/known-users.js +263 -0
  26. package/dist/src/message-queue.d.ts +50 -0
  27. package/dist/src/message-queue.js +115 -0
  28. package/dist/src/onboarding.d.ts +10 -0
  29. package/dist/src/onboarding.js +203 -0
  30. package/dist/src/outbound-deliver.d.ts +48 -0
  31. package/dist/src/outbound-deliver.js +462 -0
  32. package/dist/src/outbound.d.ts +203 -0
  33. package/dist/src/outbound.js +1102 -0
  34. package/dist/src/proactive.d.ts +170 -0
  35. package/dist/src/proactive.js +399 -0
  36. package/dist/src/ref-index-store.d.ts +70 -0
  37. package/dist/src/ref-index-store.js +273 -0
  38. package/dist/src/reply-dispatcher.d.ts +35 -0
  39. package/dist/src/reply-dispatcher.js +311 -0
  40. package/dist/src/runtime.d.ts +3 -0
  41. package/dist/src/runtime.js +10 -0
  42. package/dist/src/session-store.d.ts +52 -0
  43. package/dist/src/session-store.js +254 -0
  44. package/dist/src/slash-commands.d.ts +71 -0
  45. package/dist/src/slash-commands.js +1179 -0
  46. package/dist/src/startup-greeting.d.ts +30 -0
  47. package/dist/src/startup-greeting.js +78 -0
  48. package/dist/src/stt.d.ts +21 -0
  49. package/dist/src/stt.js +70 -0
  50. package/dist/src/tools/channel.d.ts +16 -0
  51. package/dist/src/tools/channel.js +234 -0
  52. package/dist/src/tools/remind.d.ts +2 -0
  53. package/dist/src/tools/remind.js +247 -0
  54. package/dist/src/types.d.ts +175 -0
  55. package/dist/src/types.js +1 -0
  56. package/dist/src/typing-keepalive.d.ts +27 -0
  57. package/dist/src/typing-keepalive.js +64 -0
  58. package/dist/src/update-checker.d.ts +34 -0
  59. package/dist/src/update-checker.js +166 -0
  60. package/dist/src/user-messages.d.ts +8 -0
  61. package/dist/src/user-messages.js +8 -0
  62. package/dist/src/utils/audio-convert.d.ts +89 -0
  63. package/dist/src/utils/audio-convert.js +704 -0
  64. package/dist/src/utils/file-utils.d.ts +55 -0
  65. package/dist/src/utils/file-utils.js +150 -0
  66. package/dist/src/utils/image-size.d.ts +51 -0
  67. package/dist/src/utils/image-size.js +234 -0
  68. package/dist/src/utils/media-tags.d.ts +14 -0
  69. package/dist/src/utils/media-tags.js +164 -0
  70. package/dist/src/utils/payload.d.ts +112 -0
  71. package/dist/src/utils/payload.js +186 -0
  72. package/dist/src/utils/platform.d.ts +137 -0
  73. package/dist/src/utils/platform.js +390 -0
  74. package/dist/src/utils/text-parsing.d.ts +32 -0
  75. package/dist/src/utils/text-parsing.js +80 -0
  76. package/dist/src/utils/upload-cache.d.ts +34 -0
  77. package/dist/src/utils/upload-cache.js +93 -0
  78. package/index.ts +31 -0
  79. package/moltbot.plugin.json +16 -0
  80. package/node_modules/@eshaz/web-worker/LICENSE +201 -0
  81. package/node_modules/@eshaz/web-worker/README.md +134 -0
  82. package/node_modules/@eshaz/web-worker/browser.js +17 -0
  83. package/node_modules/@eshaz/web-worker/cjs/browser.js +16 -0
  84. package/node_modules/@eshaz/web-worker/cjs/node.js +219 -0
  85. package/node_modules/@eshaz/web-worker/index.d.ts +4 -0
  86. package/node_modules/@eshaz/web-worker/node.js +223 -0
  87. package/node_modules/@eshaz/web-worker/package.json +54 -0
  88. package/node_modules/@wasm-audio-decoders/common/index.js +5 -0
  89. package/node_modules/@wasm-audio-decoders/common/package.json +36 -0
  90. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderCommon.js +231 -0
  91. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderWorker.js +129 -0
  92. package/node_modules/@wasm-audio-decoders/common/src/puff/README +67 -0
  93. package/node_modules/@wasm-audio-decoders/common/src/puff/build_puff.js +31 -0
  94. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.c +863 -0
  95. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.h +35 -0
  96. package/node_modules/@wasm-audio-decoders/common/src/utilities.js +3 -0
  97. package/node_modules/@wasm-audio-decoders/common/types.d.ts +7 -0
  98. package/node_modules/mpg123-decoder/README.md +265 -0
  99. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js +185 -0
  100. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js.map +1 -0
  101. package/node_modules/mpg123-decoder/index.js +8 -0
  102. package/node_modules/mpg123-decoder/package.json +58 -0
  103. package/node_modules/mpg123-decoder/src/EmscriptenWasm.js +464 -0
  104. package/node_modules/mpg123-decoder/src/MPEGDecoder.js +200 -0
  105. package/node_modules/mpg123-decoder/src/MPEGDecoderWebWorker.js +21 -0
  106. package/node_modules/mpg123-decoder/types.d.ts +30 -0
  107. package/node_modules/silk-wasm/LICENSE +21 -0
  108. package/node_modules/silk-wasm/README.md +85 -0
  109. package/node_modules/silk-wasm/lib/index.cjs +16 -0
  110. package/node_modules/silk-wasm/lib/index.d.ts +70 -0
  111. package/node_modules/silk-wasm/lib/index.mjs +16 -0
  112. package/node_modules/silk-wasm/lib/silk.wasm +0 -0
  113. package/node_modules/silk-wasm/lib/utils.d.ts +4 -0
  114. package/node_modules/silk-wasm/package.json +39 -0
  115. package/node_modules/simple-yenc/.github/FUNDING.yml +1 -0
  116. package/node_modules/simple-yenc/.prettierignore +1 -0
  117. package/node_modules/simple-yenc/LICENSE +7 -0
  118. package/node_modules/simple-yenc/README.md +163 -0
  119. package/node_modules/simple-yenc/dist/esm.js +1 -0
  120. package/node_modules/simple-yenc/dist/index.js +1 -0
  121. package/node_modules/simple-yenc/package.json +50 -0
  122. package/node_modules/simple-yenc/rollup.config.js +27 -0
  123. package/node_modules/simple-yenc/src/simple-yenc.js +302 -0
  124. package/node_modules/ws/LICENSE +20 -0
  125. package/node_modules/ws/README.md +548 -0
  126. package/node_modules/ws/browser.js +8 -0
  127. package/node_modules/ws/index.js +13 -0
  128. package/node_modules/ws/lib/buffer-util.js +131 -0
  129. package/node_modules/ws/lib/constants.js +19 -0
  130. package/node_modules/ws/lib/event-target.js +292 -0
  131. package/node_modules/ws/lib/extension.js +203 -0
  132. package/node_modules/ws/lib/limiter.js +55 -0
  133. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  134. package/node_modules/ws/lib/receiver.js +706 -0
  135. package/node_modules/ws/lib/sender.js +602 -0
  136. package/node_modules/ws/lib/stream.js +161 -0
  137. package/node_modules/ws/lib/subprotocol.js +62 -0
  138. package/node_modules/ws/lib/validation.js +152 -0
  139. package/node_modules/ws/lib/websocket-server.js +554 -0
  140. package/node_modules/ws/lib/websocket.js +1393 -0
  141. package/node_modules/ws/package.json +69 -0
  142. package/node_modules/ws/wrapper.mjs +8 -0
  143. package/openclaw.plugin.json +16 -0
  144. package/package.json +76 -0
  145. package/scripts/cleanup-legacy-plugins.sh +124 -0
  146. package/scripts/proactive-api-server.ts +369 -0
  147. package/scripts/send-proactive.ts +293 -0
  148. package/scripts/set-markdown.sh +156 -0
  149. package/scripts/test-sendmedia.ts +116 -0
  150. package/scripts/upgrade-via-alt-pkg.sh +307 -0
  151. package/scripts/upgrade-via-npm.ps1 +296 -0
  152. package/scripts/upgrade-via-npm.sh +301 -0
  153. package/scripts/upgrade-via-source.sh +774 -0
  154. package/skills/qqbot-channel/SKILL.md +263 -0
  155. package/skills/qqbot-channel/references/api_references.md +521 -0
  156. package/skills/qqbot-media/SKILL.md +56 -0
  157. package/skills/qqbot-remind/SKILL.md +149 -0
  158. package/src/admin-resolver.ts +140 -0
  159. package/src/api.ts +819 -0
  160. package/src/bot-logs-2026-03-21T11-21-47(2).txt +46 -0
  161. package/src/channel.ts +381 -0
  162. package/src/config.ts +187 -0
  163. package/src/credential-backup.ts +72 -0
  164. package/src/gateway.log +43 -0
  165. package/src/gateway.ts +1404 -0
  166. package/src/image-server.ts +539 -0
  167. package/src/inbound-attachments.ts +304 -0
  168. package/src/known-users.ts +353 -0
  169. package/src/message-queue.ts +169 -0
  170. package/src/onboarding.ts +274 -0
  171. package/src/openclaw-2026-03-21.log +3729 -0
  172. package/src/openclaw-plugin-sdk.d.ts +522 -0
  173. package/src/outbound-deliver.ts +552 -0
  174. package/src/outbound.ts +1266 -0
  175. package/src/proactive.ts +530 -0
  176. package/src/ref-index-store.ts +357 -0
  177. package/src/reply-dispatcher.ts +334 -0
  178. package/src/runtime.ts +14 -0
  179. package/src/session-store.ts +303 -0
  180. package/src/slash-commands.ts +1305 -0
  181. package/src/startup-greeting.ts +98 -0
  182. package/src/stt.ts +86 -0
  183. package/src/tools/channel.ts +281 -0
  184. package/src/tools/remind.ts +296 -0
  185. package/src/types.ts +183 -0
  186. package/src/typing-keepalive.ts +59 -0
  187. package/src/update-checker.ts +179 -0
  188. package/src/user-messages.ts +7 -0
  189. package/src/utils/audio-convert.ts +803 -0
  190. package/src/utils/file-utils.ts +167 -0
  191. package/src/utils/image-size.ts +266 -0
  192. package/src/utils/media-tags.ts +182 -0
  193. package/src/utils/payload.ts +265 -0
  194. package/src/utils/platform.ts +435 -0
  195. package/src/utils/text-parsing.ts +82 -0
  196. package/src/utils/upload-cache.ts +128 -0
  197. package/tsconfig.json +16 -0
@@ -0,0 +1,599 @@
1
+ /**
2
+ * QQ Bot API 鉴权和请求封装
3
+ * [修复版] 已重构为支持多实例并发,消除全局变量冲突
4
+ */
5
+ import { createRequire } from "node:module";
6
+ import os from "node:os";
7
+ import { computeFileHash, getCachedFileInfo, setCachedFileInfo } from "./utils/upload-cache.js";
8
+ import { sanitizeFileName } from "./utils/platform.js";
9
+ const API_BASE = "https://api.sgroup.qq.com";
10
+ const TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
11
+ // ============ Plugin User-Agent ============
12
+ // 格式: QQBotPlugin/{version} (Node/{nodeVersion}; {os})
13
+ // 示例: QQBotPlugin/1.6.0 (Node/22.14.0; darwin)
14
+ const _require = createRequire(import.meta.url);
15
+ let _pluginVersion = "unknown";
16
+ try {
17
+ _pluginVersion = _require("../package.json").version ?? "unknown";
18
+ }
19
+ catch { /* fallback */ }
20
+ export const PLUGIN_USER_AGENT = `QQBotPlugin/${_pluginVersion} (Node/${process.versions.node}; ${os.platform()})`;
21
+ // 运行时配置
22
+ let currentMarkdownSupport = false;
23
+ let onMessageSentHook = null;
24
+ /**
25
+ * 注册出站消息回调
26
+ * 当消息发送成功且 QQ 返回 ref_idx 时,自动回调此函数
27
+ * 用于在最底层统一缓存 bot 出站消息的 refIdx
28
+ */
29
+ export function onMessageSent(callback) {
30
+ onMessageSentHook = callback;
31
+ }
32
+ /**
33
+ * 初始化 API 配置
34
+ * @param options.markdownSupport - 是否支持 markdown 消息(默认 false,需要机器人具备该权限才能启用)
35
+ */
36
+ export function initApiConfig(options) {
37
+ currentMarkdownSupport = options.markdownSupport === true;
38
+ }
39
+ /**
40
+ * 获取当前是否支持 markdown
41
+ */
42
+ export function isMarkdownSupport() {
43
+ return currentMarkdownSupport;
44
+ }
45
+ // =========================================================================
46
+ // 🚀 [核心修复] 将全局状态改为 Map,按 appId 隔离,彻底解决多账号串号问题
47
+ // =========================================================================
48
+ const tokenCacheMap = new Map();
49
+ const tokenFetchPromises = new Map();
50
+ /**
51
+ * 获取 AccessToken(带缓存 + singleflight 并发安全)
52
+ *
53
+ * 使用 singleflight 模式:当多个请求同时发现 Token 过期时,
54
+ * 只有第一个请求会真正去获取新 Token,其他请求复用同一个 Promise。
55
+ *
56
+ * 按 appId 隔离,支持多机器人并发请求。
57
+ */
58
+ export async function getAccessToken(appId, clientSecret) {
59
+ const normalizedAppId = String(appId).trim();
60
+ const cachedToken = tokenCacheMap.get(normalizedAppId);
61
+ // 检查缓存:未过期时复用
62
+ // 提前刷新阈值:取 expiresIn 的 1/3 和 5 分钟的较小值,避免短有效期 token 永远被判定过期
63
+ const REFRESH_AHEAD_MS = cachedToken
64
+ ? Math.min(5 * 60 * 1000, (cachedToken.expiresAt - Date.now()) / 3)
65
+ : 0;
66
+ if (cachedToken && Date.now() < cachedToken.expiresAt - REFRESH_AHEAD_MS) {
67
+ return cachedToken.token;
68
+ }
69
+ // Singleflight: 如果当前 appId 已有进行中的 Token 获取请求,复用它
70
+ let fetchPromise = tokenFetchPromises.get(normalizedAppId);
71
+ if (fetchPromise) {
72
+ console.log(`[qqbot-api:${normalizedAppId}] Token fetch in progress, waiting for existing request...`);
73
+ return fetchPromise;
74
+ }
75
+ // 创建新的 Token 获取 Promise(singleflight 入口)
76
+ fetchPromise = (async () => {
77
+ try {
78
+ return await doFetchToken(normalizedAppId, clientSecret);
79
+ }
80
+ finally {
81
+ // 无论成功失败,都清除 Promise 缓存
82
+ tokenFetchPromises.delete(normalizedAppId);
83
+ }
84
+ })();
85
+ tokenFetchPromises.set(normalizedAppId, fetchPromise);
86
+ return fetchPromise;
87
+ }
88
+ /**
89
+ * 实际执行 Token 获取的内部函数
90
+ */
91
+ async function doFetchToken(appId, clientSecret) {
92
+ const requestBody = { appId, clientSecret };
93
+ const requestHeaders = { "Content-Type": "application/json", "User-Agent": PLUGIN_USER_AGENT };
94
+ // 打印请求信息(隐藏敏感信息)
95
+ console.log(`[qqbot-api:${appId}] >>> POST ${TOKEN_URL}`);
96
+ let response;
97
+ try {
98
+ response = await fetch(TOKEN_URL, {
99
+ method: "POST",
100
+ headers: requestHeaders,
101
+ body: JSON.stringify(requestBody),
102
+ });
103
+ }
104
+ catch (err) {
105
+ console.error(`[qqbot-api:${appId}] <<< Network error:`, err);
106
+ throw new Error(`Network error getting access_token: ${err instanceof Error ? err.message : String(err)}`);
107
+ }
108
+ // 打印响应头
109
+ const responseHeaders = {};
110
+ response.headers.forEach((value, key) => {
111
+ responseHeaders[key] = value;
112
+ });
113
+ const tokenTraceId = response.headers.get("x-tps-trace-id") ?? "";
114
+ console.log(`[qqbot-api:${appId}] <<< Status: ${response.status} ${response.statusText}${tokenTraceId ? ` | TraceId: ${tokenTraceId}` : ""}`);
115
+ let data;
116
+ let rawBody;
117
+ try {
118
+ rawBody = await response.text();
119
+ // 隐藏 token 值
120
+ const logBody = rawBody.replace(/"access_token"\s*:\s*"[^"]+"/g, '"access_token": "***"');
121
+ console.log(`[qqbot-api:${appId}] <<< Body:`, logBody);
122
+ data = JSON.parse(rawBody);
123
+ }
124
+ catch (err) {
125
+ console.error(`[qqbot-api:${appId}] <<< Parse error:`, err);
126
+ throw new Error(`Failed to parse access_token response: ${err instanceof Error ? err.message : String(err)}`);
127
+ }
128
+ if (!data.access_token) {
129
+ throw new Error(`Failed to get access_token: ${JSON.stringify(data)}`);
130
+ }
131
+ const expiresAt = Date.now() + (data.expires_in ?? 7200) * 1000;
132
+ tokenCacheMap.set(appId, {
133
+ token: data.access_token,
134
+ expiresAt,
135
+ appId,
136
+ });
137
+ console.log(`[qqbot-api:${appId}] Token cached, expires at: ${new Date(expiresAt).toISOString()}`);
138
+ return data.access_token;
139
+ }
140
+ /**
141
+ * 清除 Token 缓存
142
+ * @param appId 选填。如果有,只清空特定账号的缓存;如果没有,清空所有账号。
143
+ */
144
+ export function clearTokenCache(appId) {
145
+ if (appId) {
146
+ const normalizedAppId = String(appId).trim();
147
+ tokenCacheMap.delete(normalizedAppId);
148
+ console.log(`[qqbot-api:${normalizedAppId}] Token cache cleared manually.`);
149
+ }
150
+ else {
151
+ tokenCacheMap.clear();
152
+ console.log(`[qqbot-api] All token caches cleared.`);
153
+ }
154
+ }
155
+ /**
156
+ * 获取 Token 缓存状态(用于监控)
157
+ */
158
+ export function getTokenStatus(appId) {
159
+ if (tokenFetchPromises.has(appId)) {
160
+ return { status: "refreshing", expiresAt: tokenCacheMap.get(appId)?.expiresAt ?? null };
161
+ }
162
+ const cached = tokenCacheMap.get(appId);
163
+ if (!cached) {
164
+ return { status: "none", expiresAt: null };
165
+ }
166
+ const remaining = cached.expiresAt - Date.now();
167
+ const isValid = remaining > Math.min(5 * 60 * 1000, remaining / 3);
168
+ return { status: isValid ? "valid" : "expired", expiresAt: cached.expiresAt };
169
+ }
170
+ /**
171
+ * 获取全局唯一的消息序号(范围 0 ~ 65535)
172
+ * 使用毫秒级时间戳低位 + 随机数异或混合,无状态,避免碰撞
173
+ */
174
+ export function getNextMsgSeq(_msgId) {
175
+ const timePart = Date.now() % 100000000; // 毫秒时间戳后8位
176
+ const random = Math.floor(Math.random() * 65536); // 0~65535
177
+ return (timePart ^ random) % 65536; // 异或混合后限制在 0~65535
178
+ }
179
+ // API 请求超时配置(毫秒)
180
+ const DEFAULT_API_TIMEOUT = 30000; // 默认 30 秒
181
+ const FILE_UPLOAD_TIMEOUT = 120000; // 文件上传 120 秒
182
+ /**
183
+ * API 请求封装
184
+ */
185
+ export async function apiRequest(accessToken, method, path, body, timeoutMs) {
186
+ const url = `${API_BASE}${path}`;
187
+ const headers = {
188
+ Authorization: `QQBot ${accessToken}`,
189
+ "Content-Type": "application/json",
190
+ "User-Agent": PLUGIN_USER_AGENT,
191
+ };
192
+ const isFileUpload = path.includes("/files");
193
+ const timeout = timeoutMs ?? (isFileUpload ? FILE_UPLOAD_TIMEOUT : DEFAULT_API_TIMEOUT);
194
+ const controller = new AbortController();
195
+ const timeoutId = setTimeout(() => {
196
+ controller.abort();
197
+ }, timeout);
198
+ const options = {
199
+ method,
200
+ headers,
201
+ signal: controller.signal,
202
+ };
203
+ if (body) {
204
+ options.body = JSON.stringify(body);
205
+ }
206
+ // 打印请求信息
207
+ console.log(`[qqbot-api] >>> ${method} ${url} (timeout: ${timeout}ms)`);
208
+ if (body) {
209
+ const logBody = { ...body };
210
+ if (typeof logBody.file_data === "string") {
211
+ logBody.file_data = `<base64 ${logBody.file_data.length} chars>`;
212
+ }
213
+ console.log(`[qqbot-api] >>> Body:`, JSON.stringify(logBody));
214
+ }
215
+ let res;
216
+ try {
217
+ res = await fetch(url, options);
218
+ }
219
+ catch (err) {
220
+ clearTimeout(timeoutId);
221
+ if (err instanceof Error && err.name === "AbortError") {
222
+ console.error(`[qqbot-api] <<< Request timeout after ${timeout}ms`);
223
+ throw new Error(`Request timeout[${path}]: exceeded ${timeout}ms`);
224
+ }
225
+ console.error(`[qqbot-api] <<< Network error:`, err);
226
+ throw new Error(`Network error [${path}]: ${err instanceof Error ? err.message : String(err)}`);
227
+ }
228
+ finally {
229
+ clearTimeout(timeoutId);
230
+ }
231
+ const responseHeaders = {};
232
+ res.headers.forEach((value, key) => {
233
+ responseHeaders[key] = value;
234
+ });
235
+ const traceId = res.headers.get("x-tps-trace-id") ?? "";
236
+ console.log(`[qqbot-api] <<< Status: ${res.status} ${res.statusText}${traceId ? ` | TraceId: ${traceId}` : ""}`);
237
+ let data;
238
+ let rawBody;
239
+ try {
240
+ rawBody = await res.text();
241
+ console.log(`[qqbot-api] <<< Body:`, rawBody);
242
+ data = JSON.parse(rawBody);
243
+ }
244
+ catch (err) {
245
+ throw new Error(`Failed to parse response[${path}]: ${err instanceof Error ? err.message : String(err)}`);
246
+ }
247
+ if (!res.ok) {
248
+ const error = data;
249
+ throw new Error(`API Error [${path}]: ${error.message ?? JSON.stringify(data)}`);
250
+ }
251
+ return data;
252
+ }
253
+ // ============ 上传重试(指数退避) ============
254
+ const UPLOAD_MAX_RETRIES = 2;
255
+ const UPLOAD_BASE_DELAY_MS = 1000;
256
+ async function apiRequestWithRetry(accessToken, method, path, body, maxRetries = UPLOAD_MAX_RETRIES) {
257
+ let lastError = null;
258
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
259
+ try {
260
+ return await apiRequest(accessToken, method, path, body);
261
+ }
262
+ catch (err) {
263
+ lastError = err instanceof Error ? err : new Error(String(err));
264
+ const errMsg = lastError.message;
265
+ if (errMsg.includes("400") || errMsg.includes("401") || errMsg.includes("Invalid") ||
266
+ errMsg.includes("上传超时") || errMsg.includes("timeout") || errMsg.includes("Timeout")) {
267
+ throw lastError;
268
+ }
269
+ if (attempt < maxRetries) {
270
+ const delay = UPLOAD_BASE_DELAY_MS * Math.pow(2, attempt);
271
+ console.log(`[qqbot-api] Upload attempt ${attempt + 1} failed, retrying in ${delay}ms: ${errMsg.slice(0, 100)}`);
272
+ await new Promise(resolve => setTimeout(resolve, delay));
273
+ }
274
+ }
275
+ }
276
+ throw lastError;
277
+ }
278
+ export async function getGatewayUrl(accessToken) {
279
+ const data = await apiRequest(accessToken, "GET", "/gateway");
280
+ return data.url;
281
+ }
282
+ /**
283
+ * 发送消息并自动触发 refIdx 回调
284
+ * 所有消息发送函数统一经过此处,确保每条出站消息的 refIdx 都被捕获
285
+ */
286
+ async function sendAndNotify(accessToken, method, path, body, meta) {
287
+ const result = await apiRequest(accessToken, method, path, body);
288
+ if (result.ext_info?.ref_idx && onMessageSentHook) {
289
+ try {
290
+ onMessageSentHook(result.ext_info.ref_idx, meta);
291
+ }
292
+ catch (err) {
293
+ console.error(`[qqbot-api] onMessageSent hook error: ${err}`);
294
+ }
295
+ }
296
+ return result;
297
+ }
298
+ function buildMessageBody(content, msgId, msgSeq, messageReference) {
299
+ const body = currentMarkdownSupport
300
+ ? {
301
+ markdown: { content },
302
+ msg_type: 2,
303
+ msg_seq: msgSeq,
304
+ }
305
+ : {
306
+ content,
307
+ msg_type: 0,
308
+ msg_seq: msgSeq,
309
+ };
310
+ if (msgId) {
311
+ body.msg_id = msgId;
312
+ }
313
+ if (messageReference && !currentMarkdownSupport) {
314
+ body.message_reference = { message_id: messageReference };
315
+ }
316
+ return body;
317
+ }
318
+ export async function sendC2CMessage(accessToken, openid, content, msgId, messageReference) {
319
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
320
+ const body = buildMessageBody(content, msgId, msgSeq, messageReference);
321
+ return sendAndNotify(accessToken, "POST", `/v2/users/${openid}/messages`, body, { text: content });
322
+ }
323
+ export async function sendC2CInputNotify(accessToken, openid, msgId, inputSecond = 60) {
324
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
325
+ const body = {
326
+ msg_type: 6,
327
+ input_notify: {
328
+ input_type: 1,
329
+ input_second: inputSecond,
330
+ },
331
+ msg_seq: msgSeq,
332
+ ...(msgId ? { msg_id: msgId } : {}),
333
+ };
334
+ const response = await apiRequest(accessToken, "POST", `/v2/users/${openid}/messages`, body);
335
+ return { refIdx: response.ext_info?.ref_idx };
336
+ }
337
+ export async function sendChannelMessage(accessToken, channelId, content, msgId) {
338
+ return apiRequest(accessToken, "POST", `/channels/${channelId}/messages`, {
339
+ content,
340
+ ...(msgId ? { msg_id: msgId } : {}),
341
+ });
342
+ }
343
+ /**
344
+ * 发送频道私信消息
345
+ * @param guildId - 私信会话的 guild_id(由 DIRECT_MESSAGE_CREATE 事件提供)
346
+ * @param msgId - 被动回复时必填
347
+ */
348
+ export async function sendDmMessage(accessToken, guildId, content, msgId) {
349
+ return apiRequest(accessToken, "POST", `/dms/${guildId}/messages`, {
350
+ content,
351
+ ...(msgId ? { msg_id: msgId } : {}),
352
+ });
353
+ }
354
+ export async function sendGroupMessage(accessToken, groupOpenid, content, msgId) {
355
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
356
+ const body = buildMessageBody(content, msgId, msgSeq);
357
+ return apiRequest(accessToken, "POST", `/v2/groups/${groupOpenid}/messages`, body);
358
+ }
359
+ function buildProactiveMessageBody(content) {
360
+ if (!content || content.trim().length === 0) {
361
+ throw new Error("主动消息内容不能为空 (markdown.content is empty)");
362
+ }
363
+ if (currentMarkdownSupport) {
364
+ return { markdown: { content }, msg_type: 2 };
365
+ }
366
+ else {
367
+ return { content, msg_type: 0 };
368
+ }
369
+ }
370
+ export async function sendProactiveC2CMessage(accessToken, openid, content) {
371
+ const body = buildProactiveMessageBody(content);
372
+ return sendAndNotify(accessToken, "POST", `/v2/users/${openid}/messages`, body, { text: content });
373
+ }
374
+ export async function sendProactiveGroupMessage(accessToken, groupOpenid, content) {
375
+ const body = buildProactiveMessageBody(content);
376
+ return apiRequest(accessToken, "POST", `/v2/groups/${groupOpenid}/messages`, body);
377
+ }
378
+ // ============ 富媒体消息支持 ============
379
+ export var MediaFileType;
380
+ (function (MediaFileType) {
381
+ MediaFileType[MediaFileType["IMAGE"] = 1] = "IMAGE";
382
+ MediaFileType[MediaFileType["VIDEO"] = 2] = "VIDEO";
383
+ MediaFileType[MediaFileType["VOICE"] = 3] = "VOICE";
384
+ MediaFileType[MediaFileType["FILE"] = 4] = "FILE";
385
+ })(MediaFileType || (MediaFileType = {}));
386
+ export async function uploadC2CMedia(accessToken, openid, fileType, url, fileData, srvSendMsg = false, fileName) {
387
+ if (!url && !fileData)
388
+ throw new Error("uploadC2CMedia: url or fileData is required");
389
+ if (fileData) {
390
+ const contentHash = computeFileHash(fileData);
391
+ const cachedInfo = getCachedFileInfo(contentHash, "c2c", openid, fileType);
392
+ if (cachedInfo) {
393
+ return { file_uuid: "", file_info: cachedInfo, ttl: 0 };
394
+ }
395
+ }
396
+ const body = { file_type: fileType, srv_send_msg: srvSendMsg };
397
+ if (url)
398
+ body.url = url;
399
+ else if (fileData)
400
+ body.file_data = fileData;
401
+ if (fileType === MediaFileType.FILE && fileName)
402
+ body.file_name = sanitizeFileName(fileName);
403
+ const result = await apiRequestWithRetry(accessToken, "POST", `/v2/users/${openid}/files`, body);
404
+ if (fileData && result.file_info && result.ttl > 0) {
405
+ const contentHash = computeFileHash(fileData);
406
+ setCachedFileInfo(contentHash, "c2c", openid, fileType, result.file_info, result.file_uuid, result.ttl);
407
+ }
408
+ return result;
409
+ }
410
+ export async function uploadGroupMedia(accessToken, groupOpenid, fileType, url, fileData, srvSendMsg = false, fileName) {
411
+ if (!url && !fileData)
412
+ throw new Error("uploadGroupMedia: url or fileData is required");
413
+ if (fileData) {
414
+ const contentHash = computeFileHash(fileData);
415
+ const cachedInfo = getCachedFileInfo(contentHash, "group", groupOpenid, fileType);
416
+ if (cachedInfo) {
417
+ return { file_uuid: "", file_info: cachedInfo, ttl: 0 };
418
+ }
419
+ }
420
+ const body = { file_type: fileType, srv_send_msg: srvSendMsg };
421
+ if (url)
422
+ body.url = url;
423
+ else if (fileData)
424
+ body.file_data = fileData;
425
+ if (fileType === MediaFileType.FILE && fileName)
426
+ body.file_name = sanitizeFileName(fileName);
427
+ const result = await apiRequestWithRetry(accessToken, "POST", `/v2/groups/${groupOpenid}/files`, body);
428
+ if (fileData && result.file_info && result.ttl > 0) {
429
+ const contentHash = computeFileHash(fileData);
430
+ setCachedFileInfo(contentHash, "group", groupOpenid, fileType, result.file_info, result.file_uuid, result.ttl);
431
+ }
432
+ return result;
433
+ }
434
+ export async function sendC2CMediaMessage(accessToken, openid, fileInfo, msgId, content, meta) {
435
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
436
+ return sendAndNotify(accessToken, "POST", `/v2/users/${openid}/messages`, {
437
+ msg_type: 7,
438
+ media: { file_info: fileInfo },
439
+ msg_seq: msgSeq,
440
+ ...(content ? { content } : {}),
441
+ ...(msgId ? { msg_id: msgId } : {}),
442
+ }, meta ?? { text: content });
443
+ }
444
+ export async function sendGroupMediaMessage(accessToken, groupOpenid, fileInfo, msgId, content) {
445
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
446
+ return apiRequest(accessToken, "POST", `/v2/groups/${groupOpenid}/messages`, {
447
+ msg_type: 7,
448
+ media: { file_info: fileInfo },
449
+ msg_seq: msgSeq,
450
+ ...(content ? { content } : {}),
451
+ ...(msgId ? { msg_id: msgId } : {}),
452
+ });
453
+ }
454
+ export async function sendC2CImageMessage(accessToken, openid, imageUrl, msgId, content, localPath) {
455
+ let uploadResult;
456
+ const isBase64 = imageUrl.startsWith("data:");
457
+ if (isBase64) {
458
+ const matches = imageUrl.match(/^data:([^;]+);base64,(.+)$/);
459
+ if (!matches)
460
+ throw new Error("Invalid Base64 Data URL format");
461
+ uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.IMAGE, undefined, matches[2], false);
462
+ }
463
+ else {
464
+ uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.IMAGE, imageUrl, undefined, false);
465
+ }
466
+ const meta = {
467
+ text: content,
468
+ mediaType: "image",
469
+ ...(!isBase64 ? { mediaUrl: imageUrl } : {}),
470
+ ...(localPath ? { mediaLocalPath: localPath } : {}),
471
+ };
472
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, content, meta);
473
+ }
474
+ export async function sendGroupImageMessage(accessToken, groupOpenid, imageUrl, msgId, content) {
475
+ let uploadResult;
476
+ const isBase64 = imageUrl.startsWith("data:");
477
+ if (isBase64) {
478
+ const matches = imageUrl.match(/^data:([^;]+);base64,(.+)$/);
479
+ if (!matches)
480
+ throw new Error("Invalid Base64 Data URL format");
481
+ uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.IMAGE, undefined, matches[2], false);
482
+ }
483
+ else {
484
+ uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.IMAGE, imageUrl, undefined, false);
485
+ }
486
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId, content);
487
+ }
488
+ export async function sendC2CVoiceMessage(accessToken, openid, voiceBase64, voiceUrl, msgId, ttsText, filePath) {
489
+ const uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.VOICE, voiceUrl, voiceBase64, false);
490
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, undefined, {
491
+ mediaType: "voice",
492
+ ...(ttsText ? { ttsText } : {}),
493
+ ...(filePath ? { mediaLocalPath: filePath } : {})
494
+ });
495
+ }
496
+ export async function sendGroupVoiceMessage(accessToken, groupOpenid, voiceBase64, voiceUrl, msgId) {
497
+ const uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.VOICE, voiceUrl, voiceBase64, false);
498
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId);
499
+ }
500
+ export async function sendC2CFileMessage(accessToken, openid, fileBase64, fileUrl, msgId, fileName, localFilePath) {
501
+ const uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.FILE, fileUrl, fileBase64, false, fileName);
502
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, undefined, { mediaType: "file", mediaUrl: fileUrl, mediaLocalPath: localFilePath ?? fileName });
503
+ }
504
+ export async function sendGroupFileMessage(accessToken, groupOpenid, fileBase64, fileUrl, msgId, fileName) {
505
+ const uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.FILE, fileUrl, fileBase64, false, fileName);
506
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId);
507
+ }
508
+ export async function sendC2CVideoMessage(accessToken, openid, videoUrl, videoBase64, msgId, content, localPath) {
509
+ const uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.VIDEO, videoUrl, videoBase64, false);
510
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, content, { text: content, mediaType: "video", ...(videoUrl ? { mediaUrl: videoUrl } : {}), ...(localPath ? { mediaLocalPath: localPath } : {}) });
511
+ }
512
+ export async function sendGroupVideoMessage(accessToken, groupOpenid, videoUrl, videoBase64, msgId, content) {
513
+ const uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.VIDEO, videoUrl, videoBase64, false);
514
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId, content);
515
+ }
516
+ const backgroundRefreshControllers = new Map();
517
+ export function startBackgroundTokenRefresh(appId, clientSecret, options) {
518
+ if (backgroundRefreshControllers.has(appId)) {
519
+ console.log(`[qqbot-api:${appId}] Background token refresh already running`);
520
+ return;
521
+ }
522
+ const { refreshAheadMs = 5 * 60 * 1000, randomOffsetMs = 30 * 1000, minRefreshIntervalMs = 60 * 1000, retryDelayMs = 5 * 1000, log, } = options ?? {};
523
+ const controller = new AbortController();
524
+ backgroundRefreshControllers.set(appId, controller);
525
+ const signal = controller.signal;
526
+ const refreshLoop = async () => {
527
+ log?.info?.(`[qqbot-api:${appId}] Background token refresh started`);
528
+ while (!signal.aborted) {
529
+ try {
530
+ await getAccessToken(appId, clientSecret);
531
+ const cached = tokenCacheMap.get(appId);
532
+ if (cached) {
533
+ const expiresIn = cached.expiresAt - Date.now();
534
+ const randomOffset = Math.random() * randomOffsetMs;
535
+ const refreshIn = Math.max(expiresIn - refreshAheadMs - randomOffset, minRefreshIntervalMs);
536
+ log?.debug?.(`[qqbot-api:${appId}] Token valid, next refresh in ${Math.round(refreshIn / 1000)}s`);
537
+ await sleep(refreshIn, signal);
538
+ }
539
+ else {
540
+ log?.debug?.(`[qqbot-api:${appId}] No cached token, retrying soon`);
541
+ await sleep(minRefreshIntervalMs, signal);
542
+ }
543
+ }
544
+ catch (err) {
545
+ if (signal.aborted)
546
+ break;
547
+ log?.error?.(`[qqbot-api:${appId}] Background token refresh failed: ${err}`);
548
+ await sleep(retryDelayMs, signal);
549
+ }
550
+ }
551
+ backgroundRefreshControllers.delete(appId);
552
+ log?.info?.(`[qqbot-api:${appId}] Background token refresh stopped`);
553
+ };
554
+ refreshLoop().catch((err) => {
555
+ backgroundRefreshControllers.delete(appId);
556
+ log?.error?.(`[qqbot-api:${appId}] Background token refresh crashed: ${err}`);
557
+ });
558
+ }
559
+ /**
560
+ * 停止后台 Token 刷新
561
+ * @param appId 选填。如果有,仅停止该账号的定时刷新。
562
+ */
563
+ export function stopBackgroundTokenRefresh(appId) {
564
+ if (appId) {
565
+ const controller = backgroundRefreshControllers.get(appId);
566
+ if (controller) {
567
+ controller.abort();
568
+ backgroundRefreshControllers.delete(appId);
569
+ }
570
+ }
571
+ else {
572
+ for (const controller of backgroundRefreshControllers.values()) {
573
+ controller.abort();
574
+ }
575
+ backgroundRefreshControllers.clear();
576
+ }
577
+ }
578
+ export function isBackgroundTokenRefreshRunning(appId) {
579
+ if (appId)
580
+ return backgroundRefreshControllers.has(appId);
581
+ return backgroundRefreshControllers.size > 0;
582
+ }
583
+ async function sleep(ms, signal) {
584
+ return new Promise((resolve, reject) => {
585
+ const timer = setTimeout(resolve, ms);
586
+ if (signal) {
587
+ if (signal.aborted) {
588
+ clearTimeout(timer);
589
+ reject(new Error("Aborted"));
590
+ return;
591
+ }
592
+ const onAbort = () => {
593
+ clearTimeout(timer);
594
+ reject(new Error("Aborted"));
595
+ };
596
+ signal.addEventListener("abort", onAbort, { once: true });
597
+ }
598
+ });
599
+ }
@@ -0,0 +1,11 @@
1
+ import { type ChannelPlugin } from "openclaw/plugin-sdk";
2
+ import type { ResolvedQQBotAccount } from "./types.js";
3
+ /** QQ Bot 单条消息文本长度上限 */
4
+ export declare const TEXT_CHUNK_LIMIT = 5000;
5
+ /**
6
+ * Markdown 感知的文本分块函数
7
+ * 委托给 SDK 内置的 channel.text.chunkMarkdownText
8
+ * 支持代码块自动关闭/重开、括号感知等
9
+ */
10
+ export declare function chunkText(text: string, limit: number): string[];
11
+ export declare const qqbotPlugin: ChannelPlugin<ResolvedQQBotAccount>;