@leoqlin/openclaw-qqbot 1.6.7-alpha1

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 (218) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +484 -0
  3. package/README.zh.md +479 -0
  4. package/bin/qqbot-cli.js +243 -0
  5. package/dist/index.d.ts +17 -0
  6. package/dist/index.js +26 -0
  7. package/dist/src/admin-resolver.d.ts +33 -0
  8. package/dist/src/admin-resolver.js +157 -0
  9. package/dist/src/api.d.ts +301 -0
  10. package/dist/src/api.js +890 -0
  11. package/dist/src/channel.d.ts +29 -0
  12. package/dist/src/channel.js +452 -0
  13. package/dist/src/config.d.ts +56 -0
  14. package/dist/src/config.js +278 -0
  15. package/dist/src/credential-backup.d.ts +31 -0
  16. package/dist/src/credential-backup.js +66 -0
  17. package/dist/src/deliver-debounce.d.ts +74 -0
  18. package/dist/src/deliver-debounce.js +174 -0
  19. package/dist/src/gateway.d.ts +18 -0
  20. package/dist/src/gateway.js +2005 -0
  21. package/dist/src/group-history.d.ts +136 -0
  22. package/dist/src/group-history.js +226 -0
  23. package/dist/src/image-server.d.ts +87 -0
  24. package/dist/src/image-server.js +570 -0
  25. package/dist/src/inbound-attachments.d.ts +60 -0
  26. package/dist/src/inbound-attachments.js +248 -0
  27. package/dist/src/known-users.d.ts +100 -0
  28. package/dist/src/known-users.js +263 -0
  29. package/dist/src/message-gating.d.ts +53 -0
  30. package/dist/src/message-gating.js +107 -0
  31. package/dist/src/message-queue.d.ts +89 -0
  32. package/dist/src/message-queue.js +257 -0
  33. package/dist/src/onboarding.d.ts +10 -0
  34. package/dist/src/onboarding.js +203 -0
  35. package/dist/src/outbound-deliver.d.ts +48 -0
  36. package/dist/src/outbound-deliver.js +392 -0
  37. package/dist/src/outbound.d.ts +205 -0
  38. package/dist/src/outbound.js +938 -0
  39. package/dist/src/proactive.d.ts +170 -0
  40. package/dist/src/proactive.js +399 -0
  41. package/dist/src/ref-index-store.d.ts +101 -0
  42. package/dist/src/ref-index-store.js +298 -0
  43. package/dist/src/reply-dispatcher.d.ts +35 -0
  44. package/dist/src/reply-dispatcher.js +311 -0
  45. package/dist/src/request-context.d.ts +25 -0
  46. package/dist/src/request-context.js +37 -0
  47. package/dist/src/runtime.d.ts +3 -0
  48. package/dist/src/runtime.js +10 -0
  49. package/dist/src/session-store.d.ts +52 -0
  50. package/dist/src/session-store.js +254 -0
  51. package/dist/src/slash-commands.d.ts +77 -0
  52. package/dist/src/slash-commands.js +1866 -0
  53. package/dist/src/startup-greeting.d.ts +30 -0
  54. package/dist/src/startup-greeting.js +97 -0
  55. package/dist/src/streaming.d.ts +247 -0
  56. package/dist/src/streaming.js +899 -0
  57. package/dist/src/stt.d.ts +21 -0
  58. package/dist/src/stt.js +70 -0
  59. package/dist/src/tools/channel.d.ts +16 -0
  60. package/dist/src/tools/channel.js +234 -0
  61. package/dist/src/tools/remind.d.ts +2 -0
  62. package/dist/src/tools/remind.js +256 -0
  63. package/dist/src/types.d.ts +367 -0
  64. package/dist/src/types.js +17 -0
  65. package/dist/src/typing-keepalive.d.ts +27 -0
  66. package/dist/src/typing-keepalive.js +64 -0
  67. package/dist/src/update-checker.d.ts +36 -0
  68. package/dist/src/update-checker.js +171 -0
  69. package/dist/src/utils/audio-convert.d.ts +98 -0
  70. package/dist/src/utils/audio-convert.js +755 -0
  71. package/dist/src/utils/chunked-upload.d.ts +68 -0
  72. package/dist/src/utils/chunked-upload.js +341 -0
  73. package/dist/src/utils/file-utils.d.ts +61 -0
  74. package/dist/src/utils/file-utils.js +172 -0
  75. package/dist/src/utils/image-size.d.ts +51 -0
  76. package/dist/src/utils/image-size.js +234 -0
  77. package/dist/src/utils/media-send.d.ts +158 -0
  78. package/dist/src/utils/media-send.js +499 -0
  79. package/dist/src/utils/media-tags.d.ts +14 -0
  80. package/dist/src/utils/media-tags.js +165 -0
  81. package/dist/src/utils/payload.d.ts +112 -0
  82. package/dist/src/utils/payload.js +186 -0
  83. package/dist/src/utils/pkg-version.d.ts +5 -0
  84. package/dist/src/utils/pkg-version.js +61 -0
  85. package/dist/src/utils/platform.d.ts +137 -0
  86. package/dist/src/utils/platform.js +390 -0
  87. package/dist/src/utils/ssrf-guard.d.ts +25 -0
  88. package/dist/src/utils/ssrf-guard.js +91 -0
  89. package/dist/src/utils/text-parsing.d.ts +36 -0
  90. package/dist/src/utils/text-parsing.js +75 -0
  91. package/dist/src/utils/upload-cache.d.ts +34 -0
  92. package/dist/src/utils/upload-cache.js +93 -0
  93. package/index.ts +31 -0
  94. package/node_modules/@eshaz/web-worker/LICENSE +201 -0
  95. package/node_modules/@eshaz/web-worker/README.md +134 -0
  96. package/node_modules/@eshaz/web-worker/browser.js +17 -0
  97. package/node_modules/@eshaz/web-worker/cjs/browser.js +16 -0
  98. package/node_modules/@eshaz/web-worker/cjs/node.js +219 -0
  99. package/node_modules/@eshaz/web-worker/index.d.ts +4 -0
  100. package/node_modules/@eshaz/web-worker/node.js +223 -0
  101. package/node_modules/@eshaz/web-worker/package.json +54 -0
  102. package/node_modules/@wasm-audio-decoders/common/index.js +5 -0
  103. package/node_modules/@wasm-audio-decoders/common/package.json +36 -0
  104. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderCommon.js +231 -0
  105. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderWorker.js +129 -0
  106. package/node_modules/@wasm-audio-decoders/common/src/puff/README +67 -0
  107. package/node_modules/@wasm-audio-decoders/common/src/puff/build_puff.js +31 -0
  108. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.c +863 -0
  109. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.h +35 -0
  110. package/node_modules/@wasm-audio-decoders/common/src/utilities.js +3 -0
  111. package/node_modules/@wasm-audio-decoders/common/types.d.ts +7 -0
  112. package/node_modules/mpg123-decoder/README.md +265 -0
  113. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js +185 -0
  114. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js.map +1 -0
  115. package/node_modules/mpg123-decoder/index.js +8 -0
  116. package/node_modules/mpg123-decoder/package.json +58 -0
  117. package/node_modules/mpg123-decoder/src/EmscriptenWasm.js +464 -0
  118. package/node_modules/mpg123-decoder/src/MPEGDecoder.js +200 -0
  119. package/node_modules/mpg123-decoder/src/MPEGDecoderWebWorker.js +21 -0
  120. package/node_modules/mpg123-decoder/types.d.ts +30 -0
  121. package/node_modules/silk-wasm/LICENSE +21 -0
  122. package/node_modules/silk-wasm/README.md +85 -0
  123. package/node_modules/silk-wasm/lib/index.cjs +16 -0
  124. package/node_modules/silk-wasm/lib/index.d.ts +70 -0
  125. package/node_modules/silk-wasm/lib/index.mjs +16 -0
  126. package/node_modules/silk-wasm/lib/silk.wasm +0 -0
  127. package/node_modules/silk-wasm/lib/utils.d.ts +4 -0
  128. package/node_modules/silk-wasm/package.json +39 -0
  129. package/node_modules/simple-yenc/.github/FUNDING.yml +1 -0
  130. package/node_modules/simple-yenc/.prettierignore +1 -0
  131. package/node_modules/simple-yenc/LICENSE +7 -0
  132. package/node_modules/simple-yenc/README.md +163 -0
  133. package/node_modules/simple-yenc/dist/esm.js +1 -0
  134. package/node_modules/simple-yenc/dist/index.js +1 -0
  135. package/node_modules/simple-yenc/package.json +50 -0
  136. package/node_modules/simple-yenc/rollup.config.js +27 -0
  137. package/node_modules/simple-yenc/src/simple-yenc.js +302 -0
  138. package/node_modules/ws/LICENSE +20 -0
  139. package/node_modules/ws/README.md +548 -0
  140. package/node_modules/ws/browser.js +8 -0
  141. package/node_modules/ws/index.js +22 -0
  142. package/node_modules/ws/lib/buffer-util.js +131 -0
  143. package/node_modules/ws/lib/constants.js +19 -0
  144. package/node_modules/ws/lib/event-target.js +292 -0
  145. package/node_modules/ws/lib/extension.js +203 -0
  146. package/node_modules/ws/lib/limiter.js +55 -0
  147. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  148. package/node_modules/ws/lib/receiver.js +706 -0
  149. package/node_modules/ws/lib/sender.js +602 -0
  150. package/node_modules/ws/lib/stream.js +161 -0
  151. package/node_modules/ws/lib/subprotocol.js +62 -0
  152. package/node_modules/ws/lib/validation.js +152 -0
  153. package/node_modules/ws/lib/websocket-server.js +554 -0
  154. package/node_modules/ws/lib/websocket.js +1393 -0
  155. package/node_modules/ws/package.json +70 -0
  156. package/node_modules/ws/wrapper.mjs +21 -0
  157. package/openclaw.plugin.json +17 -0
  158. package/package.json +70 -0
  159. package/preload.cjs +33 -0
  160. package/scripts/cleanup-legacy-plugins.sh +124 -0
  161. package/scripts/link-sdk-core.cjs +185 -0
  162. package/scripts/postinstall-link-sdk.js +126 -0
  163. package/scripts/proactive-api-server.ts +369 -0
  164. package/scripts/send-proactive.ts +293 -0
  165. package/scripts/set-markdown.sh +156 -0
  166. package/scripts/test-sendmedia.ts +116 -0
  167. package/scripts/upgrade-via-npm.ps1 +460 -0
  168. package/scripts/upgrade-via-npm.sh +652 -0
  169. package/scripts/upgrade-via-source.sh +1026 -0
  170. package/skills/qqbot-channel/SKILL.md +263 -0
  171. package/skills/qqbot-channel/references/api_references.md +521 -0
  172. package/skills/qqbot-media/SKILL.md +60 -0
  173. package/skills/qqbot-remind/SKILL.md +159 -0
  174. package/src/admin-resolver.ts +181 -0
  175. package/src/api.ts +1284 -0
  176. package/src/channel.ts +477 -0
  177. package/src/config.ts +347 -0
  178. package/src/credential-backup.ts +72 -0
  179. package/src/deliver-debounce.ts +229 -0
  180. package/src/gateway.ts +2245 -0
  181. package/src/group-history.ts +328 -0
  182. package/src/image-server.ts +675 -0
  183. package/src/inbound-attachments.ts +321 -0
  184. package/src/known-users.ts +353 -0
  185. package/src/message-gating.ts +190 -0
  186. package/src/message-queue.ts +352 -0
  187. package/src/onboarding.ts +274 -0
  188. package/src/openclaw-plugin-sdk.d.ts +587 -0
  189. package/src/outbound-deliver.ts +473 -0
  190. package/src/outbound.ts +1131 -0
  191. package/src/proactive.ts +530 -0
  192. package/src/ref-index-store.ts +412 -0
  193. package/src/reply-dispatcher.ts +334 -0
  194. package/src/request-context.ts +49 -0
  195. package/src/runtime.ts +14 -0
  196. package/src/session-store.ts +303 -0
  197. package/src/slash-commands.ts +2030 -0
  198. package/src/startup-greeting.ts +120 -0
  199. package/src/streaming.ts +1077 -0
  200. package/src/stt.ts +86 -0
  201. package/src/tools/channel.ts +281 -0
  202. package/src/tools/remind.ts +308 -0
  203. package/src/types.ts +391 -0
  204. package/src/typing-keepalive.ts +59 -0
  205. package/src/update-checker.ts +186 -0
  206. package/src/utils/audio-convert.ts +859 -0
  207. package/src/utils/chunked-upload.ts +483 -0
  208. package/src/utils/file-utils.ts +193 -0
  209. package/src/utils/image-size.ts +266 -0
  210. package/src/utils/media-send.ts +631 -0
  211. package/src/utils/media-tags.ts +183 -0
  212. package/src/utils/payload.ts +265 -0
  213. package/src/utils/pkg-version.ts +64 -0
  214. package/src/utils/platform.ts +435 -0
  215. package/src/utils/ssrf-guard.ts +102 -0
  216. package/src/utils/text-parsing.ts +85 -0
  217. package/src/utils/upload-cache.ts +128 -0
  218. package/tsconfig.json +16 -0
@@ -0,0 +1,890 @@
1
+ /**
2
+ * QQ Bot API 鉴权和请求封装
3
+ * [修复版] 已重构为支持多实例并发,消除全局变量冲突
4
+ */
5
+ import os from "node:os";
6
+ import { computeFileHash, getCachedFileInfo, setCachedFileInfo } from "./utils/upload-cache.js";
7
+ import { sanitizeFileName } from "./utils/platform.js";
8
+ /** 默认使用 console,外部可通过 setApiLogger 注入框架 log */
9
+ let log = {
10
+ info: (msg) => console.log(msg),
11
+ error: (msg) => console.error(msg),
12
+ warn: (msg) => console.warn(msg),
13
+ debug: (msg) => console.debug(msg),
14
+ };
15
+ /**
16
+ * 注入自定义 logger(在 gateway 启动时调用,将 api 模块的日志统一接入框架日志系统)
17
+ */
18
+ export function setApiLogger(logger) {
19
+ log = logger;
20
+ }
21
+ // ============ 自定义错误 ============
22
+ /** API 请求错误,携带 HTTP status code 和业务错误码 */
23
+ export class ApiError extends Error {
24
+ status;
25
+ path;
26
+ bizCode;
27
+ bizMessage;
28
+ constructor(message, status, path,
29
+ /** 业务错误码(回包中的 code / err_code 字段),不一定存在 */
30
+ bizCode,
31
+ /** 回包中的原始 message 字段(用于向用户展示兜底文案) */
32
+ bizMessage) {
33
+ super(message);
34
+ this.status = status;
35
+ this.path = path;
36
+ this.bizCode = bizCode;
37
+ this.bizMessage = bizMessage;
38
+ this.name = "ApiError";
39
+ }
40
+ }
41
+ const API_BASE = "https://api.sgroup.qq.com";
42
+ const TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
43
+ // ============ Plugin User-Agent ============
44
+ // 格式: QQBotPlugin/{version} (Node/{nodeVersion}; {os})
45
+ // 示例: QQBotPlugin/1.6.0 (Node/22.14.0; darwin)
46
+ import { getPackageVersion } from "./utils/pkg-version.js";
47
+ const _pluginVersion = getPackageVersion(import.meta.url);
48
+ export const PLUGIN_USER_AGENT = `QQBotPlugin/${_pluginVersion} (Node/${process.versions.node}; ${os.platform()})`;
49
+ // 运行时配置
50
+ let currentMarkdownSupport = false;
51
+ let onMessageSentHook = null;
52
+ /**
53
+ * 注册出站消息回调
54
+ * 当消息发送成功且 QQ 返回 ref_idx 时,自动回调此函数
55
+ * 用于在最底层统一缓存 bot 出站消息的 refIdx
56
+ */
57
+ export function onMessageSent(callback) {
58
+ onMessageSentHook = callback;
59
+ }
60
+ /**
61
+ * 初始化 API 配置
62
+ */
63
+ export function initApiConfig(options) {
64
+ currentMarkdownSupport = options.markdownSupport === true;
65
+ }
66
+ /**
67
+ * 获取当前是否支持 markdown
68
+ */
69
+ export function isMarkdownSupport() {
70
+ return currentMarkdownSupport;
71
+ }
72
+ // =========================================================================
73
+ // 🚀 [核心修复] 将全局状态改为 Map,按 appId 隔离,彻底解决多账号串号问题
74
+ // =========================================================================
75
+ const tokenCacheMap = new Map();
76
+ const tokenFetchPromises = new Map();
77
+ /**
78
+ * 获取 AccessToken(带缓存 + singleflight 并发安全)
79
+ *
80
+ * 使用 singleflight 模式:当多个请求同时发现 Token 过期时,
81
+ * 只有第一个请求会真正去获取新 Token,其他请求复用同一个 Promise。
82
+ *
83
+ * 按 appId 隔离,支持多机器人并发请求。
84
+ */
85
+ export async function getAccessToken(appId, clientSecret) {
86
+ const normalizedAppId = String(appId).trim();
87
+ const cachedToken = tokenCacheMap.get(normalizedAppId);
88
+ // 检查缓存:未过期时复用
89
+ // 提前刷新阈值:取 expiresIn 的 1/3 和 5 分钟的较小值,避免短有效期 token 永远被判定过期
90
+ const REFRESH_AHEAD_MS = cachedToken
91
+ ? Math.min(5 * 60 * 1000, (cachedToken.expiresAt - Date.now()) / 3)
92
+ : 0;
93
+ if (cachedToken && Date.now() < cachedToken.expiresAt - REFRESH_AHEAD_MS) {
94
+ return cachedToken.token;
95
+ }
96
+ // Singleflight: 如果当前 appId 已有进行中的 Token 获取请求,复用它
97
+ let fetchPromise = tokenFetchPromises.get(normalizedAppId);
98
+ if (fetchPromise) {
99
+ log.info(`[qqbot-api:${normalizedAppId}] Token fetch in progress, waiting for existing request...`);
100
+ return fetchPromise;
101
+ }
102
+ // 创建新的 Token 获取 Promise(singleflight 入口)
103
+ fetchPromise = (async () => {
104
+ try {
105
+ return await doFetchToken(normalizedAppId, clientSecret);
106
+ }
107
+ finally {
108
+ // 无论成功失败,都清除 Promise 缓存
109
+ tokenFetchPromises.delete(normalizedAppId);
110
+ }
111
+ })();
112
+ tokenFetchPromises.set(normalizedAppId, fetchPromise);
113
+ return fetchPromise;
114
+ }
115
+ /**
116
+ * 实际执行 Token 获取的内部函数
117
+ */
118
+ async function doFetchToken(appId, clientSecret) {
119
+ const requestBody = { appId, clientSecret };
120
+ const requestHeaders = { "Content-Type": "application/json", "User-Agent": PLUGIN_USER_AGENT };
121
+ // 打印请求信息(隐藏敏感信息)
122
+ log.info(`[qqbot-api:${appId}] >>> POST ${TOKEN_URL} [secret: ${clientSecret.slice(0, 6)}...len=${clientSecret.length}]`);
123
+ let response;
124
+ try {
125
+ response = await fetch(TOKEN_URL, {
126
+ method: "POST",
127
+ headers: requestHeaders,
128
+ body: JSON.stringify(requestBody),
129
+ });
130
+ }
131
+ catch (err) {
132
+ log.error(`[qqbot-api:${appId}] <<< Network error: ${err}`);
133
+ throw new Error(`Network error getting access_token: ${err instanceof Error ? err.message : String(err)}`);
134
+ }
135
+ // 打印响应头
136
+ const responseHeaders = {};
137
+ response.headers.forEach((value, key) => {
138
+ responseHeaders[key] = value;
139
+ });
140
+ const tokenTraceId = response.headers.get("x-tps-trace-id") ?? "";
141
+ log.info(`[qqbot-api:${appId}] <<< Status: ${response.status} ${response.statusText}${tokenTraceId ? ` | TraceId: ${tokenTraceId}` : ""}`);
142
+ let data;
143
+ let rawBody;
144
+ try {
145
+ rawBody = await response.text();
146
+ // 隐藏 token 值
147
+ const logBody = rawBody.replace(/"access_token"\s*:\s*"[^"]+"/g, '"access_token": "***"');
148
+ log.info(`[qqbot-api:${appId}] <<< Body: ${logBody}`);
149
+ data = JSON.parse(rawBody);
150
+ }
151
+ catch (err) {
152
+ log.error(`[qqbot-api:${appId}] <<< Parse error: ${err}`);
153
+ throw new Error(`Failed to parse access_token response: ${err instanceof Error ? err.message : String(err)}`);
154
+ }
155
+ if (!data.access_token) {
156
+ throw new Error(`Failed to get access_token: ${JSON.stringify(data)}`);
157
+ }
158
+ const expiresAt = Date.now() + (data.expires_in ?? 7200) * 1000;
159
+ tokenCacheMap.set(appId, {
160
+ token: data.access_token,
161
+ expiresAt,
162
+ appId,
163
+ });
164
+ log.info(`[qqbot-api:${appId}] Token cached, expires at: ${new Date(expiresAt).toISOString()}`);
165
+ return data.access_token;
166
+ }
167
+ /**
168
+ * 清除 Token 缓存
169
+ * @param appId 选填。如果有,只清空特定账号的缓存;如果没有,清空所有账号。
170
+ */
171
+ export function clearTokenCache(appId) {
172
+ if (appId) {
173
+ const normalizedAppId = String(appId).trim();
174
+ tokenCacheMap.delete(normalizedAppId);
175
+ log.info(`[qqbot-api:${normalizedAppId}] Token cache cleared manually.`);
176
+ }
177
+ else {
178
+ tokenCacheMap.clear();
179
+ log.info(`[qqbot-api] All token caches cleared.`);
180
+ }
181
+ }
182
+ /**
183
+ * 获取 Token 缓存状态(用于监控)
184
+ */
185
+ export function getTokenStatus(appId) {
186
+ if (tokenFetchPromises.has(appId)) {
187
+ return { status: "refreshing", expiresAt: tokenCacheMap.get(appId)?.expiresAt ?? null };
188
+ }
189
+ const cached = tokenCacheMap.get(appId);
190
+ if (!cached) {
191
+ return { status: "none", expiresAt: null };
192
+ }
193
+ const remaining = cached.expiresAt - Date.now();
194
+ const isValid = remaining > Math.min(5 * 60 * 1000, remaining / 3);
195
+ return { status: isValid ? "valid" : "expired", expiresAt: cached.expiresAt };
196
+ }
197
+ /**
198
+ * 获取全局唯一的消息序号(范围 0 ~ 65535)
199
+ * 使用毫秒级时间戳低位 + 随机数异或混合,无状态,避免碰撞
200
+ */
201
+ export function getNextMsgSeq(_msgId) {
202
+ const timePart = Date.now() % 100000000; // 毫秒时间戳后8位
203
+ const random = Math.floor(Math.random() * 65536); // 0~65535
204
+ return (timePart ^ random) % 65536; // 异或混合后限制在 0~65535
205
+ }
206
+ // API 请求超时配置(毫秒)
207
+ const DEFAULT_API_TIMEOUT = 30000; // 默认 30 秒
208
+ const FILE_UPLOAD_TIMEOUT = 120000; // 文件上传 120 秒
209
+ /**
210
+ * API 请求封装
211
+ */
212
+ export async function apiRequest(accessToken, method, path, body, timeoutMs) {
213
+ const url = `${API_BASE}${path}`;
214
+ const reqTs = Date.now(); // 毫秒时间戳,用于关联同一次请求的所有日志
215
+ const headers = {
216
+ Authorization: `QQBot ${accessToken}`,
217
+ "Content-Type": "application/json",
218
+ "User-Agent": PLUGIN_USER_AGENT,
219
+ };
220
+ const isFileUpload = path.includes("/files");
221
+ const timeout = timeoutMs ?? (isFileUpload ? FILE_UPLOAD_TIMEOUT : DEFAULT_API_TIMEOUT);
222
+ const controller = new AbortController();
223
+ const timeoutId = setTimeout(() => {
224
+ controller.abort();
225
+ }, timeout);
226
+ const options = {
227
+ method,
228
+ headers,
229
+ signal: controller.signal,
230
+ };
231
+ if (body) {
232
+ options.body = JSON.stringify(body);
233
+ }
234
+ // 打印请求信息
235
+ log.info(`[qqbot-api][${reqTs}] >>> ${method} ${url} (timeout: ${timeout}ms)`);
236
+ if (body) {
237
+ const logBody = { ...body };
238
+ if (typeof logBody.file_data === "string") {
239
+ logBody.file_data = `<base64 ${logBody.file_data.length} chars>`;
240
+ }
241
+ log.info(`[qqbot-api][${reqTs}] >>> Body: ${JSON.stringify(logBody)}`);
242
+ }
243
+ let res;
244
+ try {
245
+ res = await fetch(url, options);
246
+ }
247
+ catch (err) {
248
+ clearTimeout(timeoutId);
249
+ if (err instanceof Error && err.name === "AbortError") {
250
+ log.error(`[qqbot-api][${reqTs}] <<< Request timeout after ${timeout}ms`);
251
+ throw new Error(`Request timeout[${path}]: exceeded ${timeout}ms`);
252
+ }
253
+ log.error(`[qqbot-api][${reqTs}] <<< Network error: ${err}`);
254
+ throw new Error(`Network error [${path}]: ${err instanceof Error ? err.message : String(err)}`);
255
+ }
256
+ finally {
257
+ clearTimeout(timeoutId);
258
+ }
259
+ const responseHeaders = {};
260
+ res.headers.forEach((value, key) => {
261
+ responseHeaders[key] = value;
262
+ });
263
+ const traceId = res.headers.get("x-tps-trace-id") ?? "";
264
+ log.info(`[qqbot-api][${reqTs}] <<< Status: ${res.status} ${res.statusText}${traceId ? ` | TraceId: ${traceId}` : ""}`);
265
+ let rawBody;
266
+ try {
267
+ rawBody = await res.text();
268
+ }
269
+ catch (err) {
270
+ throw new Error(`读取响应失败[${path}]: ${err instanceof Error ? err.message : String(err)}`);
271
+ }
272
+ log.info(`[qqbot-api][${reqTs}] <<< Body: ${rawBody}`);
273
+ // 检测非 JSON 响应(HTML 网关错误页 / CDN 限流页等)
274
+ const contentType = res.headers.get("content-type") ?? "";
275
+ const isHtmlResponse = contentType.includes("text/html") || rawBody.trimStart().startsWith("<");
276
+ if (!res.ok) {
277
+ if (isHtmlResponse) {
278
+ // HTML 响应 = 网关/限流层返回的错误页,给出友好提示
279
+ const statusHint = res.status === 502 || res.status === 503 || res.status === 504
280
+ ? "调用发生异常,请稍候重试"
281
+ : res.status === 429
282
+ ? "请求过于频繁,已被限流"
283
+ : `开放平台返回 HTTP ${res.status}`;
284
+ throw new ApiError(`${statusHint}(${path}),请稍后重试`, res.status, path);
285
+ }
286
+ // JSON 错误响应
287
+ try {
288
+ const error = JSON.parse(rawBody);
289
+ const bizCode = error.code ?? error.err_code;
290
+ throw new ApiError(`API Error [${path}]: ${error.message ?? rawBody}`, res.status, path, bizCode, error.message);
291
+ }
292
+ catch (parseErr) {
293
+ if (parseErr instanceof ApiError)
294
+ throw parseErr;
295
+ throw new ApiError(`API Error [${path}] HTTP ${res.status}: ${rawBody.slice(0, 200)}`, res.status, path);
296
+ }
297
+ }
298
+ // 成功响应但不是 JSON(极端异常情况)
299
+ if (isHtmlResponse) {
300
+ throw new ApiError(`QQ 服务端返回了非 JSON 响应(${path}),可能是临时故障,请稍后重试`, res.status, path);
301
+ }
302
+ try {
303
+ return JSON.parse(rawBody);
304
+ }
305
+ catch {
306
+ throw new ApiError(`开放平台响应格式异常(${path}),请稍后重试`, res.status, path);
307
+ }
308
+ }
309
+ // ============ 上传重试(指数退避) ============
310
+ const UPLOAD_MAX_RETRIES = 2;
311
+ const UPLOAD_BASE_DELAY_MS = 1000;
312
+ async function apiRequestWithRetry(accessToken, method, path, body, maxRetries = UPLOAD_MAX_RETRIES) {
313
+ let lastError = null;
314
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
315
+ try {
316
+ return await apiRequest(accessToken, method, path, body);
317
+ }
318
+ catch (err) {
319
+ lastError = err instanceof Error ? err : new Error(String(err));
320
+ const errMsg = lastError.message;
321
+ if (errMsg.includes("400") || errMsg.includes("401") || errMsg.includes("Invalid") ||
322
+ errMsg.includes("上传超时") || errMsg.includes("timeout") || errMsg.includes("Timeout")) {
323
+ throw lastError;
324
+ }
325
+ if (attempt < maxRetries) {
326
+ const delay = UPLOAD_BASE_DELAY_MS * Math.pow(2, attempt);
327
+ log.info(`[qqbot-api] Upload attempt ${attempt + 1} failed, retrying in ${delay}ms: ${errMsg.slice(0, 100)}`);
328
+ await new Promise(resolve => setTimeout(resolve, delay));
329
+ }
330
+ }
331
+ }
332
+ throw lastError;
333
+ }
334
+ // ============ 完成上传重试(无条件,任何错误都重试) ============
335
+ const COMPLETE_UPLOAD_MAX_RETRIES = 2;
336
+ const COMPLETE_UPLOAD_BASE_DELAY_MS = 2000;
337
+ /**
338
+ * 完成上传专用重试:无条件重试所有错误(包括 4xx、5xx、网络错误、超时等)
339
+ * 分片上传完成接口的失败往往是平台侧异步处理未就绪,重试通常能成功
340
+ */
341
+ async function completeUploadWithRetry(accessToken, method, path, body) {
342
+ let lastError = null;
343
+ for (let attempt = 0; attempt <= COMPLETE_UPLOAD_MAX_RETRIES; attempt++) {
344
+ try {
345
+ return await apiRequest(accessToken, method, path, body);
346
+ }
347
+ catch (err) {
348
+ lastError = err instanceof Error ? err : new Error(String(err));
349
+ if (attempt < COMPLETE_UPLOAD_MAX_RETRIES) {
350
+ const delay = COMPLETE_UPLOAD_BASE_DELAY_MS * Math.pow(2, attempt);
351
+ (log.warn ?? log.error)(`[qqbot-api] CompleteUpload attempt ${attempt + 1} failed, retrying in ${delay}ms: ${lastError.message.slice(0, 200)}`);
352
+ await new Promise(resolve => setTimeout(resolve, delay));
353
+ }
354
+ }
355
+ }
356
+ throw lastError;
357
+ }
358
+ // ============ 分片完成重试 ============
359
+ /** 普通错误最大重试次数 */
360
+ const PART_FINISH_MAX_RETRIES = 2;
361
+ const PART_FINISH_BASE_DELAY_MS = 1000;
362
+ /**
363
+ * 需要持续重试的业务错误码集合
364
+ * 当 upload_part_finish 返回这些错误码时,会以固定 1s 间隔持续重试直到成功或超时
365
+ */
366
+ export const PART_FINISH_RETRYABLE_CODES = new Set([
367
+ 40093001,
368
+ ]);
369
+ /**
370
+ * upload_prepare 接口命中此错误码时,携带文件信息抛出 UploadDailyLimitExceededError,
371
+ * 由上层(outbound.ts)构造包含文件路径和大小的兜底文案发送给用户,
372
+ * 而非走通用的"文件发送失败,请稍后重试"
373
+ */
374
+ export const UPLOAD_PREPARE_FALLBACK_CODE = 40093002;
375
+ /** 特定错误码持续重试的默认超时(服务端未返回 retry_timeout 时的兜底) */
376
+ const PART_FINISH_RETRYABLE_DEFAULT_TIMEOUT_MS = 2 * 60 * 1000;
377
+ /** 特定错误码重试的固定间隔(1 秒) */
378
+ const PART_FINISH_RETRYABLE_INTERVAL_MS = 1000;
379
+ /**
380
+ * 判断错误是否命中"需要持续重试"的业务错误码
381
+ */
382
+ function isRetryableBizCode(err) {
383
+ if (PART_FINISH_RETRYABLE_CODES.size === 0)
384
+ return false;
385
+ if (err instanceof ApiError && err.bizCode !== undefined) {
386
+ return PART_FINISH_RETRYABLE_CODES.has(err.bizCode);
387
+ }
388
+ return false;
389
+ }
390
+ /**
391
+ * 分片完成接口重试策略:
392
+ *
393
+ * 1. 命中 PART_FINISH_RETRYABLE_CODES 的错误码 → 每 1s 重试一次,直到成功或超时
394
+ * 超时时间 = min(API 返回的 retry_timeout, 10 分钟)
395
+ * 2. 其他错误 → 最多重试 PART_FINISH_MAX_RETRIES 次(与之前逻辑一致)
396
+ *
397
+ * 若持续重试超时或普通重试耗尽,抛出错误,调用方(chunkedUpload)
398
+ * 可据此中止后续分片上传。
399
+ *
400
+ * @param retryTimeoutMs - 持续重试的超时时间(毫秒),由 upload_prepare 返回的 retry_timeout 计算得出
401
+ */
402
+ async function partFinishWithRetry(accessToken, method, path, body, retryTimeoutMs) {
403
+ let lastError = null;
404
+ for (let attempt = 0; attempt <= PART_FINISH_MAX_RETRIES; attempt++) {
405
+ try {
406
+ await apiRequest(accessToken, method, path, body);
407
+ return;
408
+ }
409
+ catch (err) {
410
+ lastError = err instanceof Error ? err : new Error(String(err));
411
+ // 命中特定错误码 → 进入持续重试模式
412
+ if (isRetryableBizCode(err)) {
413
+ const timeoutMs = retryTimeoutMs ?? PART_FINISH_RETRYABLE_DEFAULT_TIMEOUT_MS;
414
+ (log.warn ?? log.error)(`[qqbot-api] PartFinish hit retryable bizCode=${err.bizCode}, entering persistent retry (timeout=${timeoutMs / 1000}s, interval=1s)...`);
415
+ await partFinishPersistentRetry(accessToken, method, path, body, timeoutMs);
416
+ return;
417
+ }
418
+ if (attempt < PART_FINISH_MAX_RETRIES) {
419
+ const delay = PART_FINISH_BASE_DELAY_MS * Math.pow(2, attempt);
420
+ (log.warn ?? log.error)(`[qqbot-api] PartFinish attempt ${attempt + 1} failed, retrying in ${delay}ms: ${lastError.message.slice(0, 200)}`);
421
+ await new Promise(resolve => setTimeout(resolve, delay));
422
+ }
423
+ }
424
+ }
425
+ throw lastError;
426
+ }
427
+ /**
428
+ * 特定错误码的持续重试模式
429
+ * 不限次数,仅受总超时时间约束,固定每 1 秒重试一次
430
+ */
431
+ async function partFinishPersistentRetry(accessToken, method, path, body, timeoutMs) {
432
+ const deadline = Date.now() + timeoutMs;
433
+ let attempt = 0;
434
+ let lastError = null;
435
+ while (Date.now() < deadline) {
436
+ try {
437
+ await apiRequest(accessToken, method, path, body);
438
+ log.info(`[qqbot-api] PartFinish persistent retry succeeded after ${attempt} retries`);
439
+ return;
440
+ }
441
+ catch (err) {
442
+ lastError = err instanceof Error ? err : new Error(String(err));
443
+ // 如果不再是可重试的错误码,直接抛出(可能是其他类型的错误)
444
+ if (!isRetryableBizCode(err)) {
445
+ log.error(`[qqbot-api] PartFinish persistent retry: error is no longer retryable (bizCode=${err.bizCode ?? "N/A"}), aborting`);
446
+ throw lastError;
447
+ }
448
+ attempt++;
449
+ const remaining = deadline - Date.now();
450
+ if (remaining <= 0)
451
+ break;
452
+ const actualDelay = Math.min(PART_FINISH_RETRYABLE_INTERVAL_MS, remaining);
453
+ (log.warn ?? log.error)(`[qqbot-api] PartFinish persistent retry #${attempt}: bizCode=${err.bizCode}, retrying in ${actualDelay}ms (remaining=${Math.round(remaining / 1000)}s)`);
454
+ await new Promise(resolve => setTimeout(resolve, actualDelay));
455
+ }
456
+ }
457
+ // 超时
458
+ log.error(`[qqbot-api] PartFinish persistent retry timed out after ${timeoutMs / 1000}s (${attempt} attempts)`);
459
+ throw new Error(`upload_part_finish 持续重试超时(${timeoutMs / 1000}s, ${attempt} 次重试),中止上传`);
460
+ }
461
+ export async function getGatewayUrl(accessToken) {
462
+ const data = await apiRequest(accessToken, "GET", "/gateway");
463
+ return data.url;
464
+ }
465
+ /** 回应按钮交互(INTERACTION_CREATE),避免客户端按钮持续 loading */
466
+ export async function acknowledgeInteraction(accessToken, interactionId, code = 0, data) {
467
+ await apiRequest(accessToken, "PUT", `/interactions/${interactionId}`, { code, ...(data ? { data } : {}) });
468
+ }
469
+ /** 获取插件版本号(从 package.json 读取,和 PLUGIN_USER_AGENT 同源) */
470
+ export function getApiPluginVersion() {
471
+ return _pluginVersion;
472
+ }
473
+ /**
474
+ * 发送消息并自动触发 refIdx 回调
475
+ * 所有消息发送函数统一经过此处,确保每条出站消息的 refIdx 都被捕获
476
+ */
477
+ async function sendAndNotify(accessToken, method, path, body, meta) {
478
+ const result = await apiRequest(accessToken, method, path, body);
479
+ if (result.ext_info?.ref_idx && onMessageSentHook) {
480
+ try {
481
+ onMessageSentHook(result.ext_info.ref_idx, meta);
482
+ }
483
+ catch (err) {
484
+ log.error(`[qqbot-api] onMessageSent hook error: ${err}`);
485
+ }
486
+ }
487
+ return result;
488
+ }
489
+ function buildMessageBody(content, msgId, msgSeq, messageReference) {
490
+ const body = currentMarkdownSupport
491
+ ? {
492
+ markdown: { content },
493
+ msg_type: 2,
494
+ msg_seq: msgSeq,
495
+ }
496
+ : {
497
+ content,
498
+ msg_type: 0,
499
+ msg_seq: msgSeq,
500
+ };
501
+ if (msgId) {
502
+ body.msg_id = msgId;
503
+ }
504
+ if (messageReference && !currentMarkdownSupport) {
505
+ body.message_reference = { message_id: messageReference };
506
+ }
507
+ return body;
508
+ }
509
+ export async function sendC2CMessage(accessToken, openid, content, msgId, messageReference) {
510
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
511
+ const body = buildMessageBody(content, msgId, msgSeq, messageReference);
512
+ return sendAndNotify(accessToken, "POST", `/v2/users/${openid}/messages`, body, { text: content });
513
+ }
514
+ export async function sendC2CInputNotify(accessToken, openid, msgId, inputSecond = 60) {
515
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
516
+ const body = {
517
+ msg_type: 6,
518
+ input_notify: {
519
+ input_type: 1,
520
+ input_second: inputSecond,
521
+ },
522
+ msg_seq: msgSeq,
523
+ ...(msgId ? { msg_id: msgId } : {}),
524
+ };
525
+ const response = await apiRequest(accessToken, "POST", `/v2/users/${openid}/messages`, body);
526
+ return { refIdx: response.ext_info?.ref_idx };
527
+ }
528
+ export async function sendChannelMessage(accessToken, channelId, content, msgId) {
529
+ return apiRequest(accessToken, "POST", `/channels/${channelId}/messages`, {
530
+ content,
531
+ ...(msgId ? { msg_id: msgId } : {}),
532
+ });
533
+ }
534
+ /**
535
+ * 发送频道私信消息
536
+ * @param guildId - 私信会话的 guild_id(由 DIRECT_MESSAGE_CREATE 事件提供)
537
+ * @param msgId - 被动回复时必填
538
+ */
539
+ export async function sendDmMessage(accessToken, guildId, content, msgId) {
540
+ return apiRequest(accessToken, "POST", `/dms/${guildId}/messages`, {
541
+ content,
542
+ ...(msgId ? { msg_id: msgId } : {}),
543
+ });
544
+ }
545
+ export async function sendGroupMessage(accessToken, groupOpenid, content, msgId, messageReference) {
546
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
547
+ const body = buildMessageBody(content, msgId, msgSeq, messageReference);
548
+ return sendAndNotify(accessToken, "POST", `/v2/groups/${groupOpenid}/messages`, body, { text: content });
549
+ }
550
+ function buildProactiveMessageBody(content) {
551
+ if (!content || content.trim().length === 0) {
552
+ throw new Error("主动消息内容不能为空 (markdown.content is empty)");
553
+ }
554
+ if (currentMarkdownSupport) {
555
+ return { markdown: { content }, msg_type: 2 };
556
+ }
557
+ else {
558
+ return { content, msg_type: 0 };
559
+ }
560
+ }
561
+ export async function sendProactiveC2CMessage(accessToken, openid, content) {
562
+ const body = buildProactiveMessageBody(content);
563
+ return sendAndNotify(accessToken, "POST", `/v2/users/${openid}/messages`, body, { text: content });
564
+ }
565
+ export async function sendProactiveGroupMessage(accessToken, groupOpenid, content) {
566
+ const body = buildProactiveMessageBody(content);
567
+ return apiRequest(accessToken, "POST", `/v2/groups/${groupOpenid}/messages`, body);
568
+ }
569
+ // ============ 富媒体消息支持 ============
570
+ export var MediaFileType;
571
+ (function (MediaFileType) {
572
+ MediaFileType[MediaFileType["IMAGE"] = 1] = "IMAGE";
573
+ MediaFileType[MediaFileType["VIDEO"] = 2] = "VIDEO";
574
+ MediaFileType[MediaFileType["VOICE"] = 3] = "VOICE";
575
+ MediaFileType[MediaFileType["FILE"] = 4] = "FILE";
576
+ })(MediaFileType || (MediaFileType = {}));
577
+ /**
578
+ * 申请上传(C2C)
579
+ * POST /v2/users/{user_id}/upload_prepare
580
+ *
581
+ * @param accessToken - 访问令牌
582
+ * @param userId - 用户 openid
583
+ * @param fileType - 业务类型(1=图片, 2=视频, 3=语音, 4=文件)
584
+ * @param fileName - 文件名
585
+ * @param fileSize - 文件大小(字节)
586
+ * @param hashes - 文件哈希信息(md5, sha1, md5_10m)
587
+ * @returns 上传任务 ID、分块大小、分片预签名链接列表
588
+ */
589
+ export async function c2cUploadPrepare(accessToken, userId, fileType, fileName, fileSize, hashes) {
590
+ return apiRequest(accessToken, "POST", `/v2/users/${userId}/upload_prepare`, { file_type: fileType, file_name: fileName, file_size: fileSize, md5: hashes.md5, sha1: hashes.sha1, md5_10m: hashes.md5_10m });
591
+ }
592
+ /**
593
+ * 完成分片上传(C2C)
594
+ * POST /v2/users/{user_id}/upload_part_finish
595
+ *
596
+ * @param accessToken - 访问令牌
597
+ * @param userId - 用户 openid
598
+ * @param uploadId - 上传任务 ID
599
+ * @param partIndex - 分片索引(从 1 开始)
600
+ * @param blockSize - 分块大小(字节)
601
+ * @param md5 - 分片数据的 MD5(十六进制)
602
+ */
603
+ export async function c2cUploadPartFinish(accessToken, userId, uploadId, partIndex, blockSize, md5, retryTimeoutMs) {
604
+ await partFinishWithRetry(accessToken, "POST", `/v2/users/${userId}/upload_part_finish`, { upload_id: uploadId, part_index: partIndex, block_size: blockSize, md5 }, retryTimeoutMs);
605
+ }
606
+ /**
607
+ * 完成文件上传(C2C)
608
+ * POST /v2/users/{user_id}/files
609
+ *
610
+ * @param accessToken - 访问令牌
611
+ * @param userId - 用户 openid
612
+ * @param uploadId - 上传任务 ID
613
+ * @returns 文件信息(file_uuid, file_info, ttl)
614
+ */
615
+ export async function c2cCompleteUpload(accessToken, userId, uploadId) {
616
+ return completeUploadWithRetry(accessToken, "POST", `/v2/users/${userId}/files`, { upload_id: uploadId });
617
+ }
618
+ /**
619
+ * 申请上传(Group)
620
+ * POST /v2/groups/{group_id}/upload_prepare
621
+ */
622
+ export async function groupUploadPrepare(accessToken, groupId, fileType, fileName, fileSize, hashes) {
623
+ return apiRequest(accessToken, "POST", `/v2/groups/${groupId}/upload_prepare`, { file_type: fileType, file_name: fileName, file_size: fileSize, md5: hashes.md5, sha1: hashes.sha1, md5_10m: hashes.md5_10m });
624
+ }
625
+ /**
626
+ * 完成分片上传(Group)
627
+ * POST /v2/groups/{group_id}/upload_part_finish
628
+ */
629
+ export async function groupUploadPartFinish(accessToken, groupId, uploadId, partIndex, blockSize, md5, retryTimeoutMs) {
630
+ await partFinishWithRetry(accessToken, "POST", `/v2/groups/${groupId}/upload_part_finish`, { upload_id: uploadId, part_index: partIndex, block_size: blockSize, md5 }, retryTimeoutMs);
631
+ }
632
+ /**
633
+ * 完成文件上传(Group)
634
+ * POST /v2/groups/{group_id}/files
635
+ */
636
+ export async function groupCompleteUpload(accessToken, groupId, uploadId) {
637
+ return completeUploadWithRetry(accessToken, "POST", `/v2/groups/${groupId}/files`, { upload_id: uploadId });
638
+ }
639
+ export async function uploadC2CMedia(accessToken, openid, fileType, url, fileData, srvSendMsg = false, fileName) {
640
+ if (!url && !fileData)
641
+ throw new Error("uploadC2CMedia: url or fileData is required");
642
+ if (fileData) {
643
+ const contentHash = computeFileHash(fileData);
644
+ const cachedInfo = getCachedFileInfo(contentHash, "c2c", openid, fileType);
645
+ if (cachedInfo) {
646
+ return { file_uuid: "", file_info: cachedInfo, ttl: 0 };
647
+ }
648
+ }
649
+ const body = { file_type: fileType, srv_send_msg: srvSendMsg };
650
+ if (url)
651
+ body.url = url;
652
+ else if (fileData)
653
+ body.file_data = fileData;
654
+ if (fileType === MediaFileType.FILE && fileName)
655
+ body.file_name = sanitizeFileName(fileName);
656
+ const result = await apiRequestWithRetry(accessToken, "POST", `/v2/users/${openid}/files`, body);
657
+ if (fileData && result.file_info && result.ttl > 0) {
658
+ const contentHash = computeFileHash(fileData);
659
+ setCachedFileInfo(contentHash, "c2c", openid, fileType, result.file_info, result.file_uuid, result.ttl);
660
+ }
661
+ return result;
662
+ }
663
+ export async function uploadGroupMedia(accessToken, groupOpenid, fileType, url, fileData, srvSendMsg = false, fileName) {
664
+ if (!url && !fileData)
665
+ throw new Error("uploadGroupMedia: url or fileData is required");
666
+ if (fileData) {
667
+ const contentHash = computeFileHash(fileData);
668
+ const cachedInfo = getCachedFileInfo(contentHash, "group", groupOpenid, fileType);
669
+ if (cachedInfo) {
670
+ return { file_uuid: "", file_info: cachedInfo, ttl: 0 };
671
+ }
672
+ }
673
+ const body = { file_type: fileType, srv_send_msg: srvSendMsg };
674
+ if (url)
675
+ body.url = url;
676
+ else if (fileData)
677
+ body.file_data = fileData;
678
+ if (fileType === MediaFileType.FILE && fileName)
679
+ body.file_name = sanitizeFileName(fileName);
680
+ const result = await apiRequestWithRetry(accessToken, "POST", `/v2/groups/${groupOpenid}/files`, body);
681
+ if (fileData && result.file_info && result.ttl > 0) {
682
+ const contentHash = computeFileHash(fileData);
683
+ setCachedFileInfo(contentHash, "group", groupOpenid, fileType, result.file_info, result.file_uuid, result.ttl);
684
+ }
685
+ return result;
686
+ }
687
+ export async function sendC2CMediaMessage(accessToken, openid, fileInfo, msgId, content, meta) {
688
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
689
+ return sendAndNotify(accessToken, "POST", `/v2/users/${openid}/messages`, {
690
+ msg_type: 7,
691
+ media: { file_info: fileInfo },
692
+ msg_seq: msgSeq,
693
+ ...(content ? { content } : {}),
694
+ ...(msgId ? { msg_id: msgId } : {}),
695
+ }, meta ?? { text: content });
696
+ }
697
+ export async function sendGroupMediaMessage(accessToken, groupOpenid, fileInfo, msgId, content) {
698
+ const msgSeq = msgId ? getNextMsgSeq(msgId) : 1;
699
+ return apiRequest(accessToken, "POST", `/v2/groups/${groupOpenid}/messages`, {
700
+ msg_type: 7,
701
+ media: { file_info: fileInfo },
702
+ msg_seq: msgSeq,
703
+ ...(content ? { content } : {}),
704
+ ...(msgId ? { msg_id: msgId } : {}),
705
+ });
706
+ }
707
+ export async function sendC2CImageMessage(accessToken, openid, imageUrl, msgId, content, localPath) {
708
+ let uploadResult;
709
+ const isBase64 = imageUrl.startsWith("data:");
710
+ if (isBase64) {
711
+ const matches = imageUrl.match(/^data:([^;]+);base64,(.+)$/);
712
+ if (!matches)
713
+ throw new Error("Invalid Base64 Data URL format");
714
+ uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.IMAGE, undefined, matches[2], false);
715
+ }
716
+ else {
717
+ uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.IMAGE, imageUrl, undefined, false);
718
+ }
719
+ const meta = {
720
+ text: content,
721
+ mediaType: "image",
722
+ ...(!isBase64 ? { mediaUrl: imageUrl } : {}),
723
+ ...(localPath ? { mediaLocalPath: localPath } : {}),
724
+ };
725
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, content, meta);
726
+ }
727
+ export async function sendGroupImageMessage(accessToken, groupOpenid, imageUrl, msgId, content) {
728
+ let uploadResult;
729
+ const isBase64 = imageUrl.startsWith("data:");
730
+ if (isBase64) {
731
+ const matches = imageUrl.match(/^data:([^;]+);base64,(.+)$/);
732
+ if (!matches)
733
+ throw new Error("Invalid Base64 Data URL format");
734
+ uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.IMAGE, undefined, matches[2], false);
735
+ }
736
+ else {
737
+ uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.IMAGE, imageUrl, undefined, false);
738
+ }
739
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId, content);
740
+ }
741
+ export async function sendC2CVoiceMessage(accessToken, openid, voiceBase64, voiceUrl, msgId, ttsText, filePath) {
742
+ const uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.VOICE, voiceUrl, voiceBase64, false);
743
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, undefined, {
744
+ mediaType: "voice",
745
+ ...(ttsText ? { ttsText } : {}),
746
+ ...(filePath ? { mediaLocalPath: filePath } : {})
747
+ });
748
+ }
749
+ export async function sendGroupVoiceMessage(accessToken, groupOpenid, voiceBase64, voiceUrl, msgId) {
750
+ const uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.VOICE, voiceUrl, voiceBase64, false);
751
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId);
752
+ }
753
+ export async function sendC2CFileMessage(accessToken, openid, fileBase64, fileUrl, msgId, fileName, localFilePath) {
754
+ const uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.FILE, fileUrl, fileBase64, false, fileName);
755
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, undefined, { mediaType: "file", mediaUrl: fileUrl, mediaLocalPath: localFilePath ?? fileName });
756
+ }
757
+ export async function sendGroupFileMessage(accessToken, groupOpenid, fileBase64, fileUrl, msgId, fileName) {
758
+ const uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.FILE, fileUrl, fileBase64, false, fileName);
759
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId);
760
+ }
761
+ export async function sendC2CVideoMessage(accessToken, openid, videoUrl, videoBase64, msgId, content, localPath) {
762
+ const uploadResult = await uploadC2CMedia(accessToken, openid, MediaFileType.VIDEO, videoUrl, videoBase64, false);
763
+ return sendC2CMediaMessage(accessToken, openid, uploadResult.file_info, msgId, content, { text: content, mediaType: "video", ...(videoUrl ? { mediaUrl: videoUrl } : {}), ...(localPath ? { mediaLocalPath: localPath } : {}) });
764
+ }
765
+ export async function sendGroupVideoMessage(accessToken, groupOpenid, videoUrl, videoBase64, msgId, content) {
766
+ const uploadResult = await uploadGroupMedia(accessToken, groupOpenid, MediaFileType.VIDEO, videoUrl, videoBase64, false);
767
+ return sendGroupMediaMessage(accessToken, groupOpenid, uploadResult.file_info, msgId, content);
768
+ }
769
+ const backgroundRefreshControllers = new Map();
770
+ export function startBackgroundTokenRefresh(appId, clientSecret, options) {
771
+ if (backgroundRefreshControllers.has(appId)) {
772
+ log.info(`[qqbot-api:${appId}] Background token refresh already running`);
773
+ return;
774
+ }
775
+ const { refreshAheadMs = 5 * 60 * 1000, randomOffsetMs = 30 * 1000, minRefreshIntervalMs = 60 * 1000, retryDelayMs = 5 * 1000, log: refreshLog, } = options ?? {};
776
+ const controller = new AbortController();
777
+ backgroundRefreshControllers.set(appId, controller);
778
+ const signal = controller.signal;
779
+ const refreshLoop = async () => {
780
+ refreshLog?.info?.(`[qqbot-api:${appId}] Background token refresh started`);
781
+ while (!signal.aborted) {
782
+ try {
783
+ await getAccessToken(appId, clientSecret);
784
+ const cached = tokenCacheMap.get(appId);
785
+ if (cached) {
786
+ const expiresIn = cached.expiresAt - Date.now();
787
+ const randomOffset = Math.random() * randomOffsetMs;
788
+ const refreshIn = Math.max(expiresIn - refreshAheadMs - randomOffset, minRefreshIntervalMs);
789
+ refreshLog?.debug?.(`[qqbot-api:${appId}] Token valid, next refresh in ${Math.round(refreshIn / 1000)}s`);
790
+ await sleep(refreshIn, signal);
791
+ }
792
+ else {
793
+ refreshLog?.debug?.(`[qqbot-api:${appId}] No cached token, retrying soon`);
794
+ await sleep(minRefreshIntervalMs, signal);
795
+ }
796
+ }
797
+ catch (err) {
798
+ if (signal.aborted)
799
+ break;
800
+ refreshLog?.error?.(`[qqbot-api:${appId}] Background token refresh failed: ${err}`);
801
+ await sleep(retryDelayMs, signal);
802
+ }
803
+ }
804
+ backgroundRefreshControllers.delete(appId);
805
+ refreshLog?.info?.(`[qqbot-api:${appId}] Background token refresh stopped`);
806
+ };
807
+ refreshLoop().catch((err) => {
808
+ backgroundRefreshControllers.delete(appId);
809
+ refreshLog?.error?.(`[qqbot-api:${appId}] Background token refresh crashed: ${err}`);
810
+ });
811
+ }
812
+ /**
813
+ * 停止后台 Token 刷新
814
+ * @param appId 选填。如果有,仅停止该账号的定时刷新。
815
+ */
816
+ export function stopBackgroundTokenRefresh(appId) {
817
+ if (appId) {
818
+ const controller = backgroundRefreshControllers.get(appId);
819
+ if (controller) {
820
+ controller.abort();
821
+ backgroundRefreshControllers.delete(appId);
822
+ }
823
+ }
824
+ else {
825
+ for (const controller of backgroundRefreshControllers.values()) {
826
+ controller.abort();
827
+ }
828
+ backgroundRefreshControllers.clear();
829
+ }
830
+ }
831
+ export function isBackgroundTokenRefreshRunning(appId) {
832
+ if (appId)
833
+ return backgroundRefreshControllers.has(appId);
834
+ return backgroundRefreshControllers.size > 0;
835
+ }
836
+ async function sleep(ms, signal) {
837
+ return new Promise((resolve, reject) => {
838
+ const timer = setTimeout(resolve, ms);
839
+ if (signal) {
840
+ if (signal.aborted) {
841
+ clearTimeout(timer);
842
+ reject(new Error("Aborted"));
843
+ return;
844
+ }
845
+ const onAbort = () => {
846
+ clearTimeout(timer);
847
+ reject(new Error("Aborted"));
848
+ };
849
+ signal.addEventListener("abort", onAbort, { once: true });
850
+ }
851
+ });
852
+ }
853
+ import { StreamInputState } from "./types.js";
854
+ /**
855
+ * 发送流式消息(C2C 私聊)
856
+ *
857
+ * 流式协议:
858
+ * - 首次调用时不传 stream_msg_id,由平台返回
859
+ * - 后续分片携带 stream_msg_id 和递增 msg_seq
860
+ * - input_state="1" 表示生成中,"10" 表示生成结束(终结状态)
861
+ *
862
+ * 仅在终结分片(input_state=DONE)时触发 refIdx 回调,
863
+ * 中间分片直接调用 apiRequest,避免存入过多无效的中间态数据。
864
+ *
865
+ * @param accessToken - access_token
866
+ * @param openid - 用户 openid
867
+ * @param req - 流式消息请求体
868
+ * @returns 消息响应(复用 MessageResponse,错误会直接抛出异常)
869
+ */
870
+ export async function sendC2CStreamMessage(accessToken, openid, req) {
871
+ const path = `/v2/users/${openid}/stream_messages`;
872
+ const body = {
873
+ input_mode: req.input_mode,
874
+ input_state: req.input_state,
875
+ content_type: req.content_type,
876
+ content_raw: req.content_raw,
877
+ event_id: req.event_id,
878
+ msg_id: req.msg_id,
879
+ msg_seq: req.msg_seq,
880
+ index: req.index,
881
+ };
882
+ if (req.stream_msg_id) {
883
+ body.stream_msg_id = req.stream_msg_id;
884
+ }
885
+ // 仅终结分片触发引用回调,中间分片跳过
886
+ if (req.input_state === StreamInputState.DONE) {
887
+ return sendAndNotify(accessToken, "POST", path, body, { text: req.content_raw });
888
+ }
889
+ return apiRequest(accessToken, "POST", path, body);
890
+ }