@nestim/koishi-plugin-qq-group-manager 0.1.6 → 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/index.js CHANGED
@@ -33,6 +33,8 @@ exports.Config = koishi_1.Schema.intersect([
33
33
  guildId: koishi_1.Schema.string().required().description('群号。'),
34
34
  enableAiReply: koishi_1.Schema.boolean().description('该群是否启用 AI 回复(留空则跟随全局设置)。'),
35
35
  bannedWords: koishi_1.Schema.array(String).role('table').default([]).description('该群专属违禁词列表(同样支持“关键词|分值”与顺序模糊匹配)。'),
36
+ whitelistKeywords: koishi_1.Schema.array(String).role('table').default([]).description('该群违禁词白名单:消息只要命中其中任意一个关键词,就整条跳过违禁词评分(用于校学生会招新等允许的宣传场景)。'),
37
+ whitelistOnlyOwners: koishi_1.Schema.boolean().default(false).description('白名单是否仅对群主/管理员生效。关闭时所有群成员命中白名单均可豁免。'),
36
38
  blockCardMessage: koishi_1.Schema.boolean().default(true).description('该群是否禁止卡片消息(json/xml)。'),
37
39
  blockForwardMessage: koishi_1.Schema.boolean().default(true).description('该群是否禁止合并转发消息(forward)。'),
38
40
  autoDeleteViolation: koishi_1.Schema.boolean().default(true).description('该群违规消息是否自动撤回。'),
@@ -76,7 +78,20 @@ exports.Config = koishi_1.Schema.intersect([
76
78
  joinRequestReviewTtlMinutes: koishi_1.Schema.natural().default(30).description('入群申请审核编号的有效期(分钟)。'),
77
79
  }).description('群聊互动'),
78
80
  koishi_1.Schema.object({
79
- enableAiReply: koishi_1.Schema.boolean().default(false).description('是否启用群聊 AI 自动回复。'),
81
+ customCommands: koishi_1.Schema.array(koishi_1.Schema.object({
82
+ trigger: koishi_1.Schema.string().required().description('触发词,需用方括号包裹,如 [签到]。只有整条消息与之完全相同(忽略首尾空白)才会触发。'),
83
+ replies: koishi_1.Schema.array(String).role('table').default([]).description('回复内容,可配置多条。每条支持 {user} 发送者昵称、{at} @发送者、{group} 群号。'),
84
+ enabled: koishi_1.Schema.boolean().default(true).description('是否启用该命令。'),
85
+ groups: koishi_1.Schema.array(String).role('table').default([]).description('限定生效的群号;留空表示所有群生效。'),
86
+ randomReply: koishi_1.Schema.boolean().default(false).description('配置多条回复时:开启则随机选一条,关闭则按顺序轮换。'),
87
+ quote: koishi_1.Schema.boolean().default(false).description('回复时是否引用触发的那条消息。'),
88
+ cooldownSeconds: koishi_1.Schema.natural().default(0).description('同一群内该命令的冷却时间(秒,0 表示不限制)。'),
89
+ logHit: koishi_1.Schema.boolean().default(true).description('命中时是否写入日志。'),
90
+ })).role('table').default([]).description('自定义命令:检测到指定命令后输出预设消息(触发后不再走 AI 回复)。'),
91
+ }).description('自定义命令'),
92
+ koishi_1.Schema.object({
93
+ enableAiReply: koishi_1.Schema.boolean().default(false).description('全局 AI 回复开关(当 aiReplyRequireGroupRule 关闭时,未单独配置的群会回落到此值)。'),
94
+ aiReplyRequireGroupRule: koishi_1.Schema.boolean().default(true).description('AI 回复是否要求该群已单独配置:开启后,未出现在 groupRules 里的群一律不启用 AI 回复(推荐)。'),
80
95
  aiProvider: koishi_1.Schema.union([
81
96
  koishi_1.Schema.const('openai-compatible').description('OpenAI 兼容接口(OpenAI/火山引擎/Codex API/Auth 等)'),
82
97
  koishi_1.Schema.const('gemini').description('Gemini 原生接口(Google Generative Language API)'),
package/lib/service.js CHANGED
@@ -196,8 +196,13 @@ class QQGroupManagerService extends koishi_1.Service {
196
196
  resolveAiEnabled(session) {
197
197
  const guildId = this.normalizeGuildId(session.guildId);
198
198
  const rule = this.config.groupRules.find((item) => this.normalizeGuildId(item.guildId) === guildId);
199
+ // 该群有独立配置:以其 enableAiReply 为准
199
200
  if (typeof rule?.enableAiReply === 'boolean')
200
201
  return rule.enableAiReply;
202
+ // 未单独配置的群:默认不启用 AI 回复(避免全局开关扩散到所有群)
203
+ // 如需恢复旧的「回落到全局」行为,把 aiReplyRequireGroupRule 设为 false
204
+ if (this.config.aiReplyRequireGroupRule !== false)
205
+ return false;
201
206
  return this.config.enableAiReply;
202
207
  }
203
208
  extractAiMessageText(session) {
@@ -3028,6 +3033,8 @@ class QQGroupManagerService extends koishi_1.Service {
3028
3033
  if (!rule) {
3029
3034
  return {
3030
3035
  bannedWords: this.config.bannedWords,
3036
+ whitelistKeywords: [],
3037
+ whitelistOnlyOwners: false,
3031
3038
  blockCardMessage: this.config.blockCardMessage,
3032
3039
  blockForwardMessage: this.config.blockForwardMessage,
3033
3040
  autoDeleteViolation: this.config.autoDeleteViolation,
@@ -3042,6 +3049,8 @@ class QQGroupManagerService extends koishi_1.Service {
3042
3049
  }
3043
3050
  return {
3044
3051
  bannedWords: rule.bannedWords,
3052
+ whitelistKeywords: rule.whitelistKeywords || [],
3053
+ whitelistOnlyOwners: rule.whitelistOnlyOwners === true,
3045
3054
  blockCardMessage: rule.blockCardMessage,
3046
3055
  blockForwardMessage: rule.blockForwardMessage,
3047
3056
  autoDeleteViolation: rule.autoDeleteViolation,
@@ -3213,7 +3222,34 @@ class QQGroupManagerService extends koishi_1.Service {
3213
3222
  evaluations.sort((a, b) => b.gained - a.gained);
3214
3223
  return { total: Math.round(total * 100) / 100, evaluations };
3215
3224
  }
3216
- detectViolation(session, policy, type = 'message') {
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') {
3217
3253
  // 纯图片/表情/贴纸(无实际文字内容)的消息不作为违规处理,避免表情包被当成违禁词
3218
3254
  if (type === 'message' && this.hasImageOrFace(session) && !this.hasTextContent(session)) {
3219
3255
  return null;
@@ -3227,6 +3263,13 @@ class QQGroupManagerService extends koishi_1.Service {
3227
3263
  const text = this.extractTextForFilter(session);
3228
3264
  if (!text)
3229
3265
  return null;
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
+ }
3230
3273
  const assessment = this.evaluateBannedWords(text, policy);
3231
3274
  const threshold = Math.max(1, Math.min(100, Number(this.config.bannedWordScoreThreshold ?? 70)));
3232
3275
  if (assessment.total >= threshold) {
@@ -3318,6 +3361,124 @@ class QQGroupManagerService extends koishi_1.Service {
3318
3361
  }
3319
3362
  return { ok: true, action: 'none', count, message: `累计违规 ${count} 次(自动禁言线 ${muteThreshold} 次 / 自动踢人线 ${kickThreshold} 次)。` };
3320
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
+ }
3321
3482
  async handleGroupModeration(session) {
3322
3483
  if (!this.isPlatformAllowed(session.platform))
3323
3484
  return;
@@ -3325,6 +3486,9 @@ class QQGroupManagerService extends koishi_1.Service {
3325
3486
  return;
3326
3487
  if (await this.handleMemoryCommand(session))
3327
3488
  return;
3489
+ // 自定义命令优先于违禁词管控与 AI:命中后直接结束本轮处理
3490
+ if (await this.handleCustomCommand(session))
3491
+ return;
3328
3492
  if (!session.guildId)
3329
3493
  return;
3330
3494
  if (session.userId && session.bot?.selfId && session.userId === session.bot.selfId)
@@ -3333,7 +3497,7 @@ class QQGroupManagerService extends koishi_1.Service {
3333
3497
  return;
3334
3498
  if (session.platform === 'onebot') {
3335
3499
  const policy = this.resolveModerationPolicy(session);
3336
- const violation = this.detectViolation(session, policy);
3500
+ const violation = await this.detectViolation(session, policy);
3337
3501
  if (violation) {
3338
3502
  let deleted = false;
3339
3503
  if (policy.autoDeleteViolation) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@nestim/koishi-plugin-qq-group-manager",
3
3
  "description": "Koishi QQ群管理插件(OneBot/LLOneBot):群管命令、权限校验、图片菜单、状态卡片、复读、AI群聊回复、记忆库、识图与自动管控(禁言/踢人)。",
4
- "version": "0.1.6",
4
+ "version": "0.1.7",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/readme.md CHANGED
@@ -4,6 +4,54 @@
4
4
 
5
5
  QQ群管理插件(OneBot/LLOneBot):群管命令、权限校验、图片菜单、状态卡片、复读、AI群聊回复、记忆库、识图与自动管控(禁言/踢人)。
6
6
 
7
+ ## v0.1.7 重点更新
8
+
9
+ ### 1. AI 回复限定在「已单独配置的群」
10
+
11
+ 修复了一个权限漏洞:此前群未出现在 `groupRules` 时会**回落到全局 `enableAiReply`**,
12
+ 导致所有未配置的群也会触发 AI 回复。
13
+
14
+ 现在默认要求「该群已单独配置」,可用 `aiReplyRequireGroupRule: false` 恢复旧的回落行为。
15
+
16
+ ### 2. 违禁词白名单(按群配置)
17
+
18
+ 用于校学生会招新这类场景:招新文案含「加群」「群号」等违禁词,但属于允许的宣传。
19
+
20
+ ```yaml
21
+ groupRules:
22
+ - guildId: '1009320867'
23
+ whitelistKeywords:
24
+ - 宣传部
25
+ - 纪检部
26
+ - 办公室
27
+ whitelistOnlyOwners: false # true 则仅群主/管理员可豁免
28
+ ```
29
+
30
+ - 命中**任意一个**白名单关键词即整条跳过违禁词评分;
31
+ - 只豁免违禁词,**卡片/合并转发的拦截不受影响**;
32
+ - 仅在配置了白名单的群生效。
33
+
34
+ ### 3. 自定义命令
35
+
36
+ 检测到指定命令后输出预设消息,**完全不走 AI**。
37
+
38
+ ```yaml
39
+ customCommands:
40
+ - trigger: '[签到]' # 必须方括号包裹,完全匹配(忽略首尾空白)
41
+ replies:
42
+ - '签到成功!{at} 今天也要加油喵~'
43
+ enabled: true
44
+ groups: [] # 留空=所有群;填群号=仅限这些群
45
+ randomReply: false # 多条回复:随机 or 顺序轮换
46
+ quote: true # 引用触发的那条消息
47
+ cooldownSeconds: 0
48
+ logHit: true
49
+ ```
50
+
51
+ - **完全匹配**:`[签到] 一下`、`签到`、`我要签到` 均**不触发**;
52
+ - 变量占位符:`{user}` 昵称、`{at}` @发送者、`{group}` 群号;
53
+ - 每条命令可独立配置随机/轮换、引用、限定群、冷却、日志。
54
+
7
55
  ## v0.1.6 重点更新
8
56
 
9
57
  ### 1. 识图彻底修复(此前完全不可用)