@tencent-connect/qqbot-nodejs 1.0.3
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.
- package/README.md +205 -0
- package/USAGE.md +804 -0
- package/dist/QQBot.d.ts +536 -0
- package/dist/QQBot.d.ts.map +1 -0
- package/dist/QQBot.js +752 -0
- package/dist/QQBot.js.map +1 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +66 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware/access-policy.d.ts +54 -0
- package/dist/middleware/access-policy.d.ts.map +1 -0
- package/dist/middleware/access-policy.js +93 -0
- package/dist/middleware/access-policy.js.map +1 -0
- package/dist/middleware/concurrency-guard.d.ts +105 -0
- package/dist/middleware/concurrency-guard.d.ts.map +1 -0
- package/dist/middleware/concurrency-guard.js +325 -0
- package/dist/middleware/concurrency-guard.js.map +1 -0
- package/dist/middleware/content-sanitizer.d.ts +47 -0
- package/dist/middleware/content-sanitizer.d.ts.map +1 -0
- package/dist/middleware/content-sanitizer.js +85 -0
- package/dist/middleware/content-sanitizer.js.map +1 -0
- package/dist/middleware/envelope-formatter.d.ts +51 -0
- package/dist/middleware/envelope-formatter.d.ts.map +1 -0
- package/dist/middleware/envelope-formatter.js +97 -0
- package/dist/middleware/envelope-formatter.js.map +1 -0
- package/dist/middleware/error-handler.d.ts +36 -0
- package/dist/middleware/error-handler.d.ts.map +1 -0
- package/dist/middleware/error-handler.js +59 -0
- package/dist/middleware/error-handler.js.map +1 -0
- package/dist/middleware/history-buffer.d.ts +84 -0
- package/dist/middleware/history-buffer.d.ts.map +1 -0
- package/dist/middleware/history-buffer.js +113 -0
- package/dist/middleware/history-buffer.js.map +1 -0
- package/dist/middleware/index.d.ts +71 -0
- package/dist/middleware/index.d.ts.map +1 -0
- package/dist/middleware/index.js +48 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/mention-gate.d.ts +99 -0
- package/dist/middleware/mention-gate.d.ts.map +1 -0
- package/dist/middleware/mention-gate.js +117 -0
- package/dist/middleware/mention-gate.js.map +1 -0
- package/dist/middleware/message-filter.d.ts +38 -0
- package/dist/middleware/message-filter.d.ts.map +1 -0
- package/dist/middleware/message-filter.js +60 -0
- package/dist/middleware/message-filter.js.map +1 -0
- package/dist/middleware/quote-ref.d.ts +106 -0
- package/dist/middleware/quote-ref.d.ts.map +1 -0
- package/dist/middleware/quote-ref.js +168 -0
- package/dist/middleware/quote-ref.js.map +1 -0
- package/dist/middleware/rate-limiter.d.ts +43 -0
- package/dist/middleware/rate-limiter.d.ts.map +1 -0
- package/dist/middleware/rate-limiter.js +77 -0
- package/dist/middleware/rate-limiter.js.map +1 -0
- package/dist/middleware/slash-command.d.ts +112 -0
- package/dist/middleware/slash-command.d.ts.map +1 -0
- package/dist/middleware/slash-command.js +203 -0
- package/dist/middleware/slash-command.js.map +1 -0
- package/dist/middleware/types.d.ts +175 -0
- package/dist/middleware/types.d.ts.map +1 -0
- package/dist/middleware/types.js +138 -0
- package/dist/middleware/types.js.map +1 -0
- package/dist/middleware/typing-indicator.d.ts +54 -0
- package/dist/middleware/typing-indicator.d.ts.map +1 -0
- package/dist/middleware/typing-indicator.js +68 -0
- package/dist/middleware/typing-indicator.js.map +1 -0
- package/dist/protocol/api/api-client.d.ts +27 -0
- package/dist/protocol/api/api-client.d.ts.map +1 -0
- package/dist/protocol/api/api-client.js +119 -0
- package/dist/protocol/api/api-client.js.map +1 -0
- package/dist/protocol/api/media-chunked.d.ts +68 -0
- package/dist/protocol/api/media-chunked.d.ts.map +1 -0
- package/dist/protocol/api/media-chunked.js +298 -0
- package/dist/protocol/api/media-chunked.js.map +1 -0
- package/dist/protocol/api/media.d.ts +46 -0
- package/dist/protocol/api/media.d.ts.map +1 -0
- package/dist/protocol/api/media.js +101 -0
- package/dist/protocol/api/media.js.map +1 -0
- package/dist/protocol/api/messages.d.ts +86 -0
- package/dist/protocol/api/messages.d.ts.map +1 -0
- package/dist/protocol/api/messages.js +200 -0
- package/dist/protocol/api/messages.js.map +1 -0
- package/dist/protocol/api/retry.d.ts +23 -0
- package/dist/protocol/api/retry.d.ts.map +1 -0
- package/dist/protocol/api/retry.js +102 -0
- package/dist/protocol/api/retry.js.map +1 -0
- package/dist/protocol/api/routes.d.ts +23 -0
- package/dist/protocol/api/routes.d.ts.map +1 -0
- package/dist/protocol/api/routes.js +50 -0
- package/dist/protocol/api/routes.js.map +1 -0
- package/dist/protocol/api/token.d.ts +38 -0
- package/dist/protocol/api/token.d.ts.map +1 -0
- package/dist/protocol/api/token.js +191 -0
- package/dist/protocol/api/token.js.map +1 -0
- package/dist/protocol/gateway/codec.d.ts +9 -0
- package/dist/protocol/gateway/codec.d.ts.map +1 -0
- package/dist/protocol/gateway/codec.js +32 -0
- package/dist/protocol/gateway/codec.js.map +1 -0
- package/dist/protocol/gateway/constants.d.ts +71 -0
- package/dist/protocol/gateway/constants.d.ts.map +1 -0
- package/dist/protocol/gateway/constants.js +91 -0
- package/dist/protocol/gateway/constants.js.map +1 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts +97 -0
- package/dist/protocol/gateway/event-dispatcher.d.ts.map +1 -0
- package/dist/protocol/gateway/event-dispatcher.js +155 -0
- package/dist/protocol/gateway/event-dispatcher.js.map +1 -0
- package/dist/protocol/gateway/gateway-connection.d.ts +73 -0
- package/dist/protocol/gateway/gateway-connection.d.ts.map +1 -0
- package/dist/protocol/gateway/gateway-connection.js +293 -0
- package/dist/protocol/gateway/gateway-connection.js.map +1 -0
- package/dist/protocol/gateway/reconnect.d.ts +25 -0
- package/dist/protocol/gateway/reconnect.d.ts.map +1 -0
- package/dist/protocol/gateway/reconnect.js +118 -0
- package/dist/protocol/gateway/reconnect.js.map +1 -0
- package/dist/protocol/index.d.ts +41 -0
- package/dist/protocol/index.d.ts.map +1 -0
- package/dist/protocol/index.js +46 -0
- package/dist/protocol/index.js.map +1 -0
- package/dist/protocol/transport/index.d.ts +8 -0
- package/dist/protocol/transport/index.d.ts.map +1 -0
- package/dist/protocol/transport/index.js +4 -0
- package/dist/protocol/transport/index.js.map +1 -0
- package/dist/protocol/transport/types.d.ts +109 -0
- package/dist/protocol/transport/types.d.ts.map +1 -0
- package/dist/protocol/transport/types.js +15 -0
- package/dist/protocol/transport/types.js.map +1 -0
- package/dist/protocol/transport/webhook-server-node.d.ts +14 -0
- package/dist/protocol/transport/webhook-server-node.d.ts.map +1 -0
- package/dist/protocol/transport/webhook-server-node.js +57 -0
- package/dist/protocol/transport/webhook-server-node.js.map +1 -0
- package/dist/protocol/transport/webhook-verify.d.ts +49 -0
- package/dist/protocol/transport/webhook-verify.d.ts.map +1 -0
- package/dist/protocol/transport/webhook-verify.js +98 -0
- package/dist/protocol/transport/webhook-verify.js.map +1 -0
- package/dist/protocol/transport/webhook.d.ts +37 -0
- package/dist/protocol/transport/webhook.d.ts.map +1 -0
- package/dist/protocol/transport/webhook.js +183 -0
- package/dist/protocol/transport/webhook.js.map +1 -0
- package/dist/protocol/types.d.ts +270 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +59 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/protocol/utils/audio.d.ts +79 -0
- package/dist/protocol/utils/audio.d.ts.map +1 -0
- package/dist/protocol/utils/audio.js +501 -0
- package/dist/protocol/utils/audio.js.map +1 -0
- package/dist/protocol/utils/decode-media-path.d.ts +26 -0
- package/dist/protocol/utils/decode-media-path.d.ts.map +1 -0
- package/dist/protocol/utils/decode-media-path.js +79 -0
- package/dist/protocol/utils/decode-media-path.js.map +1 -0
- package/dist/protocol/utils/ffmpeg.d.ts +38 -0
- package/dist/protocol/utils/ffmpeg.d.ts.map +1 -0
- package/dist/protocol/utils/ffmpeg.js +119 -0
- package/dist/protocol/utils/ffmpeg.js.map +1 -0
- package/dist/protocol/utils/file-utils.d.ts +42 -0
- package/dist/protocol/utils/file-utils.d.ts.map +1 -0
- package/dist/protocol/utils/file-utils.js +108 -0
- package/dist/protocol/utils/file-utils.js.map +1 -0
- package/dist/protocol/utils/format.d.ts +10 -0
- package/dist/protocol/utils/format.d.ts.map +1 -0
- package/dist/protocol/utils/format.js +68 -0
- package/dist/protocol/utils/format.js.map +1 -0
- package/dist/protocol/utils/image-size.d.ts +56 -0
- package/dist/protocol/utils/image-size.d.ts.map +1 -0
- package/dist/protocol/utils/image-size.js +185 -0
- package/dist/protocol/utils/image-size.js.map +1 -0
- package/dist/protocol/utils/media-source.d.ts +145 -0
- package/dist/protocol/utils/media-source.d.ts.map +1 -0
- package/dist/protocol/utils/media-source.js +175 -0
- package/dist/protocol/utils/media-source.js.map +1 -0
- package/dist/protocol/utils/media-tags.d.ts +15 -0
- package/dist/protocol/utils/media-tags.d.ts.map +1 -0
- package/dist/protocol/utils/media-tags.js +150 -0
- package/dist/protocol/utils/media-tags.js.map +1 -0
- package/dist/protocol/utils/media-type.d.ts +41 -0
- package/dist/protocol/utils/media-type.d.ts.map +1 -0
- package/dist/protocol/utils/media-type.js +89 -0
- package/dist/protocol/utils/media-type.js.map +1 -0
- package/dist/protocol/utils/payload.d.ts +52 -0
- package/dist/protocol/utils/payload.d.ts.map +1 -0
- package/dist/protocol/utils/payload.js +100 -0
- package/dist/protocol/utils/payload.js.map +1 -0
- package/dist/protocol/utils/ref-attachments.d.ts +80 -0
- package/dist/protocol/utils/ref-attachments.d.ts.map +1 -0
- package/dist/protocol/utils/ref-attachments.js +121 -0
- package/dist/protocol/utils/ref-attachments.js.map +1 -0
- package/dist/protocol/utils/ref-index-store.d.ts +69 -0
- package/dist/protocol/utils/ref-index-store.d.ts.map +1 -0
- package/dist/protocol/utils/ref-index-store.js +227 -0
- package/dist/protocol/utils/ref-index-store.js.map +1 -0
- package/dist/protocol/utils/reply-limiter.d.ts +75 -0
- package/dist/protocol/utils/reply-limiter.d.ts.map +1 -0
- package/dist/protocol/utils/reply-limiter.js +123 -0
- package/dist/protocol/utils/reply-limiter.js.map +1 -0
- package/dist/protocol/utils/session-store.d.ts +73 -0
- package/dist/protocol/utils/session-store.d.ts.map +1 -0
- package/dist/protocol/utils/session-store.js +274 -0
- package/dist/protocol/utils/session-store.js.map +1 -0
- package/dist/protocol/utils/target.d.ts +53 -0
- package/dist/protocol/utils/target.d.ts.map +1 -0
- package/dist/protocol/utils/target.js +104 -0
- package/dist/protocol/utils/target.js.map +1 -0
- package/dist/protocol/utils/text-chunk.d.ts +21 -0
- package/dist/protocol/utils/text-chunk.d.ts.map +1 -0
- package/dist/protocol/utils/text-chunk.js +25 -0
- package/dist/protocol/utils/text-chunk.js.map +1 -0
- package/dist/protocol/utils/text-parsing.d.ts +40 -0
- package/dist/protocol/utils/text-parsing.d.ts.map +1 -0
- package/dist/protocol/utils/text-parsing.js +126 -0
- package/dist/protocol/utils/text-parsing.js.map +1 -0
- package/dist/protocol/utils/upload-cache.d.ts +27 -0
- package/dist/protocol/utils/upload-cache.d.ts.map +1 -0
- package/dist/protocol/utils/upload-cache.js +73 -0
- package/dist/protocol/utils/upload-cache.js.map +1 -0
- package/dist/protocol/utils/voice-text.d.ts +9 -0
- package/dist/protocol/utils/voice-text.d.ts.map +1 -0
- package/dist/protocol/utils/voice-text.js +16 -0
- package/dist/protocol/utils/voice-text.js.map +1 -0
- package/dist/storage/index.d.ts +23 -0
- package/dist/storage/index.d.ts.map +1 -0
- package/dist/storage/index.js +21 -0
- package/dist/storage/index.js.map +1 -0
- package/dist/storage/kv-store.d.ts +85 -0
- package/dist/storage/kv-store.d.ts.map +1 -0
- package/dist/storage/kv-store.js +184 -0
- package/dist/storage/kv-store.js.map +1 -0
- package/dist/storage/session-adapter.d.ts +35 -0
- package/dist/storage/session-adapter.d.ts.map +1 -0
- package/dist/storage/session-adapter.js +48 -0
- package/dist/storage/session-adapter.js.map +1 -0
- package/dist/streaming.d.ts +67 -0
- package/dist/streaming.d.ts.map +1 -0
- package/dist/streaming.js +207 -0
- package/dist/streaming.js.map +1 -0
- package/package.json +90 -0
- package/src/QQBot.ts +1123 -0
- package/src/index.ts +175 -0
- package/src/middleware/access-policy.ts +139 -0
- package/src/middleware/concurrency-guard.ts +450 -0
- package/src/middleware/content-sanitizer.ts +125 -0
- package/src/middleware/envelope-formatter.ts +140 -0
- package/src/middleware/error-handler.ts +77 -0
- package/src/middleware/history-buffer.ts +169 -0
- package/src/middleware/index.ts +129 -0
- package/src/middleware/mention-gate.ts +227 -0
- package/src/middleware/message-filter.ts +82 -0
- package/src/middleware/quote-ref.ts +237 -0
- package/src/middleware/rate-limiter.ts +112 -0
- package/src/middleware/slash-command.ts +307 -0
- package/src/middleware/types.ts +273 -0
- package/src/middleware/typing-indicator.ts +107 -0
- package/src/protocol/api/api-client.ts +170 -0
- package/src/protocol/api/media-chunked.ts +517 -0
- package/src/protocol/api/media.ts +188 -0
- package/src/protocol/api/messages.ts +345 -0
- package/src/protocol/api/retry.ts +157 -0
- package/src/protocol/api/routes.ts +62 -0
- package/src/protocol/api/token.ts +250 -0
- package/src/protocol/gateway/codec.ts +33 -0
- package/src/protocol/gateway/constants.ts +98 -0
- package/src/protocol/gateway/event-dispatcher.ts +275 -0
- package/src/protocol/gateway/gateway-connection.ts +375 -0
- package/src/protocol/gateway/reconnect.ts +155 -0
- package/src/protocol/index.ts +238 -0
- package/src/protocol/transport/index.ts +17 -0
- package/src/protocol/transport/types.ts +121 -0
- package/src/protocol/transport/webhook-server-node.ts +64 -0
- package/src/protocol/transport/webhook-verify.ts +118 -0
- package/src/protocol/transport/webhook.ts +237 -0
- package/src/protocol/types.ts +305 -0
- package/src/protocol/utils/audio.ts +663 -0
- package/src/protocol/utils/decode-media-path.ts +88 -0
- package/src/protocol/utils/ffmpeg.ts +131 -0
- package/src/protocol/utils/file-utils.ts +121 -0
- package/src/protocol/utils/format.ts +69 -0
- package/src/protocol/utils/image-size.ts +236 -0
- package/src/protocol/utils/media-source.ts +243 -0
- package/src/protocol/utils/media-tags.ts +177 -0
- package/src/protocol/utils/media-type.ts +102 -0
- package/src/protocol/utils/payload.ts +157 -0
- package/src/protocol/utils/ref-attachments.ts +190 -0
- package/src/protocol/utils/ref-index-store.ts +279 -0
- package/src/protocol/utils/reply-limiter.ts +164 -0
- package/src/protocol/utils/session-store.ts +346 -0
- package/src/protocol/utils/target.ts +121 -0
- package/src/protocol/utils/text-chunk.ts +29 -0
- package/src/protocol/utils/text-parsing.ts +153 -0
- package/src/protocol/utils/upload-cache.ts +107 -0
- package/src/protocol/utils/voice-text.ts +16 -0
- package/src/storage/index.ts +24 -0
- package/src/storage/kv-store.ts +243 -0
- package/src/storage/session-adapter.ts +66 -0
- package/src/streaming.ts +255 -0
package/dist/QQBot.js
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* High-level facade for the QQ Open Platform Node.js SDK.
|
|
3
|
+
*
|
|
4
|
+
* 这是大部分用户的主要入口。它把协议层(HTTP / WebSocket / 媒体上传 / 流式
|
|
5
|
+
* 消息)组合成一个清晰的「机器人客户端」对象,类似 `@line/bot-sdk` 或
|
|
6
|
+
* `@larksuiteoapi/node-sdk` 在其他平台上的角色。
|
|
7
|
+
*
|
|
8
|
+
* Example:
|
|
9
|
+
* ```ts
|
|
10
|
+
* import { QQBot } from "@tencent-connect/qqbot-nodejs";
|
|
11
|
+
*
|
|
12
|
+
* const bot = new QQBot({
|
|
13
|
+
* appId: process.env.QQBOT_APP_ID!,
|
|
14
|
+
* appSecret: process.env.QQBOT_APP_SECRET!,
|
|
15
|
+
* });
|
|
16
|
+
*
|
|
17
|
+
* bot.on("message", async (ctx, msg) => {
|
|
18
|
+
* await bot.sendText(msg.replyTarget, `Echo: ${msg.content}`);
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* await bot.start();
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
import * as fs from "node:fs";
|
|
25
|
+
import * as path from "node:path";
|
|
26
|
+
import { createMiddlewareContext, runMiddlewareChain, } from "./middleware/types.js";
|
|
27
|
+
import { ApiClient } from "./protocol/api/api-client.js";
|
|
28
|
+
import { ChunkedMediaApi } from "./protocol/api/media-chunked.js";
|
|
29
|
+
import { MediaApi } from "./protocol/api/media.js";
|
|
30
|
+
import { MessageApi } from "./protocol/api/messages.js";
|
|
31
|
+
import { TokenManager } from "./protocol/api/token.js";
|
|
32
|
+
import { GatewayConnection } from "./protocol/gateway/gateway-connection.js";
|
|
33
|
+
import { WebhookTransport } from "./protocol/transport/webhook.js";
|
|
34
|
+
import { MediaFileType, } from "./protocol/types.js";
|
|
35
|
+
import { LARGE_FILE_THRESHOLD, sanitizeFileName } from "./protocol/utils/file-utils.js";
|
|
36
|
+
import { UploadCache } from "./protocol/utils/upload-cache.js";
|
|
37
|
+
import { StreamSession } from "./streaming.js";
|
|
38
|
+
// ============ Public types ============
|
|
39
|
+
/** QQ Open Platform message type codes (msg_type). */
|
|
40
|
+
export const MsgType = {
|
|
41
|
+
/** Plain text. */
|
|
42
|
+
TEXT: 0,
|
|
43
|
+
/** Markdown. */
|
|
44
|
+
MARKDOWN: 2,
|
|
45
|
+
/** Ark template message. */
|
|
46
|
+
ARK: 3,
|
|
47
|
+
/** Embed message. */
|
|
48
|
+
EMBED: 4,
|
|
49
|
+
/** Rich media (image/video/voice/file). */
|
|
50
|
+
MEDIA: 7,
|
|
51
|
+
};
|
|
52
|
+
// ============ QQBot class ============
|
|
53
|
+
const noopLogger = {
|
|
54
|
+
info: () => { },
|
|
55
|
+
error: () => { },
|
|
56
|
+
warn: () => { },
|
|
57
|
+
debug: () => { },
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* High-level QQ Open Platform client.
|
|
61
|
+
*
|
|
62
|
+
* Owns an isolated stack of low-level primitives (token manager, HTTP
|
|
63
|
+
* client, message API, media APIs, gateway connection) per bot instance,
|
|
64
|
+
* so multiple bots can run concurrently without sharing global state.
|
|
65
|
+
*/
|
|
66
|
+
export class QQBot {
|
|
67
|
+
// Public protocol primitives — exposed for advanced users.
|
|
68
|
+
tokenManager;
|
|
69
|
+
apiClient;
|
|
70
|
+
messageApi;
|
|
71
|
+
mediaApi;
|
|
72
|
+
chunkedMediaApi;
|
|
73
|
+
opts;
|
|
74
|
+
logger;
|
|
75
|
+
creds;
|
|
76
|
+
account;
|
|
77
|
+
userAgent;
|
|
78
|
+
uploadCache;
|
|
79
|
+
middlewares = [];
|
|
80
|
+
handlers = {
|
|
81
|
+
ready: new Set(),
|
|
82
|
+
resumed: new Set(),
|
|
83
|
+
error: new Set(),
|
|
84
|
+
message: new Set(),
|
|
85
|
+
interaction: new Set(),
|
|
86
|
+
rawEvent: new Set(),
|
|
87
|
+
};
|
|
88
|
+
gateway = null;
|
|
89
|
+
abortController = null;
|
|
90
|
+
_apiGateway = null;
|
|
91
|
+
constructor(options) {
|
|
92
|
+
if (!options.appId) {
|
|
93
|
+
throw new Error("QQBot: appId is required");
|
|
94
|
+
}
|
|
95
|
+
if (!options.appSecret) {
|
|
96
|
+
throw new Error("QQBot: appSecret is required");
|
|
97
|
+
}
|
|
98
|
+
this.opts = options;
|
|
99
|
+
this.logger = options.logger ?? noopLogger;
|
|
100
|
+
this.userAgent = options.userAgent ?? `qqbot-nodejs/0.1.0 (Node/${process.versions.node})`;
|
|
101
|
+
this.creds = {
|
|
102
|
+
appId: options.appId,
|
|
103
|
+
clientSecret: options.appSecret,
|
|
104
|
+
};
|
|
105
|
+
this.account = {
|
|
106
|
+
accountId: options.accountId ?? options.appId,
|
|
107
|
+
appId: options.appId,
|
|
108
|
+
clientSecret: options.appSecret,
|
|
109
|
+
markdownSupport: options.markdownSupport === true,
|
|
110
|
+
};
|
|
111
|
+
this.uploadCache = options.uploadCache ?? new UploadCache({ logger: this.logger });
|
|
112
|
+
this.apiClient = new ApiClient({
|
|
113
|
+
logger: this.logger,
|
|
114
|
+
userAgent: this.userAgent,
|
|
115
|
+
baseUrl: options.baseUrl,
|
|
116
|
+
});
|
|
117
|
+
this.tokenManager = new TokenManager({
|
|
118
|
+
logger: this.logger,
|
|
119
|
+
userAgent: this.userAgent,
|
|
120
|
+
baseUrl: options.tokenBaseUrl,
|
|
121
|
+
});
|
|
122
|
+
this.messageApi = new MessageApi(this.apiClient, this.tokenManager, {
|
|
123
|
+
markdownSupport: options.markdownSupport === true,
|
|
124
|
+
logger: this.logger,
|
|
125
|
+
});
|
|
126
|
+
const cacheAdapter = {
|
|
127
|
+
computeHash: (data) => this.uploadCache.computeHash(data),
|
|
128
|
+
get: (hash, scope, targetId, fileType) => this.uploadCache.get(hash, scope, targetId, fileType),
|
|
129
|
+
set: (hash, scope, targetId, fileType, fileInfo, fileUuid, ttl) => this.uploadCache.set(hash, scope, targetId, fileType, fileInfo, fileUuid, ttl),
|
|
130
|
+
};
|
|
131
|
+
this.mediaApi = new MediaApi(this.apiClient, this.tokenManager, {
|
|
132
|
+
logger: this.logger,
|
|
133
|
+
uploadCache: cacheAdapter,
|
|
134
|
+
sanitizeFileName,
|
|
135
|
+
});
|
|
136
|
+
this.chunkedMediaApi = new ChunkedMediaApi(this.apiClient, this.tokenManager, {
|
|
137
|
+
logger: this.logger,
|
|
138
|
+
uploadCache: cacheAdapter,
|
|
139
|
+
sanitizeFileName,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
// ============ Public getters ============
|
|
143
|
+
/** The QQ Open Platform AppID this bot is bound to. */
|
|
144
|
+
get appId() {
|
|
145
|
+
return this.creds.appId;
|
|
146
|
+
}
|
|
147
|
+
/** The stable account id (defaults to appId). */
|
|
148
|
+
get accountId() {
|
|
149
|
+
return this.account.accountId;
|
|
150
|
+
}
|
|
151
|
+
// ============ Event listeners ============
|
|
152
|
+
on(event, handler) {
|
|
153
|
+
this.handlers[event].add(handler);
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
156
|
+
off(event, handler) {
|
|
157
|
+
this.handlers[event].delete(handler);
|
|
158
|
+
return this;
|
|
159
|
+
}
|
|
160
|
+
// ============ Middleware ============
|
|
161
|
+
/**
|
|
162
|
+
* Register an inbound middleware. Middlewares run in registration order
|
|
163
|
+
* before the `message` event listeners; calling `ctx.stop()` (or simply
|
|
164
|
+
* not calling `next()`) short-circuits the chain — including the final
|
|
165
|
+
* `message` listener.
|
|
166
|
+
*
|
|
167
|
+
* @example
|
|
168
|
+
* ```ts
|
|
169
|
+
* import { accessPolicy, mentionGate } from "@tencent-connect/qqbot-nodejs";
|
|
170
|
+
* bot.use(accessPolicy({ group: { mode: "allowlist", allow: [...] } }));
|
|
171
|
+
* bot.use(mentionGate());
|
|
172
|
+
* bot.on("message", async (ctx, msg) => { ... });
|
|
173
|
+
* ```
|
|
174
|
+
*/
|
|
175
|
+
use(...middleware) {
|
|
176
|
+
for (const mw of middleware) {
|
|
177
|
+
if (typeof mw !== "function") {
|
|
178
|
+
throw new Error("QQBot.use: middleware must be a function");
|
|
179
|
+
}
|
|
180
|
+
this.middlewares.push(mw);
|
|
181
|
+
}
|
|
182
|
+
return this;
|
|
183
|
+
}
|
|
184
|
+
/** Read the registered middleware chain (for diagnostics). */
|
|
185
|
+
getMiddlewares() {
|
|
186
|
+
return this.middlewares;
|
|
187
|
+
}
|
|
188
|
+
async emit(event, ...args) {
|
|
189
|
+
for (const handler of this.handlers[event]) {
|
|
190
|
+
try {
|
|
191
|
+
await Promise.resolve(handler(...args));
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
this.logger.error?.(`[qqbot] handler for "${String(event)}" threw: ${err instanceof Error ? err.message : String(err)}`);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
// ============ Lifecycle ============
|
|
199
|
+
/**
|
|
200
|
+
* Start receiving events from QQ Open Platform.
|
|
201
|
+
*
|
|
202
|
+
* - **WebSocket mode** (default): connects to the WS gateway with heartbeat/RESUME.
|
|
203
|
+
* - **Webhook mode**: starts an HTTP server to receive POST callbacks.
|
|
204
|
+
*
|
|
205
|
+
* Resolves when {@link stop} or the abort signal terminates the connection.
|
|
206
|
+
*/
|
|
207
|
+
async start(externalSignal) {
|
|
208
|
+
if (this.gateway) {
|
|
209
|
+
throw new Error("QQBot: already started");
|
|
210
|
+
}
|
|
211
|
+
this.abortController = new AbortController();
|
|
212
|
+
if (externalSignal) {
|
|
213
|
+
if (externalSignal.aborted) {
|
|
214
|
+
this.abortController.abort();
|
|
215
|
+
}
|
|
216
|
+
else {
|
|
217
|
+
externalSignal.addEventListener("abort", () => this.abortController?.abort(), {
|
|
218
|
+
once: true,
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
const transportMode = this.opts.transport ?? "websocket";
|
|
223
|
+
if (transportMode === "webhook") {
|
|
224
|
+
await this.startWebhook();
|
|
225
|
+
}
|
|
226
|
+
else if (transportMode === "websocket") {
|
|
227
|
+
await this.startWebSocket();
|
|
228
|
+
}
|
|
229
|
+
else {
|
|
230
|
+
// Custom EventTransport instance
|
|
231
|
+
const custom = transportMode;
|
|
232
|
+
await custom.start();
|
|
233
|
+
}
|
|
234
|
+
// Cleanup
|
|
235
|
+
this.tokenManager.stopBackgroundRefresh(this.creds.appId);
|
|
236
|
+
this.gateway = null;
|
|
237
|
+
this.abortController = null;
|
|
238
|
+
}
|
|
239
|
+
/** Stop the transport and background refreshers. */
|
|
240
|
+
stop() {
|
|
241
|
+
this.abortController?.abort();
|
|
242
|
+
this.tokenManager.stopBackgroundRefresh(this.creds.appId);
|
|
243
|
+
this.gateway = null;
|
|
244
|
+
this.abortController = null;
|
|
245
|
+
}
|
|
246
|
+
// ============ Token initialization ============
|
|
247
|
+
/**
|
|
248
|
+
* Initialize token based on the configured prefetch strategy.
|
|
249
|
+
*
|
|
250
|
+
* - `"sync"` (default): awaits the first token fetch, providing fail-fast
|
|
251
|
+
* semantics so credential errors surface at startup.
|
|
252
|
+
* - `"async"`: fires the token fetch in the background and starts the
|
|
253
|
+
* background refresher immediately — trades fail-fast for faster startup.
|
|
254
|
+
*/
|
|
255
|
+
async initToken() {
|
|
256
|
+
const mode = this.opts.tokenPrefetch ?? "sync";
|
|
257
|
+
if (mode === "sync") {
|
|
258
|
+
await this.tokenManager.getAccessToken(this.creds.appId, this.creds.clientSecret);
|
|
259
|
+
}
|
|
260
|
+
else {
|
|
261
|
+
// Fire-and-forget: fetch token in background, log errors but don't block startup.
|
|
262
|
+
this.tokenManager.getAccessToken(this.creds.appId, this.creds.clientSecret).catch((err) => {
|
|
263
|
+
this.logger.error?.(`[qqbot] async token prefetch failed: ${err}`);
|
|
264
|
+
void this.emit("error", err instanceof Error ? err : new Error(String(err)));
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
this.tokenManager.startBackgroundRefresh(this.creds.appId, this.creds.clientSecret);
|
|
268
|
+
}
|
|
269
|
+
// ============ Transport: WebSocket ============
|
|
270
|
+
async startWebSocket() {
|
|
271
|
+
await this.initToken();
|
|
272
|
+
this.gateway = new GatewayConnection({
|
|
273
|
+
account: this.account,
|
|
274
|
+
abortSignal: this.abortController.signal,
|
|
275
|
+
log: this.logger,
|
|
276
|
+
userAgent: this.userAgent,
|
|
277
|
+
intents: this.opts.intents,
|
|
278
|
+
session: this.opts.sessionPersistence,
|
|
279
|
+
getAccessToken: () => this.tokenManager.getAccessToken(this.creds.appId, this.creds.clientSecret),
|
|
280
|
+
clearTokenCache: () => this.tokenManager.clearCache(this.creds.appId),
|
|
281
|
+
getGatewayUrl: () => this.messageApi.getGatewayUrl(this.creds),
|
|
282
|
+
onReady: (data) => {
|
|
283
|
+
this.logger.info?.(`[qqbot] gateway READY`);
|
|
284
|
+
void this.emit("ready", data);
|
|
285
|
+
},
|
|
286
|
+
onResumed: (data) => {
|
|
287
|
+
this.logger.info?.(`[qqbot] gateway RESUMED`);
|
|
288
|
+
void this.emit("resumed", data);
|
|
289
|
+
},
|
|
290
|
+
onError: (err) => {
|
|
291
|
+
void this.emit("error", err);
|
|
292
|
+
},
|
|
293
|
+
onMessage: (raw) => this.handleInboundMessage(raw),
|
|
294
|
+
onInteraction: (event) => {
|
|
295
|
+
const ctx = { bot: this, event, state: {}, receivedAt: Date.now() };
|
|
296
|
+
void this.emit("interaction", ctx, event);
|
|
297
|
+
},
|
|
298
|
+
onRawEvent: (type, data) => {
|
|
299
|
+
const ctx = { bot: this, eventType: type, data, state: {}, receivedAt: Date.now() };
|
|
300
|
+
void this.emit("rawEvent", ctx);
|
|
301
|
+
},
|
|
302
|
+
});
|
|
303
|
+
await this.gateway.start();
|
|
304
|
+
}
|
|
305
|
+
// ============ Transport: Webhook ============
|
|
306
|
+
async startWebhook() {
|
|
307
|
+
await this.initToken();
|
|
308
|
+
const webhook = new WebhookTransport({
|
|
309
|
+
appId: this.creds.appId,
|
|
310
|
+
appSecret: this.creds.clientSecret,
|
|
311
|
+
port: this.opts.webhook?.port,
|
|
312
|
+
path: this.opts.webhook?.path,
|
|
313
|
+
server: this.opts.webhook?.server,
|
|
314
|
+
accountId: this.account.accountId,
|
|
315
|
+
log: this.logger,
|
|
316
|
+
abortSignal: this.abortController.signal,
|
|
317
|
+
}, {
|
|
318
|
+
onReady: (data) => {
|
|
319
|
+
this.logger.info?.(`[qqbot] webhook READY`);
|
|
320
|
+
void this.emit("ready", data);
|
|
321
|
+
},
|
|
322
|
+
onResumed: (data) => {
|
|
323
|
+
void this.emit("resumed", data);
|
|
324
|
+
},
|
|
325
|
+
onError: (err) => {
|
|
326
|
+
void this.emit("error", err);
|
|
327
|
+
},
|
|
328
|
+
onMessage: (raw) => this.handleInboundMessage(raw),
|
|
329
|
+
onInteraction: (event) => {
|
|
330
|
+
const ctx = { bot: this, event, state: {}, receivedAt: Date.now() };
|
|
331
|
+
void this.emit("interaction", ctx, event);
|
|
332
|
+
},
|
|
333
|
+
});
|
|
334
|
+
await webhook.start();
|
|
335
|
+
}
|
|
336
|
+
// ============ Shared inbound message handler ============
|
|
337
|
+
async handleInboundMessage(raw) {
|
|
338
|
+
const replyTarget = this.deriveReplyTarget(raw);
|
|
339
|
+
if (!replyTarget) {
|
|
340
|
+
this.logger.debug?.(`[qqbot] inbound message has no reply target — skipping`);
|
|
341
|
+
return;
|
|
342
|
+
}
|
|
343
|
+
const augmented = { ...raw, replyTarget };
|
|
344
|
+
const ctx = createMiddlewareContext({
|
|
345
|
+
bot: this,
|
|
346
|
+
message: augmented,
|
|
347
|
+
log: this.logger,
|
|
348
|
+
});
|
|
349
|
+
// Koa-style: compose middleware chain with emit as the final downstream.
|
|
350
|
+
const downstream = async () => {
|
|
351
|
+
await this.emit("message", ctx, ctx.message);
|
|
352
|
+
};
|
|
353
|
+
const chain = [...this.middlewares, downstream];
|
|
354
|
+
try {
|
|
355
|
+
await runMiddlewareChain(chain, ctx);
|
|
356
|
+
}
|
|
357
|
+
catch (err) {
|
|
358
|
+
this.logger.error?.(`[qqbot] middleware chain threw: ${err instanceof Error ? err.message : String(err)}`);
|
|
359
|
+
void this.emit("error", err instanceof Error ? err : new Error(String(err)));
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
// ============ Message sending ============
|
|
363
|
+
/**
|
|
364
|
+
* Universal message send — supports all QQ Open Platform message types.
|
|
365
|
+
*
|
|
366
|
+
* This is the most flexible sending method. It accepts the full parameter
|
|
367
|
+
* set of POST `/v2/users/{openid}/messages` or `/v2/groups/{group_openid}/messages`.
|
|
368
|
+
* Use it when the convenience helpers (sendText, sendMarkdown, etc.) don't
|
|
369
|
+
* cover your use case.
|
|
370
|
+
*
|
|
371
|
+
* `msg_type` is auto-detected if not specified:
|
|
372
|
+
* - markdown field present → 2 (Markdown)
|
|
373
|
+
* - ark field present → 3 (Ark)
|
|
374
|
+
* - embed field present → 4 (Embed)
|
|
375
|
+
* - media field present → 7 (Rich media)
|
|
376
|
+
* - otherwise → 0 (Text)
|
|
377
|
+
*
|
|
378
|
+
* @example Send a keyboard message
|
|
379
|
+
* ```ts
|
|
380
|
+
* await bot.send({
|
|
381
|
+
* target: msg.replyTarget,
|
|
382
|
+
* msgType: MsgType.MARKDOWN,
|
|
383
|
+
* markdown: { content: '# Hello' },
|
|
384
|
+
* keyboard: { content: { rows: [...] } },
|
|
385
|
+
* });
|
|
386
|
+
* ```
|
|
387
|
+
*
|
|
388
|
+
* @example Send a proactive message (no msgId)
|
|
389
|
+
* ```ts
|
|
390
|
+
* await bot.send({
|
|
391
|
+
* target: { scope: 'c2c', targetId: openid },
|
|
392
|
+
* content: 'Hello from bot!',
|
|
393
|
+
* });
|
|
394
|
+
* ```
|
|
395
|
+
*/
|
|
396
|
+
async send(opts) {
|
|
397
|
+
const body = {};
|
|
398
|
+
if (opts.target.msgId)
|
|
399
|
+
body.msg_id = opts.target.msgId;
|
|
400
|
+
if (opts.msgType !== undefined)
|
|
401
|
+
body.msg_type = opts.msgType;
|
|
402
|
+
if (opts.content !== undefined)
|
|
403
|
+
body.content = opts.content;
|
|
404
|
+
if (opts.markdown)
|
|
405
|
+
body.markdown = opts.markdown;
|
|
406
|
+
if (opts.ark)
|
|
407
|
+
body.ark = opts.ark;
|
|
408
|
+
if (opts.embed)
|
|
409
|
+
body.embed = opts.embed;
|
|
410
|
+
if (opts.media)
|
|
411
|
+
body.media = opts.media;
|
|
412
|
+
if (opts.keyboard)
|
|
413
|
+
body.keyboard = opts.keyboard;
|
|
414
|
+
if (opts.messageReference)
|
|
415
|
+
body.message_reference = opts.messageReference;
|
|
416
|
+
if (opts.extra)
|
|
417
|
+
Object.assign(body, opts.extra);
|
|
418
|
+
return this.messageApi.sendRaw(opts.target.scope, opts.target.targetId, this.creds, body);
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Send a text message to a C2C user or group (smart mode).
|
|
422
|
+
*
|
|
423
|
+
* **Difference from `send()`**:
|
|
424
|
+
* - `sendText` auto-selects msg_type based on `markdownSupport` config
|
|
425
|
+
* (markdown bots automatically send as msg_type=2).
|
|
426
|
+
* - `send()` is explicit mode — you control msg_type directly.
|
|
427
|
+
*
|
|
428
|
+
* When `target.msgId` is present the message is treated as a reply
|
|
429
|
+
* (tied to the inbound message lifecycle); otherwise it is treated as
|
|
430
|
+
* a proactive push.
|
|
431
|
+
*/
|
|
432
|
+
async sendText(target, content) {
|
|
433
|
+
if (target.msgId) {
|
|
434
|
+
return this.messageApi.sendMessage(target.scope, target.targetId, content, this.creds, {
|
|
435
|
+
msgId: target.msgId,
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
return this.messageApi.sendProactiveMessage(target.scope, target.targetId, content, this.creds);
|
|
439
|
+
}
|
|
440
|
+
/** Send a text message with an inline keyboard. */
|
|
441
|
+
async sendTextWithKeyboard(target, content, inlineKeyboard) {
|
|
442
|
+
return this.messageApi.sendMessage(target.scope, target.targetId, content, this.creds, {
|
|
443
|
+
msgId: target.msgId,
|
|
444
|
+
inlineKeyboard,
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
/**
|
|
448
|
+
* Send a Markdown message (msg_type=2).
|
|
449
|
+
*
|
|
450
|
+
* @example
|
|
451
|
+
* ```ts
|
|
452
|
+
* await bot.sendMarkdown(msg.replyTarget, '# Hello **world**');
|
|
453
|
+
* await bot.sendMarkdown(msg.replyTarget, '# Click below', {
|
|
454
|
+
* keyboard: { content: { rows: [...] } },
|
|
455
|
+
* });
|
|
456
|
+
* ```
|
|
457
|
+
*/
|
|
458
|
+
async sendMarkdown(target, content, opts) {
|
|
459
|
+
return this.send({
|
|
460
|
+
target,
|
|
461
|
+
msgType: MsgType.MARKDOWN,
|
|
462
|
+
markdown: { content },
|
|
463
|
+
keyboard: opts?.keyboard,
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Recall (delete) a previously sent message.
|
|
468
|
+
*
|
|
469
|
+
* @example
|
|
470
|
+
* ```ts
|
|
471
|
+
* const sent = await bot.sendText(target, 'oops');
|
|
472
|
+
* await bot.recallMessage(target, sent.id);
|
|
473
|
+
* ```
|
|
474
|
+
*/
|
|
475
|
+
async recallMessage(target, messageId) {
|
|
476
|
+
return this.messageApi.recallMessage(target.scope, target.targetId, messageId, this.creds);
|
|
477
|
+
}
|
|
478
|
+
/**
|
|
479
|
+
* Send a wakeup/recall message (C2C only, 30-day window).
|
|
480
|
+
*
|
|
481
|
+
* After a user initiates a conversation, the bot can send periodic
|
|
482
|
+
* recall messages within 30 days using `is_wakeup: true`.
|
|
483
|
+
* Platform enforces frequency limits.
|
|
484
|
+
*
|
|
485
|
+
* @example
|
|
486
|
+
* ```ts
|
|
487
|
+
* await bot.sendWakeup({ scope: 'c2c', targetId: openid }, '你有新消息!');
|
|
488
|
+
* ```
|
|
489
|
+
*/
|
|
490
|
+
async sendWakeup(target, content) {
|
|
491
|
+
if (target.scope !== "c2c") {
|
|
492
|
+
throw new Error("sendWakeup is only supported for C2C targets");
|
|
493
|
+
}
|
|
494
|
+
return this.send({ target, content, extra: { is_wakeup: true } });
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* Send a message to a guild text channel.
|
|
498
|
+
*
|
|
499
|
+
* @example
|
|
500
|
+
* ```ts
|
|
501
|
+
* await bot.sendChannelMessage(channelId, '频道消息', { msgId });
|
|
502
|
+
* ```
|
|
503
|
+
*/
|
|
504
|
+
async sendChannelMessage(channelId, content, opts) {
|
|
505
|
+
const body = { content };
|
|
506
|
+
if (opts?.msgId)
|
|
507
|
+
body.msg_id = opts.msgId;
|
|
508
|
+
if (opts?.keyboard)
|
|
509
|
+
body.keyboard = opts.keyboard;
|
|
510
|
+
if (opts?.messageReference)
|
|
511
|
+
body.message_reference = { message_id: opts.messageReference };
|
|
512
|
+
return this.messageApi.sendChannelMessageRaw(channelId, this.creds, body);
|
|
513
|
+
}
|
|
514
|
+
/**
|
|
515
|
+
* Send a direct message (DM) in a guild.
|
|
516
|
+
*
|
|
517
|
+
* @example
|
|
518
|
+
* ```ts
|
|
519
|
+
* await bot.sendDmMessage(guildId, '私信内容', { msgId });
|
|
520
|
+
* ```
|
|
521
|
+
*/
|
|
522
|
+
async sendDmMessage(guildId, content, opts) {
|
|
523
|
+
const body = { content };
|
|
524
|
+
if (opts?.msgId)
|
|
525
|
+
body.msg_id = opts.msgId;
|
|
526
|
+
return this.messageApi.sendDmMessageRaw(guildId, this.creds, body);
|
|
527
|
+
}
|
|
528
|
+
/** Send a typing indicator (C2C only). */
|
|
529
|
+
async sendTyping(target, durationSec = 30) {
|
|
530
|
+
if (target.scope !== "c2c") {
|
|
531
|
+
throw new Error("sendTyping is only supported for C2C targets");
|
|
532
|
+
}
|
|
533
|
+
return this.messageApi.sendInputNotify({
|
|
534
|
+
openid: target.targetId,
|
|
535
|
+
creds: this.creds,
|
|
536
|
+
msgId: target.msgId,
|
|
537
|
+
inputSecond: durationSec,
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
/** Acknowledge an INTERACTION_CREATE event. */
|
|
541
|
+
async acknowledgeInteraction(interactionId, code = 0, data) {
|
|
542
|
+
return this.messageApi.acknowledgeInteraction(interactionId, this.creds, code, data);
|
|
543
|
+
}
|
|
544
|
+
// ============ API Gateway ============
|
|
545
|
+
/**
|
|
546
|
+
* Open Platform API Gateway — call any QQ Open Platform REST API with
|
|
547
|
+
* automatic token injection and refresh.
|
|
548
|
+
*
|
|
549
|
+
* This is the "escape hatch" for any API not wrapped by a dedicated method.
|
|
550
|
+
* All requests are authenticated, rate-limit aware, and return structured errors.
|
|
551
|
+
*
|
|
552
|
+
* @example List guilds
|
|
553
|
+
* ```ts
|
|
554
|
+
* const guilds = await bot.api.get('/users/@me/guilds');
|
|
555
|
+
* ```
|
|
556
|
+
*
|
|
557
|
+
* @example Create an announcement
|
|
558
|
+
* ```ts
|
|
559
|
+
* await bot.api.post(`/guilds/${guildId}/announces`, {
|
|
560
|
+
* message_id: msgId, channel_id: channelId,
|
|
561
|
+
* });
|
|
562
|
+
* ```
|
|
563
|
+
*
|
|
564
|
+
* @example Get a raw access token
|
|
565
|
+
* ```ts
|
|
566
|
+
* const token = await bot.api.getToken();
|
|
567
|
+
* ```
|
|
568
|
+
*/
|
|
569
|
+
get api() {
|
|
570
|
+
if (this._apiGateway)
|
|
571
|
+
return this._apiGateway;
|
|
572
|
+
this._apiGateway = {
|
|
573
|
+
get: (path, query) => this.apiRequest("GET", path, undefined, query),
|
|
574
|
+
post: (path, body) => this.apiRequest("POST", path, body),
|
|
575
|
+
put: (path, body) => this.apiRequest("PUT", path, body),
|
|
576
|
+
patch: (path, body) => this.apiRequest("PATCH", path, body),
|
|
577
|
+
delete: (path) => this.apiRequest("DELETE", path),
|
|
578
|
+
getToken: () => this.tokenManager.getAccessToken(this.creds.appId, this.creds.clientSecret),
|
|
579
|
+
};
|
|
580
|
+
return this._apiGateway;
|
|
581
|
+
}
|
|
582
|
+
async apiRequest(method, path, body, query) {
|
|
583
|
+
const token = await this.tokenManager.getAccessToken(this.creds.appId, this.creds.clientSecret);
|
|
584
|
+
let fullPath = path;
|
|
585
|
+
if (query && Object.keys(query).length > 0) {
|
|
586
|
+
const params = new URLSearchParams();
|
|
587
|
+
for (const [k, v] of Object.entries(query)) {
|
|
588
|
+
if (v !== undefined && v !== null)
|
|
589
|
+
params.set(k, String(v));
|
|
590
|
+
}
|
|
591
|
+
fullPath = `${path}?${params.toString()}`;
|
|
592
|
+
}
|
|
593
|
+
return this.apiClient.request(token, method, fullPath, body ?? undefined);
|
|
594
|
+
}
|
|
595
|
+
// ============ Streaming ============
|
|
596
|
+
/**
|
|
597
|
+
* Open a C2C stream session for incremental output.
|
|
598
|
+
*
|
|
599
|
+
* @returns A {@link StreamSession} — call `update(fullText)` repeatedly,
|
|
600
|
+
* then `complete()` when finished.
|
|
601
|
+
*/
|
|
602
|
+
openStream(opts) {
|
|
603
|
+
if (opts.target.scope !== "c2c") {
|
|
604
|
+
throw new Error("Streaming is only supported for C2C targets");
|
|
605
|
+
}
|
|
606
|
+
if (!opts.target.msgId) {
|
|
607
|
+
throw new Error("Streaming requires target.msgId from the inbound message");
|
|
608
|
+
}
|
|
609
|
+
const sessionOptions = {
|
|
610
|
+
openid: opts.target.targetId,
|
|
611
|
+
msgId: opts.target.msgId,
|
|
612
|
+
creds: this.creds,
|
|
613
|
+
eventId: opts.eventId,
|
|
614
|
+
throttleMs: opts.throttleMs,
|
|
615
|
+
logger: this.logger,
|
|
616
|
+
};
|
|
617
|
+
return new StreamSession(this.messageApi, sessionOptions);
|
|
618
|
+
}
|
|
619
|
+
// ============ Media ============
|
|
620
|
+
/**
|
|
621
|
+
* Upload media (image / voice / video / file) to a target. Automatically
|
|
622
|
+
* dispatches to the chunked-upload path when the source exceeds
|
|
623
|
+
* {@link LARGE_FILE_THRESHOLD} bytes.
|
|
624
|
+
*/
|
|
625
|
+
async uploadMedia(opts) {
|
|
626
|
+
const sources = [opts.url, opts.fileData, opts.buffer, opts.localPath].filter((v) => v !== undefined);
|
|
627
|
+
if (sources.length === 0) {
|
|
628
|
+
throw new Error("uploadMedia: one of url/fileData/buffer/localPath is required");
|
|
629
|
+
}
|
|
630
|
+
if (sources.length > 1) {
|
|
631
|
+
throw new Error("uploadMedia: provide exactly one source");
|
|
632
|
+
}
|
|
633
|
+
const size = await this.computeSourceSize(opts);
|
|
634
|
+
const useChunked = size !== null && size >= LARGE_FILE_THRESHOLD;
|
|
635
|
+
// Auto-fill fileName from localPath or URL when not explicitly provided
|
|
636
|
+
const fileName = opts.fileName
|
|
637
|
+
?? (opts.localPath ? path.basename(opts.localPath) : undefined)
|
|
638
|
+
?? (opts.url ? decodeURIComponent(path.basename(new URL(opts.url).pathname)) || undefined : undefined);
|
|
639
|
+
if (useChunked && (opts.localPath || opts.buffer)) {
|
|
640
|
+
const source = opts.localPath
|
|
641
|
+
? { kind: "localPath", path: opts.localPath, size: size }
|
|
642
|
+
: {
|
|
643
|
+
kind: "buffer",
|
|
644
|
+
buffer: opts.buffer,
|
|
645
|
+
fileName,
|
|
646
|
+
};
|
|
647
|
+
return this.chunkedMediaApi.uploadChunked({
|
|
648
|
+
scope: opts.target.scope,
|
|
649
|
+
targetId: opts.target.targetId,
|
|
650
|
+
fileType: opts.fileType,
|
|
651
|
+
source,
|
|
652
|
+
creds: this.creds,
|
|
653
|
+
fileName,
|
|
654
|
+
onProgress: opts.onProgress
|
|
655
|
+
? (p) => opts.onProgress(p.uploadedBytes, p.totalBytes)
|
|
656
|
+
: undefined,
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
return this.mediaApi.uploadMedia(opts.target.scope, opts.target.targetId, opts.fileType, this.creds, {
|
|
660
|
+
url: opts.url,
|
|
661
|
+
fileData: opts.fileData,
|
|
662
|
+
buffer: opts.buffer,
|
|
663
|
+
localPath: opts.localPath,
|
|
664
|
+
srvSendMsg: opts.srvSendMsg,
|
|
665
|
+
fileName,
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
/**
|
|
669
|
+
* Upload + send a media message to a C2C user or group.
|
|
670
|
+
*/
|
|
671
|
+
async sendMedia(opts) {
|
|
672
|
+
const upload = await this.uploadMedia({ ...opts, srvSendMsg: false });
|
|
673
|
+
const message = await this.mediaApi.sendMediaMessage(opts.target.scope, opts.target.targetId, upload.file_info, this.creds, {
|
|
674
|
+
msgId: opts.target.msgId,
|
|
675
|
+
content: opts.content,
|
|
676
|
+
});
|
|
677
|
+
return { upload, message };
|
|
678
|
+
}
|
|
679
|
+
/** Convenience: upload + send an image. */
|
|
680
|
+
async sendImage(target, source, opts) {
|
|
681
|
+
return this.sendMedia({
|
|
682
|
+
target,
|
|
683
|
+
fileType: MediaFileType.IMAGE,
|
|
684
|
+
...source,
|
|
685
|
+
content: opts?.content,
|
|
686
|
+
onProgress: opts?.onProgress,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
/** Convenience: upload + send a video. */
|
|
690
|
+
async sendVideo(target, source, opts) {
|
|
691
|
+
return this.sendMedia({
|
|
692
|
+
target,
|
|
693
|
+
fileType: MediaFileType.VIDEO,
|
|
694
|
+
...source,
|
|
695
|
+
content: opts?.content,
|
|
696
|
+
onProgress: opts?.onProgress,
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
/** Convenience: upload + send a voice message. */
|
|
700
|
+
async sendVoice(target, source, opts) {
|
|
701
|
+
return this.sendMedia({
|
|
702
|
+
target,
|
|
703
|
+
fileType: MediaFileType.VOICE,
|
|
704
|
+
...source,
|
|
705
|
+
onProgress: opts?.onProgress,
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
/** Convenience: upload + send a generic file (for users with file-message permission). */
|
|
709
|
+
async sendFile(target, source, opts) {
|
|
710
|
+
return this.sendMedia({
|
|
711
|
+
target,
|
|
712
|
+
fileType: MediaFileType.FILE,
|
|
713
|
+
...source,
|
|
714
|
+
fileName: opts?.fileName,
|
|
715
|
+
content: opts?.content,
|
|
716
|
+
onProgress: opts?.onProgress,
|
|
717
|
+
});
|
|
718
|
+
}
|
|
719
|
+
// ============ Internal ============
|
|
720
|
+
deriveReplyTarget(raw) {
|
|
721
|
+
if (raw.kind === "c2c") {
|
|
722
|
+
return { scope: "c2c", targetId: raw.senderId, msgId: raw.messageId };
|
|
723
|
+
}
|
|
724
|
+
if (raw.kind === "group" && raw.groupOpenid) {
|
|
725
|
+
return { scope: "group", targetId: raw.groupOpenid, msgId: raw.messageId };
|
|
726
|
+
}
|
|
727
|
+
// Guild / DM 暂时没有 channel-level 的 c2c/group 等价。SDK 选择忽略
|
|
728
|
+
// 这两类消息(业务侧仍然可以通过 raw 字段自己处理)。
|
|
729
|
+
return null;
|
|
730
|
+
}
|
|
731
|
+
async computeSourceSize(opts) {
|
|
732
|
+
if (opts.buffer) {
|
|
733
|
+
return opts.buffer.length;
|
|
734
|
+
}
|
|
735
|
+
if (opts.localPath) {
|
|
736
|
+
try {
|
|
737
|
+
const stat = await fs.promises.stat(opts.localPath);
|
|
738
|
+
return stat.size;
|
|
739
|
+
}
|
|
740
|
+
catch {
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
if (opts.fileData) {
|
|
745
|
+
// base64 length → byte length estimate.
|
|
746
|
+
return Math.floor((opts.fileData.length * 3) / 4);
|
|
747
|
+
}
|
|
748
|
+
// url upload — server-side size, can't know up-front.
|
|
749
|
+
return null;
|
|
750
|
+
}
|
|
751
|
+
}
|
|
752
|
+
//# sourceMappingURL=QQBot.js.map
|