@nestim/koishi-plugin-qq-group-manager 1.1.3 → 1.2.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.
- package/CHANGELOG.md +299 -0
- package/lib/ai/engine.d.ts +74 -0
- package/lib/ai/engine.js +525 -0
- package/lib/ai/memory.d.ts +30 -0
- package/lib/ai/memory.js +89 -0
- package/lib/ai/prompt.d.ts +36 -0
- package/lib/ai/prompt.js +125 -0
- package/lib/ai/provider.d.ts +48 -0
- package/lib/ai/provider.js +194 -0
- package/lib/ai/state.d.ts +53 -0
- package/lib/ai/state.js +62 -0
- package/lib/ai/trigger.d.ts +28 -0
- package/lib/ai/trigger.js +41 -0
- package/lib/ai/vision.d.ts +15 -0
- package/lib/ai/vision.js +64 -0
- package/lib/core/names.d.ts +48 -0
- package/lib/core/names.js +144 -0
- package/lib/core/text.d.ts +47 -0
- package/lib/core/text.js +284 -0
- package/lib/index.d.ts +263 -54
- package/lib/index.js +19 -13
- package/lib/service.d.ts +574 -153
- package/lib/service.js +56 -1221
- package/package.json +20 -7
- package/readme.md +149 -11
- package/src/ai/engine.ts +568 -0
- package/src/ai/memory.ts +104 -0
- package/src/ai/prompt.ts +142 -0
- package/src/ai/provider.ts +221 -0
- package/src/ai/state.ts +91 -0
- package/src/ai/trigger.ts +60 -0
- package/src/ai/vision.ts +81 -0
- package/src/core/names.ts +158 -0
- package/src/core/text.ts +332 -0
- package/src/index.ts +186 -0
- package/src/service.js +3327 -0
- package/tsconfig.json +24 -0
- package/lib/commands.d.ts +0 -4
- package/lib/commands.js +0 -18
- package/lib/types.d.ts +0 -23
- package/lib/types.js +0 -2
package/lib/service.js
CHANGED
|
@@ -7,20 +7,18 @@ exports.QQGroupManagerService = void 0;
|
|
|
7
7
|
const koishi_1 = require("koishi");
|
|
8
8
|
const node_path_1 = __importDefault(require("node:path"));
|
|
9
9
|
const node_fs_1 = __importDefault(require("node:fs"));
|
|
10
|
+
const { AiEngine } = require("./ai/engine");
|
|
11
|
+
let PLUGIN_VERSION = 'unknown';
|
|
12
|
+
try {
|
|
13
|
+
PLUGIN_VERSION = require('../package.json').version || 'unknown';
|
|
14
|
+
}
|
|
15
|
+
catch { /* ignore */ }
|
|
10
16
|
class QQGroupManagerService extends koishi_1.Service {
|
|
11
17
|
ctx;
|
|
12
18
|
config;
|
|
13
19
|
_logger;
|
|
14
20
|
unauthorizedMuteAttempts = new Map();
|
|
15
|
-
aiBuffers = new Map();
|
|
16
|
-
aiCounters = new Map();
|
|
17
|
-
aiLastReplyAt = new Map();
|
|
18
|
-
aiInFlight = new Set();
|
|
19
|
-
aiHandledEvents = new Map();
|
|
20
|
-
aiFollowups = new Map();
|
|
21
|
-
aiUserMemory = new Map();
|
|
22
21
|
repeatStates = new Map();
|
|
23
|
-
aiTopicMemory = new Map();
|
|
24
22
|
pendingJoinRequests = new Map();
|
|
25
23
|
pendingJoinRequestFlags = new Map();
|
|
26
24
|
violationRecords = new Map();
|
|
@@ -166,7 +164,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
166
164
|
return;
|
|
167
165
|
if (!(await this.isBlacklisted(session, qq)))
|
|
168
166
|
return;
|
|
169
|
-
|
|
170
167
|
const onebot = this.getOneBotApi(session);
|
|
171
168
|
const groupId = this.toGroupId(session);
|
|
172
169
|
if (!onebot?.setGroupKick || groupId == null) {
|
|
@@ -187,6 +184,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
187
184
|
this.ctx = ctx;
|
|
188
185
|
this.config = config;
|
|
189
186
|
this._logger = ctx.logger('nestim-qq-group-manager');
|
|
187
|
+
this.ai = new AiEngine(this);
|
|
188
|
+
this._logger.info(`[qqgm] v${PLUGIN_VERSION} 已加载 | ai=single-call+pass | ctx=${this.config.aiContextWindow || 30}`);
|
|
190
189
|
ctx.on('message', (session) => this.handleGroupModeration(session));
|
|
191
190
|
ctx.on('guild-member-request', (session) => this.handleGuildMemberRequest(session));
|
|
192
191
|
// 被踢出群(含群主/管理员踢人)→ 记入本群黑名单
|
|
@@ -250,11 +249,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
250
249
|
return rule[ruleKey];
|
|
251
250
|
return this.config[globalKey];
|
|
252
251
|
}
|
|
253
|
-
resolveAiEnabled(session) {
|
|
254
|
-
const guildId = this.normalizeGuildId(session.guildId);
|
|
255
|
-
const rule = this.config.groupRules.find((item) => this.normalizeGuildId(item.guildId) === guildId);
|
|
256
|
-
return this.resolveSwitch(rule, 'enableAiReply', 'enableAiReply');
|
|
257
|
-
}
|
|
258
252
|
extractAiMessageText(session) {
|
|
259
253
|
const text = this.getMessageText(session)
|
|
260
254
|
.replace(/\s+/g, ' ')
|
|
@@ -480,19 +474,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
480
474
|
return blocks.slice(-limit);
|
|
481
475
|
return blocks.filter((b) => b.includes(kw)).slice(-limit);
|
|
482
476
|
}
|
|
483
|
-
async decoratePromptWithMemory(prompt, options) {
|
|
484
|
-
if (!this.config.enableMemory || this.config.memoryInAi === false)
|
|
485
|
-
return prompt;
|
|
486
|
-
const keyword = (options?.focusText || options?.topicSummary || '').trim();
|
|
487
|
-
let results = await this.searchMemory(keyword, 6);
|
|
488
|
-
// 关键词没命中时(中文分词易漏),退而注入最近记忆,由模型自行判断相关性
|
|
489
|
-
if (!results.length && keyword)
|
|
490
|
-
results = await this.searchMemory('', 6);
|
|
491
|
-
if (!results.length)
|
|
492
|
-
return prompt;
|
|
493
|
-
const memoryLines = results.map((b, i) => `${i + 1}. ${b.replace(/\n+/g, ' ').trim().slice(0, 140)}`).join('\n');
|
|
494
|
-
return `${prompt}\n\n【记忆库参考】(若与当前话题相关可引用;不相关请忽略,不要编造,不要暴露"系统记忆"字样):\n${memoryLines}\n`;
|
|
495
|
-
}
|
|
496
477
|
/** 按关键词删除记忆条目(含该关键词的整条记忆块)。返回 { ok, removed, message } */
|
|
497
478
|
async deleteMemoryByKeyword(keyword) {
|
|
498
479
|
const kw = String(keyword ?? '').trim();
|
|
@@ -513,562 +494,14 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
513
494
|
});
|
|
514
495
|
}
|
|
515
496
|
getDisplayName(session) {
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
497
|
+
// 群名片优先(author.nick = sender.card),其次 QQ 昵称,最后 QQ 号;
|
|
498
|
+
// author.nickname 在 onebot 适配器里恒为 undefined,不再作为一级。
|
|
499
|
+
return session.author?.nick?.trim()
|
|
500
|
+
|| session.author?.name?.trim()
|
|
501
|
+
|| session.username?.trim()
|
|
519
502
|
|| session.userId
|
|
520
503
|
|| 'unknown';
|
|
521
504
|
}
|
|
522
|
-
isHomeUser(session) {
|
|
523
|
-
const ownerPlatform = this.config.aiOwnerPlatform?.trim() || this.config.aiHomePlatform?.trim();
|
|
524
|
-
const ownerUserId = this.config.aiOwnerUserId?.trim() || this.config.aiHomeUserId?.trim();
|
|
525
|
-
if (!ownerPlatform || !ownerUserId)
|
|
526
|
-
return false;
|
|
527
|
-
return session.platform === ownerPlatform && session.userId === ownerUserId;
|
|
528
|
-
}
|
|
529
|
-
rememberUser(session) {
|
|
530
|
-
if (!session.userId)
|
|
531
|
-
return;
|
|
532
|
-
const key = `${session.platform ?? 'unknown'}:${session.userId}`;
|
|
533
|
-
this.aiUserMemory.set(key, {
|
|
534
|
-
platform: session.platform ?? 'unknown',
|
|
535
|
-
userId: session.userId,
|
|
536
|
-
name: this.getDisplayName(session),
|
|
537
|
-
isHomeUser: this.isHomeUser(session),
|
|
538
|
-
updatedAt: Date.now(),
|
|
539
|
-
});
|
|
540
|
-
if (this.aiUserMemory.size > 2048) {
|
|
541
|
-
const expireBefore = Date.now() - 7 * 24 * 60 * 60 * 1000;
|
|
542
|
-
for (const [id, item] of this.aiUserMemory) {
|
|
543
|
-
if (item.updatedAt < expireBefore)
|
|
544
|
-
this.aiUserMemory.delete(id);
|
|
545
|
-
}
|
|
546
|
-
}
|
|
547
|
-
}
|
|
548
|
-
getFollowupSession(groupKey) {
|
|
549
|
-
const state = this.aiFollowups.get(groupKey);
|
|
550
|
-
if (!state)
|
|
551
|
-
return null;
|
|
552
|
-
if (Date.now() > state.expiresAt) {
|
|
553
|
-
this.aiFollowups.delete(groupKey);
|
|
554
|
-
return null;
|
|
555
|
-
}
|
|
556
|
-
return state;
|
|
557
|
-
}
|
|
558
|
-
tokenizeTopic(text) {
|
|
559
|
-
const normalized = text
|
|
560
|
-
.toLowerCase()
|
|
561
|
-
.replace(/[^\u4e00-\u9fa5a-z0-9]+/g, ' ')
|
|
562
|
-
.trim();
|
|
563
|
-
if (!normalized)
|
|
564
|
-
return [];
|
|
565
|
-
return [...new Set(normalized.split(/\s+/g).filter((item) => item.length >= 2))].slice(0, 24);
|
|
566
|
-
}
|
|
567
|
-
scoreTopicRelevance(text, topicTokens) {
|
|
568
|
-
if (!topicTokens.length)
|
|
569
|
-
return 0;
|
|
570
|
-
const tokens = this.tokenizeTopic(text);
|
|
571
|
-
if (!tokens.length)
|
|
572
|
-
return 0;
|
|
573
|
-
const overlap = tokens.filter((token) => topicTokens.includes(token)).length;
|
|
574
|
-
if (!overlap)
|
|
575
|
-
return 0;
|
|
576
|
-
return overlap / Math.max(1, Math.min(tokens.length, topicTokens.length));
|
|
577
|
-
}
|
|
578
|
-
startFollowupSession(groupKey, userId, anchorText) {
|
|
579
|
-
if (!this.config.aiEnableFollowupAfterMention)
|
|
580
|
-
return;
|
|
581
|
-
const seconds = Math.max(1, this.config.aiFollowupWindowSeconds || 120);
|
|
582
|
-
this.aiFollowups.set(groupKey, {
|
|
583
|
-
userId,
|
|
584
|
-
turns: 0,
|
|
585
|
-
expiresAt: Date.now() + seconds * 1000,
|
|
586
|
-
anchorTokens: this.tokenizeTopic(anchorText),
|
|
587
|
-
lastText: anchorText,
|
|
588
|
-
});
|
|
589
|
-
}
|
|
590
|
-
bumpFollowupSession(groupKey) {
|
|
591
|
-
const state = this.getFollowupSession(groupKey);
|
|
592
|
-
if (!state)
|
|
593
|
-
return;
|
|
594
|
-
state.turns += 1;
|
|
595
|
-
const seconds = Math.max(1, this.config.aiFollowupWindowSeconds || 120);
|
|
596
|
-
state.expiresAt = Date.now() + seconds * 1000;
|
|
597
|
-
const maxTurns = Math.max(1, this.config.aiFollowupMaxTurns || 3);
|
|
598
|
-
if (state.turns >= maxTurns) {
|
|
599
|
-
this.aiFollowups.delete(groupKey);
|
|
600
|
-
return;
|
|
601
|
-
}
|
|
602
|
-
this.aiFollowups.set(groupKey, state);
|
|
603
|
-
}
|
|
604
|
-
shouldContinueFollowup(text, state) {
|
|
605
|
-
const value = text.trim();
|
|
606
|
-
if (!value)
|
|
607
|
-
return false;
|
|
608
|
-
if (/^[/.!!##]/.test(value))
|
|
609
|
-
return false;
|
|
610
|
-
if (value.length <= 2)
|
|
611
|
-
return false;
|
|
612
|
-
if (/^[\u{1F300}-\u{1FAFF}\s~~!!.。]+$/u.test(value))
|
|
613
|
-
return false;
|
|
614
|
-
const shiftMarker = /(换个话题|换个问题|另外|题外话|不聊这个|先不说这个|说点别的|再问个新的|顺便问)/.test(value);
|
|
615
|
-
if (shiftMarker)
|
|
616
|
-
return false;
|
|
617
|
-
if (/(何意|何意味|hyw|什么意思|啥意思|怎么回事|发生了什么)/.test(value))
|
|
618
|
-
return true;
|
|
619
|
-
if (state?.anchorTokens?.length) {
|
|
620
|
-
const current = this.tokenizeTopic(value);
|
|
621
|
-
if (current.length) {
|
|
622
|
-
const overlap = current.filter((token) => state.anchorTokens.includes(token)).length;
|
|
623
|
-
const ratio = overlap / Math.max(1, Math.min(current.length, state.anchorTokens.length));
|
|
624
|
-
// Topic drift: almost no overlap with the original mentioned topic.
|
|
625
|
-
if (value.length >= 8 && overlap === 0)
|
|
626
|
-
return false;
|
|
627
|
-
if (value.length >= 8 && ratio <= 0.12 && /[??]/.test(value))
|
|
628
|
-
return false;
|
|
629
|
-
}
|
|
630
|
-
}
|
|
631
|
-
if (/[??]/.test(value))
|
|
632
|
-
return true;
|
|
633
|
-
if (/(继续|然后|再|那|所以|为什么|怎么|如何|帮我|请问|还能|可以吗|行吗|能否)/.test(value))
|
|
634
|
-
return true;
|
|
635
|
-
return value.length >= 8;
|
|
636
|
-
}
|
|
637
|
-
getActivePersona() {
|
|
638
|
-
const id = this.config.aiActivePersona?.trim();
|
|
639
|
-
if (!id)
|
|
640
|
-
return null;
|
|
641
|
-
return this.config.aiPersonas.find((item) => item.id?.trim() === id) ?? null;
|
|
642
|
-
}
|
|
643
|
-
getActiveAgentName() {
|
|
644
|
-
const persona = this.getActivePersona();
|
|
645
|
-
const fromPersona = persona?.selfName?.trim();
|
|
646
|
-
if (fromPersona)
|
|
647
|
-
return fromPersona;
|
|
648
|
-
return this.config.aiAgentName?.trim() || 'MeowBot';
|
|
649
|
-
}
|
|
650
|
-
getActiveSystemPrompt() {
|
|
651
|
-
const persona = this.getActivePersona();
|
|
652
|
-
const fromPersona = persona?.prompt?.trim();
|
|
653
|
-
if (fromPersona)
|
|
654
|
-
return fromPersona;
|
|
655
|
-
return this.config.aiSystemPrompt?.trim() || '你是群聊中的友好机器人,请简洁、自然、符合中文互联网语境地回复。';
|
|
656
|
-
}
|
|
657
|
-
containsAgentName(text) {
|
|
658
|
-
const agentName = this.getActiveAgentName();
|
|
659
|
-
if (!agentName)
|
|
660
|
-
return false;
|
|
661
|
-
return text.toLowerCase().includes(agentName.toLowerCase());
|
|
662
|
-
}
|
|
663
|
-
isMentionBot(session) {
|
|
664
|
-
const selfId = session.bot?.selfId;
|
|
665
|
-
if (!selfId)
|
|
666
|
-
return false;
|
|
667
|
-
const content = session.content ?? '';
|
|
668
|
-
if (content.includes(`<at id="${selfId}"`))
|
|
669
|
-
return true;
|
|
670
|
-
const escaped = selfId.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
671
|
-
const cqAt = new RegExp(`\\[CQ:at,[^\\]]*(qq|id)=${escaped}(?:,|\\])`, 'i');
|
|
672
|
-
return cqAt.test(content);
|
|
673
|
-
}
|
|
674
|
-
isCommandLikeMessage(text) {
|
|
675
|
-
const value = text.trim();
|
|
676
|
-
if (!value)
|
|
677
|
-
return false;
|
|
678
|
-
if (/^[/.!!##]/.test(value))
|
|
679
|
-
return true;
|
|
680
|
-
const prefixes = [this.config.command, this.config.menuCommand, 'help', 'status']
|
|
681
|
-
.map((item) => item?.trim())
|
|
682
|
-
.filter(Boolean);
|
|
683
|
-
return prefixes.some((prefix) => value === prefix || value.startsWith(`${prefix} `) || value === `${prefix}菜单`);
|
|
684
|
-
}
|
|
685
|
-
isDuplicateAiEvent(session) {
|
|
686
|
-
if (!session.messageId)
|
|
687
|
-
return false;
|
|
688
|
-
const key = `${session.platform ?? 'unknown'}:${session.guildId ?? 'private'}:${session.userId ?? 'unknown'}:${session.messageId}`;
|
|
689
|
-
const now = Date.now();
|
|
690
|
-
const previous = this.aiHandledEvents.get(key) ?? 0;
|
|
691
|
-
this.aiHandledEvents.set(key, now);
|
|
692
|
-
const expireBefore = now - 120_000;
|
|
693
|
-
if (this.aiHandledEvents.size > 512) {
|
|
694
|
-
for (const [id, ts] of this.aiHandledEvents) {
|
|
695
|
-
if (ts < expireBefore)
|
|
696
|
-
this.aiHandledEvents.delete(id);
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
return previous > 0 && now - previous < 15_000;
|
|
700
|
-
}
|
|
701
|
-
pushAiRecord(session, text) {
|
|
702
|
-
const key = this.aiGroupKey(session);
|
|
703
|
-
if (!key || !session.userId)
|
|
704
|
-
return;
|
|
705
|
-
const name = session.username?.trim()
|
|
706
|
-
|| session.author?.nick?.trim()
|
|
707
|
-
|| session.author?.nickname?.trim()
|
|
708
|
-
|| session.userId;
|
|
709
|
-
const record = {
|
|
710
|
-
userId: session.userId,
|
|
711
|
-
name,
|
|
712
|
-
text,
|
|
713
|
-
imageUrls: this.extractImageUrls(session),
|
|
714
|
-
timestamp: Date.now(),
|
|
715
|
-
};
|
|
716
|
-
const current = this.aiBuffers.get(key) ?? [];
|
|
717
|
-
current.push(record);
|
|
718
|
-
const maxWindow = Math.max(6, this.config.aiContextWindow || 24);
|
|
719
|
-
const next = current.slice(-maxWindow);
|
|
720
|
-
this.aiBuffers.set(key, next);
|
|
721
|
-
this.aiCounters.set(key, (this.aiCounters.get(key) ?? 0) + 1);
|
|
722
|
-
}
|
|
723
|
-
appendAiContextNote(groupKey, text) {
|
|
724
|
-
if (!groupKey || !text.trim())
|
|
725
|
-
return;
|
|
726
|
-
const current = this.aiBuffers.get(groupKey) ?? [];
|
|
727
|
-
current.push({
|
|
728
|
-
userId: 'system',
|
|
729
|
-
name: '系统',
|
|
730
|
-
text,
|
|
731
|
-
imageUrls: [],
|
|
732
|
-
timestamp: Date.now(),
|
|
733
|
-
});
|
|
734
|
-
const maxWindow = Math.max(6, this.config.aiContextWindow || 24);
|
|
735
|
-
this.aiBuffers.set(groupKey, current.slice(-maxWindow));
|
|
736
|
-
}
|
|
737
|
-
shouldTriggerAiReply(session, forceMention = false) {
|
|
738
|
-
const key = this.aiGroupKey(session);
|
|
739
|
-
if (!key)
|
|
740
|
-
return { ok: false, reason: 'no-group' };
|
|
741
|
-
const now = Date.now();
|
|
742
|
-
const last = this.aiLastReplyAt.get(key) ?? 0;
|
|
743
|
-
const minIntervalMs = Math.max(0, this.config.aiMinReplyIntervalSeconds || 0) * 1000;
|
|
744
|
-
if (!forceMention && now - last < minIntervalMs)
|
|
745
|
-
return { ok: false, reason: 'cooldown' };
|
|
746
|
-
if (this.aiInFlight.has(key))
|
|
747
|
-
return { ok: false, reason: 'in-flight' };
|
|
748
|
-
if (forceMention)
|
|
749
|
-
return { ok: true, reason: 'direct-mention' };
|
|
750
|
-
const mode = this.config.aiReplyMode;
|
|
751
|
-
const messageCount = this.aiCounters.get(key) ?? 0;
|
|
752
|
-
const threshold = Math.max(1, this.config.aiMessageThreshold || 1);
|
|
753
|
-
// 闸门一(消息阈值):threshold / hybrid 模式下,累计消息数未达阈值一律不触发。
|
|
754
|
-
// 计数器只在成功回复后清零(见 maybeReplyWithAi 末尾),因此回复后需重新累计。
|
|
755
|
-
const thresholdRequired = mode === 'threshold' || mode === 'hybrid';
|
|
756
|
-
if (thresholdRequired && messageCount < threshold)
|
|
757
|
-
return { ok: false, reason: `below-threshold(${messageCount}/${threshold})` };
|
|
758
|
-
// 闸门二(随机概率):random / hybrid 模式下对每条消息掷一次骰,未掷中直接返回,
|
|
759
|
-
// 不会触发后续的兴趣判定与生成请求。
|
|
760
|
-
const randomRequired = mode === 'random' || mode === 'hybrid';
|
|
761
|
-
if (randomRequired) {
|
|
762
|
-
const probability = Math.max(0, Math.min(1, Number(this.config.aiRandomReplyProbability ?? 0.08)));
|
|
763
|
-
if (probability <= 0)
|
|
764
|
-
return { ok: false, reason: 'random-disabled' };
|
|
765
|
-
if (Math.random() >= probability)
|
|
766
|
-
return { ok: false, reason: `random-miss(${probability})` };
|
|
767
|
-
return thresholdRequired
|
|
768
|
-
? { ok: true, reason: `threshold(${messageCount}/${threshold})+random(${probability})` }
|
|
769
|
-
: { ok: true, reason: `random(${probability})` };
|
|
770
|
-
}
|
|
771
|
-
return { ok: true, reason: `threshold(${messageCount}/${threshold})` };
|
|
772
|
-
}
|
|
773
|
-
parseInterestDecision(raw) {
|
|
774
|
-
const text = raw.trim();
|
|
775
|
-
if (!text)
|
|
776
|
-
return { reply: false, score: 0, reason: 'empty' };
|
|
777
|
-
const jsonMatch = text.match(/\{[\s\S]*\}/);
|
|
778
|
-
const candidate = jsonMatch ? jsonMatch[0] : text;
|
|
779
|
-
try {
|
|
780
|
-
const parsed = JSON.parse(candidate);
|
|
781
|
-
const reply = !!parsed.reply;
|
|
782
|
-
const score = Number.isFinite(parsed.score) ? Number(parsed.score) : 0;
|
|
783
|
-
return { reply, score: Math.max(0, Math.min(100, score)), reason: parsed.reason || '' };
|
|
784
|
-
}
|
|
785
|
-
catch {
|
|
786
|
-
const lowered = text.toLowerCase();
|
|
787
|
-
const reply = lowered.includes('true') || lowered.includes('yes');
|
|
788
|
-
const scoreMatch = lowered.match(/(\d{1,3})/);
|
|
789
|
-
const score = scoreMatch ? Math.max(0, Math.min(100, Number(scoreMatch[1]))) : 0;
|
|
790
|
-
return { reply, score, reason: 'parse-fallback' };
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
buildInterestContextPrompt(groupKey, currentText, window = 8, extras = {}) {
|
|
794
|
-
const size = Math.max(4, Math.min(16, window));
|
|
795
|
-
const records = (this.aiBuffers.get(groupKey) ?? []).slice(-size);
|
|
796
|
-
const lines = records.map((item, idx) => {
|
|
797
|
-
const imageHint = item.imageUrls?.length ? ` [图片:${item.imageUrls.length}张]` : '';
|
|
798
|
-
const content = item.text?.trim() || '[图片消息]';
|
|
799
|
-
return `${idx + 1}. ${item.name}(${item.userId}): ${content}${imageHint}`;
|
|
800
|
-
});
|
|
801
|
-
const topicHint = (this.aiTopicMemory.get(groupKey)?.text || '').replace(/\s+/g, ' ').trim().slice(0, 120);
|
|
802
|
-
const currentHint = extras.hasSticker
|
|
803
|
-
? '(当前消息是表情包/贴纸,没有文字。表情包是常见的互动方式,可以顺势接梗或回应其情绪,不要因为"没有文字"就直接判定为无价值。)'
|
|
804
|
-
: (extras.hasImage
|
|
805
|
-
? '(当前消息含图片,没有文字。图片内容是重要的可回应素材,可以描述或调侃画面内容。)'
|
|
806
|
-
: '');
|
|
807
|
-
const prompt = [
|
|
808
|
-
`当前消息:${currentText || '[空文本]'}`,
|
|
809
|
-
currentHint,
|
|
810
|
-
topicHint ? `当前群话题参考:${topicHint}` : '',
|
|
811
|
-
`最近上下文(最多${size}条):`,
|
|
812
|
-
...(lines.length ? lines : ['(无历史上下文)']),
|
|
813
|
-
'判定要点:表情包/图片本身就是群聊中正常的互动内容,尤其是当对方在回应你刚才的发言时,应当积极接话。',
|
|
814
|
-
'只有在明显与你无关、且属于无意义刷屏时才选择不回复。不要仅因为「没有文字」就压低评分。',
|
|
815
|
-
].filter(Boolean).join('\n');
|
|
816
|
-
return { prompt, ctxSize: lines.length, topicHint };
|
|
817
|
-
}
|
|
818
|
-
/**
|
|
819
|
-
* 兴趣判定专用模型:留空时沿用 aiModel。
|
|
820
|
-
* 兴趣判定只是二分类任务,指向非推理的轻量模型可显著降低耗时与成本。
|
|
821
|
-
*/
|
|
822
|
-
resolveInterestModel() {
|
|
823
|
-
return (this.config.aiInterestModel?.trim() || this.config.aiModel?.trim() || '');
|
|
824
|
-
}
|
|
825
|
-
/**
|
|
826
|
-
* 兴趣判定的最大输出 token。
|
|
827
|
-
* 带思考的推理模型会先消耗 reasoning token,额度太小会导致正文为空
|
|
828
|
-
* (finish_reason=length),判定静默失效——表现为「该回的也不回」。
|
|
829
|
-
*/
|
|
830
|
-
resolveInterestMaxTokens() {
|
|
831
|
-
const raw = Number(this.config.aiInterestMaxTokens ?? 2048);
|
|
832
|
-
if (!Number.isFinite(raw))
|
|
833
|
-
return 2048;
|
|
834
|
-
return Math.max(256, Math.min(16384, Math.floor(raw)));
|
|
835
|
-
}
|
|
836
|
-
async decideInterestByOpenAI(contextPrompt) {
|
|
837
|
-
const apiKey = this.config.aiApiKey?.trim();
|
|
838
|
-
if (!apiKey)
|
|
839
|
-
return { reply: false, score: 0, reason: 'no-api-key' };
|
|
840
|
-
const base = (this.config.aiBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
|
|
841
|
-
const model = this.resolveInterestModel();
|
|
842
|
-
if (!model)
|
|
843
|
-
return { reply: false, score: 0, reason: 'no-model' };
|
|
844
|
-
const controller = new AbortController();
|
|
845
|
-
const timeout = setTimeout(() => controller.abort(), 18_000);
|
|
846
|
-
try {
|
|
847
|
-
const response = await fetch(`${base}/chat/completions`, {
|
|
848
|
-
method: 'POST',
|
|
849
|
-
headers: {
|
|
850
|
-
Authorization: `Bearer ${apiKey}`,
|
|
851
|
-
'Content-Type': 'application/json',
|
|
852
|
-
},
|
|
853
|
-
body: JSON.stringify({
|
|
854
|
-
model,
|
|
855
|
-
temperature: 0.15,
|
|
856
|
-
// 带思考的模型会先消耗 reasoning tokens:额度太小会导致 content 为空
|
|
857
|
-
// (finish_reason=length),判定直接失效。默认 2048,可用 aiInterestMaxTokens 调整。
|
|
858
|
-
max_tokens: this.resolveInterestMaxTokens(),
|
|
859
|
-
messages: [
|
|
860
|
-
{
|
|
861
|
-
role: 'system',
|
|
862
|
-
content: '你是群聊回复开关决策器。只输出 JSON: {"reply":boolean,"score":0-100,"reason":"..."}。除 JSON 外不输出任何文字。',
|
|
863
|
-
},
|
|
864
|
-
{
|
|
865
|
-
role: 'user',
|
|
866
|
-
content: `请判断是否值得回复这条消息。表情包/图片是群聊中正常的互动内容,不要因为「没有文字」就判定为无价值;仅在与本群无关且明显无意义刷屏时才不回复。以下是消息与上下文:\n${contextPrompt}`,
|
|
867
|
-
},
|
|
868
|
-
],
|
|
869
|
-
}),
|
|
870
|
-
signal: controller.signal,
|
|
871
|
-
});
|
|
872
|
-
const payload = await response.json().catch(() => ({}));
|
|
873
|
-
const choice = payload?.choices?.[0];
|
|
874
|
-
const content = choice?.message?.content;
|
|
875
|
-
if (!response.ok)
|
|
876
|
-
return { reply: false, score: 0, reason: `http-${response.status}` };
|
|
877
|
-
let plain = typeof content === 'string'
|
|
878
|
-
? content
|
|
879
|
-
: Array.isArray(content)
|
|
880
|
-
? content.map((item) => item?.text || '').join('')
|
|
881
|
-
: '';
|
|
882
|
-
// 兜底:若仍为空(思考模型额度被截断),从 reasoning_content 里捞 JSON
|
|
883
|
-
if (!plain.trim()) {
|
|
884
|
-
const reasoning = String(choice?.message?.reasoning_content || '');
|
|
885
|
-
const jsonLike = reasoning.match(/\{[\s\S]*\}/);
|
|
886
|
-
if (jsonLike)
|
|
887
|
-
plain = jsonLike[0];
|
|
888
|
-
if (!plain.trim()) {
|
|
889
|
-
this._logger.warn(`[ai-interest] 判定返回空内容 finish=${choice?.finish_reason} reasoningTokens=${payload?.usage?.completion_tokens_details?.reasoning_tokens}/${this.resolveInterestMaxTokens()} model=${model} | ${this.sessionTag?.('') ?? ''}`);
|
|
890
|
-
return { reply: false, score: 0, reason: `empty(finish=${choice?.finish_reason || 'unknown'})` };
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
return this.parseInterestDecision(plain);
|
|
894
|
-
}
|
|
895
|
-
catch {
|
|
896
|
-
return { reply: false, score: 0, reason: 'request-failed' };
|
|
897
|
-
}
|
|
898
|
-
finally {
|
|
899
|
-
clearTimeout(timeout);
|
|
900
|
-
}
|
|
901
|
-
}
|
|
902
|
-
async decideInterestByGemini(contextPrompt) {
|
|
903
|
-
const apiKey = this.config.aiApiKey?.trim();
|
|
904
|
-
if (!apiKey)
|
|
905
|
-
return { reply: false, score: 0, reason: 'no-api-key' };
|
|
906
|
-
const model = this.resolveInterestModel();
|
|
907
|
-
if (!model)
|
|
908
|
-
return { reply: false, score: 0, reason: 'no-model' };
|
|
909
|
-
const rawBase = (this.config.aiBaseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/+$/, '');
|
|
910
|
-
const base = /\/v\d/i.test(rawBase) ? rawBase : `${rawBase}/v1beta`;
|
|
911
|
-
const endpoint = `${base}/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
|
|
912
|
-
const controller = new AbortController();
|
|
913
|
-
const timeout = setTimeout(() => controller.abort(), 18_000);
|
|
914
|
-
try {
|
|
915
|
-
const response = await fetch(endpoint, {
|
|
916
|
-
method: 'POST',
|
|
917
|
-
headers: { 'Content-Type': 'application/json' },
|
|
918
|
-
body: JSON.stringify({
|
|
919
|
-
systemInstruction: {
|
|
920
|
-
parts: [{ text: '你是群聊回复开关决策器。只输出 JSON: {"reply":boolean,"score":0-100,"reason":"..."}。除 JSON 外不输出任何文字。' }],
|
|
921
|
-
},
|
|
922
|
-
contents: [{ role: 'user', parts: [{ text: `请判断是否值得回复这条消息。表情包/图片是群聊中正常的互动内容,不要因为「没有文字」就判定为无价值;仅在与本群无关且明显无意义刷屏时才不回复。以下是消息与上下文:\n${contextPrompt}` }] }],
|
|
923
|
-
generationConfig: {
|
|
924
|
-
temperature: 0.15,
|
|
925
|
-
// 带思考的模型会先消耗思考 token,额度太小会导致正文为空
|
|
926
|
-
maxOutputTokens: this.resolveInterestMaxTokens(),
|
|
927
|
-
},
|
|
928
|
-
}),
|
|
929
|
-
signal: controller.signal,
|
|
930
|
-
});
|
|
931
|
-
const payload = await response.json().catch(() => ({}));
|
|
932
|
-
if (!response.ok)
|
|
933
|
-
return { reply: false, score: 0, reason: `http-${response.status}` };
|
|
934
|
-
const plain = (payload?.candidates?.[0]?.content?.parts ?? [])
|
|
935
|
-
.map((item) => item?.text || '')
|
|
936
|
-
.join('');
|
|
937
|
-
return this.parseInterestDecision(plain);
|
|
938
|
-
}
|
|
939
|
-
catch {
|
|
940
|
-
return { reply: false, score: 0, reason: 'request-failed' };
|
|
941
|
-
}
|
|
942
|
-
finally {
|
|
943
|
-
clearTimeout(timeout);
|
|
944
|
-
}
|
|
945
|
-
}
|
|
946
|
-
async shouldReplyByInterest(params) {
|
|
947
|
-
const context = this.buildInterestContextPrompt(params.groupKey, params.text, this.config.aiInterestContextWindow || 8, {
|
|
948
|
-
hasSticker: !!params.hasSticker,
|
|
949
|
-
hasImage: !!params.hasImage,
|
|
950
|
-
});
|
|
951
|
-
const decision = this.config.aiProvider === 'gemini'
|
|
952
|
-
? await this.decideInterestByGemini(context.prompt)
|
|
953
|
-
: await this.decideInterestByOpenAI(context.prompt);
|
|
954
|
-
const threshold = Math.max(0, Math.min(100, this.config.aiInterestMinScore ?? 82));
|
|
955
|
-
return {
|
|
956
|
-
ok: decision.reply && decision.score >= threshold,
|
|
957
|
-
score: decision.score,
|
|
958
|
-
reason: decision.reason,
|
|
959
|
-
threshold,
|
|
960
|
-
ctxSize: context.ctxSize,
|
|
961
|
-
topicHint: context.topicHint,
|
|
962
|
-
};
|
|
963
|
-
}
|
|
964
|
-
buildAiUserPrompt(records, options) {
|
|
965
|
-
const scored = records.map((item, index) => ({ item, index, score: this.scoreTopicRelevance(item.text, options?.topicTokens ?? []) }));
|
|
966
|
-
const renderLine = (item, idx, score) => {
|
|
967
|
-
const imageHint = item.imageUrls.length ? ` [图片:${item.imageUrls.length}张]` : '';
|
|
968
|
-
const relHint = typeof score === 'number' && options?.thresholdMode && (options?.topicTokens?.length ?? 0) > 0
|
|
969
|
-
? ` [相关度:${score.toFixed(2)}]`
|
|
970
|
-
: '';
|
|
971
|
-
return `${idx + 1}. ${item.name}(${item.userId}): ${item.text}${imageHint}${relHint}`;
|
|
972
|
-
};
|
|
973
|
-
const ordered = options?.thresholdMode && (options?.topicTokens?.length ?? 0) > 0
|
|
974
|
-
? [...scored].sort((a, b) => b.score - a.score || a.index - b.index)
|
|
975
|
-
: scored;
|
|
976
|
-
let lines = ordered.map((entry, idx) => renderLine(entry.item, idx, entry.score));
|
|
977
|
-
const selectedIndex = options?.selectedRecord
|
|
978
|
-
? records.findIndex((item) => item === options.selectedRecord)
|
|
979
|
-
: -1;
|
|
980
|
-
if (options?.thresholdMode && selectedIndex >= 0) {
|
|
981
|
-
const start = Math.max(0, selectedIndex - 2);
|
|
982
|
-
const end = Math.min(records.length, selectedIndex + 3);
|
|
983
|
-
const local = records.slice(start, end);
|
|
984
|
-
lines = local.map((item, idx) => renderLine(item, idx, this.scoreTopicRelevance(item.text, options?.topicTokens ?? [])));
|
|
985
|
-
}
|
|
986
|
-
const selfName = this.getActiveAgentName();
|
|
987
|
-
const thresholdFocus = options?.thresholdMode && options?.selectedRecord
|
|
988
|
-
? [
|
|
989
|
-
'SELECTED_TARGET_BEGIN',
|
|
990
|
-
`${options.selectedRecord.name}(${options.selectedRecord.userId}): ${options.selectedRecord.text}`,
|
|
991
|
-
'SELECTED_TARGET_END',
|
|
992
|
-
'FORBIDDEN: 不要优先回复最后一条,除非与选定目标是同一对象同一问题。',
|
|
993
|
-
].join('\n')
|
|
994
|
-
: '';
|
|
995
|
-
const focusLine = options?.focusText
|
|
996
|
-
? `当前点名消息来自 ${options.focusUserName || '某用户'}(${options.focusUserId || 'unknown'}):${options.focusText}`
|
|
997
|
-
: (thresholdFocus || '请从下面的聊天记录中选择一条你认为最值得回应的消息并回复。');
|
|
998
|
-
const formatHint = '只输出最终要发送到群里的回复正文,不要解释,不要输出编号,不要代码块。';
|
|
999
|
-
const imageHint = options?.focusImages?.length
|
|
1000
|
-
? `本条点名消息附带图片 ${options.focusImages.length} 张,请结合图片理解后作答。`
|
|
1001
|
-
: '';
|
|
1002
|
-
if (options?.directMention) {
|
|
1003
|
-
const ownerPlatform = this.config.aiOwnerPlatform?.trim() || this.config.aiHomePlatform?.trim();
|
|
1004
|
-
const ownerUserId = this.config.aiOwnerUserId?.trim() || this.config.aiHomeUserId?.trim();
|
|
1005
|
-
const homeHint = options.focusUserId && ownerUserId && options.focusUserId === ownerUserId
|
|
1006
|
-
&& (ownerPlatform ? `当前发言者命中主人身份(${ownerPlatform}:${ownerUserId})。` : '');
|
|
1007
|
-
return [
|
|
1008
|
-
'你现在在一个QQ群中。',
|
|
1009
|
-
`你的自称是「${selfName}」。当你描述自己时请使用这个自称,不要在每句话前机械加前缀。`,
|
|
1010
|
-
focusLine,
|
|
1011
|
-
homeHint || '',
|
|
1012
|
-
imageHint,
|
|
1013
|
-
'用户正在直接点名你,请优先围绕该点名问题回复;可结合其他人的反馈补充说明。',
|
|
1014
|
-
formatHint,
|
|
1015
|
-
'如果主人或其他用户在上下文里追问该问题,可向追问者解释,但不要偏离当前话题。',
|
|
1016
|
-
'',
|
|
1017
|
-
'最近上下文(仅参考):',
|
|
1018
|
-
...lines.slice(-8),
|
|
1019
|
-
].join('\n');
|
|
1020
|
-
}
|
|
1021
|
-
if (options?.followup) {
|
|
1022
|
-
return [
|
|
1023
|
-
'你现在在一个QQ群中。',
|
|
1024
|
-
`你的自称是「${selfName}」。当你描述自己时请使用这个自称,不要在每句话前机械加前缀。`,
|
|
1025
|
-
focusLine,
|
|
1026
|
-
'这是点名话题的后续追问,允许回应上下文中对该话题的相关追问(包括主人)。',
|
|
1027
|
-
formatHint,
|
|
1028
|
-
'',
|
|
1029
|
-
'最近上下文(仅参考):',
|
|
1030
|
-
...lines.slice(-8),
|
|
1031
|
-
].join('\n');
|
|
1032
|
-
}
|
|
1033
|
-
return [
|
|
1034
|
-
'你现在在一个QQ群中。',
|
|
1035
|
-
`你的自称是「${selfName}」。当你描述自己时请使用这个自称,不要在每句话前机械加前缀。`,
|
|
1036
|
-
focusLine,
|
|
1037
|
-
options?.thresholdMode && options?.topicSummary ? `当前群主话题摘要:${options.topicSummary}` : '',
|
|
1038
|
-
imageHint,
|
|
1039
|
-
formatHint,
|
|
1040
|
-
options?.thresholdMode
|
|
1041
|
-
? `当前为阈值触发:你必须优先回复“已选定优先回复消息”;不要回复最后一条,除非它就是该消息。既有主题关键词:${(options.topicTokens ?? []).join(', ') || '无'}`
|
|
1042
|
-
: '',
|
|
1043
|
-
'请自然、简洁,尽量控制在80字内。',
|
|
1044
|
-
'',
|
|
1045
|
-
'聊天记录:',
|
|
1046
|
-
...lines,
|
|
1047
|
-
].join('\n');
|
|
1048
|
-
}
|
|
1049
|
-
normalizeAiOutput(text, preserveLines = false) {
|
|
1050
|
-
const cleaned = text
|
|
1051
|
-
.replace(/^```[\s\S]*?\n/, '')
|
|
1052
|
-
.replace(/```$/g, '')
|
|
1053
|
-
.replace(/\r\n/g, '\n')
|
|
1054
|
-
.trim();
|
|
1055
|
-
if (!preserveLines) {
|
|
1056
|
-
return cleaned.replace(/\s+/g, ' ').trim();
|
|
1057
|
-
}
|
|
1058
|
-
return cleaned
|
|
1059
|
-
.split('\n')
|
|
1060
|
-
.map((line) => line.replace(/[ \t]+/g, ' ').trim())
|
|
1061
|
-
.filter(Boolean)
|
|
1062
|
-
.join('\n');
|
|
1063
|
-
}
|
|
1064
|
-
sanitizeAiOutputForSend(text) {
|
|
1065
|
-
// Prevent model output from being parsed into platform segments (CQ/image/html image/markdown image).
|
|
1066
|
-
return text
|
|
1067
|
-
.replace(/\[CQ:[^\]]+\]/gi, '')
|
|
1068
|
-
.replace(/<img\b[^>]*>/gi, '')
|
|
1069
|
-
.replace(/!\[[^\]]*]\((https?:\/\/[^)\s]+)\)/gi, '$1')
|
|
1070
|
-
.trim();
|
|
1071
|
-
}
|
|
1072
505
|
splitAiReplyParts(text) {
|
|
1073
506
|
const source = text.trim();
|
|
1074
507
|
if (!source)
|
|
@@ -1094,151 +527,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
1094
527
|
const delay = Math.floor(Math.random() * (upper - lower + 1)) + lower;
|
|
1095
528
|
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
1096
529
|
}
|
|
1097
|
-
isAddressingOtherThanBot(session) {
|
|
1098
|
-
const selfId = session.bot?.selfId;
|
|
1099
|
-
const content = session.content ?? '';
|
|
1100
|
-
const mentionMatches = content.match(/\[CQ:at,[^\]]*\]/gi) ?? [];
|
|
1101
|
-
const ids = mentionMatches
|
|
1102
|
-
.map((item) => item.match(/(?:qq|id)=(\d+)/i)?.[1] || '')
|
|
1103
|
-
.filter(Boolean);
|
|
1104
|
-
if (!ids.length)
|
|
1105
|
-
return false;
|
|
1106
|
-
return ids.some((id) => !selfId || id !== selfId);
|
|
1107
|
-
}
|
|
1108
|
-
extractAiImageUrls(text) {
|
|
1109
|
-
const urls = new Set();
|
|
1110
|
-
const maxCount = Math.max(0, this.config.aiImageMaxCount || 0) || 4;
|
|
1111
|
-
const source = text || '';
|
|
1112
|
-
const cqImagePattern = /\[CQ:image,[^\]]*\]/gi;
|
|
1113
|
-
for (const chunk of source.match(cqImagePattern) ?? []) {
|
|
1114
|
-
const match = chunk.match(/(?:url|file)=([^,\]]+)/i);
|
|
1115
|
-
if (!match)
|
|
1116
|
-
continue;
|
|
1117
|
-
const value = decodeURIComponent(match[1].trim());
|
|
1118
|
-
if (!/^https?:\/\//i.test(value))
|
|
1119
|
-
continue;
|
|
1120
|
-
urls.add(value);
|
|
1121
|
-
if (urls.size >= maxCount)
|
|
1122
|
-
return [...urls];
|
|
1123
|
-
}
|
|
1124
|
-
const htmlImgPattern = /<img\b[^>]*src=["']([^"']+)["'][^>]*>/gi;
|
|
1125
|
-
let htmlMatch;
|
|
1126
|
-
while ((htmlMatch = htmlImgPattern.exec(source))) {
|
|
1127
|
-
const value = htmlMatch[1]?.trim();
|
|
1128
|
-
if (!value || !/^https?:\/\//i.test(value))
|
|
1129
|
-
continue;
|
|
1130
|
-
urls.add(value);
|
|
1131
|
-
if (urls.size >= maxCount)
|
|
1132
|
-
return [...urls];
|
|
1133
|
-
}
|
|
1134
|
-
const markdownImgPattern = /!\[[^\]]*]\((https?:\/\/[^)\s]+)\)/gi;
|
|
1135
|
-
let mdMatch;
|
|
1136
|
-
while ((mdMatch = markdownImgPattern.exec(source))) {
|
|
1137
|
-
const value = mdMatch[1]?.trim();
|
|
1138
|
-
if (!value)
|
|
1139
|
-
continue;
|
|
1140
|
-
urls.add(value);
|
|
1141
|
-
if (urls.size >= maxCount)
|
|
1142
|
-
return [...urls];
|
|
1143
|
-
}
|
|
1144
|
-
return [...urls].slice(0, maxCount);
|
|
1145
|
-
}
|
|
1146
|
-
async callOpenAiCompatible(prompt) {
|
|
1147
|
-
const apiKey = this.config.aiApiKey?.trim();
|
|
1148
|
-
if (!apiKey)
|
|
1149
|
-
return { ok: false, message: 'AI 未配置 apiKey。' };
|
|
1150
|
-
const base = (this.config.aiBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
|
|
1151
|
-
const model = this.config.aiModel?.trim();
|
|
1152
|
-
if (!model)
|
|
1153
|
-
return { ok: false, message: 'AI 未配置 model。' };
|
|
1154
|
-
const controller = new AbortController();
|
|
1155
|
-
const timeout = setTimeout(() => controller.abort(), 25_000);
|
|
1156
|
-
try {
|
|
1157
|
-
const response = await fetch(`${base}/chat/completions`, {
|
|
1158
|
-
method: 'POST',
|
|
1159
|
-
headers: {
|
|
1160
|
-
Authorization: `Bearer ${apiKey}`,
|
|
1161
|
-
'Content-Type': 'application/json',
|
|
1162
|
-
},
|
|
1163
|
-
body: JSON.stringify({
|
|
1164
|
-
model,
|
|
1165
|
-
temperature: this.config.aiTemperature,
|
|
1166
|
-
max_tokens: this.config.aiMaxOutputTokens,
|
|
1167
|
-
messages: [
|
|
1168
|
-
{ role: 'system', content: this.getActiveSystemPrompt() },
|
|
1169
|
-
{ role: 'user', content: prompt },
|
|
1170
|
-
],
|
|
1171
|
-
}),
|
|
1172
|
-
signal: controller.signal,
|
|
1173
|
-
});
|
|
1174
|
-
const payload = await response.json().catch(() => ({}));
|
|
1175
|
-
if (!response.ok) {
|
|
1176
|
-
const errorMessage = payload?.error?.message;
|
|
1177
|
-
return { ok: false, message: `OpenAI兼容接口错误: ${errorMessage || response.statusText}` };
|
|
1178
|
-
}
|
|
1179
|
-
const content = payload?.choices?.[0]?.message?.content;
|
|
1180
|
-
if (typeof content === 'string')
|
|
1181
|
-
return { ok: true, message: content };
|
|
1182
|
-
if (Array.isArray(content)) {
|
|
1183
|
-
const text = content.map((item) => item?.text || '').join('').trim();
|
|
1184
|
-
if (text)
|
|
1185
|
-
return { ok: true, message: text };
|
|
1186
|
-
}
|
|
1187
|
-
return { ok: false, message: 'OpenAI兼容接口未返回可用文本。' };
|
|
1188
|
-
}
|
|
1189
|
-
catch (error) {
|
|
1190
|
-
return { ok: false, message: `OpenAI兼容请求失败: ${String(error)}` };
|
|
1191
|
-
}
|
|
1192
|
-
finally {
|
|
1193
|
-
clearTimeout(timeout);
|
|
1194
|
-
}
|
|
1195
|
-
}
|
|
1196
|
-
async callGemini(prompt) {
|
|
1197
|
-
const apiKey = this.config.aiApiKey?.trim();
|
|
1198
|
-
if (!apiKey)
|
|
1199
|
-
return { ok: false, message: 'Gemini 未配置 apiKey。' };
|
|
1200
|
-
const model = this.config.aiModel?.trim();
|
|
1201
|
-
if (!model)
|
|
1202
|
-
return { ok: false, message: 'Gemini 未配置 model。' };
|
|
1203
|
-
const rawBase = (this.config.aiBaseUrl || 'https://generativelanguage.googleapis.com/v1beta').replace(/\/+$/, '');
|
|
1204
|
-
const base = /\/v\d/i.test(rawBase) ? rawBase : `${rawBase}/v1beta`;
|
|
1205
|
-
const endpoint = `${base}/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
|
|
1206
|
-
const controller = new AbortController();
|
|
1207
|
-
const timeout = setTimeout(() => controller.abort(), 25_000);
|
|
1208
|
-
try {
|
|
1209
|
-
const response = await fetch(endpoint, {
|
|
1210
|
-
method: 'POST',
|
|
1211
|
-
headers: { 'Content-Type': 'application/json' },
|
|
1212
|
-
body: JSON.stringify({
|
|
1213
|
-
systemInstruction: { parts: [{ text: this.getActiveSystemPrompt() }] },
|
|
1214
|
-
contents: [{ role: 'user', parts: [{ text: prompt }] }],
|
|
1215
|
-
generationConfig: {
|
|
1216
|
-
temperature: this.config.aiTemperature,
|
|
1217
|
-
maxOutputTokens: this.config.aiMaxOutputTokens,
|
|
1218
|
-
},
|
|
1219
|
-
}),
|
|
1220
|
-
signal: controller.signal,
|
|
1221
|
-
});
|
|
1222
|
-
const payload = await response.json().catch(() => ({}));
|
|
1223
|
-
if (!response.ok) {
|
|
1224
|
-
const errorMessage = payload?.error?.message;
|
|
1225
|
-
return { ok: false, message: `Gemini接口错误: ${errorMessage || response.statusText}` };
|
|
1226
|
-
}
|
|
1227
|
-
const text = (payload?.candidates?.[0]?.content?.parts ?? [])
|
|
1228
|
-
.map((item) => item?.text || '')
|
|
1229
|
-
.join('')
|
|
1230
|
-
.trim();
|
|
1231
|
-
if (!text)
|
|
1232
|
-
return { ok: false, message: 'Gemini接口未返回可用文本。' };
|
|
1233
|
-
return { ok: true, message: text };
|
|
1234
|
-
}
|
|
1235
|
-
catch (error) {
|
|
1236
|
-
return { ok: false, message: `Gemini请求失败: ${String(error)}` };
|
|
1237
|
-
}
|
|
1238
|
-
finally {
|
|
1239
|
-
clearTimeout(timeout);
|
|
1240
|
-
}
|
|
1241
|
-
}
|
|
1242
530
|
extractImageUrls(session) {
|
|
1243
531
|
if (!this.config.aiEnableImageRecognition)
|
|
1244
532
|
return [];
|
|
@@ -1280,17 +568,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
1280
568
|
}
|
|
1281
569
|
return out.slice(0, Math.max(1, maxCount));
|
|
1282
570
|
}
|
|
1283
|
-
collectReplyAwareImageCandidates(session, maxCount = 2) {
|
|
1284
|
-
const own = this.extractImageCandidates(session, maxCount);
|
|
1285
|
-
const quotedSession = session?.quote;
|
|
1286
|
-
const quoted = quotedSession ? this.extractImageCandidates(quotedSession, maxCount) : [];
|
|
1287
|
-
const merged = [];
|
|
1288
|
-
for (const item of [...own, ...quoted]) {
|
|
1289
|
-
if (!merged.includes(item))
|
|
1290
|
-
merged.push(item);
|
|
1291
|
-
}
|
|
1292
|
-
return { own, quoted, merged: merged.slice(0, Math.max(1, maxCount)) };
|
|
1293
|
-
}
|
|
1294
571
|
detectImageMime(buffer, fallback = 'image/jpeg') {
|
|
1295
572
|
if (!buffer || buffer.length < 12)
|
|
1296
573
|
return fallback;
|
|
@@ -1549,7 +826,8 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
1549
826
|
const type = String(element?.type ?? '').toLowerCase();
|
|
1550
827
|
const attrs = element?.attrs ?? {};
|
|
1551
828
|
const rawAttrs = {};
|
|
1552
|
-
for (const k of Object.keys(attrs))
|
|
829
|
+
for (const k of Object.keys(attrs))
|
|
830
|
+
rawAttrs[String(k).toLowerCase().replace(/-/g, '')] = attrs[k];
|
|
1553
831
|
const isImgLike = type === 'img' || type === 'image';
|
|
1554
832
|
const isStickerLike = type === 'face' || type === 'sticker' || type === 'mface';
|
|
1555
833
|
if (!isImgLike && !isStickerLike)
|
|
@@ -1583,16 +861,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
1583
861
|
return t === 'img' || t === 'image' || t === 'face' || t === 'sticker' || t === 'mface';
|
|
1584
862
|
});
|
|
1585
863
|
}
|
|
1586
|
-
isStickerElement(element) {
|
|
1587
|
-
if (!element || typeof element !== 'object')
|
|
1588
|
-
return false;
|
|
1589
|
-
const type = String(element.type ?? '').toLowerCase();
|
|
1590
|
-
if (type === 'face' || type === 'sticker' || type === 'mface' || type === 'img' || type === 'image')
|
|
1591
|
-
return true;
|
|
1592
|
-
const attrs = element.attrs ?? {};
|
|
1593
|
-
const sub = String(attrs.subType ?? attrs.subtype ?? attrs['sub-type'] ?? '');
|
|
1594
|
-
return type === 'image' && sub === '1';
|
|
1595
|
-
}
|
|
1596
864
|
hasStickerContent(session) {
|
|
1597
865
|
if (!session)
|
|
1598
866
|
return false;
|
|
@@ -1603,41 +871,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
1603
871
|
extractMessageImageUrls(session, maxCount = 4) {
|
|
1604
872
|
return this.extractImageUrlsFromSession(session, maxCount);
|
|
1605
873
|
}
|
|
1606
|
-
describeImageMessage(session) {
|
|
1607
|
-
const content = session.content ?? '';
|
|
1608
|
-
const rawCq = (content.match(/\[CQ:image,[^\]]*\]/gi) ?? []);
|
|
1609
|
-
const rawHtml = (content.match(/<img\b[^>]*\/?>/gi) ?? []);
|
|
1610
|
-
const items = this.extractImageElements(session);
|
|
1611
|
-
const elems = [];
|
|
1612
|
-
for (const el of session.elements ?? []) {
|
|
1613
|
-
const t = String(el?.type ?? '').toLowerCase();
|
|
1614
|
-
if (t !== 'image' && t !== 'img' && t !== 'face' && t !== 'sticker' && t !== 'mface')
|
|
1615
|
-
continue;
|
|
1616
|
-
const attrs = el.attrs ?? {};
|
|
1617
|
-
elems.push({
|
|
1618
|
-
type: el.type,
|
|
1619
|
-
url: el.url || attrs.url || '',
|
|
1620
|
-
src: el.src || attrs.src || '',
|
|
1621
|
-
file: el.file || attrs.file || '',
|
|
1622
|
-
fileId: el.fileId || el.file_id || attrs.fileId || attrs.fileid || attrs.file_id || '',
|
|
1623
|
-
subType: attrs.subType ?? attrs.subtype ?? attrs['sub-type'] ?? '',
|
|
1624
|
-
summary: attrs.summary || '',
|
|
1625
|
-
});
|
|
1626
|
-
}
|
|
1627
|
-
return {
|
|
1628
|
-
hasCqImage: rawCq.length > 0,
|
|
1629
|
-
rawCq,
|
|
1630
|
-
rawHtml,
|
|
1631
|
-
items,
|
|
1632
|
-
elementImages: elems,
|
|
1633
|
-
extractableUrls: this.extractImageUrlsFromSession(session, 10),
|
|
1634
|
-
candidates: this.extractImageCandidates(session, 10),
|
|
1635
|
-
};
|
|
1636
|
-
}
|
|
1637
|
-
logImageDebug(session) {
|
|
1638
|
-
const info = this.describeImageMessage(session);
|
|
1639
|
-
this._logger.info(`[img-debug] cq=${info.rawCq.length} html=${info.rawHtml.length} elements=${info.elementImages.length} sendable=${JSON.stringify(info.extractableUrls)} candidates=${JSON.stringify(info.candidates)} items=${JSON.stringify(info.items).slice(0, 400)} | ${this.sessionTag(session)}`);
|
|
1640
|
-
}
|
|
1641
874
|
extractImageFingerprintKeys(session, maxCount = 6) {
|
|
1642
875
|
const keys = [];
|
|
1643
876
|
const content = session.content ?? '';
|
|
@@ -2093,7 +1326,9 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2093
1326
|
}
|
|
2094
1327
|
}
|
|
2095
1328
|
const noSendableReason = !imageSent && payload.imageKeys.length ? 'no-sendable-image-payload' : '';
|
|
2096
|
-
|
|
1329
|
+
const hadImages = payload.imageKeys.length > 0 || payload.sendRefs.length > 0;
|
|
1330
|
+
// 纯文字复读没有图片是正常的,不要误报"没有可发送的图片"
|
|
1331
|
+
if (!imageSent && (hadImages || !meaningfulText)) {
|
|
2097
1332
|
this._logger.warn(`[repeater] triggered but no sendable image payload | ${this.sessionTag(session)} keys=${JSON.stringify(payload.imageKeys)} refs=${JSON.stringify(payload.sendRefs)}`);
|
|
2098
1333
|
}
|
|
2099
1334
|
this.repeatStates.set(groupKey, {
|
|
@@ -2113,309 +1348,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2113
1348
|
sendSuccessCount,
|
|
2114
1349
|
reason: noSendableReason || undefined,
|
|
2115
1350
|
});
|
|
2116
|
-
this.
|
|
2117
|
-
}
|
|
2118
|
-
async callOpenAiCompatibleWithImages(prompt, imageUrls) {
|
|
2119
|
-
const apiKey = this.config.aiApiKey?.trim();
|
|
2120
|
-
if (!apiKey)
|
|
2121
|
-
return { ok: false, message: 'AI 未配置 apiKey。' };
|
|
2122
|
-
const base = (this.config.aiBaseUrl || 'https://api.openai.com/v1').replace(/\/+$/, '');
|
|
2123
|
-
const model = this.config.aiModel?.trim();
|
|
2124
|
-
if (!model)
|
|
2125
|
-
return { ok: false, message: 'AI 未配置 model。' };
|
|
2126
|
-
const userContent = [{ type: 'text', text: prompt }];
|
|
2127
|
-
for (const url of imageUrls) {
|
|
2128
|
-
userContent.push({ type: 'image_url', image_url: { url } });
|
|
2129
|
-
}
|
|
2130
|
-
const controller = new AbortController();
|
|
2131
|
-
const timeout = setTimeout(() => controller.abort(), 25_000);
|
|
2132
|
-
try {
|
|
2133
|
-
const response = await fetch(`${base}/chat/completions`, {
|
|
2134
|
-
method: 'POST',
|
|
2135
|
-
headers: {
|
|
2136
|
-
Authorization: `Bearer ${apiKey}`,
|
|
2137
|
-
'Content-Type': 'application/json',
|
|
2138
|
-
},
|
|
2139
|
-
body: JSON.stringify({
|
|
2140
|
-
model,
|
|
2141
|
-
temperature: this.config.aiTemperature,
|
|
2142
|
-
max_tokens: this.config.aiMaxOutputTokens,
|
|
2143
|
-
messages: [
|
|
2144
|
-
{ role: 'system', content: this.getActiveSystemPrompt() },
|
|
2145
|
-
{ role: 'user', content: userContent },
|
|
2146
|
-
],
|
|
2147
|
-
}),
|
|
2148
|
-
signal: controller.signal,
|
|
2149
|
-
});
|
|
2150
|
-
const payload = await response.json().catch(() => ({}));
|
|
2151
|
-
if (!response.ok) {
|
|
2152
|
-
const errorMessage = payload?.error?.message;
|
|
2153
|
-
return { ok: false, message: `OpenAI兼容接口错误: ${errorMessage || response.statusText}` };
|
|
2154
|
-
}
|
|
2155
|
-
const content = payload?.choices?.[0]?.message?.content;
|
|
2156
|
-
if (typeof content === 'string')
|
|
2157
|
-
return { ok: true, message: content };
|
|
2158
|
-
if (Array.isArray(content)) {
|
|
2159
|
-
const text = content.map((item) => item?.text || '').join('').trim();
|
|
2160
|
-
if (text)
|
|
2161
|
-
return { ok: true, message: text };
|
|
2162
|
-
}
|
|
2163
|
-
return { ok: false, message: 'OpenAI兼容接口未返回可用文本。' };
|
|
2164
|
-
}
|
|
2165
|
-
catch (error) {
|
|
2166
|
-
return { ok: false, message: `OpenAI兼容请求失败: ${String(error)}` };
|
|
2167
|
-
}
|
|
2168
|
-
finally {
|
|
2169
|
-
clearTimeout(timeout);
|
|
2170
|
-
}
|
|
2171
|
-
}
|
|
2172
|
-
async generateAiReply(session, options) {
|
|
2173
|
-
const key = this.aiGroupKey(session);
|
|
2174
|
-
if (!key)
|
|
2175
|
-
return { ok: false, message: '缺少群聊上下文。' };
|
|
2176
|
-
const records = this.aiBuffers.get(key) ?? [];
|
|
2177
|
-
if (!records.length)
|
|
2178
|
-
return { ok: false, message: '无可用聊天上下文。' };
|
|
2179
|
-
let prompt = this.buildAiUserPrompt(records, options);
|
|
2180
|
-
prompt = await this.decoratePromptWithMemory(prompt, options);
|
|
2181
|
-
const focusImages = (options?.focusImages ?? [])
|
|
2182
|
-
.filter((url) => typeof url === 'string' && (/^https?:\/\//i.test(url) || /^data:image\//i.test(url)))
|
|
2183
|
-
.slice(0, Math.max(1, this.config.aiImageMaxCount || 2));
|
|
2184
|
-
const result = this.config.aiProvider === 'gemini'
|
|
2185
|
-
? await this.callGemini(focusImages.length
|
|
2186
|
-
? `${prompt}\n\n点名消息图片链接(如可访问请一并识别):\n${focusImages.map((item, i) => `${i + 1}. ${item}`).join('\n')}`
|
|
2187
|
-
: prompt)
|
|
2188
|
-
: (focusImages.length
|
|
2189
|
-
? await this.callOpenAiCompatibleWithImages(prompt, focusImages)
|
|
2190
|
-
: await this.callOpenAiCompatible(prompt));
|
|
2191
|
-
if (!result.ok)
|
|
2192
|
-
return result;
|
|
2193
|
-
const text = this.normalizeAiOutput(result.message, false).trim();
|
|
2194
|
-
if (!text)
|
|
2195
|
-
return { ok: false, message: 'AI 返回空响应。' };
|
|
2196
|
-
const normalized = text.length > 600 ? `${text.slice(0, 600)}...` : text;
|
|
2197
|
-
return { ok: true, message: normalized };
|
|
2198
|
-
}
|
|
2199
|
-
async maybeReplyWithAi(session) {
|
|
2200
|
-
if (!this.resolveAiEnabled(session))
|
|
2201
|
-
return;
|
|
2202
|
-
if (!session.guildId || !session.userId)
|
|
2203
|
-
return;
|
|
2204
|
-
if (session.userId === session.bot?.selfId)
|
|
2205
|
-
return;
|
|
2206
|
-
if (this.isDuplicateAiEvent(session))
|
|
2207
|
-
return;
|
|
2208
|
-
this.rememberUser(session);
|
|
2209
|
-
const groupKey = this.aiGroupKey(session);
|
|
2210
|
-
if (!groupKey)
|
|
2211
|
-
return;
|
|
2212
|
-
const text = this.extractAiMessageText(session);
|
|
2213
|
-
const atBot = this.isMentionBot(session);
|
|
2214
|
-
const messageImages = this.extractImageUrls(session);
|
|
2215
|
-
// 识图:当前消息没有图时,回退到「被回复的那条消息」里的图(适配器已把原消息放在 session.quote)
|
|
2216
|
-
const ownItems = this.extractImageElements(session);
|
|
2217
|
-
const quoteItems = session.quote ? this.extractImageElements(session.quote) : [];
|
|
2218
|
-
const itemsForModel = ownItems.length ? ownItems : quoteItems;
|
|
2219
|
-
const imageCandidates = this.collectReplyAwareImageCandidates(session, Math.max(1, this.config.aiImageMaxCount || 2));
|
|
2220
|
-
const replyImageRefs = messageImages.length ? [] : imageCandidates.quoted;
|
|
2221
|
-
const rawImageRefs = messageImages.length ? [] : imageCandidates.merged;
|
|
2222
|
-
// 注意:图片下载(http -> data URL)延迟到"确认要回复"之后,避免每条含图消息都产生网络开销
|
|
2223
|
-
let focusImages = messageImages;
|
|
2224
|
-
const hasSticker = this.hasStickerContent(session)
|
|
2225
|
-
|| !!(session.quote && this.hasStickerContent(session.quote));
|
|
2226
|
-
// 识图调试:消息里带图/表情但提取不到可发送图片时,记录原始字段,便于排查
|
|
2227
|
-
if (this.config.aiEnableImageRecognition) {
|
|
2228
|
-
const quotedHasImage = this.hasAnyImageElement(session.quote);
|
|
2229
|
-
if ((this.hasAnyImageElement(session) || quotedHasImage) && !messageImages.length) {
|
|
2230
|
-
this.logImageDebug(session);
|
|
2231
|
-
this._logger.info(`[img-debug] reply-aware ownItems=${ownItems.length} quoteItems=${quoteItems.length} own=${JSON.stringify(imageCandidates.own)} quoted=${JSON.stringify(replyImageRefs)} hasQuote=${!!session.quote} | ${this.sessionTag(session)}`);
|
|
2232
|
-
}
|
|
2233
|
-
}
|
|
2234
|
-
// 纯图片/表情包消息也参与 AI 判定(此前会被下面的空文本早退直接丢弃)
|
|
2235
|
-
const hasVisualContent = hasSticker || !!rawImageRefs.length || focusImages.length > 0;
|
|
2236
|
-
const visualText = hasVisualContent ? '[图片/表情]' : '';
|
|
2237
|
-
const effectiveText = text || visualText;
|
|
2238
|
-
// 记录上下文(放在视觉变量计算之后,避免 const 暂时性死区)
|
|
2239
|
-
this.pushAiRecord(session, text || visualText || '@bot');
|
|
2240
|
-
if (hasVisualContent) {
|
|
2241
|
-
// 用视觉占位文本刷新上下文,避免 buffer 里该条为空文本
|
|
2242
|
-
const buffered = this.aiBuffers.get(groupKey) ?? [];
|
|
2243
|
-
const last = buffered[buffered.length - 1];
|
|
2244
|
-
if (last && !String(last.text ?? '').trim()) {
|
|
2245
|
-
last.text = visualText;
|
|
2246
|
-
last.imageUrls = last.imageUrls?.length ? last.imageUrls : (hasSticker ? ['sticker'] : ['image']);
|
|
2247
|
-
}
|
|
2248
|
-
}
|
|
2249
|
-
const directMention = this.config.aiEnableDirectMentionTrigger && (this.containsAgentName(text) || atBot);
|
|
2250
|
-
const followup = this.getFollowupSession(groupKey);
|
|
2251
|
-
const isFollowupUser = !!followup && followup.userId === session.userId;
|
|
2252
|
-
const talkingToOthers = isFollowupUser && this.isAddressingOtherThanBot(session);
|
|
2253
|
-
const isOwnerUser = this.isHomeUser(session);
|
|
2254
|
-
const followupForce = !!(this.config.aiEnableFollowupAfterMention
|
|
2255
|
-
&& isFollowupUser
|
|
2256
|
-
&& !directMention
|
|
2257
|
-
&& !talkingToOthers
|
|
2258
|
-
&& this.shouldContinueFollowup(text, followup));
|
|
2259
|
-
const relatedContextFollowup = !!(this.config.aiEnableFollowupAfterMention
|
|
2260
|
-
&& followup
|
|
2261
|
-
&& !isFollowupUser
|
|
2262
|
-
&& !directMention
|
|
2263
|
-
&& this.shouldContinueFollowup(text, followup)
|
|
2264
|
-
&& (isOwnerUser || /[??]|(何意|何意味|什么意思|啥意思|怎么回事|发生了什么)/.test(text)));
|
|
2265
|
-
if (talkingToOthers) {
|
|
2266
|
-
this.aiFollowups.delete(groupKey);
|
|
2267
|
-
}
|
|
2268
|
-
if (followup && !isFollowupUser && !directMention && !relatedContextFollowup)
|
|
2269
|
-
return;
|
|
2270
|
-
// 纯图片/表情消息也允许进入随机/阈值/兴趣判定(visualText 已给出占位文本)
|
|
2271
|
-
if (!effectiveText && !hasVisualContent && !directMention && !followupForce && !relatedContextFollowup)
|
|
2272
|
-
return;
|
|
2273
|
-
if (this.config.aiIgnoreCommandMessage && !directMention && !followupForce && !relatedContextFollowup && this.isCommandLikeMessage(text))
|
|
2274
|
-
return;
|
|
2275
|
-
const trigger = directMention
|
|
2276
|
-
? { ok: true, reason: 'direct-mention' }
|
|
2277
|
-
: (followupForce || relatedContextFollowup)
|
|
2278
|
-
? { ok: true, reason: 'followup' }
|
|
2279
|
-
: this.shouldTriggerAiReply(session, false);
|
|
2280
|
-
if (!trigger.ok)
|
|
2281
|
-
return;
|
|
2282
|
-
const topicHint = (this.aiTopicMemory.get(groupKey)?.text || '').replace(/\s+/g, ' ').trim().slice(0, 120);
|
|
2283
|
-
const thresholdMode = typeof trigger.reason === 'string' && trigger.reason.startsWith('threshold(');
|
|
2284
|
-
// 闸门三(兴趣评分):所有非点名触发的回复都先过兴趣判定,达标才继续生成。
|
|
2285
|
-
// 点名(direct-mention)与点名后跟随(followup)不受此限。
|
|
2286
|
-
if (!directMention && !followupForce && !relatedContextFollowup) {
|
|
2287
|
-
const interest = await this.shouldReplyByInterest({ groupKey, text: effectiveText, hasSticker, hasImage: focusImages.length > 0 });
|
|
2288
|
-
this.logCommandResult(thresholdMode ? 'ai-threshold-interest' : 'ai-interest', { ok: interest.ok, message: `score=${interest.score} threshold=${interest.threshold} reason=${interest.reason} trigger=${trigger.reason}` }, session, { ctxSize: interest.ctxSize, topicHint: interest.topicHint || topicHint || undefined });
|
|
2289
|
-
if (!interest.ok) {
|
|
2290
|
-
this.logCommandResult(thresholdMode ? 'ai-threshold-skip-by-interest' : 'ai-skip-by-interest', { ok: true, message: 'triggered but skipped by low interest' }, session, {
|
|
2291
|
-
score: interest.score,
|
|
2292
|
-
threshold: interest.threshold,
|
|
2293
|
-
reason: interest.reason,
|
|
2294
|
-
trigger: trigger.reason,
|
|
2295
|
-
});
|
|
2296
|
-
return;
|
|
2297
|
-
}
|
|
2298
|
-
}
|
|
2299
|
-
const topicMemory = this.aiTopicMemory.get(groupKey);
|
|
2300
|
-
const topicTokens = topicMemory?.tokens ?? [];
|
|
2301
|
-
let selectedRecord;
|
|
2302
|
-
if (thresholdMode && topicTokens.length) {
|
|
2303
|
-
const records = this.aiBuffers.get(groupKey) ?? [];
|
|
2304
|
-
let bestScore = -1;
|
|
2305
|
-
for (const record of records) {
|
|
2306
|
-
if (!record.text?.trim())
|
|
2307
|
-
continue;
|
|
2308
|
-
const score = this.scoreTopicRelevance(record.text, topicTokens);
|
|
2309
|
-
if (score > bestScore) {
|
|
2310
|
-
bestScore = score;
|
|
2311
|
-
selectedRecord = record;
|
|
2312
|
-
}
|
|
2313
|
-
}
|
|
2314
|
-
}
|
|
2315
|
-
this.aiInFlight.add(groupKey);
|
|
2316
|
-
const startedAt = Date.now();
|
|
2317
|
-
// 已确认要回复,此时才把图片下载/转换为 base64(模型需要可直接读取的图片数据)
|
|
2318
|
-
const maxImg = Math.max(1, this.config.aiImageMaxCount || 2);
|
|
2319
|
-
let modelImages = focusImages.filter((u) => /^data:image\//i.test(u)).slice(0, maxImg);
|
|
2320
|
-
if (this.config.aiEnableImageRecognition && modelImages.length < maxImg) {
|
|
2321
|
-
const pendingItems = itemsForModel.slice();
|
|
2322
|
-
if (pendingItems.length) {
|
|
2323
|
-
const resolved = await this.resolveVisualItemsForModel(pendingItems, session, maxImg - modelImages.length);
|
|
2324
|
-
modelImages = [...modelImages, ...resolved].slice(0, maxImg);
|
|
2325
|
-
}
|
|
2326
|
-
else if (rawImageRefs.length) {
|
|
2327
|
-
const resolved = await this.resolveImagesForModel(rawImageRefs, session, maxImg - modelImages.length);
|
|
2328
|
-
modelImages = [...modelImages, ...resolved].slice(0, maxImg);
|
|
2329
|
-
}
|
|
2330
|
-
}
|
|
2331
|
-
this._logger.info(`[img-probe] trigger=${trigger.reason} ownItems=${ownItems.length} quoteItems=${quoteItems.length} candidates=${rawImageRefs.length} modelImages=${modelImages.length} sticker=${hasSticker} | ${this.sessionTag(session)}`);
|
|
2332
|
-
try {
|
|
2333
|
-
const result = await this.generateAiReply(session, {
|
|
2334
|
-
directMention,
|
|
2335
|
-
followup: (followupForce || relatedContextFollowup),
|
|
2336
|
-
thresholdMode,
|
|
2337
|
-
focusText: (directMention || followupForce || relatedContextFollowup) ? (effectiveText || '@bot') : undefined,
|
|
2338
|
-
focusUserId: (directMention || followupForce || relatedContextFollowup) ? session.userId : undefined,
|
|
2339
|
-
focusImages: modelImages,
|
|
2340
|
-
focusUserName: (directMention || followupForce || relatedContextFollowup) ? this.getDisplayName(session) : undefined,
|
|
2341
|
-
topicTokens: thresholdMode ? topicTokens : undefined,
|
|
2342
|
-
selectedRecord,
|
|
2343
|
-
topicSummary: thresholdMode ? (topicHint || undefined) : undefined,
|
|
2344
|
-
});
|
|
2345
|
-
if (!result.ok) {
|
|
2346
|
-
this.logCommandResult('ai-reply', { ok: false, message: result.message }, session, { trigger: trigger.reason });
|
|
2347
|
-
return;
|
|
2348
|
-
}
|
|
2349
|
-
const imageUrls = this.extractAiImageUrls(result.message);
|
|
2350
|
-
const safeText = this.sanitizeAiOutputForSend(result.message);
|
|
2351
|
-
if (!safeText) {
|
|
2352
|
-
this.logCommandResult('ai-reply', { ok: false, message: 'ai reply empty after sanitize' }, session, { trigger: trigger.reason });
|
|
2353
|
-
return;
|
|
2354
|
-
}
|
|
2355
|
-
const parts = this.splitAiReplyParts(safeText);
|
|
2356
|
-
if (!parts.length)
|
|
2357
|
-
return;
|
|
2358
|
-
if (session.messageId) {
|
|
2359
|
-
try {
|
|
2360
|
-
await session.send([koishi_1.h.quote(session.messageId), koishi_1.h.text(parts[0])]);
|
|
2361
|
-
}
|
|
2362
|
-
catch (error) {
|
|
2363
|
-
// Some OneBot implementations reject reply ids in specific ranges; fallback to plain text.
|
|
2364
|
-
this._logger.warn(`[ai-reply] quote send failed, fallback to plain: ${String(error)} | ${this.sessionTag(session)}`);
|
|
2365
|
-
await session.send(koishi_1.h.text(parts[0]));
|
|
2366
|
-
}
|
|
2367
|
-
for (const part of parts.slice(1)) {
|
|
2368
|
-
await this.waitHumanLikeDelay();
|
|
2369
|
-
await session.send(koishi_1.h.text(part));
|
|
2370
|
-
}
|
|
2371
|
-
}
|
|
2372
|
-
else {
|
|
2373
|
-
let first = true;
|
|
2374
|
-
for (const part of parts) {
|
|
2375
|
-
if (!first)
|
|
2376
|
-
await this.waitHumanLikeDelay();
|
|
2377
|
-
await session.send(koishi_1.h.text(part));
|
|
2378
|
-
first = false;
|
|
2379
|
-
}
|
|
2380
|
-
}
|
|
2381
|
-
for (const url of imageUrls) {
|
|
2382
|
-
try {
|
|
2383
|
-
await this.waitHumanLikeDelay(500, 1200);
|
|
2384
|
-
await session.send(koishi_1.h.image(url));
|
|
2385
|
-
}
|
|
2386
|
-
catch (error) {
|
|
2387
|
-
this._logger.warn(`[ai-reply] image send failed: ${String(error)} url=${url} | ${this.sessionTag(session)}`);
|
|
2388
|
-
}
|
|
2389
|
-
}
|
|
2390
|
-
this.aiLastReplyAt.set(groupKey, Date.now());
|
|
2391
|
-
if (!directMention && !followupForce && !relatedContextFollowup)
|
|
2392
|
-
this.aiCounters.set(groupKey, 0);
|
|
2393
|
-
if (directMention)
|
|
2394
|
-
this.startFollowupSession(groupKey, session.userId, text || '@bot');
|
|
2395
|
-
if (followupForce || relatedContextFollowup) {
|
|
2396
|
-
this.bumpFollowupSession(groupKey);
|
|
2397
|
-
const latest = this.getFollowupSession(groupKey);
|
|
2398
|
-
if (latest) {
|
|
2399
|
-
latest.lastText = text;
|
|
2400
|
-
this.aiFollowups.set(groupKey, latest);
|
|
2401
|
-
}
|
|
2402
|
-
}
|
|
2403
|
-
const replyTokens = this.tokenizeTopic(safeText);
|
|
2404
|
-
if (replyTokens.length) {
|
|
2405
|
-
this.aiTopicMemory.set(groupKey, {
|
|
2406
|
-
tokens: replyTokens,
|
|
2407
|
-
text: safeText,
|
|
2408
|
-
updatedAt: Date.now(),
|
|
2409
|
-
});
|
|
2410
|
-
}
|
|
2411
|
-
this.logCommandResult('ai-reply', { ok: true, message: 'ai reply sent' }, session, { trigger: trigger.reason, latencyMs: Date.now() - startedAt });
|
|
2412
|
-
}
|
|
2413
|
-
catch (error) {
|
|
2414
|
-
this.logCommandResult('ai-reply', { ok: false, message: `ai reply failed: ${String(error)}` }, session, { trigger: trigger.reason });
|
|
2415
|
-
}
|
|
2416
|
-
finally {
|
|
2417
|
-
this.aiInFlight.delete(groupKey);
|
|
2418
|
-
}
|
|
1351
|
+
this.ai.note(`群内触发复读:${payload.text || '[图片消息]'} (${payload.images.length}张图)`, groupKey);
|
|
2419
1352
|
}
|
|
2420
1353
|
logAuth(stage, result, session) {
|
|
2421
1354
|
if (!this.config.logAuthCheck)
|
|
@@ -2578,32 +1511,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2578
1511
|
randomMinutes(min = 1, max = 60) {
|
|
2579
1512
|
return Math.floor(Math.random() * (max - min + 1)) + min;
|
|
2580
1513
|
}
|
|
2581
|
-
extractAtIds(session) {
|
|
2582
|
-
const ids = [];
|
|
2583
|
-
const seen = new Set();
|
|
2584
|
-
const selfId = session?.bot?.selfId != null ? String(session.bot.selfId) : '';
|
|
2585
|
-
const add = (id) => {
|
|
2586
|
-
if (id == null)
|
|
2587
|
-
return;
|
|
2588
|
-
const text = String(id).trim();
|
|
2589
|
-
if (!/^\d+$/.test(text) || seen.has(text) || (selfId && text === selfId))
|
|
2590
|
-
return;
|
|
2591
|
-
seen.add(text);
|
|
2592
|
-
ids.push(text);
|
|
2593
|
-
};
|
|
2594
|
-
for (const el of session?.elements ?? []) {
|
|
2595
|
-
if (el?.type === 'at' || el?.type === 'mention') {
|
|
2596
|
-
add(el.id ?? el.pid ?? el.qq);
|
|
2597
|
-
}
|
|
2598
|
-
}
|
|
2599
|
-
const content = session?.content ?? '';
|
|
2600
|
-
const cqRegex = /\[CQ:at,qq=(\d+)(?:,[^\]]*)?\]/gi;
|
|
2601
|
-
let match;
|
|
2602
|
-
while ((match = cqRegex.exec(content)) !== null) {
|
|
2603
|
-
add(match[1]);
|
|
2604
|
-
}
|
|
2605
|
-
return ids;
|
|
2606
|
-
}
|
|
2607
1514
|
parseDurationToken(token) {
|
|
2608
1515
|
if (typeof token !== 'string')
|
|
2609
1516
|
return null;
|
|
@@ -2627,18 +1534,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2627
1534
|
}
|
|
2628
1535
|
return { raw: String(token).trim(), value, hasUnit: !!unit, minutes: Math.ceil(value * factor) };
|
|
2629
1536
|
}
|
|
2630
|
-
extractMuteTokens(session) {
|
|
2631
|
-
const content = session?.content ?? '';
|
|
2632
|
-
const cleaned = content.replace(/\[CQ:[^\]]+\]/g, ' ');
|
|
2633
|
-
const rawTokens = cleaned.split(/\s+/).filter(Boolean);
|
|
2634
|
-
const tokens = [];
|
|
2635
|
-
for (const token of rawTokens) {
|
|
2636
|
-
const parsed = this.parseDurationToken(token);
|
|
2637
|
-
if (parsed)
|
|
2638
|
-
tokens.push(parsed);
|
|
2639
|
-
}
|
|
2640
|
-
return { atIds: this.extractAtIds(session), tokens };
|
|
2641
|
-
}
|
|
2642
1537
|
async looksLikeMemberInGroup(session, targetIdRaw) {
|
|
2643
1538
|
const onebot = this.getOneBotApi(session);
|
|
2644
1539
|
const groupId = this.toGroupId(session);
|
|
@@ -2653,81 +1548,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2653
1548
|
return false;
|
|
2654
1549
|
}
|
|
2655
1550
|
}
|
|
2656
|
-
async parseMuteArguments(session) {
|
|
2657
|
-
const usage = '禁言用法:群管 mute <@用户|QQ号> <时长>(时长示例:10、10分钟、1小时、1天)。';
|
|
2658
|
-
const { atIds, tokens } = this.extractMuteTokens(session);
|
|
2659
|
-
const withUnit = tokens.filter((t) => t.hasUnit);
|
|
2660
|
-
const bare = tokens.filter((t) => !t.hasUnit);
|
|
2661
|
-
let targetId = '';
|
|
2662
|
-
let duration = null;
|
|
2663
|
-
const fail = (message, id = '') => ({ ok: false, targetId: id, minutes: 0, message });
|
|
2664
|
-
if (atIds.length > 0) {
|
|
2665
|
-
targetId = atIds[0];
|
|
2666
|
-
if (withUnit.length === 1) {
|
|
2667
|
-
duration = withUnit[0];
|
|
2668
|
-
}
|
|
2669
|
-
else if (withUnit.length > 1) {
|
|
2670
|
-
return fail('检测到多个带单位的时长,无法确认要禁言多久。', targetId);
|
|
2671
|
-
}
|
|
2672
|
-
else if (bare.length === 0) {
|
|
2673
|
-
return fail(`已识别目标 ${targetId},但缺少禁言时长。${usage}`, targetId);
|
|
2674
|
-
}
|
|
2675
|
-
else {
|
|
2676
|
-
// 无单位数字:取最后一个看起来像时长的数字(≤30天分钟数),其余忽略
|
|
2677
|
-
const candidates = bare.filter((t) => t.minutes <= 43200);
|
|
2678
|
-
duration = candidates.length > 0 ? candidates[candidates.length - 1] : null;
|
|
2679
|
-
if (!duration)
|
|
2680
|
-
return fail('未识别到有效禁言时长(支持 1~43200 分钟)。', targetId);
|
|
2681
|
-
}
|
|
2682
|
-
}
|
|
2683
|
-
else if (tokens.length === 0) {
|
|
2684
|
-
return fail(usage);
|
|
2685
|
-
}
|
|
2686
|
-
else if (tokens.length === 1 && !tokens[0].hasUnit) {
|
|
2687
|
-
// 单个数字且无 @:默认是目标 QQ 号,需要补充时长(避免把时长当 QQ 用)
|
|
2688
|
-
return fail(`已识别目标 QQ ${tokens[0].raw},请补充禁言时长。${usage}`, tokens[0].raw);
|
|
2689
|
-
}
|
|
2690
|
-
else {
|
|
2691
|
-
// 无 @:目标与时长都要从数字里区分
|
|
2692
|
-
if (withUnit.length === 1) {
|
|
2693
|
-
duration = withUnit[0];
|
|
2694
|
-
}
|
|
2695
|
-
else if (withUnit.length > 1) {
|
|
2696
|
-
return fail('检测到多个带单位的时长,无法确认要禁言多久。');
|
|
2697
|
-
}
|
|
2698
|
-
else {
|
|
2699
|
-
const candidates = bare.filter((t) => t.minutes <= 43200);
|
|
2700
|
-
duration = candidates.length > 0 ? candidates[candidates.length - 1] : null;
|
|
2701
|
-
if (!duration)
|
|
2702
|
-
return fail('未识别到有效禁言时长(支持 1~43200 分钟)。');
|
|
2703
|
-
}
|
|
2704
|
-
const others = tokens.filter((t) => t !== duration);
|
|
2705
|
-
if (others.length === 0) {
|
|
2706
|
-
return fail(`已识别禁言时长 ${duration.raw} 分钟,但缺少目标 QQ 号。${usage}`);
|
|
2707
|
-
}
|
|
2708
|
-
targetId = others[0].raw;
|
|
2709
|
-
// 两个数字且“时长在后”时,若第一个不像群成员而第二个像,则说明用户把时长写在了前面,交换一次
|
|
2710
|
-
if (others.length === 1 && bare.length === 2 && duration.raw !== targetId) {
|
|
2711
|
-
const firstIsMember = await this.looksLikeMemberInGroup(session, targetId);
|
|
2712
|
-
const secondIsMember = await this.looksLikeMemberInGroup(session, duration.raw);
|
|
2713
|
-
if (!firstIsMember && secondIsMember) {
|
|
2714
|
-
targetId = duration.raw;
|
|
2715
|
-
duration = others[0];
|
|
2716
|
-
}
|
|
2717
|
-
}
|
|
2718
|
-
}
|
|
2719
|
-
if (!targetId) {
|
|
2720
|
-
return fail(usage);
|
|
2721
|
-
}
|
|
2722
|
-
if (!duration) {
|
|
2723
|
-
return fail(`已识别目标 ${targetId},请补充禁言时长。${usage}`, targetId);
|
|
2724
|
-
}
|
|
2725
|
-
const minutes = Math.max(1, Math.floor(duration.minutes));
|
|
2726
|
-
if (minutes > 43200) {
|
|
2727
|
-
return fail('禁言时长不能超过 30 天(43200 分钟)。', targetId);
|
|
2728
|
-
}
|
|
2729
|
-
return { ok: true, targetId, minutes, message: '' };
|
|
2730
|
-
}
|
|
2731
1551
|
isPrivilegedUser(session, role) {
|
|
2732
1552
|
if (!session?.userId)
|
|
2733
1553
|
return false;
|
|
@@ -2852,6 +1672,30 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
2852
1672
|
const onebot = session.onebot;
|
|
2853
1673
|
return onebot ?? null;
|
|
2854
1674
|
}
|
|
1675
|
+
// ============ AI 引擎所需的宿主能力 ============
|
|
1676
|
+
/** 供 AI 引擎抽取图片结构 */
|
|
1677
|
+
extractImages(session) {
|
|
1678
|
+
return this.extractImageElements(session);
|
|
1679
|
+
}
|
|
1680
|
+
/** 供 AI 引擎把图片引用转成 data URL */
|
|
1681
|
+
resolveImage(ref, session) {
|
|
1682
|
+
return this.resolveImageReferenceToDataUrl(ref, session);
|
|
1683
|
+
}
|
|
1684
|
+
/** AI 回复发送:优先引用触发消息,失败则退化为纯文本 */
|
|
1685
|
+
async sendReply(session, text) {
|
|
1686
|
+
if (!text)
|
|
1687
|
+
return;
|
|
1688
|
+
if (session.messageId) {
|
|
1689
|
+
try {
|
|
1690
|
+
await session.send([koishi_1.h.quote(session.messageId), koishi_1.h.text(text)]);
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
catch (error) {
|
|
1694
|
+
this._logger.warn(`[ai] quote send failed, fallback to plain: ${String(error)} | ${this.sessionTag(session)}`);
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
await session.send(koishi_1.h.text(text));
|
|
1698
|
+
}
|
|
2855
1699
|
extractTextForFilter(session) {
|
|
2856
1700
|
const raw = (session.content ?? '')
|
|
2857
1701
|
.replace(/<[^>]+>/g, ' ')
|
|
@@ -3268,7 +2112,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3268
2112
|
const text = this.getMessageText(session).trim();
|
|
3269
2113
|
if (!text)
|
|
3270
2114
|
return false;
|
|
3271
|
-
|
|
3272
2115
|
const guildId = this.normalizeGuildId(session.guildId);
|
|
3273
2116
|
const cmd = list.find((c) => {
|
|
3274
2117
|
if (!c || c.enabled === false)
|
|
@@ -3281,7 +2124,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3281
2124
|
});
|
|
3282
2125
|
if (!cmd)
|
|
3283
2126
|
return false;
|
|
3284
|
-
|
|
3285
2127
|
// 冷却
|
|
3286
2128
|
const cd = Number(cmd.cooldownSeconds || 0);
|
|
3287
2129
|
if (cd > 0) {
|
|
@@ -3293,17 +2135,15 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3293
2135
|
if (left > 0) {
|
|
3294
2136
|
if (cmd.logHit !== false)
|
|
3295
2137
|
this._logger.info(`[custom-cmd] 「${cmd.trigger}」冷却中(剩余 ${left}s) | ${this.sessionTag(session)}`);
|
|
3296
|
-
return true;
|
|
2138
|
+
return true; // 命中但冷却中,同样不交给 AI
|
|
3297
2139
|
}
|
|
3298
2140
|
this._customCmdAt.set(key, Date.now());
|
|
3299
2141
|
}
|
|
3300
|
-
|
|
3301
2142
|
const replies = (cmd.replies ?? []).map((r) => String(r ?? '')).filter(Boolean);
|
|
3302
2143
|
if (!replies.length) {
|
|
3303
2144
|
this._logger.warn(`[custom-cmd] 「${cmd.trigger}」未配置回复内容 | ${this.sessionTag(session)}`);
|
|
3304
2145
|
return true;
|
|
3305
2146
|
}
|
|
3306
|
-
|
|
3307
2147
|
// 多回复:随机 或 轮换
|
|
3308
2148
|
let raw;
|
|
3309
2149
|
if (replies.length === 1) {
|
|
@@ -3320,7 +2160,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3320
2160
|
this._customCmdIdx.set(key, i + 1);
|
|
3321
2161
|
raw = replies[i];
|
|
3322
2162
|
}
|
|
3323
|
-
|
|
3324
2163
|
try {
|
|
3325
2164
|
const parts = [];
|
|
3326
2165
|
if (cmd.quote && session.messageId)
|
|
@@ -3364,7 +2203,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3364
2203
|
parts.push(koishi_1.h.text(seg));
|
|
3365
2204
|
if (!parts.length)
|
|
3366
2205
|
parts.push(koishi_1.h.text(raw));
|
|
3367
|
-
|
|
3368
2206
|
await session.send(parts);
|
|
3369
2207
|
if (cmd.logHit !== false)
|
|
3370
2208
|
this._logger.info(`[custom-cmd] 命中「${cmd.trigger}」已回复 | ${this.sessionTag(session)}`);
|
|
@@ -3396,7 +2234,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3396
2234
|
const rest = (m[2] || '').trim();
|
|
3397
2235
|
// @ 到的目标(可代替 QQ 号)
|
|
3398
2236
|
const mentions = this.extractMentionedTargets(session);
|
|
3399
|
-
|
|
3400
2237
|
// 菜单:单独发送 [bot]
|
|
3401
2238
|
if (name === this.cmdPrefix('command', '[bot]')) {
|
|
3402
2239
|
if (!rest) {
|
|
@@ -3451,9 +2288,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3451
2288
|
'踢人 ' + P('cmdKick', '[kick]') + ' qq reason',
|
|
3452
2289
|
'插件信息 ' + P('cmdVersion', '[Version]'),
|
|
3453
2290
|
];
|
|
3454
|
-
await session.send(this.styleText(
|
|
3455
|
-
'可用指令:\n\n' + lines.join('\n')
|
|
3456
|
-
));
|
|
2291
|
+
await session.send(this.styleText('可用指令:\n\n' + lines.join('\n')));
|
|
3457
2292
|
}
|
|
3458
2293
|
/** 自定义指令集:列出当前生效的自定义命令;没有配置时明确提示暂无指令 */
|
|
3459
2294
|
async sendCustomCommandList(session) {
|
|
@@ -3537,7 +2372,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3537
2372
|
}
|
|
3538
2373
|
else if (mentions.length) {
|
|
3539
2374
|
target = mentions[0];
|
|
3540
|
-
consumed = 0;
|
|
2375
|
+
consumed = 0; // @ 不在 tokens 里(已从 content 剥离)
|
|
3541
2376
|
}
|
|
3542
2377
|
if (!target) {
|
|
3543
2378
|
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdMute', '[mute]')} qq|@user duration [reason](时长如 10 / 10m / 1h / 1d)`));
|
|
@@ -3700,7 +2535,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3700
2535
|
}
|
|
3701
2536
|
else if (mentions.length) {
|
|
3702
2537
|
qq = mentions[0];
|
|
3703
|
-
reason = tokens.join(' ');
|
|
2538
|
+
reason = tokens.join(' '); // @ 已从 content 剥离,剩余全是原因
|
|
3704
2539
|
}
|
|
3705
2540
|
if (!/^\d{5,12}$/.test(qq)) {
|
|
3706
2541
|
await session.send(this.styleText(`用法:${this.cmdPrefix('cmdBan', '[ban]')} qq号|@某人 原因(原因选填)`));
|
|
@@ -3776,20 +2611,16 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3776
2611
|
const raw = (session.content || '').replace(/<at\b[^>]*\/?>/gi, ' ').trim();
|
|
3777
2612
|
if (!raw.startsWith(prefix))
|
|
3778
2613
|
return false;
|
|
3779
|
-
|
|
3780
2614
|
const rest = raw.slice(prefix.length).trim();
|
|
3781
2615
|
const parts = rest.split(/\s+/).filter(Boolean);
|
|
3782
2616
|
const sub = (parts[0] || '').toLowerCase();
|
|
3783
2617
|
const arg = parts[1] || '';
|
|
3784
|
-
|
|
3785
2618
|
// 是否启用(单群设置优先,未设置跟随全局)
|
|
3786
2619
|
if (!this.resolveBlacklistEnabled(session)) {
|
|
3787
2620
|
await session.send(this.styleText('本群未启用黑名单系统。'));
|
|
3788
2621
|
return true;
|
|
3789
2622
|
}
|
|
3790
|
-
|
|
3791
2623
|
const isAdmin = await this.canUseAdminCommand(session).then((r) => r && r.ok).catch(() => false);
|
|
3792
|
-
|
|
3793
2624
|
if (sub === 'list') {
|
|
3794
2625
|
const list = await this.getBlacklist(session);
|
|
3795
2626
|
if (!list.length) {
|
|
@@ -3800,7 +2631,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3800
2631
|
await session.send(this.styleText(`本群黑名单共 ${list.length} 人:\n${lines.join('\n')}`));
|
|
3801
2632
|
return true;
|
|
3802
2633
|
}
|
|
3803
|
-
|
|
3804
2634
|
if (sub === 'add') {
|
|
3805
2635
|
if (!isAdmin) {
|
|
3806
2636
|
await session.send(this.styleText('你没有权限操作黑名单。'));
|
|
@@ -3821,7 +2651,6 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3821
2651
|
this._logger.info(`[ban] add qq=${member.qq} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
3822
2652
|
return true;
|
|
3823
2653
|
}
|
|
3824
|
-
|
|
3825
2654
|
if (sub === 'delete' || sub === 'del') {
|
|
3826
2655
|
if (!isAdmin) {
|
|
3827
2656
|
await session.send(this.styleText('你没有权限操作黑名单。'));
|
|
@@ -3836,13 +2665,19 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3836
2665
|
this._logger.info(`[ban] delete qq=${arg} ok=${r.ok} | ${this.sessionTag(session)}`);
|
|
3837
2666
|
return true;
|
|
3838
2667
|
}
|
|
3839
|
-
|
|
3840
2668
|
await session.send(this.styleText(`用法:${prefix} list | ${prefix} add QQ号 | ${prefix} delete QQ号`));
|
|
3841
2669
|
return true;
|
|
3842
2670
|
}
|
|
3843
2671
|
async handleGroupModeration(session) {
|
|
3844
2672
|
if (!this.isPlatformAllowed(session.platform))
|
|
3845
2673
|
return;
|
|
2674
|
+
// AI 上下文先记录:被管控/被指令拦截的消息也要进上下文(指令类由引擎自行忽略)
|
|
2675
|
+
try {
|
|
2676
|
+
await this.ai.record(session);
|
|
2677
|
+
}
|
|
2678
|
+
catch (error) {
|
|
2679
|
+
this._logger.warn(`[ai] record failed: ${String(error)}`);
|
|
2680
|
+
}
|
|
3846
2681
|
// 注:旧的 [记忆] 文本入口已停用,记忆功能统一由 routeBracketCommand 处理,只认 [memory]
|
|
3847
2682
|
// 统一方括号指令路由([mute]/[unmute]/[kick]/[memory]/[ban]/[unban]/[banlist]/[custom]/[bot])
|
|
3848
2683
|
if (await this.routeBracketCommand(session))
|
|
@@ -3918,7 +2753,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3918
2753
|
catch (error) {
|
|
3919
2754
|
this._logger.warn(`[repeater] failed: ${String(error)} | ${this.sessionTag(session)}`);
|
|
3920
2755
|
}
|
|
3921
|
-
await this.
|
|
2756
|
+
await this.ai.handle(session);
|
|
3922
2757
|
}
|
|
3923
2758
|
/**
|
|
3924
2759
|
* 待审入群申请的落盘文件路径。
|
|
@@ -3973,7 +2808,7 @@ class QQGroupManagerService extends koishi_1.Service {
|
|
|
3973
2808
|
clearTimeout(this._pendingJoinSaveTimer);
|
|
3974
2809
|
this._pendingJoinSaveTimer = setTimeout(() => {
|
|
3975
2810
|
this._pendingJoinSaveTimer = null;
|
|
3976
|
-
this.persistPendingJoinRequestsNow().catch(() => {
|
|
2811
|
+
this.persistPendingJoinRequestsNow().catch(() => { });
|
|
3977
2812
|
}, delayMs);
|
|
3978
2813
|
if (typeof this._pendingJoinSaveTimer.unref === 'function')
|
|
3979
2814
|
this._pendingJoinSaveTimer.unref();
|