@nestim/koishi-plugin-qq-group-manager 0.1.5 → 0.1.7

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/lib/service.js CHANGED
@@ -29,6 +29,7 @@ class QQGroupManagerService extends koishi_1.Service {
29
29
  pendingJoinRequests = new Map();
30
30
  pendingJoinRequestFlags = new Map();
31
31
  violationRecords = new Map();
32
+ _imageDataUrlCache = new Map();
32
33
  constructor(ctx, config) {
33
34
  super(ctx, 'nestimQqGroupManager', true);
34
35
  this.ctx = ctx;
@@ -181,7 +182,11 @@ class QQGroupManagerService extends koishi_1.Service {
181
182
  }
182
183
  getMessageText(session) {
183
184
  const raw = session?.content ?? '';
184
- return raw.replace(/\[CQ:[^\]]+\]/g, ' ').trim();
185
+ return raw
186
+ .replace(/\[CQ:[^\]]+\]/g, ' ')
187
+ .replace(/<[^>]+>/g, ' ')
188
+ .replace(/\s+/g, ' ')
189
+ .trim();
185
190
  }
186
191
  aiGroupKey(session) {
187
192
  if (!session?.guildId)
@@ -191,8 +196,13 @@ class QQGroupManagerService extends koishi_1.Service {
191
196
  resolveAiEnabled(session) {
192
197
  const guildId = this.normalizeGuildId(session.guildId);
193
198
  const rule = this.config.groupRules.find((item) => this.normalizeGuildId(item.guildId) === guildId);
199
+ // 该群有独立配置:以其 enableAiReply 为准
194
200
  if (typeof rule?.enableAiReply === 'boolean')
195
201
  return rule.enableAiReply;
202
+ // 未单独配置的群:默认不启用 AI 回复(避免全局开关扩散到所有群)
203
+ // 如需恢复旧的「回落到全局」行为,把 aiReplyRequireGroupRule 设为 false
204
+ if (this.config.aiReplyRequireGroupRule !== false)
205
+ return false;
196
206
  return this.config.enableAiReply;
197
207
  }
198
208
  extractAiMessageText(session) {
@@ -582,20 +592,28 @@ class QQGroupManagerService extends koishi_1.Service {
582
592
  return { reply, score, reason: 'parse-fallback' };
583
593
  }
584
594
  }
585
- buildInterestContextPrompt(groupKey, currentText, window = 8) {
595
+ buildInterestContextPrompt(groupKey, currentText, window = 8, extras = {}) {
586
596
  const size = Math.max(4, Math.min(16, window));
587
597
  const records = (this.aiBuffers.get(groupKey) ?? []).slice(-size);
588
598
  const lines = records.map((item, idx) => {
589
- const imageHint = item.imageUrls.length ? ` [图片:${item.imageUrls.length}张]` : '';
599
+ const imageHint = item.imageUrls?.length ? ` [图片:${item.imageUrls.length}张]` : '';
590
600
  const content = item.text?.trim() || '[图片消息]';
591
601
  return `${idx + 1}. ${item.name}(${item.userId}): ${content}${imageHint}`;
592
602
  });
593
603
  const topicHint = (this.aiTopicMemory.get(groupKey)?.text || '').replace(/\s+/g, ' ').trim().slice(0, 120);
604
+ const currentHint = extras.hasSticker
605
+ ? '(当前消息是表情包/贴纸,没有文字。表情包是常见的互动方式,可以顺势接梗或回应其情绪,不要因为"没有文字"就直接判定为无价值。)'
606
+ : (extras.hasImage
607
+ ? '(当前消息含图片,没有文字。图片内容是重要的可回应素材,可以描述或调侃画面内容。)'
608
+ : '');
594
609
  const prompt = [
595
610
  `当前消息:${currentText || '[空文本]'}`,
611
+ currentHint,
596
612
  topicHint ? `当前群话题参考:${topicHint}` : '',
597
613
  `最近上下文(最多${size}条):`,
598
614
  ...(lines.length ? lines : ['(无历史上下文)']),
615
+ '判定要点:表情包/图片本身就是群聊中正常的互动内容,尤其是当对方在回应你刚才的发言时,应当积极接话。',
616
+ '只有在明显与你无关、且属于无意义刷屏时才选择不回复。不要仅因为「没有文字」就压低评分。',
599
617
  ].filter(Boolean).join('\n');
600
618
  return { prompt, ctxSize: lines.length, topicHint };
601
619
  }
@@ -619,7 +637,9 @@ class QQGroupManagerService extends koishi_1.Service {
619
637
  body: JSON.stringify({
620
638
  model,
621
639
  temperature: 0.15,
622
- max_tokens: 48,
640
+ // deepseek-flash 等带思考的模型会先消耗 reasoning tokens,
641
+ // 额度太小会导致 content 为空(finish_reason=length),判定直接失效
642
+ max_tokens: 512,
623
643
  messages: [
624
644
  {
625
645
  role: 'system',
@@ -627,21 +647,33 @@ class QQGroupManagerService extends koishi_1.Service {
627
647
  },
628
648
  {
629
649
  role: 'user',
630
- content: `请判断是否值得回复这条消息(从严,降低热度)。以下是消息与上下文:\n${contextPrompt}`,
650
+ content: `请判断是否值得回复这条消息。表情包/图片是群聊中正常的互动内容,不要因为「没有文字」就判定为无价值;仅在与本群无关且明显无意义刷屏时才不回复。以下是消息与上下文:\n${contextPrompt}`,
631
651
  },
632
652
  ],
633
653
  }),
634
654
  signal: controller.signal,
635
655
  });
636
656
  const payload = await response.json().catch(() => ({}));
637
- const content = payload?.choices?.[0]?.message?.content;
657
+ const choice = payload?.choices?.[0];
658
+ const content = choice?.message?.content;
638
659
  if (!response.ok)
639
660
  return { reply: false, score: 0, reason: `http-${response.status}` };
640
- const plain = typeof content === 'string'
661
+ let plain = typeof content === 'string'
641
662
  ? content
642
663
  : Array.isArray(content)
643
664
  ? content.map((item) => item?.text || '').join('')
644
665
  : '';
666
+ // 兜底:若仍为空(思考模型额度被截断),从 reasoning_content 里捞 JSON
667
+ if (!plain.trim()) {
668
+ const reasoning = String(choice?.message?.reasoning_content || '');
669
+ const jsonLike = reasoning.match(/\{[\s\S]*\}/);
670
+ if (jsonLike)
671
+ plain = jsonLike[0];
672
+ if (!plain.trim()) {
673
+ this._logger.warn(`[ai-interest] 判定返回空内容 finish=${choice?.finish_reason} reasoningTokens=${payload?.usage?.completion_tokens_details?.reasoning_tokens} | ${this.sessionTag?.('') ?? ''}`);
674
+ return { reply: false, score: 0, reason: `empty(finish=${choice?.finish_reason || 'unknown'})` };
675
+ }
676
+ }
645
677
  return this.parseInterestDecision(plain);
646
678
  }
647
679
  catch {
@@ -671,10 +703,11 @@ class QQGroupManagerService extends koishi_1.Service {
671
703
  systemInstruction: {
672
704
  parts: [{ text: '你是群聊回复开关决策器。只输出 JSON: {"reply":boolean,"score":0-100,"reason":"..."}。除 JSON 外不输出任何文字。' }],
673
705
  },
674
- contents: [{ role: 'user', parts: [{ text: `请判断是否值得回复这条消息(从严,降低热度)。以下是消息与上下文:\n${contextPrompt}` }] }],
706
+ contents: [{ role: 'user', parts: [{ text: `请判断是否值得回复这条消息。表情包/图片是群聊中正常的互动内容,不要因为「没有文字」就判定为无价值;仅在与本群无关且明显无意义刷屏时才不回复。以下是消息与上下文:\n${contextPrompt}` }] }],
675
707
  generationConfig: {
676
708
  temperature: 0.15,
677
- maxOutputTokens: 64,
709
+ // 带思考的模型会先消耗思考 token,额度太小会导致正文为空
710
+ maxOutputTokens: 512,
678
711
  },
679
712
  }),
680
713
  signal: controller.signal,
@@ -695,7 +728,10 @@ class QQGroupManagerService extends koishi_1.Service {
695
728
  }
696
729
  }
697
730
  async shouldReplyByInterest(params) {
698
- const context = this.buildInterestContextPrompt(params.groupKey, params.text, this.config.aiInterestContextWindow || 8);
731
+ const context = this.buildInterestContextPrompt(params.groupKey, params.text, this.config.aiInterestContextWindow || 8, {
732
+ hasSticker: !!params.hasSticker,
733
+ hasImage: !!params.hasImage,
734
+ });
699
735
  const decision = this.config.aiProvider === 'gemini'
700
736
  ? await this.decideInterestByGemini(context.prompt)
701
737
  : await this.decideInterestByOpenAI(context.prompt);
@@ -995,82 +1031,396 @@ class QQGroupManagerService extends koishi_1.Service {
995
1031
  return [];
996
1032
  return this.extractMessageImageUrls(session, maxCount);
997
1033
  }
998
- isImageSendableUrl(value) {
1034
+ isImageReference(value) {
999
1035
  if (!value || typeof value !== 'string')
1000
1036
  return false;
1001
1037
  const v = value.trim();
1038
+ if (!v)
1039
+ return false;
1002
1040
  if (/^https?:\/\//i.test(v))
1003
1041
  return true;
1004
1042
  if (/^data:image\//i.test(v))
1005
1043
  return true;
1044
+ if (/^base64:\/\//i.test(v))
1045
+ return true;
1046
+ if (/^file:\/\//i.test(v))
1047
+ return true;
1048
+ if (/^[A-Za-z]:[\\/]/.test(v) || v.startsWith('/'))
1049
+ return true;
1050
+ // NapCat 常见:纯文件名 / hash.jpg
1051
+ if (/^[0-9A-Fa-f]{16,}\.[A-Za-z0-9]{2,5}$/.test(v))
1052
+ return true;
1006
1053
  return false;
1007
1054
  }
1008
- extractMessageImageUrls(session, maxCount = 4) {
1009
- const urls = [];
1010
- const content = session.content ?? '';
1011
- const cqPattern = /\[CQ:image,[^\]]*\]/gi;
1012
- const cqList = content.match(cqPattern) ?? [];
1013
- for (const chunk of cqList) {
1014
- const match = chunk.match(/(?:url|src)=([^,\]]+)/i);
1015
- let value = match ? decodeURIComponent(match[1].trim()) : '';
1016
- if (!this.isImageSendableUrl(value)) {
1017
- // 部分适配器把 url 放在 file 字段
1018
- const fm = chunk.match(/file=([^,\]]+)/i);
1019
- if (fm) {
1020
- const f = decodeURIComponent(fm[1].trim());
1021
- if (this.isImageSendableUrl(f))
1022
- value = f;
1055
+ extractImageCandidates(session, maxCount = 6) {
1056
+ const out = [];
1057
+ for (const item of this.extractImageElements(session)) {
1058
+ for (const candidate of [item.url, item.ref]) {
1059
+ if (!this.isImageReference(candidate))
1060
+ continue;
1061
+ if (!out.includes(candidate))
1062
+ out.push(candidate);
1063
+ }
1064
+ }
1065
+ return out.slice(0, Math.max(1, maxCount));
1066
+ }
1067
+ collectReplyAwareImageCandidates(session, maxCount = 2) {
1068
+ const own = this.extractImageCandidates(session, maxCount);
1069
+ const quotedSession = session?.quote;
1070
+ const quoted = quotedSession ? this.extractImageCandidates(quotedSession, maxCount) : [];
1071
+ const merged = [];
1072
+ for (const item of [...own, ...quoted]) {
1073
+ if (!merged.includes(item))
1074
+ merged.push(item);
1075
+ }
1076
+ return { own, quoted, merged: merged.slice(0, Math.max(1, maxCount)) };
1077
+ }
1078
+ detectImageMime(buffer, fallback = 'image/jpeg') {
1079
+ if (!buffer || buffer.length < 12)
1080
+ return fallback;
1081
+ const b = buffer;
1082
+ if (b[0] === 0xFF && b[1] === 0xD8 && b[2] === 0xFF)
1083
+ return 'image/jpeg';
1084
+ if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4E && b[3] === 0x47)
1085
+ return 'image/png';
1086
+ if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46)
1087
+ return 'image/gif';
1088
+ if (b[0] === 0x52 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x46
1089
+ && b[8] === 0x57 && b[9] === 0x45 && b[10] === 0x42 && b[11] === 0x50)
1090
+ return 'image/webp';
1091
+ if (b[0] === 0x42 && b[1] === 0x4D)
1092
+ return 'image/bmp';
1093
+ return fallback;
1094
+ }
1095
+ async resolveImageReferenceToDataUrl(ref, session) {
1096
+ const value = String(ref ?? '').trim();
1097
+ if (!value)
1098
+ return '';
1099
+ // 已经是 data URL,直接沿用
1100
+ if (/^data:image\//i.test(value)) {
1101
+ return value.length > 64 * 1024 * 1024 ? '' : value;
1102
+ }
1103
+ try {
1104
+ let finalUrl = value;
1105
+ let headers = {};
1106
+ if (/^base64:\/\//i.test(value)) {
1107
+ // Koishi/OneBot 常见形态:base64://<裸base64>
1108
+ const raw = value.replace(/^base64:\/\//i, '');
1109
+ const buffer = Buffer.from(raw, 'base64');
1110
+ if (!buffer.length)
1111
+ return '';
1112
+ return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
1113
+ }
1114
+ if (/^https?:\/\//i.test(value)) {
1115
+ // OneBot 的 get_image 能把 file_id 换成可访问链接
1116
+ const direct = await this.fetchImageAsDataUrl(value, headers);
1117
+ if (direct)
1118
+ return direct;
1119
+ return '';
1120
+ }
1121
+ // 其余形态(file_id / 文件名 / 本地路径)交给 get_image 解析
1122
+ const onebot = this.getOneBotApi(session);
1123
+ if (onebot?.getImage) {
1124
+ const resolved = await onebot.getImage(value).catch(() => null);
1125
+ const url = resolved?.url || resolved?.file || resolved?.filename || '';
1126
+ const isLocal = url && !/^https?:\/\//i.test(url) && !/^data:/i.test(url);
1127
+ if (isLocal) {
1128
+ try {
1129
+ finalUrl = String(url).replace(/^file:\/\//i, '');
1130
+ }
1131
+ catch {
1132
+ finalUrl = '';
1133
+ }
1134
+ }
1135
+ else if (url) {
1136
+ const dataUrl = await this.fetchImageAsDataUrl(url, headers);
1137
+ if (dataUrl)
1138
+ return dataUrl;
1139
+ }
1140
+ if (finalUrl && finalUrl !== value && !/^https?:\/\//i.test(finalUrl)) {
1141
+ try {
1142
+ const buffer = await node_fs_1.default.promises.readFile(finalUrl);
1143
+ if (buffer.length)
1144
+ return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
1145
+ }
1146
+ catch {
1147
+ return '';
1148
+ }
1023
1149
  }
1024
1150
  }
1025
- if (!this.isImageSendableUrl(value))
1026
- continue;
1027
- urls.push(value);
1028
- if (urls.length >= maxCount)
1029
- return urls;
1151
+ if (/^file:\/\//i.test(value) || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith('/')) {
1152
+ const localPath = value.replace(/^file:\/\//i, '');
1153
+ const buffer = await node_fs_1.default.promises.readFile(localPath).catch(() => null);
1154
+ if (buffer?.length)
1155
+ return `data:${this.detectImageMime(buffer)};base64,${buffer.toString('base64')}`;
1156
+ }
1157
+ return '';
1030
1158
  }
1031
- const elements = session.elements ?? [];
1032
- for (const element of elements) {
1033
- if (element.type !== 'image')
1034
- continue;
1035
- const maybeUrl = (typeof element.url === 'string' && element.url)
1036
- || (typeof element.src === 'string' && element.src)
1037
- || (typeof element.attrs?.url === 'string' && element.attrs.url)
1038
- || (typeof element.attrs?.src === 'string' && element.attrs.src);
1039
- if (!this.isImageSendableUrl(maybeUrl))
1040
- continue;
1041
- urls.push(maybeUrl);
1042
- if (urls.length >= maxCount)
1159
+ catch (error) {
1160
+ this._logger.warn(`[img-fetch] resolve failed: ${String(error)} ref=${value.slice(0, 120)} | ${this.sessionTag(session)}`);
1161
+ return '';
1162
+ }
1163
+ }
1164
+ async fetchImageAsDataUrl(url, extraHeaders = {}) {
1165
+ const MAX_BYTES = 8 * 1024 * 1024;
1166
+ const cached = this._imageDataUrlCache?.get(url);
1167
+ if (cached !== undefined)
1168
+ return cached;
1169
+ if (!this._imageDataUrlCache)
1170
+ this._imageDataUrlCache = new Map();
1171
+ const controller = new AbortController();
1172
+ const timeout = setTimeout(() => controller.abort(), 12_000);
1173
+ try {
1174
+ const response = await fetch(url, {
1175
+ headers: {
1176
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) NapCat/QQ',
1177
+ Accept: 'image/avif,image/webp,image/apng,image/*,*/*;q=0.8',
1178
+ ...extraHeaders,
1179
+ },
1180
+ redirect: 'follow',
1181
+ signal: controller.signal,
1182
+ });
1183
+ if (!response.ok) {
1184
+ this._logger.warn(`[img-fetch] http ${response.status} url=${url.slice(0, 140)}`);
1185
+ this.rememberImageDataUrl(url, '');
1186
+ return '';
1187
+ }
1188
+ const arrayBuffer = await response.arrayBuffer();
1189
+ const buffer = Buffer.from(arrayBuffer);
1190
+ if (!buffer.length) {
1191
+ this.rememberImageDataUrl(url, '');
1192
+ return '';
1193
+ }
1194
+ if (buffer.length > MAX_BYTES) {
1195
+ this._logger.warn(`[img-fetch] image too large (${buffer.length} bytes) url=${url.slice(0, 140)}`);
1196
+ this.rememberImageDataUrl(url, '');
1197
+ return '';
1198
+ }
1199
+ const mime = this.detectImageMime(buffer, response.headers.get('content-type')?.split(';')[0] || 'image/jpeg');
1200
+ const dataUrl = `data:${mime};base64,${buffer.toString('base64')}`;
1201
+ this.rememberImageDataUrl(url, dataUrl);
1202
+ return dataUrl;
1203
+ }
1204
+ catch (error) {
1205
+ this._logger.warn(`[img-fetch] download failed: ${String(error)} url=${url.slice(0, 140)}`);
1206
+ this.rememberImageDataUrl(url, '');
1207
+ return '';
1208
+ }
1209
+ finally {
1210
+ clearTimeout(timeout);
1211
+ }
1212
+ }
1213
+ rememberImageDataUrl(url, dataUrl) {
1214
+ if (!this._imageDataUrlCache)
1215
+ this._imageDataUrlCache = new Map();
1216
+ if (this._imageDataUrlCache.size > 64)
1217
+ this._imageDataUrlCache.clear();
1218
+ this._imageDataUrlCache.set(url, dataUrl);
1219
+ }
1220
+ async resolveImagesForModel(refs, session, maxCount) {
1221
+ const limit = Math.max(1, maxCount || 1);
1222
+ const out = [];
1223
+ for (const ref of refs) {
1224
+ if (out.length >= limit)
1225
+ break;
1226
+ const candidates = Array.isArray(ref) ? ref : [ref];
1227
+ for (const candidate of candidates) {
1228
+ const dataUrl = await this.resolveImageReferenceToDataUrl(candidate, session);
1229
+ if (dataUrl) {
1230
+ out.push(dataUrl);
1231
+ break;
1232
+ }
1233
+ }
1234
+ }
1235
+ return out;
1236
+ }
1237
+ /**
1238
+ * 把 extractImageElements 的结构化条目解析为可直接喂给模型的 data URL。
1239
+ * 每个条目会依次尝试:原始 URL -> 本地文件名(走 OneBot get_image)。
1240
+ */
1241
+ async resolveVisualItemsForModel(items, session, maxCount) {
1242
+ const limit = Math.max(1, maxCount || 1);
1243
+ const out = [];
1244
+ for (const item of items) {
1245
+ if (out.length >= limit)
1043
1246
  break;
1247
+ const attempts = [];
1248
+ if (item.url)
1249
+ attempts.push(item.url);
1250
+ if (item.ref && item.ref !== item.url)
1251
+ attempts.push(item.ref);
1252
+ for (const candidate of attempts) {
1253
+ const dataUrl = await this.resolveImageReferenceToDataUrl(candidate, session);
1254
+ if (dataUrl) {
1255
+ out.push(dataUrl);
1256
+ break;
1257
+ }
1258
+ }
1044
1259
  }
1045
- return [...new Set(urls)].slice(0, maxCount);
1260
+ return out;
1261
+ }
1262
+ isImageSendableUrl(value) {
1263
+ if (!value || typeof value !== 'string')
1264
+ return false;
1265
+ const v = value.trim();
1266
+ if (/^https?:\/\//i.test(v))
1267
+ return true;
1268
+ if (/^data:image\//i.test(v))
1269
+ return true;
1270
+ return false;
1271
+ }
1272
+ decodeHtmlEntities(value) {
1273
+ if (typeof value !== 'string' || !value)
1274
+ return '';
1275
+ return value
1276
+ .replace(/&amp;/gi, '&')
1277
+ .replace(/&lt;/gi, '<')
1278
+ .replace(/&gt;/gi, '>')
1279
+ .replace(/&quot;/gi, '"')
1280
+ .replace(/&#0?39;/g, "'")
1281
+ .replace(/&apos;/gi, "'")
1282
+ .replace(/&#x2f;/gi, '/')
1283
+ .replace(/&#0?38;/g, '&');
1284
+ }
1285
+ parseHtmlTagParams(tag) {
1286
+ const params = {};
1287
+ const re = /([a-zA-Z][\w-]*)\s*=\s*"([^"]*)"|([a-zA-Z][\w-]*)\s*=\s*'([^']*)'/g;
1288
+ let m;
1289
+ while ((m = re.exec(tag))) {
1290
+ const key = (m[1] || m[3] || '').toLowerCase();
1291
+ const raw = m[2] !== undefined ? m[2] : m[4];
1292
+ if (!key)
1293
+ continue;
1294
+ params[key.replace(/-/g, '')] = this.decodeHtmlEntities(raw);
1295
+ }
1296
+ return params;
1297
+ }
1298
+ extractImageElements(session) {
1299
+ const items = [];
1300
+ const seen = new Set();
1301
+ const push = (url, ref, sticker) => {
1302
+ const u = this.decodeHtmlEntities(url || '').trim();
1303
+ const r = (ref || '').trim();
1304
+ const key = u || r;
1305
+ if (!key || seen.has(key))
1306
+ return;
1307
+ seen.add(key);
1308
+ items.push({
1309
+ url: u,
1310
+ ref: r,
1311
+ sticker: !!sticker,
1312
+ sendable: this.isImageSendableUrl(u),
1313
+ });
1314
+ };
1315
+ const isStickerParams = (params) => {
1316
+ const sub = String(params.subtype ?? params.subType ?? params['sub-type'] ?? '');
1317
+ const summary = String(params.summary ?? '');
1318
+ return sub === '1' || /动画表情|表情|贴纸|sticker|mface/i.test(summary);
1319
+ };
1320
+ // 1) CQ 码形态
1321
+ const content = session?.content ?? '';
1322
+ for (const chunk of content.match(/\[CQ:image,[^\]]*\]/gi) ?? []) {
1323
+ const params = this.parseCqImageParams(chunk);
1324
+ push(params.url || params.src || params.file, params.file_id || params.file || params.id, isStickerParams(params));
1325
+ }
1326
+ // 2) koishi onebot 适配器的 HTML 形态:<img src="..." summary="[动画表情]" .../>
1327
+ for (const tag of content.match(/<img\b[^>]*\/?>/gi) ?? []) {
1328
+ const attrs = this.parseHtmlTagParams(tag);
1329
+ push(attrs.src || attrs.url || attrs.file, attrs.file || attrs.fileid, isStickerParams(attrs));
1330
+ }
1331
+ // 3) 元素形态:type 可能是 image / img / face / sticker / mface
1332
+ for (const element of session?.elements ?? []) {
1333
+ const type = String(element?.type ?? '').toLowerCase();
1334
+ const attrs = element?.attrs ?? {};
1335
+ const rawAttrs = {};
1336
+ for (const k of Object.keys(attrs)) rawAttrs[String(k).toLowerCase().replace(/-/g, '')] = attrs[k];
1337
+ const isImgLike = type === 'img' || type === 'image';
1338
+ const isStickerLike = type === 'face' || type === 'sticker' || type === 'mface';
1339
+ if (!isImgLike && !isStickerLike)
1340
+ continue;
1341
+ const url = element?.url || element?.src
1342
+ || attrs.url || attrs.src
1343
+ || attrs.image || attrs.href || '';
1344
+ const ref = element?.file || element?.fileId || element?.file_id || element?.id
1345
+ || attrs.file || attrs.fileid || attrs.file_id || attrs.id || '';
1346
+ const sticker = isStickerLike || isStickerParams(rawAttrs) || isStickerParams(attrs);
1347
+ push(url, ref, sticker);
1348
+ }
1349
+ return items;
1350
+ }
1351
+ extractImageUrlsFromSession(session, maxCount = 4) {
1352
+ return this.extractImageElements(session)
1353
+ .filter((item) => item.sendable)
1354
+ .map((item) => item.url)
1355
+ .slice(0, Math.max(1, maxCount));
1356
+ }
1357
+ hasAnyImageElement(session) {
1358
+ if (!session)
1359
+ return false;
1360
+ if (this.extractImageElements(session).length)
1361
+ return true;
1362
+ const content = session.content ?? '';
1363
+ return /\[CQ:image,/i.test(content)
1364
+ || /<img\b/i.test(content)
1365
+ || (session.elements ?? []).some((el) => {
1366
+ const t = String(el?.type ?? '').toLowerCase();
1367
+ return t === 'img' || t === 'image' || t === 'face' || t === 'sticker' || t === 'mface';
1368
+ });
1369
+ }
1370
+ isStickerElement(element) {
1371
+ if (!element || typeof element !== 'object')
1372
+ return false;
1373
+ const type = String(element.type ?? '').toLowerCase();
1374
+ if (type === 'face' || type === 'sticker' || type === 'mface' || type === 'img' || type === 'image')
1375
+ return true;
1376
+ const attrs = element.attrs ?? {};
1377
+ const sub = String(attrs.subType ?? attrs.subtype ?? attrs['sub-type'] ?? '');
1378
+ return type === 'image' && sub === '1';
1379
+ }
1380
+ hasStickerContent(session) {
1381
+ if (!session)
1382
+ return false;
1383
+ if (/\[CQ:(face|mface|sticker),/i.test(session.content ?? ''))
1384
+ return true;
1385
+ return this.extractImageElements(session).some((item) => item.sticker);
1386
+ }
1387
+ extractMessageImageUrls(session, maxCount = 4) {
1388
+ return this.extractImageUrlsFromSession(session, maxCount);
1046
1389
  }
1047
1390
  describeImageMessage(session) {
1048
1391
  const content = session.content ?? '';
1049
- const rawCq = (content.match(/\[CQ:image,[^\]]+\]/gi) ?? []);
1392
+ const rawCq = (content.match(/\[CQ:image,[^\]]*\]/gi) ?? []);
1393
+ const rawHtml = (content.match(/<img\b[^>]*\/?>/gi) ?? []);
1394
+ const items = this.extractImageElements(session);
1050
1395
  const elems = [];
1051
1396
  for (const el of session.elements ?? []) {
1052
- if (el?.type !== 'image')
1397
+ const t = String(el?.type ?? '').toLowerCase();
1398
+ if (t !== 'image' && t !== 'img' && t !== 'face' && t !== 'sticker' && t !== 'mface')
1053
1399
  continue;
1054
- const fields = {
1400
+ const attrs = el.attrs ?? {};
1401
+ elems.push({
1055
1402
  type: el.type,
1056
- url: el.url || el.attrs?.url || '',
1057
- src: el.src || el.attrs?.src || '',
1058
- file: el.file || el.attrs?.file || '',
1059
- fileId: el.fileId || el.file_id || el.attrs?.file_id || '',
1060
- data: el.data ? String(el.data).slice(0, 40) : (el.attrs?.data ? String(el.attrs.data).slice(0, 40) : ''),
1061
- };
1062
- elems.push(fields);
1403
+ url: el.url || attrs.url || '',
1404
+ src: el.src || attrs.src || '',
1405
+ file: el.file || attrs.file || '',
1406
+ fileId: el.fileId || el.file_id || attrs.fileId || attrs.fileid || attrs.file_id || '',
1407
+ subType: attrs.subType ?? attrs.subtype ?? attrs['sub-type'] ?? '',
1408
+ summary: attrs.summary || '',
1409
+ });
1063
1410
  }
1064
1411
  return {
1065
1412
  hasCqImage: rawCq.length > 0,
1066
1413
  rawCq,
1414
+ rawHtml,
1415
+ items,
1067
1416
  elementImages: elems,
1068
- extractableUrls: this.extractMessageImageUrls(session, 10),
1417
+ extractableUrls: this.extractImageUrlsFromSession(session, 10),
1418
+ candidates: this.extractImageCandidates(session, 10),
1069
1419
  };
1070
1420
  }
1071
1421
  logImageDebug(session) {
1072
1422
  const info = this.describeImageMessage(session);
1073
- this._logger.info(`[img-debug] cq=${info.rawCq.length} elements=${info.elementImages.length} urls=${JSON.stringify(info.extractableUrls)} cqRaw=${JSON.stringify(info.rawCq.slice(0, 2))} elems=${JSON.stringify(info.elementImages).slice(0, 300)} | ${this.sessionTag(session)}`);
1423
+ 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)}`);
1074
1424
  }
1075
1425
  extractImageFingerprintKeys(session, maxCount = 6) {
1076
1426
  const keys = [];
@@ -1362,11 +1712,18 @@ class QQGroupManagerService extends koishi_1.Service {
1362
1712
  extractImageSendRefs(session, maxCount = 6) {
1363
1713
  const refs = [];
1364
1714
  const pushRef = (value) => {
1365
- const v = value.trim();
1715
+ const v = String(value ?? '').trim();
1366
1716
  if (!v)
1367
1717
  return;
1368
1718
  refs.push(v);
1369
1719
  };
1720
+ // 统一走 extractImageElements:同时覆盖 CQ 与 koishi HTML(<img>) 两种形态
1721
+ for (const item of this.extractImageElements(session)) {
1722
+ pushRef(item.ref);
1723
+ pushRef(item.url);
1724
+ if (refs.length >= maxCount)
1725
+ return [...new Set(refs)].slice(0, maxCount);
1726
+ }
1370
1727
  const content = session.content ?? '';
1371
1728
  const cqPattern = /\[CQ:image,[^\]]*\]/gi;
1372
1729
  for (const chunk of content.match(cqPattern) ?? []) {
@@ -1384,27 +1741,6 @@ class QQGroupManagerService extends koishi_1.Service {
1384
1741
  if (refs.length >= maxCount)
1385
1742
  return [...new Set(refs)].slice(0, maxCount);
1386
1743
  }
1387
- const elements = session.elements ?? [];
1388
- for (const element of elements) {
1389
- if (element.type !== 'image')
1390
- continue;
1391
- const candidates = [
1392
- typeof element.id === 'string' ? element.id : '',
1393
- typeof element.file === 'string' ? element.file : '',
1394
- typeof element.url === 'string' ? element.url : '',
1395
- typeof element.src === 'string' ? element.src : '',
1396
- typeof element.attrs?.file_id === 'string' ? element.attrs.file_id : '',
1397
- typeof element.attrs?.id === 'string' ? element.attrs.id : '',
1398
- typeof element.attrs?.file === 'string' ? element.attrs.file : '',
1399
- typeof element.attrs?.url === 'string' ? element.attrs.url : '',
1400
- typeof element.attrs?.src === 'string' ? element.attrs.src : '',
1401
- ].filter(Boolean);
1402
- for (const item of candidates) {
1403
- pushRef(item);
1404
- if (refs.length >= maxCount)
1405
- return [...new Set(refs)].slice(0, maxCount);
1406
- }
1407
- }
1408
1744
  return [...new Set(refs)].slice(0, maxCount);
1409
1745
  }
1410
1746
  async fetchMessageImagePayload(session, maxCount = 6) {
@@ -1626,7 +1962,9 @@ class QQGroupManagerService extends koishi_1.Service {
1626
1962
  return { ok: false, message: '无可用聊天上下文。' };
1627
1963
  let prompt = this.buildAiUserPrompt(records, options);
1628
1964
  prompt = await this.decoratePromptWithMemory(prompt, options);
1629
- const focusImages = (options?.focusImages ?? []).filter((url) => /^https?:\/\//i.test(url));
1965
+ const focusImages = (options?.focusImages ?? [])
1966
+ .filter((url) => typeof url === 'string' && (/^https?:\/\//i.test(url) || /^data:image\//i.test(url)))
1967
+ .slice(0, Math.max(1, this.config.aiImageMaxCount || 2));
1630
1968
  const result = this.config.aiProvider === 'gemini'
1631
1969
  ? await this.callGemini(focusImages.length
1632
1970
  ? `${prompt}\n\n点名消息图片链接(如可访问请一并识别):\n${focusImages.map((item, i) => `${i + 1}. ${item}`).join('\n')}`
@@ -1656,16 +1994,40 @@ class QQGroupManagerService extends koishi_1.Service {
1656
1994
  if (!groupKey)
1657
1995
  return;
1658
1996
  const text = this.extractAiMessageText(session);
1659
- // Always record context first, including other users during follow-up windows.
1660
- this.pushAiRecord(session, text || '@bot');
1661
1997
  const atBot = this.isMentionBot(session);
1662
1998
  const messageImages = this.extractImageUrls(session);
1663
- // 识图调试:消息里带图但提取不到可发送链接时,记录原始图片字段,便于排查
1999
+ // 识图:当前消息没有图时,回退到「被回复的那条消息」里的图(适配器已把原消息放在 session.quote)
2000
+ const ownItems = this.extractImageElements(session);
2001
+ const quoteItems = session.quote ? this.extractImageElements(session.quote) : [];
2002
+ const itemsForModel = ownItems.length ? ownItems : quoteItems;
2003
+ const imageCandidates = this.collectReplyAwareImageCandidates(session, Math.max(1, this.config.aiImageMaxCount || 2));
2004
+ const replyImageRefs = messageImages.length ? [] : imageCandidates.quoted;
2005
+ const rawImageRefs = messageImages.length ? [] : imageCandidates.merged;
2006
+ // 注意:图片下载(http -> data URL)延迟到"确认要回复"之后,避免每条含图消息都产生网络开销
2007
+ let focusImages = messageImages;
2008
+ const hasSticker = this.hasStickerContent(session)
2009
+ || !!(session.quote && this.hasStickerContent(session.quote));
2010
+ // 识图调试:消息里带图/表情但提取不到可发送图片时,记录原始字段,便于排查
1664
2011
  if (this.config.aiEnableImageRecognition) {
1665
- const hasImage = /\[CQ:image,/i.test(session.content ?? '')
1666
- || (session.elements ?? []).some((el) => el?.type === 'image');
1667
- if (hasImage && !messageImages.length) {
2012
+ const quotedHasImage = this.hasAnyImageElement(session.quote);
2013
+ if ((this.hasAnyImageElement(session) || quotedHasImage) && !messageImages.length) {
1668
2014
  this.logImageDebug(session);
2015
+ 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)}`);
2016
+ }
2017
+ }
2018
+ // 纯图片/表情包消息也参与 AI 判定(此前会被下面的空文本早退直接丢弃)
2019
+ const hasVisualContent = hasSticker || !!rawImageRefs.length || focusImages.length > 0;
2020
+ const visualText = hasVisualContent ? '[图片/表情]' : '';
2021
+ const effectiveText = text || visualText;
2022
+ // 记录上下文(放在视觉变量计算之后,避免 const 暂时性死区)
2023
+ this.pushAiRecord(session, text || visualText || '@bot');
2024
+ if (hasVisualContent) {
2025
+ // 用视觉占位文本刷新上下文,避免 buffer 里该条为空文本
2026
+ const buffered = this.aiBuffers.get(groupKey) ?? [];
2027
+ const last = buffered[buffered.length - 1];
2028
+ if (last && !String(last.text ?? '').trim()) {
2029
+ last.text = visualText;
2030
+ last.imageUrls = last.imageUrls?.length ? last.imageUrls : (hasSticker ? ['sticker'] : ['image']);
1669
2031
  }
1670
2032
  }
1671
2033
  const directMention = this.config.aiEnableDirectMentionTrigger && (this.containsAgentName(text) || atBot);
@@ -1689,7 +2051,8 @@ class QQGroupManagerService extends koishi_1.Service {
1689
2051
  }
1690
2052
  if (followup && !isFollowupUser && !directMention && !relatedContextFollowup)
1691
2053
  return;
1692
- if (!text && !directMention && !followupForce && !relatedContextFollowup)
2054
+ // 纯图片/表情消息也允许进入随机/阈值/兴趣判定(visualText 已给出占位文本)
2055
+ if (!effectiveText && !hasVisualContent && !directMention && !followupForce && !relatedContextFollowup)
1693
2056
  return;
1694
2057
  if (this.config.aiIgnoreCommandMessage && !directMention && !followupForce && !relatedContextFollowup && this.isCommandLikeMessage(text))
1695
2058
  return;
@@ -1702,7 +2065,7 @@ class QQGroupManagerService extends koishi_1.Service {
1702
2065
  return;
1703
2066
  const topicHint = (this.aiTopicMemory.get(groupKey)?.text || '').replace(/\s+/g, ' ').trim().slice(0, 120);
1704
2067
  if (trigger.reason === 'interest-check') {
1705
- const interest = await this.shouldReplyByInterest({ groupKey, text });
2068
+ const interest = await this.shouldReplyByInterest({ groupKey, text: effectiveText, hasSticker, hasImage: focusImages.length > 0 });
1706
2069
  this.logCommandResult('ai-interest', { ok: interest.ok, message: `score=${interest.score} threshold=${interest.threshold} reason=${interest.reason}` }, session, { ctxSize: interest.ctxSize, topicHint: interest.topicHint || topicHint || undefined });
1707
2070
  if (!interest.ok)
1708
2071
  return;
@@ -1725,7 +2088,7 @@ class QQGroupManagerService extends koishi_1.Service {
1725
2088
  }
1726
2089
  }
1727
2090
  if (thresholdMode) {
1728
- const interest = await this.shouldReplyByInterest({ groupKey, text });
2091
+ const interest = await this.shouldReplyByInterest({ groupKey, text: effectiveText, hasSticker, hasImage: focusImages.length > 0 });
1729
2092
  this.logCommandResult('ai-threshold-interest', { ok: interest.ok, message: `score=${interest.score} threshold=${interest.threshold} reason=${interest.reason}` }, session, { ctxSize: interest.ctxSize, topicHint: interest.topicHint || topicHint || undefined });
1730
2093
  if (!interest.ok) {
1731
2094
  this.logCommandResult('ai-threshold-skip-by-interest', { ok: true, message: 'threshold hit but skipped by low interest' }, session, {
@@ -1738,14 +2101,29 @@ class QQGroupManagerService extends koishi_1.Service {
1738
2101
  }
1739
2102
  this.aiInFlight.add(groupKey);
1740
2103
  const startedAt = Date.now();
2104
+ // 已确认要回复,此时才把图片下载/转换为 base64(模型需要可直接读取的图片数据)
2105
+ const maxImg = Math.max(1, this.config.aiImageMaxCount || 2);
2106
+ let modelImages = focusImages.filter((u) => /^data:image\//i.test(u)).slice(0, maxImg);
2107
+ if (this.config.aiEnableImageRecognition && modelImages.length < maxImg) {
2108
+ const pendingItems = itemsForModel.slice();
2109
+ if (pendingItems.length) {
2110
+ const resolved = await this.resolveVisualItemsForModel(pendingItems, session, maxImg - modelImages.length);
2111
+ modelImages = [...modelImages, ...resolved].slice(0, maxImg);
2112
+ }
2113
+ else if (rawImageRefs.length) {
2114
+ const resolved = await this.resolveImagesForModel(rawImageRefs, session, maxImg - modelImages.length);
2115
+ modelImages = [...modelImages, ...resolved].slice(0, maxImg);
2116
+ }
2117
+ }
2118
+ 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)}`);
1741
2119
  try {
1742
2120
  const result = await this.generateAiReply(session, {
1743
2121
  directMention,
1744
2122
  followup: (followupForce || relatedContextFollowup),
1745
2123
  thresholdMode,
1746
- focusText: (directMention || followupForce || relatedContextFollowup) ? (text || '@bot') : undefined,
2124
+ focusText: (directMention || followupForce || relatedContextFollowup) ? (effectiveText || '@bot') : undefined,
1747
2125
  focusUserId: (directMention || followupForce || relatedContextFollowup) ? session.userId : undefined,
1748
- focusImages: messageImages,
2126
+ focusImages: modelImages,
1749
2127
  focusUserName: (directMention || followupForce || relatedContextFollowup) ? this.getDisplayName(session) : undefined,
1750
2128
  topicTokens: thresholdMode ? topicTokens : undefined,
1751
2129
  selectedRecord,
@@ -2602,7 +2980,9 @@ class QQGroupManagerService extends koishi_1.Service {
2602
2980
  return onebot ?? null;
2603
2981
  }
2604
2982
  extractTextForFilter(session) {
2605
- const raw = (session.content ?? '').replace(/\[CQ:[^\]]+\]/g, ' ');
2983
+ const raw = (session.content ?? '')
2984
+ .replace(/<[^>]+>/g, ' ')
2985
+ .replace(/\[CQ:[^\]]+\]/g, ' ');
2606
2986
  return raw.trim();
2607
2987
  }
2608
2988
  hasTextContent(session) {
@@ -2620,7 +3000,12 @@ class QQGroupManagerService extends koishi_1.Service {
2620
3000
  const content = session.content ?? '';
2621
3001
  if (/\[CQ:(image|face|record|video|flash),/i.test(content))
2622
3002
  return true;
2623
- return (session.elements ?? []).some((el) => el.type === 'image' || el.type === 'face' || el.type === 'record' || el.type === 'video' || el.type === 'flash');
3003
+ if (/<img\b/i.test(content))
3004
+ return true;
3005
+ return (session.elements ?? []).some((el) => {
3006
+ const t = String(el?.type ?? '').toLowerCase();
3007
+ return t === 'img' || t === 'image' || t === 'face' || t === 'record' || t === 'video' || t === 'flash';
3008
+ });
2624
3009
  }
2625
3010
  hasCardMessage(session) {
2626
3011
  const content = session.content ?? '';
@@ -2648,6 +3033,8 @@ class QQGroupManagerService extends koishi_1.Service {
2648
3033
  if (!rule) {
2649
3034
  return {
2650
3035
  bannedWords: this.config.bannedWords,
3036
+ whitelistKeywords: [],
3037
+ whitelistOnlyOwners: false,
2651
3038
  blockCardMessage: this.config.blockCardMessage,
2652
3039
  blockForwardMessage: this.config.blockForwardMessage,
2653
3040
  autoDeleteViolation: this.config.autoDeleteViolation,
@@ -2662,6 +3049,8 @@ class QQGroupManagerService extends koishi_1.Service {
2662
3049
  }
2663
3050
  return {
2664
3051
  bannedWords: rule.bannedWords,
3052
+ whitelistKeywords: rule.whitelistKeywords || [],
3053
+ whitelistOnlyOwners: rule.whitelistOnlyOwners === true,
2665
3054
  blockCardMessage: rule.blockCardMessage,
2666
3055
  blockForwardMessage: rule.blockForwardMessage,
2667
3056
  autoDeleteViolation: rule.autoDeleteViolation,
@@ -2674,9 +3063,195 @@ class QQGroupManagerService extends koishi_1.Service {
2674
3063
  violationWindowMinutes: rule.autoViolationWindowMinutes ?? this.config.autoViolationWindowMinutes,
2675
3064
  };
2676
3065
  }
2677
- detectViolation(session, policy) {
2678
- // 防误判:纯图片/表情/贴纸(无实际文字内容)的消息不作为违规处理,避免表情包被当成违禁词
2679
- if (this.hasImageOrFace(session) && !this.hasTextContent(session)) {
3066
+ /**
3067
+ * 违禁词分档默认分值(可通过配置用 "关键词|分值" 或 {keyword,score} 覆盖)
3068
+ * 设计原则:单独出现时属于强广告特征的词给高分(可独立触发),
3069
+ * 需要组合才能确认的弱特征词给低分(需多条累计)。
3070
+ */
3071
+ static DEFAULT_BANNED_WORD_SCORES = {
3072
+ // 显式广告行为(单条精确命中即可接近/达到阈值)
3073
+ '加群': 50, '拉人': 50, '拉群': 50, '互推': 50, '引流': 55,
3074
+ '加微信': 55, '加v': 50, '加V': 50, '加qq': 50, '加QQ': 50,
3075
+ '扫码进群': 80, '进群领': 60, '加我好友': 50, '私信我': 50,
3076
+ '点击链接': 50, '刷单': 60, '躺赚': 60, '日结': 50,
3077
+ // 需要组合确认的运营/营销词
3078
+ '邀请你': 35, '问卷': 30, '兼职': 40, '赚钱': 35, '赚米': 35,
3079
+ '返利': 45, '代理': 30, '招人': 35, '零成本': 40, '速来': 30,
3080
+ '福利群': 45, '红包群': 45, '活动群': 40, '转发群': 40,
3081
+ '免费领': 50, '免费送': 45, '领红包': 40, '抢红包': 35, '领福利': 40,
3082
+ '点击查看': 35, '名额有限': 35,
3083
+ };
3084
+ static DEFAULT_BANNED_WORD_SCORE = 40;
3085
+ normalizeBannedWordEntry(entry) {
3086
+ const raw = String(entry ?? '').trim();
3087
+ if (!raw)
3088
+ return null;
3089
+ let keyword = raw;
3090
+ let score = null;
3091
+ // 支持 "关键词|分值"、全角竖线、逗号分隔
3092
+ const m = raw.match(/^(.+?)\s*[||,,::]\s*(\d{1,3})$/);
3093
+ if (m) {
3094
+ keyword = m[1].trim();
3095
+ const parsed = parseInt(m[2], 10);
3096
+ if (Number.isFinite(parsed))
3097
+ score = Math.max(0, Math.min(100, parsed));
3098
+ }
3099
+ if (!keyword)
3100
+ return null;
3101
+ if (score === null) {
3102
+ const table = this.constructor.DEFAULT_BANNED_WORD_SCORES || {};
3103
+ const hit = Object.keys(table).find((k) => k.toLowerCase() === keyword.toLowerCase());
3104
+ score = hit ? table[hit] : this.constructor.DEFAULT_BANNED_WORD_SCORE;
3105
+ }
3106
+ return { keyword, score };
3107
+ }
3108
+ normalizeBannedWordList(list) {
3109
+ const out = [];
3110
+ const seen = new Set();
3111
+ for (const entry of list ?? []) {
3112
+ let keyword;
3113
+ let score;
3114
+ if (entry && typeof entry === 'object') {
3115
+ keyword = String(entry.keyword ?? entry.word ?? entry.text ?? '').trim();
3116
+ const parsed = Number(entry.score ?? entry.weight ?? NaN);
3117
+ score = Number.isFinite(parsed) ? Math.max(0, Math.min(100, parsed)) : null;
3118
+ if (keyword && score === null) {
3119
+ const table = this.constructor.DEFAULT_BANNED_WORD_SCORES || {};
3120
+ const hit = Object.keys(table).find((k) => k.toLowerCase() === keyword.toLowerCase());
3121
+ score = hit ? table[hit] : this.constructor.DEFAULT_BANNED_WORD_SCORE;
3122
+ }
3123
+ }
3124
+ else {
3125
+ const norm = this.normalizeBannedWordEntry(entry);
3126
+ if (!norm)
3127
+ continue;
3128
+ keyword = norm.keyword;
3129
+ score = norm.score;
3130
+ }
3131
+ if (!keyword)
3132
+ continue;
3133
+ const key = keyword.toLowerCase();
3134
+ if (seen.has(key))
3135
+ continue;
3136
+ seen.add(key);
3137
+ out.push({ keyword, score });
3138
+ }
3139
+ return out;
3140
+ }
3141
+ /**
3142
+ * 顺序子序列匹配:关键词的字符按顺序出现在文本中即命中,允许中间隔词。
3143
+ * 返回匹配跨度与紧凑度(跨度越接近词长,置信度越高)。
3144
+ */
3145
+ /**
3146
+ * 模糊命中的最低置信度门槛。
3147
+ * 短关键词(2~4 字)极易被无关文本凑齐(如「领导说…红色包装袋」凑出「领红包」),
3148
+ * 因此对短词要求更高的置信度;长词本身信息量足,门槛可放宽。
3149
+ */
3150
+ minBannedWordConfidence(keywordLength) {
3151
+ if (keywordLength <= 1)
3152
+ return 1;
3153
+ if (keywordLength <= 2)
3154
+ return 0.6;
3155
+ if (keywordLength <= 4)
3156
+ return 0.65;
3157
+ if (keywordLength <= 6)
3158
+ return 0.55;
3159
+ return 0.45;
3160
+ }
3161
+ subsequenceMatch(text, keyword) {
3162
+ if (!text || !keyword)
3163
+ return null;
3164
+ const first = text.indexOf(keyword);
3165
+ if (first >= 0) {
3166
+ return { start: first, end: first + keyword.length, span: keyword.length, ratio: 1, exact: true };
3167
+ }
3168
+ const chars = Array.from(keyword);
3169
+ let pos = 0;
3170
+ let start = -1;
3171
+ let end = -1;
3172
+ for (let i = 0; i < chars.length; i++) {
3173
+ const idx = text.indexOf(chars[i], pos);
3174
+ if (idx < 0) {
3175
+ // 单个字符找不到即判定不命中
3176
+ return null;
3177
+ }
3178
+ if (i === 0)
3179
+ start = idx;
3180
+ end = idx;
3181
+ pos = idx + 1;
3182
+ }
3183
+ const span = end - start + 1;
3184
+ const overflow = span - chars.length;
3185
+ // 分散过滤:隔得太开(跨度超过词长 + 8 或 3 倍词长)视为偶然凑齐
3186
+ if (span > chars.length * 3 || overflow > 8) {
3187
+ return null;
3188
+ }
3189
+ // 置信度按「词长归一化的溢出」衰减:短词对间隔更敏感
3190
+ // 例:领红包(len3) 在「领xxx元红包」(span6,overflow3) → 1-0.25*1 = 0.75
3191
+ const confidence = Math.max(0.25, 1 - 0.25 * (overflow / chars.length));
3192
+ // 短词需要更高置信度才算命中,避免无关文本偶然凑齐字符
3193
+ if (confidence < this.minBannedWordConfidence(chars.length)) {
3194
+ return null;
3195
+ }
3196
+ return { start, end: end + 1, span, overflow, ratio: chars.length / span, confidence, exact: false };
3197
+ }
3198
+ evaluateBannedWords(text, policy) {
3199
+ const words = this.normalizeBannedWordList(policy?.bannedWords ?? []);
3200
+ const evaluations = [];
3201
+ let total = 0;
3202
+ for (const { keyword, score } of words) {
3203
+ if (!keyword || keyword.length < 1)
3204
+ continue;
3205
+ const match = this.subsequenceMatch(text, keyword);
3206
+ if (!match)
3207
+ continue;
3208
+ const confidence = match.exact ? 1 : (match.confidence ?? 0.3);
3209
+ const gained = Math.round(score * Math.min(1, confidence) * 100) / 100;
3210
+ if (gained <= 0)
3211
+ continue;
3212
+ total += gained;
3213
+ evaluations.push({
3214
+ keyword,
3215
+ score,
3216
+ confidence: Math.round(Math.min(1, confidence) * 100) / 100,
3217
+ gained,
3218
+ span: match.span,
3219
+ exact: !!match.exact,
3220
+ });
3221
+ }
3222
+ evaluations.sort((a, b) => b.gained - a.gained);
3223
+ return { total: Math.round(total * 100) / 100, evaluations };
3224
+ }
3225
+ /**
3226
+ * 违禁词白名单豁免检查。
3227
+ *
3228
+ * 用于「校学生会招新」这类特殊场景:招新文案本身会包含“加群”“群号”等
3229
+ * 违禁词,但只要命中白名单关键词(如“宣传部”“纪检部”),就整条跳过违禁词评分。
3230
+ *
3231
+ * 返回 { keyword, reason } 表示命中并豁免;返回 null 表示未命中。
3232
+ */
3233
+ async checkWhitelistBypass(session, policy, text) {
3234
+ const keywords = (policy?.whitelistKeywords ?? [])
3235
+ .map((w) => String(w ?? '').trim())
3236
+ .filter(Boolean);
3237
+ if (!keywords.length || !text)
3238
+ return null;
3239
+ const hit = keywords.find((kw) => text.includes(kw));
3240
+ if (!hit)
3241
+ return null;
3242
+ // 可选的权限收紧:仅群主/管理员可用白名单
3243
+ if (policy.whitelistOnlyOwners) {
3244
+ const role = await this.resolveMemberRole(session);
3245
+ if (role !== 'owner' && role !== 'admin') {
3246
+ this._logger.info(`[whitelist] 命中「${hit}」但发送者非群主/管理员(role=${role}),不豁免 | ${this.sessionTag(session)}`);
3247
+ return null;
3248
+ }
3249
+ }
3250
+ return { keyword: hit, reason: 'whitelist' };
3251
+ }
3252
+ async detectViolation(session, policy, type = 'message') {
3253
+ // 纯图片/表情/贴纸(无实际文字内容)的消息不作为违规处理,避免表情包被当成违禁词
3254
+ if (type === 'message' && this.hasImageOrFace(session) && !this.hasTextContent(session)) {
2680
3255
  return null;
2681
3256
  }
2682
3257
  if (policy.blockCardMessage && this.hasCardMessage(session)) {
@@ -2688,13 +3263,24 @@ class QQGroupManagerService extends koishi_1.Service {
2688
3263
  const text = this.extractTextForFilter(session);
2689
3264
  if (!text)
2690
3265
  return null;
2691
- for (const word of policy.bannedWords) {
2692
- const keyword = word?.trim();
2693
- if (!keyword)
2694
- continue;
2695
- if (text.includes(keyword)) {
2696
- return { type: 'banned-word', detail: `命中违禁词: ${keyword}` };
2697
- }
3266
+ // 白名单豁免:命中白名单关键词则跳过违禁词评分(招新等允许的宣传场景)。
3267
+ // 注意:卡片/合并转发的拦截在上面已判定,白名单只豁免「违禁词」,不放过卡片类消息。
3268
+ const bypass = await this.checkWhitelistBypass(session, policy, text);
3269
+ if (bypass) {
3270
+ this._logger.info(`[whitelist] 命中「${bypass.keyword}」,跳过违禁词管控 | ${this.sessionTag(session)}`);
3271
+ return null;
3272
+ }
3273
+ const assessment = this.evaluateBannedWords(text, policy);
3274
+ const threshold = Math.max(1, Math.min(100, Number(this.config.bannedWordScoreThreshold ?? 70)));
3275
+ if (assessment.total >= threshold) {
3276
+ const top = assessment.evaluations.slice(0, 4)
3277
+ .map((item) => `${item.keyword}(+${item.gained}${item.exact ? '' : `/${item.confidence}`})`)
3278
+ .join(' ');
3279
+ return {
3280
+ type: 'banned-word',
3281
+ detail: `违禁词评分 ${assessment.total}/${threshold}:${top}`,
3282
+ assessment,
3283
+ };
2698
3284
  }
2699
3285
  return null;
2700
3286
  }
@@ -2775,6 +3361,124 @@ class QQGroupManagerService extends koishi_1.Service {
2775
3361
  }
2776
3362
  return { ok: true, action: 'none', count, message: `累计违规 ${count} 次(自动禁言线 ${muteThreshold} 次 / 自动踢人线 ${kickThreshold} 次)。` };
2777
3363
  }
3364
+ /**
3365
+ * 自定义命令处理器:整条消息与触发词完全一致(忽略首尾空白)即回复预设内容。
3366
+ * 触发词约定用方括号包裹(如 [签到])。命中后返回 true,调用方据此跳过后续
3367
+ * 违禁词管控与 AI 回复(自定义命令完全不走 AI)。
3368
+ */
3369
+ async handleCustomCommand(session) {
3370
+ const list = Array.isArray(this.config.customCommands) ? this.config.customCommands : [];
3371
+ if (!list.length)
3372
+ return false;
3373
+ const text = this.getMessageText(session).trim();
3374
+ if (!text)
3375
+ return false;
3376
+
3377
+ const guildId = this.normalizeGuildId(session.guildId);
3378
+ const cmd = list.find((c) => {
3379
+ if (!c || c.enabled === false)
3380
+ return false;
3381
+ const trigger = String(c.trigger ?? '').trim();
3382
+ if (!trigger || trigger !== text)
3383
+ return false;
3384
+ const groups = (c.groups ?? []).map((g) => this.normalizeGuildId(g)).filter(Boolean);
3385
+ return !groups.length || groups.includes(guildId);
3386
+ });
3387
+ if (!cmd)
3388
+ return false;
3389
+
3390
+ // 冷却
3391
+ const cd = Number(cmd.cooldownSeconds || 0);
3392
+ if (cd > 0) {
3393
+ const key = `${guildId}:${cmd.trigger}`;
3394
+ if (!this._customCmdAt)
3395
+ this._customCmdAt = new Map();
3396
+ const last = this._customCmdAt.get(key) ?? 0;
3397
+ const left = Math.ceil((cd * 1000 - (Date.now() - last)) / 1000);
3398
+ if (left > 0) {
3399
+ if (cmd.logHit !== false)
3400
+ this._logger.info(`[custom-cmd] 「${cmd.trigger}」冷却中(剩余 ${left}s) | ${this.sessionTag(session)}`);
3401
+ return true; // 命中但冷却中,同样不交给 AI
3402
+ }
3403
+ this._customCmdAt.set(key, Date.now());
3404
+ }
3405
+
3406
+ const replies = (cmd.replies ?? []).map((r) => String(r ?? '')).filter(Boolean);
3407
+ if (!replies.length) {
3408
+ this._logger.warn(`[custom-cmd] 「${cmd.trigger}」未配置回复内容 | ${this.sessionTag(session)}`);
3409
+ return true;
3410
+ }
3411
+
3412
+ // 多回复:随机 或 轮换
3413
+ let raw;
3414
+ if (replies.length === 1) {
3415
+ raw = replies[0];
3416
+ }
3417
+ else if (cmd.randomReply === true) {
3418
+ raw = replies[Math.floor(Math.random() * replies.length)];
3419
+ }
3420
+ else {
3421
+ const key = `${guildId}:${cmd.trigger}`;
3422
+ if (!this._customCmdIdx)
3423
+ this._customCmdIdx = new Map();
3424
+ const i = (this._customCmdIdx.get(key) ?? 0) % replies.length;
3425
+ this._customCmdIdx.set(key, i + 1);
3426
+ raw = replies[i];
3427
+ }
3428
+
3429
+ try {
3430
+ const parts = [];
3431
+ if (cmd.quote && session.messageId)
3432
+ parts.push(koishi_1.h.quote(session.messageId));
3433
+ // 变量占位符:{user} 昵称 / {at} @发送者 / {group} 群号
3434
+ const name = this.getDisplayName(session);
3435
+ let seg = raw;
3436
+ let guard = 0;
3437
+ while (guard++ < 20) {
3438
+ const atIdx = seg.indexOf('{at}');
3439
+ const userIdx = seg.indexOf('{user}');
3440
+ const groupIdx = seg.indexOf('{group}');
3441
+ const cands = [
3442
+ atIdx >= 0 ? { i: atIdx, k: 'at' } : null,
3443
+ userIdx >= 0 ? { i: userIdx, k: 'user' } : null,
3444
+ groupIdx >= 0 ? { i: groupIdx, k: 'group' } : null,
3445
+ ].filter(Boolean).sort((a, b) => a.i - b.i);
3446
+ if (!cands.length)
3447
+ break;
3448
+ const first = cands[0];
3449
+ if (first.k === 'at') {
3450
+ if (seg.slice(0, first.i))
3451
+ parts.push(koishi_1.h.text(seg.slice(0, first.i)));
3452
+ parts.push(koishi_1.h.at(session.userId));
3453
+ seg = seg.slice(first.i + 4);
3454
+ }
3455
+ else if (first.k === 'user') {
3456
+ if (seg.slice(0, first.i))
3457
+ parts.push(koishi_1.h.text(seg.slice(0, first.i)));
3458
+ parts.push(koishi_1.h.text(name));
3459
+ seg = seg.slice(first.i + 6);
3460
+ }
3461
+ else {
3462
+ if (seg.slice(0, first.i))
3463
+ parts.push(koishi_1.h.text(seg.slice(0, first.i)));
3464
+ parts.push(koishi_1.h.text(String(session.guildId ?? '')));
3465
+ seg = seg.slice(first.i + 7);
3466
+ }
3467
+ }
3468
+ if (seg)
3469
+ parts.push(koishi_1.h.text(seg));
3470
+ if (!parts.length)
3471
+ parts.push(koishi_1.h.text(raw));
3472
+
3473
+ await session.send(parts);
3474
+ if (cmd.logHit !== false)
3475
+ this._logger.info(`[custom-cmd] 命中「${cmd.trigger}」已回复 | ${this.sessionTag(session)}`);
3476
+ }
3477
+ catch (error) {
3478
+ this._logger.warn(`[custom-cmd] 「${cmd.trigger}」回复失败: ${String(error)} | ${this.sessionTag(session)}`);
3479
+ }
3480
+ return true;
3481
+ }
2778
3482
  async handleGroupModeration(session) {
2779
3483
  if (!this.isPlatformAllowed(session.platform))
2780
3484
  return;
@@ -2782,6 +3486,9 @@ class QQGroupManagerService extends koishi_1.Service {
2782
3486
  return;
2783
3487
  if (await this.handleMemoryCommand(session))
2784
3488
  return;
3489
+ // 自定义命令优先于违禁词管控与 AI:命中后直接结束本轮处理
3490
+ if (await this.handleCustomCommand(session))
3491
+ return;
2785
3492
  if (!session.guildId)
2786
3493
  return;
2787
3494
  if (session.userId && session.bot?.selfId && session.userId === session.bot.selfId)
@@ -2790,16 +3497,19 @@ class QQGroupManagerService extends koishi_1.Service {
2790
3497
  return;
2791
3498
  if (session.platform === 'onebot') {
2792
3499
  const policy = this.resolveModerationPolicy(session);
2793
- const violation = this.detectViolation(session, policy);
3500
+ const violation = await this.detectViolation(session, policy);
2794
3501
  if (violation) {
2795
3502
  let deleted = false;
2796
3503
  if (policy.autoDeleteViolation) {
2797
3504
  deleted = await this.deleteMessage(session);
2798
3505
  }
2799
- this._logger.warn(`[moderation] type=${violation.type} detail="${violation.detail}" deleted=${deleted} | ${this.sessionTag(session)}`);
3506
+ const scoreInfo = violation.assessment
3507
+ ? ` score=${violation.assessment.total} hits=${violation.assessment.evaluations.map((item) => `${item.keyword}:${item.gained}${item.exact ? '' : '/fuzzy'}`).join(',')}`
3508
+ : '';
3509
+ this._logger.warn(`[moderation] type=${violation.type} detail="${violation.detail}"${scoreInfo} deleted=${deleted} | ${this.sessionTag(session)}`);
2800
3510
  if (policy.sendViolationNotice) {
2801
3511
  const notice = violation.type === 'banned-word'
2802
- ? '检测到违禁词,消息已处理。'
3512
+ ? `检测到违禁内容(评分 ${violation.assessment?.total ?? '-'}),消息已处理。`
2803
3513
  : violation.type === 'card'
2804
3514
  ? '卡片消息不被允许,消息已处理。'
2805
3515
  : '合并转发消息不被允许,消息已处理。';