@sliverp/qqbot 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +231 -0
  2. package/clawdbot.plugin.json +16 -0
  3. package/dist/index.d.ts +17 -0
  4. package/dist/index.js +22 -0
  5. package/dist/src/api.d.ts +194 -0
  6. package/dist/src/api.js +555 -0
  7. package/dist/src/channel.d.ts +3 -0
  8. package/dist/src/channel.js +146 -0
  9. package/dist/src/config.d.ts +25 -0
  10. package/dist/src/config.js +148 -0
  11. package/dist/src/gateway.d.ts +17 -0
  12. package/dist/src/gateway.js +722 -0
  13. package/dist/src/image-server.d.ts +62 -0
  14. package/dist/src/image-server.js +401 -0
  15. package/dist/src/known-users.d.ts +100 -0
  16. package/dist/src/known-users.js +264 -0
  17. package/dist/src/onboarding.d.ts +10 -0
  18. package/dist/src/onboarding.js +190 -0
  19. package/dist/src/outbound.d.ts +149 -0
  20. package/dist/src/outbound.js +476 -0
  21. package/dist/src/proactive.d.ts +170 -0
  22. package/dist/src/proactive.js +398 -0
  23. package/dist/src/runtime.d.ts +3 -0
  24. package/dist/src/runtime.js +10 -0
  25. package/dist/src/session-store.d.ts +49 -0
  26. package/dist/src/session-store.js +242 -0
  27. package/dist/src/types.d.ts +116 -0
  28. package/dist/src/types.js +1 -0
  29. package/dist/src/utils/image-size.d.ts +51 -0
  30. package/dist/src/utils/image-size.js +234 -0
  31. package/dist/src/utils/payload.d.ts +112 -0
  32. package/dist/src/utils/payload.js +186 -0
  33. package/index.ts +27 -0
  34. package/moltbot.plugin.json +16 -0
  35. package/node_modules/ws/LICENSE +20 -0
  36. package/node_modules/ws/README.md +548 -0
  37. package/node_modules/ws/browser.js +8 -0
  38. package/node_modules/ws/index.js +13 -0
  39. package/node_modules/ws/lib/buffer-util.js +131 -0
  40. package/node_modules/ws/lib/constants.js +19 -0
  41. package/node_modules/ws/lib/event-target.js +292 -0
  42. package/node_modules/ws/lib/extension.js +203 -0
  43. package/node_modules/ws/lib/limiter.js +55 -0
  44. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  45. package/node_modules/ws/lib/receiver.js +706 -0
  46. package/node_modules/ws/lib/sender.js +602 -0
  47. package/node_modules/ws/lib/stream.js +161 -0
  48. package/node_modules/ws/lib/subprotocol.js +62 -0
  49. package/node_modules/ws/lib/validation.js +152 -0
  50. package/node_modules/ws/lib/websocket-server.js +554 -0
  51. package/node_modules/ws/lib/websocket.js +1393 -0
  52. package/node_modules/ws/package.json +69 -0
  53. package/node_modules/ws/wrapper.mjs +8 -0
  54. package/openclaw.plugin.json +16 -0
  55. package/package.json +38 -0
  56. package/qqbot-1.3.0.tgz +0 -0
  57. package/scripts/proactive-api-server.ts +346 -0
  58. package/scripts/send-proactive.ts +273 -0
  59. package/scripts/upgrade.sh +106 -0
  60. package/skills/qqbot-cron/SKILL.md +490 -0
  61. package/skills/qqbot-media/SKILL.md +138 -0
  62. package/src/api.ts +752 -0
  63. package/src/channel.ts +303 -0
  64. package/src/config.ts +172 -0
  65. package/src/gateway.ts +1588 -0
  66. package/src/image-server.ts +474 -0
  67. package/src/known-users.ts +358 -0
  68. package/src/onboarding.ts +254 -0
  69. package/src/openclaw-plugin-sdk.d.ts +483 -0
  70. package/src/outbound.ts +571 -0
  71. package/src/proactive.ts +528 -0
  72. package/src/runtime.ts +14 -0
  73. package/src/session-store.ts +292 -0
  74. package/src/types.ts +123 -0
  75. package/src/utils/image-size.ts +266 -0
  76. package/src/utils/payload.ts +265 -0
  77. package/tsconfig.json +16 -0
  78. package/upgrade-and-run.sh +89 -0
@@ -0,0 +1,474 @@
1
+ /**
2
+ * 本地图床服务器
3
+ * 提供安全的图片存储和访问服务
4
+ */
5
+
6
+ import http from "node:http";
7
+ import fs from "node:fs";
8
+ import path from "node:path";
9
+ import crypto from "node:crypto";
10
+
11
+ export interface ImageServerConfig {
12
+ /** 监听端口 */
13
+ port: number;
14
+ /** 图片存储目录 */
15
+ storageDir: string;
16
+ /** 外部访问的基础 URL(如 http://your-server:port),留空则自动生成 */
17
+ baseUrl?: string;
18
+ /** 图片过期时间(秒),0 表示不过期 */
19
+ ttlSeconds?: number;
20
+ /** 允许的图片格式 */
21
+ allowedFormats?: string[];
22
+ }
23
+
24
+ interface StoredImage {
25
+ id: string;
26
+ filename: string;
27
+ mimeType: string;
28
+ createdAt: number;
29
+ ttl: number;
30
+ }
31
+
32
+ const DEFAULT_CONFIG: Required<ImageServerConfig> = {
33
+ port: 18765,
34
+ storageDir: "./qqbot-images",
35
+ baseUrl: "",
36
+ ttlSeconds: 3600, // 默认 1 小时过期
37
+ allowedFormats: ["png", "jpg", "jpeg", "gif", "webp"],
38
+ };
39
+
40
+ let serverInstance: http.Server | null = null;
41
+ let currentConfig: Required<ImageServerConfig> = { ...DEFAULT_CONFIG };
42
+ let imageIndex = new Map<string, StoredImage>();
43
+
44
+ /**
45
+ * 生成安全的随机 ID
46
+ */
47
+ function generateImageId(): string {
48
+ return crypto.randomBytes(16).toString("hex");
49
+ }
50
+
51
+ /**
52
+ * 验证请求路径是否安全(防止目录遍历攻击)
53
+ */
54
+ function isPathSafe(requestPath: string, baseDir: string): boolean {
55
+ const normalizedBase = path.resolve(baseDir);
56
+ const normalizedPath = path.resolve(baseDir, requestPath);
57
+ return normalizedPath.startsWith(normalizedBase + path.sep) || normalizedPath === normalizedBase;
58
+ }
59
+
60
+ /**
61
+ * 获取 MIME 类型
62
+ */
63
+ function getMimeType(ext: string): string {
64
+ const mimeTypes: Record<string, string> = {
65
+ png: "image/png",
66
+ jpg: "image/jpeg",
67
+ jpeg: "image/jpeg",
68
+ gif: "image/gif",
69
+ webp: "image/webp",
70
+ };
71
+ return mimeTypes[ext.toLowerCase()] || "application/octet-stream";
72
+ }
73
+
74
+ /**
75
+ * 从 MIME 类型获取扩展名
76
+ */
77
+ function getExtFromMime(mimeType: string): string | null {
78
+ const extMap: Record<string, string> = {
79
+ "image/png": "png",
80
+ "image/jpeg": "jpg",
81
+ "image/gif": "gif",
82
+ "image/webp": "webp",
83
+ "application/pdf": "pdf",
84
+ "application/json": "json",
85
+ "text/plain": "txt",
86
+ "text/csv": "csv",
87
+ "application/msword": "doc",
88
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
89
+ "application/vnd.ms-excel": "xls",
90
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
91
+ };
92
+ return extMap[mimeType] || null;
93
+ }
94
+
95
+ /**
96
+ * 清理过期图片
97
+ */
98
+ function cleanupExpiredImages(): void {
99
+ const now = Date.now();
100
+ const expiredIds: string[] = [];
101
+
102
+ for (const [id, image] of imageIndex) {
103
+ if (image.ttl > 0 && now - image.createdAt > image.ttl * 1000) {
104
+ expiredIds.push(id);
105
+ }
106
+ }
107
+
108
+ for (const id of expiredIds) {
109
+ const image = imageIndex.get(id);
110
+ if (image) {
111
+ const filePath = path.join(currentConfig.storageDir, image.filename);
112
+ try {
113
+ if (fs.existsSync(filePath)) {
114
+ fs.unlinkSync(filePath);
115
+ }
116
+ } catch {
117
+ // 忽略删除错误
118
+ }
119
+ imageIndex.delete(id);
120
+ }
121
+ }
122
+ }
123
+
124
+ /**
125
+ * 加载已有的图片索引
126
+ */
127
+ function loadImageIndex(): void {
128
+ const indexPath = path.join(currentConfig.storageDir, ".index.json");
129
+ try {
130
+ if (fs.existsSync(indexPath)) {
131
+ const data = JSON.parse(fs.readFileSync(indexPath, "utf-8"));
132
+ imageIndex = new Map(Object.entries(data));
133
+ }
134
+ } catch {
135
+ imageIndex = new Map();
136
+ }
137
+ }
138
+
139
+ /**
140
+ * 保存图片索引
141
+ */
142
+ function saveImageIndex(): void {
143
+ const indexPath = path.join(currentConfig.storageDir, ".index.json");
144
+ try {
145
+ const data = Object.fromEntries(imageIndex);
146
+ fs.writeFileSync(indexPath, JSON.stringify(data, null, 2));
147
+ } catch {
148
+ // 忽略保存错误
149
+ }
150
+ }
151
+
152
+ /**
153
+ * 处理 HTTP 请求
154
+ */
155
+ function handleRequest(req: http.IncomingMessage, res: http.ServerResponse): void {
156
+ const url = new URL(req.url || "/", `http://localhost:${currentConfig.port}`);
157
+ const pathname = url.pathname;
158
+
159
+ // 设置 CORS 头(允许 QQ 服务器访问)
160
+ res.setHeader("Access-Control-Allow-Origin", "*");
161
+ res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
162
+
163
+ if (req.method === "OPTIONS") {
164
+ res.writeHead(204);
165
+ res.end();
166
+ return;
167
+ }
168
+
169
+ // 只允许 GET 请求访问图片
170
+ if (req.method !== "GET") {
171
+ res.writeHead(405, { "Content-Type": "text/plain" });
172
+ res.end("Method Not Allowed");
173
+ return;
174
+ }
175
+
176
+ // 解析图片 ID(路径格式: /images/{id}.{ext})
177
+ const match = pathname.match(/^\/images\/([a-f0-9]{32})\.(\w+)$/);
178
+ if (!match) {
179
+ res.writeHead(404, { "Content-Type": "text/plain" });
180
+ res.end("Not Found");
181
+ return;
182
+ }
183
+
184
+ const [, imageId, requestedExt] = match;
185
+ const image = imageIndex.get(imageId);
186
+
187
+ if (!image) {
188
+ res.writeHead(404, { "Content-Type": "text/plain" });
189
+ res.end("Image Not Found");
190
+ return;
191
+ }
192
+
193
+ // 检查是否过期
194
+ if (image.ttl > 0 && Date.now() - image.createdAt > image.ttl * 1000) {
195
+ res.writeHead(410, { "Content-Type": "text/plain" });
196
+ res.end("Image Expired");
197
+ return;
198
+ }
199
+
200
+ // 安全检查:确保文件路径在存储目录内
201
+ const filePath = path.join(currentConfig.storageDir, image.filename);
202
+ if (!isPathSafe(image.filename, currentConfig.storageDir)) {
203
+ res.writeHead(403, { "Content-Type": "text/plain" });
204
+ res.end("Forbidden");
205
+ return;
206
+ }
207
+
208
+ // 读取并返回图片
209
+ try {
210
+ if (!fs.existsSync(filePath)) {
211
+ res.writeHead(404, { "Content-Type": "text/plain" });
212
+ res.end("File Not Found");
213
+ return;
214
+ }
215
+
216
+ const imageData = fs.readFileSync(filePath);
217
+ res.writeHead(200, {
218
+ "Content-Type": image.mimeType,
219
+ "Content-Length": imageData.length,
220
+ "Cache-Control": image.ttl > 0 ? `max-age=${image.ttl}` : "max-age=31536000",
221
+ });
222
+ res.end(imageData);
223
+ } catch (err) {
224
+ res.writeHead(500, { "Content-Type": "text/plain" });
225
+ res.end("Internal Server Error");
226
+ }
227
+ }
228
+
229
+ /**
230
+ * 启动图床服务器
231
+ */
232
+ export function startImageServer(config?: Partial<ImageServerConfig>): Promise<string> {
233
+ return new Promise((resolve, reject) => {
234
+ if (serverInstance) {
235
+ const baseUrl = currentConfig.baseUrl || `http://localhost:${currentConfig.port}`;
236
+ resolve(baseUrl);
237
+ return;
238
+ }
239
+
240
+ currentConfig = { ...DEFAULT_CONFIG, ...config };
241
+
242
+ // 确保存储目录存在
243
+ if (!fs.existsSync(currentConfig.storageDir)) {
244
+ fs.mkdirSync(currentConfig.storageDir, { recursive: true });
245
+ }
246
+
247
+ // 加载图片索引
248
+ loadImageIndex();
249
+
250
+ // 启动定期清理
251
+ const cleanupInterval = setInterval(cleanupExpiredImages, 60000); // 每分钟清理一次
252
+
253
+ serverInstance = http.createServer(handleRequest);
254
+
255
+ serverInstance.on("error", (err) => {
256
+ clearInterval(cleanupInterval);
257
+ reject(err);
258
+ });
259
+
260
+ serverInstance.listen(currentConfig.port, () => {
261
+ const baseUrl = currentConfig.baseUrl || `http://localhost:${currentConfig.port}`;
262
+ resolve(baseUrl);
263
+ });
264
+ });
265
+ }
266
+
267
+ /**
268
+ * 停止图床服务器
269
+ */
270
+ export function stopImageServer(): Promise<void> {
271
+ return new Promise((resolve) => {
272
+ if (serverInstance) {
273
+ serverInstance.close(() => {
274
+ serverInstance = null;
275
+ saveImageIndex();
276
+ resolve();
277
+ });
278
+ } else {
279
+ resolve();
280
+ }
281
+ });
282
+ }
283
+
284
+ /**
285
+ * 保存图片并返回访问 URL
286
+ * @param imageData 图片数据(Buffer 或 base64 字符串)
287
+ * @param mimeType 图片 MIME 类型
288
+ * @param ttlSeconds 过期时间(秒),默认使用配置值
289
+ * @returns 图片访问 URL
290
+ */
291
+ export function saveImage(
292
+ imageData: Buffer | string,
293
+ mimeType: string = "image/png",
294
+ ttlSeconds?: number
295
+ ): string {
296
+ // 转换 base64 为 Buffer
297
+ let buffer: Buffer;
298
+ if (typeof imageData === "string") {
299
+ // 处理 data URL 格式
300
+ const base64Match = imageData.match(/^data:([^;]+);base64,(.+)$/);
301
+ if (base64Match) {
302
+ mimeType = base64Match[1];
303
+ buffer = Buffer.from(base64Match[2], "base64");
304
+ } else {
305
+ buffer = Buffer.from(imageData, "base64");
306
+ }
307
+ } else {
308
+ buffer = imageData;
309
+ }
310
+
311
+ // 生成唯一 ID 和文件名
312
+ const imageId = generateImageId();
313
+ const ext = getExtFromMime(mimeType) || "png";
314
+ const filename = `${imageId}.${ext}`;
315
+
316
+ // 确保存储目录存在
317
+ if (!fs.existsSync(currentConfig.storageDir)) {
318
+ fs.mkdirSync(currentConfig.storageDir, { recursive: true });
319
+ }
320
+
321
+ // 保存文件
322
+ const filePath = path.join(currentConfig.storageDir, filename);
323
+ fs.writeFileSync(filePath, buffer);
324
+
325
+ // 记录到索引
326
+ const image: StoredImage = {
327
+ id: imageId,
328
+ filename,
329
+ mimeType,
330
+ createdAt: Date.now(),
331
+ ttl: ttlSeconds ?? currentConfig.ttlSeconds,
332
+ };
333
+ imageIndex.set(imageId, image);
334
+ saveImageIndex();
335
+
336
+ // 返回访问 URL
337
+ const baseUrl = currentConfig.baseUrl || `http://localhost:${currentConfig.port}`;
338
+ return `${baseUrl}/images/${imageId}.${ext}`;
339
+ }
340
+
341
+ /**
342
+ * 从本地文件路径保存图片到图床
343
+ * @param filePath 本地文件路径
344
+ * @param ttlSeconds 过期时间(秒),默认使用配置值
345
+ * @returns 图片访问 URL,如果文件不存在或不是图片则返回 null
346
+ */
347
+ export function saveImageFromPath(filePath: string, ttlSeconds?: number): string | null {
348
+ try {
349
+ console.log(`[image-server] saveImageFromPath: ${filePath}`);
350
+
351
+ // 检查文件是否存在
352
+ if (!fs.existsSync(filePath)) {
353
+ console.log(`[image-server] File not found: ${filePath}`);
354
+ return null;
355
+ }
356
+
357
+ // 读取文件
358
+ const buffer = fs.readFileSync(filePath);
359
+ console.log(`[image-server] File size: ${buffer.length}`);
360
+
361
+ // 根据扩展名获取 MIME 类型
362
+ const ext = path.extname(filePath).toLowerCase().replace(".", "");
363
+ console.log(`[image-server] Extension: "${ext}"`);
364
+ const mimeType = getMimeType(ext);
365
+ console.log(`[image-server] MIME type: ${mimeType}`);
366
+
367
+ // 只处理图片文件
368
+ if (!mimeType.startsWith("image/")) {
369
+ console.log(`[image-server] Not an image file`);
370
+ return null;
371
+ }
372
+
373
+ // 使用 saveImage 保存
374
+ return saveImage(buffer, mimeType, ttlSeconds);
375
+ } catch (err) {
376
+ console.error(`[image-server] saveImageFromPath error:`, err);
377
+ return null;
378
+ }
379
+ }
380
+
381
+ /**
382
+ * 检查图床服务器是否运行中
383
+ */
384
+ export function isImageServerRunning(): boolean {
385
+ return serverInstance !== null;
386
+ }
387
+
388
+ /**
389
+ * 确保图床服务器正在运行
390
+ * 如果未运行,则自动启动
391
+ * @param publicBaseUrl 公网访问的基础 URL(如 http://your-server:18765)
392
+ * @returns 基础 URL,启动失败返回 null
393
+ */
394
+ export async function ensureImageServer(publicBaseUrl?: string): Promise<string | null> {
395
+ if (isImageServerRunning()) {
396
+ return publicBaseUrl || currentConfig.baseUrl || `http://0.0.0.0:${currentConfig.port}`;
397
+ }
398
+
399
+ try {
400
+ const config: Partial<ImageServerConfig> = {
401
+ port: DEFAULT_CONFIG.port,
402
+ storageDir: DEFAULT_CONFIG.storageDir,
403
+ // 使用用户配置的公网地址
404
+ baseUrl: publicBaseUrl || `http://0.0.0.0:${DEFAULT_CONFIG.port}`,
405
+ ttlSeconds: 3600, // 1 小时过期
406
+ };
407
+ await startImageServer(config);
408
+ console.log(`[image-server] Auto-started on port ${config.port}, baseUrl: ${config.baseUrl}`);
409
+ return config.baseUrl!;
410
+ } catch (err) {
411
+ console.error(`[image-server] Failed to auto-start: ${err}`);
412
+ return null;
413
+ }
414
+ }
415
+
416
+ /**
417
+ * 下载远程文件并保存到本地
418
+ * @param url 远程文件 URL
419
+ * @param destDir 目标目录
420
+ * @param originalFilename 原始文件名(可选,完整文件名包含扩展名)
421
+ * @returns 本地文件路径,失败返回 null
422
+ */
423
+ export async function downloadFile(
424
+ url: string,
425
+ destDir: string,
426
+ originalFilename?: string
427
+ ): Promise<string | null> {
428
+ try {
429
+ // 确保目录存在
430
+ if (!fs.existsSync(destDir)) {
431
+ fs.mkdirSync(destDir, { recursive: true });
432
+ }
433
+
434
+ // 下载文件
435
+ const response = await fetch(url);
436
+ if (!response.ok) {
437
+ console.error(`[image-server] Download failed: ${response.status} ${response.statusText}`);
438
+ return null;
439
+ }
440
+
441
+ const buffer = Buffer.from(await response.arrayBuffer());
442
+
443
+ // 确定文件名
444
+ let finalFilename: string;
445
+ if (originalFilename) {
446
+ // 使用原始文件名,但添加时间戳避免冲突
447
+ const ext = path.extname(originalFilename);
448
+ const baseName = path.basename(originalFilename, ext);
449
+ const timestamp = Date.now();
450
+ finalFilename = `${baseName}_${timestamp}${ext}`;
451
+ } else {
452
+ // 没有原始文件名,生成随机名
453
+ finalFilename = `${generateImageId()}.bin`;
454
+ }
455
+
456
+ const filePath = path.join(destDir, finalFilename);
457
+
458
+ // 保存文件
459
+ fs.writeFileSync(filePath, buffer);
460
+ console.log(`[image-server] Downloaded file: ${filePath}`);
461
+
462
+ return filePath;
463
+ } catch (err) {
464
+ console.error(`[image-server] Download error:`, err);
465
+ return null;
466
+ }
467
+ }
468
+
469
+ /**
470
+ * 获取图床服务器配置
471
+ */
472
+ export function getImageServerConfig(): Required<ImageServerConfig> {
473
+ return { ...currentConfig };
474
+ }