@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
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mention-gate middleware — decide whether a group message should be answered.
|
|
3
|
+
*
|
|
4
|
+
* QQ Bot group messages may or may not contain an `@bot` mention. Many
|
|
5
|
+
* production bots want to **only respond to mentions** in group chats while
|
|
6
|
+
* still listening to all C2C messages. This middleware encapsulates that
|
|
7
|
+
* common decision.
|
|
8
|
+
*
|
|
9
|
+
* The decision is exposed in `ctx.state.mention` for downstream middleware
|
|
10
|
+
* to inspect (e.g. a history-buffer middleware may still record non-mention
|
|
11
|
+
* messages without triggering a reply).
|
|
12
|
+
*/
|
|
13
|
+
import { resolvePolicy } from "./types.js";
|
|
14
|
+
// ============ Helpers ============
|
|
15
|
+
/** Heuristic: detect `<@!{appId}>` or `<@{appId}>` mention markers in content. */
|
|
16
|
+
function detectMentionInContent(content, appId) {
|
|
17
|
+
if (!content || !appId)
|
|
18
|
+
return false;
|
|
19
|
+
const re = new RegExp(`<@!?${appId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}>`);
|
|
20
|
+
return re.test(content);
|
|
21
|
+
}
|
|
22
|
+
// ============ Middleware ============
|
|
23
|
+
/**
|
|
24
|
+
* Build a mention-gate middleware.
|
|
25
|
+
*
|
|
26
|
+
* @example
|
|
27
|
+
* ```ts
|
|
28
|
+
* // Static config
|
|
29
|
+
* bot.use(mentionGate({ requireMentionInGroup: true }));
|
|
30
|
+
*
|
|
31
|
+
* // Dynamic per-group config
|
|
32
|
+
* bot.use(mentionGate({
|
|
33
|
+
* resolveConfig: (ctx) => {
|
|
34
|
+
* const cfg = resolveGroupConfig(ctx.message.groupId);
|
|
35
|
+
* return {
|
|
36
|
+
* requireMentionInGroup: cfg.requireMention,
|
|
37
|
+
* ignoreOtherMentions: cfg.ignoreOtherMentions,
|
|
38
|
+
* };
|
|
39
|
+
* },
|
|
40
|
+
* }));
|
|
41
|
+
* ```
|
|
42
|
+
*/
|
|
43
|
+
export function mentionGate(options = {}) {
|
|
44
|
+
const { requireMentionInGroup = true, alwaysAnswerC2C = true, isImplicitMention, onSkip, ignoreOtherMentions = false, passthrough = false, resolveConfig, } = options;
|
|
45
|
+
return async (ctx, next) => {
|
|
46
|
+
const msg = ctx.message;
|
|
47
|
+
const appId = ctx.bot.appId;
|
|
48
|
+
// Only group messages need gating
|
|
49
|
+
if (msg.kind !== "group") {
|
|
50
|
+
const decision = {
|
|
51
|
+
wasMentioned: true,
|
|
52
|
+
implicit: false,
|
|
53
|
+
shouldAnswer: alwaysAnswerC2C || (msg.kind !== "c2c" && msg.kind !== "dm"),
|
|
54
|
+
reason: "passthrough",
|
|
55
|
+
};
|
|
56
|
+
ctx.state.mention = decision;
|
|
57
|
+
await next();
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
// Dynamic config resolution — priority:
|
|
61
|
+
// 1. resolveConfig callback (explicit per-middleware override)
|
|
62
|
+
// 2. ctx.state.policy (injected by upstream policy injector)
|
|
63
|
+
// 3. static option defaults
|
|
64
|
+
const dynamic = resolveConfig?.(ctx);
|
|
65
|
+
const effectiveRequireMention = resolvePolicy(ctx, "group.requireMention", dynamic?.requireMentionInGroup, requireMentionInGroup);
|
|
66
|
+
const effectiveIgnoreOther = resolvePolicy(ctx, "group.ignoreOtherMentions", dynamic?.ignoreOtherMentions, ignoreOtherMentions);
|
|
67
|
+
// ---- Group: decide ----
|
|
68
|
+
//
|
|
69
|
+
// Priority order for "was mentioned":
|
|
70
|
+
// 1. rawEventType === GROUP_AT_MESSAGE_CREATE
|
|
71
|
+
// The event itself is QQ's authoritative signal — the Open Platform
|
|
72
|
+
// only delivers this event when the user actually @-ed the bot.
|
|
73
|
+
// 2. mentions[].is_you === true
|
|
74
|
+
// Server-marked structured mention list (present on some payloads).
|
|
75
|
+
// 3. Content contains `<@!{appId}>` or `<@{appId}>`
|
|
76
|
+
// Fallback scan for self-hosted / private-domain bots that also
|
|
77
|
+
// receive GROUP_MESSAGE_CREATE (every group message, not just @).
|
|
78
|
+
const wasMentioned = msg.rawEventType === "GROUP_AT_MESSAGE_CREATE" ||
|
|
79
|
+
(Array.isArray(msg.mentions) && msg.mentions.some((m) => m?.is_you === true)) ||
|
|
80
|
+
detectMentionInContent(msg.content, appId);
|
|
81
|
+
const implicit = isImplicitMention?.(ctx) ?? false;
|
|
82
|
+
// ---- Determine shouldAnswer & reason ----
|
|
83
|
+
let shouldAnswer = !effectiveRequireMention || wasMentioned || implicit;
|
|
84
|
+
let reason = shouldAnswer ? "passthrough" : "no_mention";
|
|
85
|
+
// ignoreOtherMentions: when requireMention is true and the message
|
|
86
|
+
// @-ed someone else but NOT this bot, override to skip.
|
|
87
|
+
// When requireMention is false the user explicitly wants all group
|
|
88
|
+
// messages answered, so ignoreOtherMentions does not apply.
|
|
89
|
+
if (effectiveIgnoreOther &&
|
|
90
|
+
effectiveRequireMention &&
|
|
91
|
+
!wasMentioned &&
|
|
92
|
+
!implicit) {
|
|
93
|
+
const mentions = msg.mentions;
|
|
94
|
+
if (Array.isArray(mentions) && mentions.length > 0) {
|
|
95
|
+
shouldAnswer = false;
|
|
96
|
+
reason = "other_mention";
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
const decision = {
|
|
100
|
+
wasMentioned,
|
|
101
|
+
implicit,
|
|
102
|
+
shouldAnswer,
|
|
103
|
+
reason,
|
|
104
|
+
};
|
|
105
|
+
ctx.state.mention = decision;
|
|
106
|
+
if (!shouldAnswer) {
|
|
107
|
+
onSkip?.(ctx, decision);
|
|
108
|
+
ctx.log.debug?.(`[mention-gate] skip group message (${reason}): wasMentioned=${wasMentioned}, implicit=${implicit}`);
|
|
109
|
+
if (!passthrough) {
|
|
110
|
+
ctx.stop(`mention-gate:${reason}`);
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
await next();
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
//# sourceMappingURL=mention-gate.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mention-gate.js","sourceRoot":"","sources":["../../src/middleware/mention-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAGH,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AA4E3C,oCAAoC;AAEpC,kFAAkF;AAClF,SAAS,sBAAsB,CAAC,OAAe,EAAE,KAAa;IAC5D,IAAI,CAAC,OAAO,IAAI,CAAC,KAAK;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,OAAO,KAAK,CAAC,OAAO,CAAC,qBAAqB,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC;IAC9E,OAAO,EAAE,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAC1B,CAAC;AAED,uCAAuC;AAEvC;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,WAAW,CAAC,UAA8B,EAAE;IAC1D,MAAM,EACJ,qBAAqB,GAAG,IAAI,EAC5B,eAAe,GAAG,IAAI,EACtB,iBAAiB,EACjB,MAAM,EACN,mBAAmB,GAAG,KAAK,EAC3B,WAAW,GAAG,KAAK,EACnB,aAAa,GACd,GAAG,OAAO,CAAC;IAEZ,OAAO,KAAK,EAAE,GAAG,EAAE,IAAI,EAAE,EAAE;QACzB,MAAM,GAAG,GAAG,GAAG,CAAC,OAAO,CAAC;QACxB,MAAM,KAAK,GAAG,GAAG,CAAC,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-echo messages.
|
|
3
|
+
*
|
|
4
|
+
* Combines two common filtering needs into a single middleware:
|
|
5
|
+
* 1. **Self-echo**: QQ may deliver the bot's own outbound messages back
|
|
6
|
+
* as inbound events (especially in group chats).
|
|
7
|
+
* 2. **Deduplication**: QQ occasionally pushes the same event more than
|
|
8
|
+
* once (network retries, reconnect overlap, etc.).
|
|
9
|
+
*
|
|
10
|
+
* Both are enabled by default. Disable either via options.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* bot.use(messageFilter()); // both enabled
|
|
15
|
+
* bot.use(messageFilter({ skipSelfEcho: false })); // only dedup
|
|
16
|
+
* bot.use(messageFilter({ dedup: { windowMs: 10_000 }})); // custom window
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
import type { Middleware } from "./types.js";
|
|
20
|
+
export interface MessageFilterOptions {
|
|
21
|
+
/**
|
|
22
|
+
* Drop messages where `senderIsBot === true`.
|
|
23
|
+
* Defaults to `true`.
|
|
24
|
+
*/
|
|
25
|
+
skipSelfEcho?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Deduplication settings. Set to `false` to disable entirely.
|
|
28
|
+
* Defaults to `{ windowMs: 5000, maxSize: 1000 }`.
|
|
29
|
+
*/
|
|
30
|
+
dedup?: false | {
|
|
31
|
+
/** Time window (ms) to keep messageIds. Defaults to `5000`. */
|
|
32
|
+
windowMs?: number;
|
|
33
|
+
/** Max tracked ids. Defaults to `1000`. */
|
|
34
|
+
maxSize?: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export declare function messageFilter(options?: MessageFilterOptions): Middleware;
|
|
38
|
+
//# sourceMappingURL=message-filter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message-filter.d.ts","sourceRoot":"","sources":["../../src/middleware/message-filter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,WAAW,oBAAoB;IACnC;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;;OAGG;IACH,KAAK,CAAC,EAAE,KAAK,GAAG;QACd,+DAA+D;QAC/D,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,2CAA2C;QAC3C,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,CAAC;CACH;AAED,wBAAgB,aAAa,CAAC,OAAO,GAAE,oBAAyB,GAAG,UAAU,CA0C5E"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Message filter middleware — drop invalid/duplicate/self-echo messages.
|
|
3
|
+
*
|
|
4
|
+
* Combines two common filtering needs into a single middleware:
|
|
5
|
+
* 1. **Self-echo**: QQ may deliver the bot's own outbound messages back
|
|
6
|
+
* as inbound events (especially in group chats).
|
|
7
|
+
* 2. **Deduplication**: QQ occasionally pushes the same event more than
|
|
8
|
+
* once (network retries, reconnect overlap, etc.).
|
|
9
|
+
*
|
|
10
|
+
* Both are enabled by default. Disable either via options.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* bot.use(messageFilter()); // both enabled
|
|
15
|
+
* bot.use(messageFilter({ skipSelfEcho: false })); // only dedup
|
|
16
|
+
* bot.use(messageFilter({ dedup: { windowMs: 10_000 }})); // custom window
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
export function messageFilter(options = {}) {
|
|
20
|
+
const skipSelfEcho = options.skipSelfEcho ?? true;
|
|
21
|
+
const dedupOpts = options.dedup !== false
|
|
22
|
+
? { windowMs: 5000, maxSize: 1000, ...(options.dedup ?? {}) }
|
|
23
|
+
: null;
|
|
24
|
+
const seen = dedupOpts ? new Map() : null;
|
|
25
|
+
function evict(now) {
|
|
26
|
+
if (!seen || !dedupOpts)
|
|
27
|
+
return;
|
|
28
|
+
if (seen.size <= dedupOpts.maxSize)
|
|
29
|
+
return;
|
|
30
|
+
for (const [key, ts] of seen) {
|
|
31
|
+
if (now - ts > dedupOpts.windowMs || seen.size > dedupOpts.maxSize) {
|
|
32
|
+
seen.delete(key);
|
|
33
|
+
}
|
|
34
|
+
else {
|
|
35
|
+
break;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return async (ctx, next) => {
|
|
40
|
+
// 1. Self-echo check
|
|
41
|
+
if (skipSelfEcho && ctx.message.senderIsBot) {
|
|
42
|
+
ctx.stop("self-echo");
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
// 2. Deduplication check
|
|
46
|
+
if (seen && dedupOpts) {
|
|
47
|
+
const id = ctx.message.messageId;
|
|
48
|
+
const now = Date.now();
|
|
49
|
+
if (seen.has(id)) {
|
|
50
|
+
ctx.log.debug?.(`[message-filter] dropping duplicate messageId=${id}`);
|
|
51
|
+
ctx.stop("deduplication");
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
seen.set(id, now);
|
|
55
|
+
evict(now);
|
|
56
|
+
}
|
|
57
|
+
await next();
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=message-filter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"message-filter.js","sourceRoot":"","sources":["../../src/middleware/message-filter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAsBH,MAAM,UAAU,aAAa,CAAC,UAAgC,EAAE;IAC9D,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,IAAI,CAAC;IAClD,MAAM,SAAS,GAAG,OAAO,CAAC,KAAK,KAAK,KAAK;QACvC,CAAC,CAAC,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,OAAO,CAAC,KAAK,IAAI,EAAE,CAAC,EAAE;QAC7D,CAAC,CAAC,IAAI,CAAC;IAET,MAAM,IAAI,GAAG,SAA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,MAAM,IAAI,EAAE,CAAC;IACf,CAAC,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quote & Ref-Index middleware — record messages + resolve quoted references.
|
|
3
|
+
*
|
|
4
|
+
* A single middleware that does two things in one pass:
|
|
5
|
+
* 1. **Record** — captures a compact summary of the current message into
|
|
6
|
+
* a pluggable store (default: in-memory LRU), keyed by `msgIdx` or `messageId`.
|
|
7
|
+
* 2. **Resolve** — if the current message quotes/replies to a previous one
|
|
8
|
+
* (`refMsgIdx` set), looks it up from the store or falls back to QQ's
|
|
9
|
+
* `msg_elements[0]` push data.
|
|
10
|
+
*
|
|
11
|
+
* The resolved quote is attached to `ctx.state.quote`.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { quoteRef } from "@tencent-connect/qqbot-nodejs";
|
|
16
|
+
*
|
|
17
|
+
* bot.use(quoteRef()); // zero-config
|
|
18
|
+
* bot.use(quoteRef({ maxSize: 1000 })); // custom LRU size
|
|
19
|
+
* bot.use(quoteRef({ store: myRedisStore })); // custom backend
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
23
|
+
/** Compact summary stored per message. */
|
|
24
|
+
export interface RefEntry {
|
|
25
|
+
messageId: string;
|
|
26
|
+
senderId: string;
|
|
27
|
+
senderName?: string;
|
|
28
|
+
content: string;
|
|
29
|
+
timestamp: string;
|
|
30
|
+
/** Extensible: stores may accept extra keys for domain-specific metadata. */
|
|
31
|
+
[key: string]: unknown;
|
|
32
|
+
}
|
|
33
|
+
/** Pluggable store interface for ref-index. */
|
|
34
|
+
export interface RefIndexStore {
|
|
35
|
+
get(key: string): RefEntry | undefined | Promise<RefEntry | undefined>;
|
|
36
|
+
set(key: string, entry: RefEntry): void | Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/** Attachment summary from the quoted message (from msg_elements). */
|
|
39
|
+
export interface QuotedAttachment {
|
|
40
|
+
contentType: string;
|
|
41
|
+
url: string;
|
|
42
|
+
filename?: string;
|
|
43
|
+
/** ASR text for voice messages (QQ built-in speech recognition). */
|
|
44
|
+
asrText?: string;
|
|
45
|
+
}
|
|
46
|
+
/** Resolved quote attached to `ctx.state.quote`. */
|
|
47
|
+
export interface ResolvedQuote {
|
|
48
|
+
/** The ref key that was looked up. */
|
|
49
|
+
refKey: string;
|
|
50
|
+
/** Source of the resolution. */
|
|
51
|
+
source: "store" | "msg_elements" | "none";
|
|
52
|
+
/** The resolved entry from store (cache hit). */
|
|
53
|
+
entry?: RefEntry;
|
|
54
|
+
/** Raw content from msg_elements[0] (cache miss fallback). */
|
|
55
|
+
rawContent?: string;
|
|
56
|
+
/** Attachments from the quoted message (from msg_elements[0]). */
|
|
57
|
+
attachments?: QuotedAttachment[];
|
|
58
|
+
/**
|
|
59
|
+
* Combined text representation of the quoted message.
|
|
60
|
+
* Prefers store entry content; falls back to msg_elements content.
|
|
61
|
+
*/
|
|
62
|
+
text: string;
|
|
63
|
+
}
|
|
64
|
+
export interface QuoteRefOptions {
|
|
65
|
+
/** Backing store. Defaults to an in-memory LRU. */
|
|
66
|
+
store?: RefIndexStore;
|
|
67
|
+
/** Max entries in the default in-memory LRU. Defaults to 500. */
|
|
68
|
+
maxSize?: number;
|
|
69
|
+
/** Max content chars stored per entry. Defaults to 200. */
|
|
70
|
+
contentLimit?: number;
|
|
71
|
+
/** Enrich the stored entry with extra fields before writing. */
|
|
72
|
+
enrichEntry?: (entry: RefEntry, ctx: MiddlewareContext) => RefEntry;
|
|
73
|
+
/** When true, prefer msg_elements data over stored entry for richer content. */
|
|
74
|
+
preferMsgElements?: boolean;
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Default in-memory ref-index store (LRU eviction).
|
|
78
|
+
*
|
|
79
|
+
* Suitable for single-process bots. For multi-instance deployments,
|
|
80
|
+
* implement `RefIndexStore` with Redis / SQL / etc.
|
|
81
|
+
*/
|
|
82
|
+
export declare class MemoryRefIndexStore implements RefIndexStore {
|
|
83
|
+
private readonly map;
|
|
84
|
+
private readonly maxSize;
|
|
85
|
+
constructor(maxSize?: number);
|
|
86
|
+
get(key: string): RefEntry | undefined;
|
|
87
|
+
set(key: string, entry: RefEntry): void;
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Combined quote & ref-index middleware.
|
|
91
|
+
*
|
|
92
|
+
* One middleware does both: records the current message into the store
|
|
93
|
+
* **and** resolves any quoted message reference.
|
|
94
|
+
*
|
|
95
|
+
* @example
|
|
96
|
+
* ```ts
|
|
97
|
+
* bot.use(quoteRef()); // that's it — zero config
|
|
98
|
+
*
|
|
99
|
+
* bot.on("message", (msg) => {
|
|
100
|
+
* // Access resolved quote via middleware state
|
|
101
|
+
* // (ctx.state.quote is typed as ResolvedQuote)
|
|
102
|
+
* });
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
export declare function quoteRef(options?: QuoteRefOptions): Middleware;
|
|
106
|
+
//# sourceMappingURL=quote-ref.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"quote-ref.d.ts","sourceRoot":"","sources":["../../src/middleware/quote-ref.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAIhE,0CAA0C;AAC1C,MAAM,WAAW,QAAQ;IACvB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,6EAA6E;IAC7E,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CACxB;AAED,+CAA+C;AAC/C,MAAM,WAAW,aAAa;IAC5B,GAAG,CAAC,GAAG,EAA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CAAS;gBAErB,OAAO,SAAM;IAIzB,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,QAAQ,GAAG,SAAS;IAItC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,QAAQ,GAAG,IAAI;CAOxC;AAID;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,QAAQ,CAAC,OAAO,GAAE,eAAoB,GAAG,UAAU,CAyElE"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quote & Ref-Index middleware — record messages + resolve quoted references.
|
|
3
|
+
*
|
|
4
|
+
* A single middleware that does two things in one pass:
|
|
5
|
+
* 1. **Record** — captures a compact summary of the current message into
|
|
6
|
+
* a pluggable store (default: in-memory LRU), keyed by `msgIdx` or `messageId`.
|
|
7
|
+
* 2. **Resolve** — if the current message quotes/replies to a previous one
|
|
8
|
+
* (`refMsgIdx` set), looks it up from the store or falls back to QQ's
|
|
9
|
+
* `msg_elements[0]` push data.
|
|
10
|
+
*
|
|
11
|
+
* The resolved quote is attached to `ctx.state.quote`.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* import { quoteRef } from "@tencent-connect/qqbot-nodejs";
|
|
16
|
+
*
|
|
17
|
+
* bot.use(quoteRef()); // zero-config
|
|
18
|
+
* bot.use(quoteRef({ maxSize: 1000 })); // custom LRU size
|
|
19
|
+
* bot.use(quoteRef({ store: myRedisStore })); // custom backend
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
// ============ Default in-memory LRU ============
|
|
23
|
+
/**
|
|
24
|
+
* Default in-memory ref-index store (LRU eviction).
|
|
25
|
+
*
|
|
26
|
+
* Suitable for single-process bots. For multi-instance deployments,
|
|
27
|
+
* implement `RefIndexStore` with Redis / SQL / etc.
|
|
28
|
+
*/
|
|
29
|
+
export class MemoryRefIndexStore {
|
|
30
|
+
map = new Map();
|
|
31
|
+
maxSize;
|
|
32
|
+
constructor(maxSize = 500) {
|
|
33
|
+
this.maxSize = maxSize;
|
|
34
|
+
}
|
|
35
|
+
get(key) {
|
|
36
|
+
return this.map.get(key);
|
|
37
|
+
}
|
|
38
|
+
set(key, entry) {
|
|
39
|
+
if (this.map.size >= this.maxSize) {
|
|
40
|
+
const first = this.map.keys().next().value;
|
|
41
|
+
if (first !== undefined)
|
|
42
|
+
this.map.delete(first);
|
|
43
|
+
}
|
|
44
|
+
this.map.set(key, entry);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// ============ Middleware ============
|
|
48
|
+
/**
|
|
49
|
+
* Combined quote & ref-index middleware.
|
|
50
|
+
*
|
|
51
|
+
* One middleware does both: records the current message into the store
|
|
52
|
+
* **and** resolves any quoted message reference.
|
|
53
|
+
*
|
|
54
|
+
* @example
|
|
55
|
+
* ```ts
|
|
56
|
+
* bot.use(quoteRef()); // that's it — zero config
|
|
57
|
+
*
|
|
58
|
+
* bot.on("message", (msg) => {
|
|
59
|
+
* // Access resolved quote via middleware state
|
|
60
|
+
* // (ctx.state.quote is typed as ResolvedQuote)
|
|
61
|
+
* });
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export function quoteRef(options = {}) {
|
|
65
|
+
const contentLimit = options.contentLimit ?? 200;
|
|
66
|
+
const store = options.store ?? new MemoryRefIndexStore(options.maxSize ?? 500);
|
|
67
|
+
return async (ctx, next) => {
|
|
68
|
+
const msg = ctx.message;
|
|
69
|
+
// ── 1. Record current message ──
|
|
70
|
+
const key = msg.msgIdx ?? msg.messageId;
|
|
71
|
+
if (key) {
|
|
72
|
+
let entry = {
|
|
73
|
+
messageId: msg.messageId,
|
|
74
|
+
senderId: msg.senderId,
|
|
75
|
+
senderName: msg.senderName,
|
|
76
|
+
content: (msg.content ?? "").slice(0, contentLimit),
|
|
77
|
+
timestamp: msg.timestamp,
|
|
78
|
+
isBot: msg.senderIsBot,
|
|
79
|
+
scope: msg.kind,
|
|
80
|
+
};
|
|
81
|
+
if (options.enrichEntry) {
|
|
82
|
+
entry = options.enrichEntry(entry, ctx);
|
|
83
|
+
}
|
|
84
|
+
await store.set(key, entry);
|
|
85
|
+
}
|
|
86
|
+
// ── 2. Resolve quoted message (if any) ──
|
|
87
|
+
const refKey = msg.refMsgIdx;
|
|
88
|
+
if (refKey) {
|
|
89
|
+
const entry = await store.get(refKey);
|
|
90
|
+
// 尝试从 msg_elements 解析引用内容(优先于 store entry 时使用)
|
|
91
|
+
const resolveFromElements = () => {
|
|
92
|
+
const el = msg.msgElements?.[0];
|
|
93
|
+
if (!el || (!el.content && !el.attachments?.length))
|
|
94
|
+
return null;
|
|
95
|
+
const rawContent = el.content ?? "";
|
|
96
|
+
const attachments = parseAttachments(el.attachments);
|
|
97
|
+
return { rawContent, attachments, text: buildText(rawContent, attachments) };
|
|
98
|
+
};
|
|
99
|
+
if (entry) {
|
|
100
|
+
const elementsQuote = options.preferMsgElements !== false ? resolveFromElements() : null;
|
|
101
|
+
if (elementsQuote) {
|
|
102
|
+
ctx.state.quote = {
|
|
103
|
+
refKey, source: "msg_elements",
|
|
104
|
+
rawContent: elementsQuote.rawContent,
|
|
105
|
+
attachments: elementsQuote.attachments,
|
|
106
|
+
text: elementsQuote.text,
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
ctx.state.quote = {
|
|
111
|
+
refKey, source: "store", entry,
|
|
112
|
+
text: entry.content || "[empty message]",
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
ctx.log.debug?.(`[quote-ref] hit refKey=${refKey} sender=${entry.senderId}`);
|
|
116
|
+
}
|
|
117
|
+
else {
|
|
118
|
+
const elementsQuote = resolveFromElements();
|
|
119
|
+
if (elementsQuote) {
|
|
120
|
+
ctx.state.quote = {
|
|
121
|
+
refKey, source: "msg_elements",
|
|
122
|
+
rawContent: elementsQuote.rawContent,
|
|
123
|
+
attachments: elementsQuote.attachments,
|
|
124
|
+
text: elementsQuote.text,
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
ctx.state.quote = { refKey, source: "none", text: "" };
|
|
129
|
+
}
|
|
130
|
+
ctx.log.debug?.(`[quote-ref] ${elementsQuote ? 'fallback' : 'miss'} refKey=${refKey}`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
await next();
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
// ============ Helpers ============
|
|
137
|
+
function parseAttachments(raw) {
|
|
138
|
+
if (!raw || raw.length === 0)
|
|
139
|
+
return [];
|
|
140
|
+
return raw.map((a) => ({
|
|
141
|
+
contentType: a.content_type,
|
|
142
|
+
url: a.url,
|
|
143
|
+
filename: a.filename,
|
|
144
|
+
asrText: a.asr_refer_text,
|
|
145
|
+
}));
|
|
146
|
+
}
|
|
147
|
+
function buildText(content, attachments) {
|
|
148
|
+
const parts = [];
|
|
149
|
+
if (content.trim())
|
|
150
|
+
parts.push(content.trim());
|
|
151
|
+
for (const att of attachments) {
|
|
152
|
+
const t = att.contentType.toLowerCase();
|
|
153
|
+
if (t.startsWith("audio/")) {
|
|
154
|
+
parts.push(att.asrText ? `[voice: ${att.asrText}]` : "[voice]");
|
|
155
|
+
}
|
|
156
|
+
else if (t.startsWith("image/")) {
|
|
157
|
+
parts.push(att.filename ? `[image: ${att.filename}]` : "[image]");
|
|
158
|
+
}
|
|
159
|
+
else if (t.startsWith("video/")) {
|
|
160
|
+
parts.push(att.filename ? `[video: ${att.filename}]` : "[video]");
|
|
161
|
+
}
|
|
162
|
+
else {
|
|
163
|
+
parts.push(`[file: ${att.filename ?? "untitled"}]`);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return parts.join("\n") || "[empty message]";
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=quote-ref.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"quote-ref.js","sourceRoot":"","sources":["../../src/middleware/quote-ref.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;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AAC;aAAM,IAAI,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC,EAAE,CAAC;YAClC,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,WAAW,GAAG,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QACpE,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,IAAI,CAAC,UAAU,GAAG,CAAC,QAAQ,IAAI,UAAU,GAAG,CAAC,CAAC;QACtD,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,iBAAiB,CAAC;AAC/C,CAAC"}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate-limiter middleware — configurable multi-tier rate limiting.
|
|
3
|
+
*
|
|
4
|
+
* Supports three tiers: per-sender, per-group, and global. Uses a
|
|
5
|
+
* sliding-window counter algorithm. When a message exceeds the limit,
|
|
6
|
+
* the chain is short-circuited; an optional `onLimit` hook lets users
|
|
7
|
+
* send a friendly rejection or log the event.
|
|
8
|
+
*/
|
|
9
|
+
import type { Middleware, MiddlewareContext } from "./types.js";
|
|
10
|
+
export interface RateLimitTier {
|
|
11
|
+
/** Max requests within the window. */
|
|
12
|
+
max: number;
|
|
13
|
+
/** Window duration in milliseconds. */
|
|
14
|
+
windowMs: number;
|
|
15
|
+
}
|
|
16
|
+
export interface RateLimiterOptions {
|
|
17
|
+
/** Per-sender limit. Keyed by `senderId`. */
|
|
18
|
+
perSender?: RateLimitTier;
|
|
19
|
+
/** Per-group limit. Keyed by `groupOpenid` (group only; C2C uses senderId). */
|
|
20
|
+
perGroup?: RateLimitTier;
|
|
21
|
+
/** Global limit across all messages. */
|
|
22
|
+
global?: RateLimitTier;
|
|
23
|
+
/**
|
|
24
|
+
* Hook invoked when a message is rate-limited. Use to send a reply or
|
|
25
|
+
* log. Return value is ignored.
|
|
26
|
+
*/
|
|
27
|
+
onLimit?: (ctx: MiddlewareContext, tier: "perSender" | "perGroup" | "global") => void | Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* @example
|
|
31
|
+
* ```ts
|
|
32
|
+
* bot.use(rateLimiter({
|
|
33
|
+
* perSender: { max: 5, windowMs: 60_000 }, // 5 msg/min per user
|
|
34
|
+
* perGroup: { max: 30, windowMs: 60_000 }, // 30 msg/min per group
|
|
35
|
+
* global: { max: 100, windowMs: 60_000 }, // 100 msg/min total
|
|
36
|
+
* onLimit: async (ctx, tier) => {
|
|
37
|
+
* await ctx.bot.sendText(ctx.replyTarget, `请稍后再试(${tier}限流)`);
|
|
38
|
+
* },
|
|
39
|
+
* }));
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export declare function rateLimiter(options?: RateLimiterOptions): Middleware;
|
|
43
|
+
//# sourceMappingURL=rate-limiter.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limiter.d.ts","sourceRoot":"","sources":["../../src/middleware/rate-limiter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,UAAU,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAEhE,MAAM,WAAW,aAAa;IAC5B,sCAAsC;IACtC,GAAG,EAAE,MAAM,CAAC;IACZ,uCAAuC;IACvC,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,kBAAkB;IACjC,6CAA6C;IAC7C,SAAS,CAAC,EAAE,aAAa,CAAC;IAC1B,+EAA+E;IAC/E,QAAQ,CAAC,EAAE,aAAa,CAAC;IACzB,wCAAwC;IACxC,MAAM,CAAC,EAAE,aAAa,CAAC;IACvB;;;OAGG;IACH,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,iBAAiB,EAAE,IAAI,EAAE,WAAW,GAAG,UAAU,GAAG,QAAQ,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvG;AAqCD;;;;;;;;;;;;GAYG;AACH,wBAAgB,WAAW,CAAC,OAAO,GAAE,kBAAuB,GAAG,UAAU,CA+BxE"}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rate-limiter middleware — configurable multi-tier rate limiting.
|
|
3
|
+
*
|
|
4
|
+
* Supports three tiers: per-sender, per-group, and global. Uses a
|
|
5
|
+
* sliding-window counter algorithm. When a message exceeds the limit,
|
|
6
|
+
* the chain is short-circuited; an optional `onLimit` hook lets users
|
|
7
|
+
* send a friendly rejection or log the event.
|
|
8
|
+
*/
|
|
9
|
+
// ============ Sliding window counter ============
|
|
10
|
+
class SlidingWindow {
|
|
11
|
+
buckets = new Map();
|
|
12
|
+
max;
|
|
13
|
+
windowMs;
|
|
14
|
+
constructor(tier) {
|
|
15
|
+
this.max = tier.max;
|
|
16
|
+
this.windowMs = tier.windowMs;
|
|
17
|
+
}
|
|
18
|
+
/** Returns `true` if allowed, `false` if rate-limited. */
|
|
19
|
+
check(key) {
|
|
20
|
+
const now = Date.now();
|
|
21
|
+
let arr = this.buckets.get(key);
|
|
22
|
+
if (!arr) {
|
|
23
|
+
arr = [];
|
|
24
|
+
this.buckets.set(key, arr);
|
|
25
|
+
}
|
|
26
|
+
// Evict expired entries
|
|
27
|
+
while (arr.length > 0 && now - arr[0] > this.windowMs) {
|
|
28
|
+
arr.shift();
|
|
29
|
+
}
|
|
30
|
+
if (arr.length >= this.max) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
arr.push(now);
|
|
34
|
+
return true;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* @example
|
|
39
|
+
* ```ts
|
|
40
|
+
* bot.use(rateLimiter({
|
|
41
|
+
* perSender: { max: 5, windowMs: 60_000 }, // 5 msg/min per user
|
|
42
|
+
* perGroup: { max: 30, windowMs: 60_000 }, // 30 msg/min per group
|
|
43
|
+
* global: { max: 100, windowMs: 60_000 }, // 100 msg/min total
|
|
44
|
+
* onLimit: async (ctx, tier) => {
|
|
45
|
+
* await ctx.bot.sendText(ctx.replyTarget, `请稍后再试(${tier}限流)`);
|
|
46
|
+
* },
|
|
47
|
+
* }));
|
|
48
|
+
* ```
|
|
49
|
+
*/
|
|
50
|
+
export function rateLimiter(options = {}) {
|
|
51
|
+
const { onLimit } = options;
|
|
52
|
+
const perSender = options.perSender ? new SlidingWindow(options.perSender) : undefined;
|
|
53
|
+
const perGroup = options.perGroup ? new SlidingWindow(options.perGroup) : undefined;
|
|
54
|
+
const global = options.global ? new SlidingWindow(options.global) : undefined;
|
|
55
|
+
return async (ctx, next) => {
|
|
56
|
+
const senderId = ctx.message.senderId;
|
|
57
|
+
const groupKey = ctx.message.groupOpenid ?? senderId;
|
|
58
|
+
// Check global first (cheapest to short-circuit)
|
|
59
|
+
if (global && !global.check("__global__")) {
|
|
60
|
+
await onLimit?.(ctx, "global");
|
|
61
|
+
ctx.stop("rate-limit:global");
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
if (perGroup && !perGroup.check(groupKey)) {
|
|
65
|
+
await onLimit?.(ctx, "perGroup");
|
|
66
|
+
ctx.stop("rate-limit:perGroup");
|
|
67
|
+
return;
|
|
68
|
+
}
|
|
69
|
+
if (perSender && !perSender.check(senderId)) {
|
|
70
|
+
await onLimit?.(ctx, "perSender");
|
|
71
|
+
ctx.stop("rate-limit:perSender");
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
await next();
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=rate-limiter.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limiter.js","sourceRoot":"","sources":["../../src/middleware/rate-limiter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAyBH,mDAAmD;AAEnD,MAAM,aAAa;IACA,OAAO,GAAG,IAAI,GAAG,EAAoB,CAAC;IACtC,GAAG,CAAS;IACZ,QAAQ,CAAS;IA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