@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,243 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * qqbot CLI - 用于升级和管理 qqbot 插件
5
+ *
6
+ * 用法:
7
+ * npx openclaw-qqbot upgrade # 升级插件
8
+ * npx openclaw-qqbot install # 安装插件
9
+ */
10
+
11
+ import { execSync } from 'child_process';
12
+ import { existsSync, readFileSync, writeFileSync, rmSync } from 'fs';
13
+ import { homedir } from 'os';
14
+ import { join, dirname } from 'path';
15
+ import { fileURLToPath } from 'url';
16
+
17
+ const __filename = fileURLToPath(import.meta.url);
18
+ const __dirname = dirname(__filename);
19
+
20
+ // 获取包的根目录
21
+ const PKG_ROOT = join(__dirname, '..');
22
+
23
+ const args = process.argv.slice(2);
24
+ const command = args[0];
25
+
26
+ // 检测使用的是 clawdbot 还是 openclaw
27
+ function detectInstallation() {
28
+ const home = homedir();
29
+ if (existsSync(join(home, '.openclaw'))) {
30
+ return 'openclaw';
31
+ }
32
+ if (existsSync(join(home, '.clawdbot'))) {
33
+ return 'clawdbot';
34
+ }
35
+ return null;
36
+ }
37
+
38
+ // 需要清理的所有可能的插件 ID / 包名(原仓库 + 本仓库 + 框架推断名)
39
+ const PLUGIN_IDS = ['qqbot', 'openclaw-qq', '@sliverp/qqbot', '@tencent-connect/openclaw-qq', '@tencent-connect/qqbot', '@tencent-connect/openclaw-qqbot', 'openclaw-qqbot'];
40
+ // 可能的扩展目录名
41
+ const EXTENSION_DIR_NAMES = ['qqbot', 'openclaw-qq', 'openclaw-qqbot'];
42
+
43
+ // 清理旧版本插件,返回旧的 qqbot 配置
44
+ function cleanupInstallation(appName) {
45
+ const home = homedir();
46
+ const appDir = join(home, `.${appName}`);
47
+ const configFile = join(appDir, `${appName}.json`);
48
+
49
+ let oldQqbotConfig = null;
50
+
51
+ console.log(`\n>>> 处理 ${appName} 安装...`);
52
+
53
+ // 1. 先读取旧的 qqbot 配置(尝试所有可能的 channel key)
54
+ if (existsSync(configFile)) {
55
+ try {
56
+ const config = JSON.parse(readFileSync(configFile, 'utf8'));
57
+ if (config.channels?.qqbot) {
58
+ oldQqbotConfig = { ...config.channels.qqbot };
59
+ console.log('已保存旧的 qqbot 配置');
60
+ }
61
+ } catch (err) {
62
+ console.error('读取配置文件失败:', err.message);
63
+ }
64
+ }
65
+
66
+ // 2. 删除所有可能的旧扩展目录
67
+ for (const dirName of EXTENSION_DIR_NAMES) {
68
+ const extensionDir = join(appDir, 'extensions', dirName);
69
+ if (existsSync(extensionDir)) {
70
+ console.log(`删除旧版本插件: ${extensionDir}`);
71
+ rmSync(extensionDir, { recursive: true, force: true });
72
+ }
73
+ }
74
+
75
+ // 3. 清理配置文件中所有可能的插件 ID 相关字段
76
+ if (existsSync(configFile)) {
77
+ console.log('清理配置文件中的插件字段...');
78
+ try {
79
+ const config = JSON.parse(readFileSync(configFile, 'utf8'));
80
+
81
+ for (const id of PLUGIN_IDS) {
82
+ // 删除 channels.<id>
83
+ if (config.channels?.[id]) {
84
+ delete config.channels[id];
85
+ console.log(` - 已删除 channels.${id}`);
86
+ }
87
+
88
+ // 删除 plugins.entries.<id>
89
+ if (config.plugins?.entries?.[id]) {
90
+ delete config.plugins.entries[id];
91
+ console.log(` - 已删除 plugins.entries.${id}`);
92
+ }
93
+
94
+ // 删除 plugins.installs.<id>
95
+ if (config.plugins?.installs?.[id]) {
96
+ delete config.plugins.installs[id];
97
+ console.log(` - 已删除 plugins.installs.${id}`);
98
+ }
99
+
100
+ // 删除 plugins.allow 中的 <id>
101
+ if (Array.isArray(config.plugins?.allow)) {
102
+ const before = config.plugins.allow.length;
103
+ config.plugins.allow = config.plugins.allow.filter((x) => x !== id);
104
+ if (config.plugins.allow.length !== before) {
105
+ console.log(` - 已删除 plugins.allow.${id}`);
106
+ }
107
+ }
108
+ }
109
+
110
+ writeFileSync(configFile, JSON.stringify(config, null, 2));
111
+ console.log('配置文件已更新');
112
+ } catch (err) {
113
+ console.error('清理配置文件失败:', err.message);
114
+ }
115
+ } else {
116
+ console.log(`未找到配置文件: ${configFile}`);
117
+ }
118
+
119
+ return oldQqbotConfig;
120
+ }
121
+
122
+ // 执行命令并继承 stdio
123
+ function runCommand(cmd, args = []) {
124
+ try {
125
+ execSync([cmd, ...args].join(' '), { stdio: 'inherit' });
126
+ return true;
127
+ } catch (err) {
128
+ return false;
129
+ }
130
+ }
131
+
132
+ // 升级命令
133
+ function upgrade() {
134
+ console.log('=== qqbot 插件升级脚本 ===');
135
+
136
+ let foundInstallation = null;
137
+ let savedConfig = null;
138
+ const home = homedir();
139
+
140
+ // 检查 openclaw
141
+ if (existsSync(join(home, '.openclaw'))) {
142
+ savedConfig = cleanupInstallation('openclaw');
143
+ foundInstallation = 'openclaw';
144
+ }
145
+
146
+ // 检查 clawdbot
147
+ if (existsSync(join(home, '.clawdbot'))) {
148
+ const clawdbotConfig = cleanupInstallation('clawdbot');
149
+ if (!savedConfig) savedConfig = clawdbotConfig;
150
+ foundInstallation = 'clawdbot';
151
+ }
152
+
153
+ if (!foundInstallation) {
154
+ console.log('\n未找到 clawdbot 或 openclaw 安装目录');
155
+ console.log('请确认已安装 clawdbot 或 openclaw');
156
+ process.exit(1);
157
+ }
158
+
159
+ console.log('\n=== 清理完成 ===');
160
+
161
+ // 自动安装插件
162
+ console.log('\n[1/2] 安装新版本插件...');
163
+ runCommand(foundInstallation, ['plugins', 'install', 'openclaw-qqbot']);
164
+
165
+ // 自动配置通道(使用保存的 appId 和 clientSecret)
166
+ console.log('\n[2/2] 配置机器人通道...');
167
+ if (savedConfig?.appId && savedConfig?.clientSecret) {
168
+ const token = `${savedConfig.appId}:${savedConfig.clientSecret}`;
169
+ console.log(`使用已保存的配置: appId=${savedConfig.appId}`);
170
+ runCommand(foundInstallation, ['channels', 'add', '--channel', 'qqbot', '--token', `"${token}"`]);
171
+
172
+ // 恢复其他配置项(如 markdownSupport)
173
+ if (savedConfig.markdownSupport !== undefined) {
174
+ runCommand(foundInstallation, ['config', 'set', 'channels.qqbot.markdownSupport', String(savedConfig.markdownSupport)]);
175
+ }
176
+ } else {
177
+ console.log('未找到已保存的 qqbot 配置,请手动配置:');
178
+ console.log(` ${foundInstallation} channels add --channel qqbot --token "appid:appsecret"`);
179
+ return;
180
+ }
181
+
182
+ console.log('\n=== 升级完成 ===');
183
+ console.log(`\n可以运行以下命令前台运行启动机器人:`);
184
+ console.log(` ${foundInstallation} gateway stop && ${foundInstallation} gateway --port 18789 --verbose`);
185
+ }
186
+
187
+ // 安装命令
188
+ function install() {
189
+ console.log('=== qqbot 插件安装 ===');
190
+
191
+ const cmd = detectInstallation();
192
+ if (!cmd) {
193
+ console.log('未找到 clawdbot 或 openclaw 安装');
194
+ console.log('请先安装 openclaw 或 clawdbot');
195
+ process.exit(1);
196
+ }
197
+
198
+ console.log(`\n使用 ${cmd} 安装插件...`);
199
+ runCommand(cmd, ['plugins', 'install', '@tencent-connect/openclaw-qqbot']);
200
+
201
+ console.log('\n=== 安装完成 ===');
202
+ console.log('\n请配置机器人通道:');
203
+ console.log(` ${cmd} channels add --channel qqbot --token "appid:appsecret"`);
204
+ }
205
+
206
+ // 显示帮助
207
+ function showHelp() {
208
+ console.log(`
209
+ qqbot CLI - QQ机器人插件管理工具
210
+
211
+ 用法:
212
+ npx openclaw-qqbot <命令>
213
+
214
+ 命令:
215
+ upgrade 清理旧版本插件(升级前执行)
216
+ install 安装插件到 openclaw/clawdbot
217
+
218
+ 示例:
219
+ npx openclaw-qqbot upgrade
220
+ npx openclaw-qqbot install
221
+ `);
222
+ }
223
+
224
+ // 主入口
225
+ switch (command) {
226
+ case 'upgrade':
227
+ upgrade();
228
+ break;
229
+ case 'install':
230
+ install();
231
+ break;
232
+ case '-h':
233
+ case '--help':
234
+ case 'help':
235
+ showHelp();
236
+ break;
237
+ default:
238
+ if (command) {
239
+ console.log(`未知命令: ${command}`);
240
+ }
241
+ showHelp();
242
+ process.exit(command ? 1 : 0);
243
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "id": "openclaw-qqbot",
3
+ "name": "OpenClaw QQ Bot",
4
+ "description": "QQ Bot channel plugin with message support, cron jobs, and proactive messaging",
5
+ "channels": ["qqbot"],
6
+ "skills": ["skills/qqbot-channel", "skills/qqbot-remind", "skills/qqbot-media"],
7
+ "capabilities": {
8
+ "proactiveMessaging": true,
9
+ "cronJobs": true
10
+ },
11
+ "configSchema": {
12
+ "type": "object",
13
+ "additionalProperties": false,
14
+ "properties": {}
15
+ }
16
+ }
@@ -0,0 +1,17 @@
1
+ import type { OpenClawPluginApi } from "openclaw/plugin-sdk";
2
+ declare const plugin: {
3
+ id: string;
4
+ name: string;
5
+ description: string;
6
+ configSchema: unknown;
7
+ register(api: OpenClawPluginApi): void;
8
+ };
9
+ export default plugin;
10
+ export { qqbotPlugin } from "./src/channel.js";
11
+ export { setQQBotRuntime, getQQBotRuntime } from "./src/runtime.js";
12
+ export { qqbotOnboardingAdapter } from "./src/onboarding.js";
13
+ export * from "./src/types.js";
14
+ export * from "./src/api.js";
15
+ export * from "./src/config.js";
16
+ export * from "./src/gateway.js";
17
+ export * from "./src/outbound.js";
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ import { emptyPluginConfigSchema } from "openclaw/plugin-sdk";
2
+ import { qqbotPlugin } from "./src/channel.js";
3
+ import { setQQBotRuntime } from "./src/runtime.js";
4
+ import { registerChannelTool } from "./src/tools/channel.js";
5
+ import { registerRemindTool } from "./src/tools/remind.js";
6
+ const plugin = {
7
+ id: "openclaw-qqbot",
8
+ name: "QQ Bot",
9
+ description: "QQ Bot channel plugin",
10
+ configSchema: emptyPluginConfigSchema(),
11
+ register(api) {
12
+ setQQBotRuntime(api.runtime);
13
+ api.registerChannel({ plugin: qqbotPlugin });
14
+ registerChannelTool(api);
15
+ registerRemindTool(api);
16
+ },
17
+ };
18
+ export default plugin;
19
+ export { qqbotPlugin } from "./src/channel.js";
20
+ export { setQQBotRuntime, getQQBotRuntime } from "./src/runtime.js";
21
+ export { qqbotOnboardingAdapter } from "./src/onboarding.js";
22
+ export * from "./src/types.js";
23
+ export * from "./src/api.js";
24
+ export * from "./src/config.js";
25
+ export * from "./src/gateway.js";
26
+ export * from "./src/outbound.js";
@@ -0,0 +1,27 @@
1
+ /**
2
+ * 管理员解析器模块
3
+ * - 管理员 openid 持久化读写
4
+ * - 升级问候目标读写
5
+ * - 启动问候语发送
6
+ */
7
+ export interface AdminResolverContext {
8
+ accountId: string;
9
+ appId: string;
10
+ clientSecret: string;
11
+ log?: {
12
+ info: (msg: string) => void;
13
+ error: (msg: string) => void;
14
+ };
15
+ }
16
+ export declare function loadAdminOpenId(accountId: string): string | undefined;
17
+ export declare function saveAdminOpenId(accountId: string, openid: string): void;
18
+ export declare function loadUpgradeGreetingTargetOpenId(accountId: string, appId: string): string | undefined;
19
+ export declare function clearUpgradeGreetingTargetOpenId(accountId: string, appId: string): void;
20
+ /**
21
+ * 解析管理员 openid:
22
+ * 1. 优先读持久化文件(稳定)
23
+ * 2. fallback 取第一个私聊用户,并写入文件锁定
24
+ */
25
+ export declare function resolveAdminOpenId(ctx: Pick<AdminResolverContext, "accountId" | "log">): string | undefined;
26
+ /** 异步发送启动问候语(仅发给管理员) */
27
+ export declare function sendStartupGreetings(ctx: AdminResolverContext, trigger: "READY" | "RESUMED"): void;
@@ -0,0 +1,122 @@
1
+ /**
2
+ * 管理员解析器模块
3
+ * - 管理员 openid 持久化读写
4
+ * - 升级问候目标读写
5
+ * - 启动问候语发送
6
+ */
7
+ import path from "node:path";
8
+ import * as fs from "node:fs";
9
+ import { getQQBotDataDir } from "./utils/platform.js";
10
+ import { listKnownUsers } from "./known-users.js";
11
+ import { getAccessToken, sendProactiveC2CMessage } from "./api.js";
12
+ import { getStartupGreetingPlan, markStartupGreetingSent, markStartupGreetingFailed } from "./startup-greeting.js";
13
+ // ---- 文件路径 ----
14
+ function getAdminMarkerFile(accountId) {
15
+ return path.join(getQQBotDataDir("data"), `admin-${accountId}.json`);
16
+ }
17
+ function getUpgradeGreetingTargetFile(accountId, appId) {
18
+ const safeAccountId = accountId.replace(/[^a-zA-Z0-9._-]/g, "_");
19
+ const safeAppId = appId.replace(/[^a-zA-Z0-9._-]/g, "_");
20
+ return path.join(getQQBotDataDir("data"), `upgrade-greeting-target-${safeAccountId}-${safeAppId}.json`);
21
+ }
22
+ // ---- 管理员 openid 持久化 ----
23
+ export function loadAdminOpenId(accountId) {
24
+ try {
25
+ const file = getAdminMarkerFile(accountId);
26
+ if (fs.existsSync(file)) {
27
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
28
+ if (data.openid)
29
+ return data.openid;
30
+ }
31
+ }
32
+ catch { /* 文件损坏视为无 */ }
33
+ return undefined;
34
+ }
35
+ export function saveAdminOpenId(accountId, openid) {
36
+ try {
37
+ fs.writeFileSync(getAdminMarkerFile(accountId), JSON.stringify({ openid, savedAt: new Date().toISOString() }));
38
+ }
39
+ catch { /* ignore */ }
40
+ }
41
+ // ---- 升级问候目标 ----
42
+ export function loadUpgradeGreetingTargetOpenId(accountId, appId) {
43
+ try {
44
+ const file = getUpgradeGreetingTargetFile(accountId, appId);
45
+ if (fs.existsSync(file)) {
46
+ const data = JSON.parse(fs.readFileSync(file, "utf8"));
47
+ if (!data.openid)
48
+ return undefined;
49
+ if (data.appId && data.appId !== appId)
50
+ return undefined;
51
+ if (data.accountId && data.accountId !== accountId)
52
+ return undefined;
53
+ return data.openid;
54
+ }
55
+ }
56
+ catch { /* 文件损坏视为无 */ }
57
+ return undefined;
58
+ }
59
+ export function clearUpgradeGreetingTargetOpenId(accountId, appId) {
60
+ try {
61
+ const file = getUpgradeGreetingTargetFile(accountId, appId);
62
+ if (fs.existsSync(file)) {
63
+ fs.unlinkSync(file);
64
+ }
65
+ }
66
+ catch { /* ignore */ }
67
+ }
68
+ // ---- 解析管理员 ----
69
+ /**
70
+ * 解析管理员 openid:
71
+ * 1. 优先读持久化文件(稳定)
72
+ * 2. fallback 取第一个私聊用户,并写入文件锁定
73
+ */
74
+ export function resolveAdminOpenId(ctx) {
75
+ const saved = loadAdminOpenId(ctx.accountId);
76
+ if (saved)
77
+ return saved;
78
+ const first = listKnownUsers({ accountId: ctx.accountId, type: "c2c", sortBy: "firstSeenAt", sortOrder: "asc", limit: 1 })[0]?.openid;
79
+ if (first) {
80
+ saveAdminOpenId(ctx.accountId, first);
81
+ ctx.log?.info(`[qqbot:${ctx.accountId}] Auto-detected admin openid: ${first} (persisted)`);
82
+ }
83
+ return first;
84
+ }
85
+ // ---- 启动问候语 ----
86
+ /** 异步发送启动问候语(仅发给管理员) */
87
+ export function sendStartupGreetings(ctx, trigger) {
88
+ (async () => {
89
+ const plan = getStartupGreetingPlan();
90
+ if (!plan.shouldSend || !plan.greeting) {
91
+ ctx.log?.info(`[qqbot:${ctx.accountId}] Skipping startup greeting (${plan.reason ?? "debounced"}, trigger=${trigger})`);
92
+ return;
93
+ }
94
+ const upgradeTargetOpenId = loadUpgradeGreetingTargetOpenId(ctx.accountId, ctx.appId);
95
+ const targetOpenId = upgradeTargetOpenId || resolveAdminOpenId(ctx);
96
+ if (!targetOpenId) {
97
+ markStartupGreetingFailed(plan.version, "no-admin");
98
+ ctx.log?.info(`[qqbot:${ctx.accountId}] Skipping startup greeting (no admin or known user)`);
99
+ return;
100
+ }
101
+ try {
102
+ const receiverType = upgradeTargetOpenId ? "upgrade-requester" : "admin";
103
+ ctx.log?.info(`[qqbot:${ctx.accountId}] Sending startup greeting to ${receiverType} (trigger=${trigger}): "${plan.greeting}"`);
104
+ const token = await getAccessToken(ctx.appId, ctx.clientSecret);
105
+ const GREETING_TIMEOUT_MS = 10_000;
106
+ await Promise.race([
107
+ sendProactiveC2CMessage(token, targetOpenId, plan.greeting),
108
+ new Promise((_, reject) => setTimeout(() => reject(new Error("Startup greeting send timeout (10s)")), GREETING_TIMEOUT_MS)),
109
+ ]);
110
+ markStartupGreetingSent(plan.version);
111
+ if (upgradeTargetOpenId) {
112
+ clearUpgradeGreetingTargetOpenId(ctx.accountId, ctx.appId);
113
+ }
114
+ ctx.log?.info(`[qqbot:${ctx.accountId}] Sent startup greeting to ${receiverType}: ${targetOpenId}`);
115
+ }
116
+ catch (err) {
117
+ const message = err instanceof Error ? err.message : String(err);
118
+ markStartupGreetingFailed(plan.version, message);
119
+ ctx.log?.error(`[qqbot:${ctx.accountId}] Failed to send startup greeting: ${message}`);
120
+ }
121
+ })();
122
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * QQ Bot API 鉴权和请求封装
3
+ * [修复版] 已重构为支持多实例并发,消除全局变量冲突
4
+ */
5
+ export declare const PLUGIN_USER_AGENT: string;
6
+ /** 出站消息元信息(结构化存储,不做预格式化) */
7
+ export interface OutboundMeta {
8
+ /** 消息文本内容 */
9
+ text?: string;
10
+ /** 媒体类型 */
11
+ mediaType?: "image" | "voice" | "video" | "file";
12
+ /** 媒体来源:在线 URL */
13
+ mediaUrl?: string;
14
+ /** 媒体来源:本地文件路径或文件名 */
15
+ mediaLocalPath?: string;
16
+ /** TTS 原文本(仅 voice 类型有效,用于保存 TTS 前的文本内容) */
17
+ ttsText?: string;
18
+ }
19
+ type OnMessageSentCallback = (refIdx: string, meta: OutboundMeta) => void;
20
+ /**
21
+ * 注册出站消息回调
22
+ * 当消息发送成功且 QQ 返回 ref_idx 时,自动回调此函数
23
+ * 用于在最底层统一缓存 bot 出站消息的 refIdx
24
+ */
25
+ export declare function onMessageSent(callback: OnMessageSentCallback): void;
26
+ /**
27
+ * 初始化 API 配置
28
+ * @param options.markdownSupport - 是否支持 markdown 消息(默认 false,需要机器人具备该权限才能启用)
29
+ */
30
+ export declare function initApiConfig(options: {
31
+ markdownSupport?: boolean;
32
+ }): void;
33
+ /**
34
+ * 获取当前是否支持 markdown
35
+ */
36
+ export declare function isMarkdownSupport(): boolean;
37
+ /**
38
+ * 获取 AccessToken(带缓存 + singleflight 并发安全)
39
+ *
40
+ * 使用 singleflight 模式:当多个请求同时发现 Token 过期时,
41
+ * 只有第一个请求会真正去获取新 Token,其他请求复用同一个 Promise。
42
+ *
43
+ * 按 appId 隔离,支持多机器人并发请求。
44
+ */
45
+ export declare function getAccessToken(appId: string, clientSecret: string): Promise<string>;
46
+ /**
47
+ * 清除 Token 缓存
48
+ * @param appId 选填。如果有,只清空特定账号的缓存;如果没有,清空所有账号。
49
+ */
50
+ export declare function clearTokenCache(appId?: string): void;
51
+ /**
52
+ * 获取 Token 缓存状态(用于监控)
53
+ */
54
+ export declare function getTokenStatus(appId: string): {
55
+ status: "valid" | "expired" | "refreshing" | "none";
56
+ expiresAt: number | null;
57
+ };
58
+ /**
59
+ * 获取全局唯一的消息序号(范围 0 ~ 65535)
60
+ * 使用毫秒级时间戳低位 + 随机数异或混合,无状态,避免碰撞
61
+ */
62
+ export declare function getNextMsgSeq(_msgId: string): number;
63
+ /**
64
+ * API 请求封装
65
+ */
66
+ export declare function apiRequest<T = unknown>(accessToken: string, method: string, path: string, body?: unknown, timeoutMs?: number): Promise<T>;
67
+ export declare function getGatewayUrl(accessToken: string): Promise<string>;
68
+ export interface MessageResponse {
69
+ id: string;
70
+ timestamp: number | string;
71
+ /** 消息的引用索引信息(出站时由 QQ 服务端返回) */
72
+ ext_info?: {
73
+ ref_idx?: string;
74
+ };
75
+ }
76
+ export declare function sendC2CMessage(accessToken: string, openid: string, content: string, msgId?: string, messageReference?: string): Promise<MessageResponse>;
77
+ export declare function sendC2CInputNotify(accessToken: string, openid: string, msgId?: string, inputSecond?: number): Promise<{
78
+ refIdx?: string;
79
+ }>;
80
+ export declare function sendChannelMessage(accessToken: string, channelId: string, content: string, msgId?: string): Promise<{
81
+ id: string;
82
+ timestamp: string;
83
+ }>;
84
+ /**
85
+ * 发送频道私信消息
86
+ * @param guildId - 私信会话的 guild_id(由 DIRECT_MESSAGE_CREATE 事件提供)
87
+ * @param msgId - 被动回复时必填
88
+ */
89
+ export declare function sendDmMessage(accessToken: string, guildId: string, content: string, msgId?: string): Promise<{
90
+ id: string;
91
+ timestamp: string;
92
+ }>;
93
+ export declare function sendGroupMessage(accessToken: string, groupOpenid: string, content: string, msgId?: string): Promise<MessageResponse>;
94
+ export declare function sendProactiveC2CMessage(accessToken: string, openid: string, content: string): Promise<MessageResponse>;
95
+ export declare function sendProactiveGroupMessage(accessToken: string, groupOpenid: string, content: string): Promise<{
96
+ id: string;
97
+ timestamp: string;
98
+ }>;
99
+ export declare enum MediaFileType {
100
+ IMAGE = 1,
101
+ VIDEO = 2,
102
+ VOICE = 3,
103
+ FILE = 4
104
+ }
105
+ export interface UploadMediaResponse {
106
+ file_uuid: string;
107
+ file_info: string;
108
+ ttl: number;
109
+ id?: string;
110
+ }
111
+ export declare function uploadC2CMedia(accessToken: string, openid: string, fileType: MediaFileType, url?: string, fileData?: string, srvSendMsg?: boolean, fileName?: string): Promise<UploadMediaResponse>;
112
+ export declare function uploadGroupMedia(accessToken: string, groupOpenid: string, fileType: MediaFileType, url?: string, fileData?: string, srvSendMsg?: boolean, fileName?: string): Promise<UploadMediaResponse>;
113
+ export declare function sendC2CMediaMessage(accessToken: string, openid: string, fileInfo: string, msgId?: string, content?: string, meta?: OutboundMeta): Promise<MessageResponse>;
114
+ export declare function sendGroupMediaMessage(accessToken: string, groupOpenid: string, fileInfo: string, msgId?: string, content?: string): Promise<{
115
+ id: string;
116
+ timestamp: string;
117
+ }>;
118
+ export declare function sendC2CImageMessage(accessToken: string, openid: string, imageUrl: string, msgId?: string, content?: string, localPath?: string): Promise<MessageResponse>;
119
+ export declare function sendGroupImageMessage(accessToken: string, groupOpenid: string, imageUrl: string, msgId?: string, content?: string): Promise<{
120
+ id: string;
121
+ timestamp: string;
122
+ }>;
123
+ export declare function sendC2CVoiceMessage(accessToken: string, openid: string, voiceBase64?: string, voiceUrl?: string, msgId?: string, ttsText?: string, filePath?: string): Promise<MessageResponse>;
124
+ export declare function sendGroupVoiceMessage(accessToken: string, groupOpenid: string, voiceBase64?: string, voiceUrl?: string, msgId?: string): Promise<{
125
+ id: string;
126
+ timestamp: string;
127
+ }>;
128
+ export declare function sendC2CFileMessage(accessToken: string, openid: string, fileBase64?: string, fileUrl?: string, msgId?: string, fileName?: string, localFilePath?: string): Promise<MessageResponse>;
129
+ export declare function sendGroupFileMessage(accessToken: string, groupOpenid: string, fileBase64?: string, fileUrl?: string, msgId?: string, fileName?: string): Promise<{
130
+ id: string;
131
+ timestamp: string;
132
+ }>;
133
+ export declare function sendC2CVideoMessage(accessToken: string, openid: string, videoUrl?: string, videoBase64?: string, msgId?: string, content?: string, localPath?: string): Promise<MessageResponse>;
134
+ export declare function sendGroupVideoMessage(accessToken: string, groupOpenid: string, videoUrl?: string, videoBase64?: string, msgId?: string, content?: string): Promise<{
135
+ id: string;
136
+ timestamp: string;
137
+ }>;
138
+ interface BackgroundTokenRefreshOptions {
139
+ refreshAheadMs?: number;
140
+ randomOffsetMs?: number;
141
+ minRefreshIntervalMs?: number;
142
+ retryDelayMs?: number;
143
+ log?: {
144
+ info: (msg: string) => void;
145
+ error: (msg: string) => void;
146
+ debug?: (msg: string) => void;
147
+ };
148
+ }
149
+ export declare function startBackgroundTokenRefresh(appId: string, clientSecret: string, options?: BackgroundTokenRefreshOptions): void;
150
+ /**
151
+ * 停止后台 Token 刷新
152
+ * @param appId 选填。如果有,仅停止该账号的定时刷新。
153
+ */
154
+ export declare function stopBackgroundTokenRefresh(appId?: string): void;
155
+ export declare function isBackgroundTokenRefreshRunning(appId?: string): boolean;
156
+ export {};