@nestim/koishi-plugin-qq-group-manager 1.2.4 → 1.2.6

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
@@ -13,6 +13,73 @@ try {
13
13
  PLUGIN_VERSION = require('../package.json').version || 'unknown';
14
14
  }
15
15
  catch { /* ignore */ }
16
+ /** 解析“提醒/定时”文本;返回 { at, content } 或 null。纯函数,便于测试。 */
17
+ function parseReminderText(rawText, now = Date.now()) {
18
+ let text = String(rawText || '')
19
+ .replace(/<at\b[^>]*\/?>/gi, ' ')
20
+ .replace(/\[CQ:at,[^\]]+\]/gi, ' ')
21
+ .replace(/^\s*\[bot\]\s*/i, ' ')
22
+ .replace(/\s+/g, ' ')
23
+ .trim();
24
+ if (!text || !/(提醒|定时|叫我)/.test(text))
25
+ return null;
26
+ let at = null;
27
+ let timeMatch = '';
28
+ const rel = text.match(/(半|一|两|二|\d+)\s*(秒钟?|分钟?|小时|钟头)\s*(?:之后|以后|后)/);
29
+ if (rel) {
30
+ const raw = rel[1];
31
+ const num = raw === '半' ? 0.5 : raw === '一' ? 1 : (raw === '两' || raw === '二' ? 2 : Number(raw));
32
+ if (!Number.isFinite(num) || num <= 0)
33
+ return null;
34
+ const ms = /秒/.test(rel[2]) ? num * 1000 : (/小时|钟头/.test(rel[2]) ? num * 3600000 : num * 60000);
35
+ at = now + ms;
36
+ timeMatch = rel[0];
37
+ }
38
+ else {
39
+ const abs = text.match(/(今天|明天|后天)?\s*(早上|上午|中午|下午|晚上|夜里)?\s*(\d{1,2})\s*[::点时]\s*(\d{1,2})?\s*分?/);
40
+ if (!abs)
41
+ return null;
42
+ const dayWord = abs[1] || '';
43
+ const period = abs[2] || '';
44
+ let hour = Number(abs[3]);
45
+ const minute = abs[4] === undefined ? 0 : Number(abs[4]);
46
+ if (!Number.isFinite(hour) || hour > 23 || minute > 59)
47
+ return null;
48
+ if (period === '下午' || period === '晚上' || period === '夜里') {
49
+ if (hour < 12)
50
+ hour += 12;
51
+ }
52
+ else if (period === '中午') {
53
+ if (hour < 11)
54
+ hour += 12;
55
+ }
56
+ else if (period === '早上' || period === '上午') {
57
+ if (hour === 12)
58
+ hour = 0;
59
+ }
60
+ const date = new Date(now);
61
+ date.setSeconds(0, 0);
62
+ date.setHours(hour, minute, 0, 0);
63
+ const offset = dayWord === '明天' ? 1 : (dayWord === '后天' ? 2 : 0);
64
+ if (offset)
65
+ date.setDate(date.getDate() + offset);
66
+ else if (date.getTime() <= now + 30000) {
67
+ if (dayWord === '今天')
68
+ return null;
69
+ date.setDate(date.getDate() + 1);
70
+ }
71
+ at = date.getTime();
72
+ timeMatch = abs[0];
73
+ }
74
+ let content = text.replace(timeMatch, ' ')
75
+ .replace(/^(?:请|麻烦|帮我|帮忙)?\s*(?:提醒我?|定个?时(?:提醒)?|叫我|记得)\s*/, ' ')
76
+ .replace(/\s+/g, ' ')
77
+ .trim();
78
+ content = content.replace(/^[,,。::\s]+/, '').trim();
79
+ if (!content)
80
+ content = '该做你之前说的事了';
81
+ return { at, content };
82
+ }
16
83
  class QQGroupManagerService extends koishi_1.Service {
17
84
  ctx;
18
85
  config;
@@ -23,6 +90,14 @@ class QQGroupManagerService extends koishi_1.Service {
23
90
  pendingJoinRequestFlags = new Map();
24
91
  violationRecords = new Map();
25
92
  _imageDataUrlCache = new Map();
93
+ /** 定时提醒:id -> reminder */
94
+ _reminders = new Map();
95
+ /** 定时提醒:id -> timer */
96
+ _reminderTimers = new Map();
97
+ /** 群空闲话题:groupId -> timer */
98
+ _idleTimers = new Map();
99
+ /** 上次主动话题时间:groupId -> ts */
100
+ _lastIdleTopicAt = new Map();
26
101
  /** 记忆库写锁:串行化「读整档→改→整写」,防止并发写互相覆盖 */
27
102
  _memoryWriteLock = Promise.resolve();
28
103
  /** 待审入群申请的落盘去抖定时器 */
@@ -189,10 +264,18 @@ class QQGroupManagerService extends koishi_1.Service {
189
264
  // 额外把扩展点挂到 root,外部插件 inject 'qqgmAiHooks' 即可。
190
265
  try {
191
266
  ctx.root.set('qqgmAiHooks', this.ai.hooks);
267
+ const runtime = {
268
+ config: this.config,
269
+ hooks: this.ai.hooks,
270
+ chat: (request) => this.ai.chat(request),
271
+ };
272
+ ctx.root.set('qqgmAiRuntime', runtime);
192
273
  ctx.on('dispose', () => {
193
274
  try {
194
275
  if (ctx.root.get('qqgmAiHooks') === this.ai.hooks)
195
276
  ctx.root.set('qqgmAiHooks', undefined);
277
+ if (ctx.root.get('qqgmAiRuntime')?.hooks === this.ai.hooks)
278
+ ctx.root.set('qqgmAiRuntime', undefined);
196
279
  }
197
280
  catch { /* ignore */ }
198
281
  });
@@ -218,11 +301,249 @@ class QQGroupManagerService extends koishi_1.Service {
218
301
  catch (error) {
219
302
  this._logger.warn(`[join-review] 恢复待审单失败: ${String(error)}`);
220
303
  }
304
+ try {
305
+ this.loadReminders();
306
+ }
307
+ catch (error) {
308
+ this._logger.warn(`[reminder] 恢复待审提醒失败: ${String(error)}`);
309
+ }
310
+ ctx.on('dispose', () => this.disposeSchedulers());
221
311
  }
222
312
  /** 外部插件扩展点:提示词风格段 + 输出过滤(接口版本见 AiHookRegistry.version) */
223
313
  get aiHooks() {
224
314
  return this.ai ? this.ai.hooks : null;
225
315
  }
316
+ reminderFilePath() {
317
+ const base = (this.ctx && this.ctx.baseDir) || process.cwd();
318
+ return node_path_1.default.join(base, 'data', 'qqgm-reminders.json');
319
+ }
320
+ loadReminders() {
321
+ const file = this.reminderFilePath();
322
+ if (!node_fs_1.default.existsSync(file))
323
+ return;
324
+ const list = JSON.parse(node_fs_1.default.readFileSync(file, 'utf8'));
325
+ if (!Array.isArray(list))
326
+ return;
327
+ for (const item of list) {
328
+ if (!item || !item.id || !item.groupId || !item.userId || !Number.isFinite(Number(item.at)))
329
+ continue;
330
+ this._reminders.set(item.id, item);
331
+ this.scheduleReminder(item);
332
+ }
333
+ this._logger.info(`[reminder] 恢复 ${this._reminders.size} 条待提醒`);
334
+ }
335
+ saveReminders() {
336
+ try {
337
+ const file = this.reminderFilePath();
338
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(file), { recursive: true });
339
+ node_fs_1.default.writeFileSync(file, JSON.stringify([...this._reminders.values()], null, 2));
340
+ }
341
+ catch (error) {
342
+ this._logger.warn(`[reminder] 保存失败: ${String(error)}`);
343
+ }
344
+ }
345
+ clearReminderTimer(id) {
346
+ const timer = this._reminderTimers.get(id);
347
+ if (timer)
348
+ clearTimeout(timer);
349
+ this._reminderTimers.delete(id);
350
+ }
351
+ scheduleReminder(reminder) {
352
+ this.clearReminderTimer(reminder.id);
353
+ const delay = Math.max(0, Number(reminder.at) - Date.now());
354
+ const max = 2147483647;
355
+ const timer = setTimeout(() => {
356
+ if (delay > max) {
357
+ this.scheduleReminder(reminder);
358
+ return;
359
+ }
360
+ this.fireReminder(reminder.id).catch((error) => this._logger.warn(`[reminder] 触发失败 ${reminder.id}: ${String(error)}`));
361
+ }, Math.min(delay, max));
362
+ timer.unref?.();
363
+ this._reminderTimers.set(reminder.id, timer);
364
+ }
365
+ async fireReminder(id) {
366
+ const reminder = this._reminders.get(id);
367
+ if (!reminder)
368
+ return;
369
+ this._reminders.delete(id);
370
+ this.clearReminderTimer(id);
371
+ this.saveReminders();
372
+ const bots = this.ctx?.bots || [];
373
+ const bot = bots.find((b) => b.platform === 'onebot' && b.status !== 'offline')
374
+ || bots.find((b) => b.platform === 'onebot')
375
+ || bots[0];
376
+ if (!bot) {
377
+ this._logger.warn(`[reminder] 没有可用 bot,跳过 ${id}`);
378
+ return;
379
+ }
380
+ try {
381
+ await bot.sendMessage(reminder.groupId, [koishi_1.h.at(reminder.userId), koishi_1.h.text(` ${reminder.text}`)], reminder.groupId);
382
+ this._logger.info(`[reminder] sent ${id} group=${reminder.groupId} user=${reminder.userId}`);
383
+ }
384
+ catch (error) {
385
+ this._logger.warn(`[reminder] 发送失败 ${id}: ${String(error)}`);
386
+ }
387
+ }
388
+ addReminder(reminder) {
389
+ this._reminders.set(reminder.id, reminder);
390
+ this.saveReminders();
391
+ this.scheduleReminder(reminder);
392
+ }
393
+ formatReminderTime(at) {
394
+ const date = new Date(at);
395
+ const now = new Date();
396
+ const pad = (n) => String(n).padStart(2, '0');
397
+ const day = date.toDateString() === now.toDateString()
398
+ ? '今天'
399
+ : (new Date(now.getTime() + 86400000).toDateString() === date.toDateString()
400
+ ? '明天'
401
+ : `${date.getMonth() + 1}月${date.getDate()}日`);
402
+ return `${day} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
403
+ }
404
+ async sendReminderList(session) {
405
+ const userId = String(session.userId || '');
406
+ const items = [...this._reminders.values()]
407
+ .filter((item) => item.userId === userId)
408
+ .sort((a, b) => a.at - b.at);
409
+ if (!items.length) {
410
+ await this.sendReply(session, '你还没有定时提醒');
411
+ return;
412
+ }
413
+ const lines = items.slice(0, 10).map((item, index) => `${index + 1}. ${this.formatReminderTime(item.at)} ${item.text}`);
414
+ await this.sendReply(session, lines.join('\n'));
415
+ }
416
+ async cancelReminder(session, id) {
417
+ const key = String(id || '').trim();
418
+ const reminder = this._reminders.get(key);
419
+ if (!reminder || reminder.userId !== String(session.userId || '')) {
420
+ await this.sendReply(session, '没找到这条提醒');
421
+ return;
422
+ }
423
+ this._reminders.delete(key);
424
+ this.clearReminderTimer(key);
425
+ this.saveReminders();
426
+ await this.sendReply(session, `已取消:${reminder.text}`);
427
+ }
428
+ async handleReminderCommand(session, rest) {
429
+ const cmd = String(rest || '').trim();
430
+ if (!cmd)
431
+ return false;
432
+ if (/^(提醒|定时)列表$/.test(cmd)) {
433
+ await this.sendReminderList(session);
434
+ return true;
435
+ }
436
+ const cancel = cmd.match(/^(?:取消提醒|取消定时)\s+(\S+)$/);
437
+ if (cancel) {
438
+ await this.cancelReminder(session, cancel[1]);
439
+ return true;
440
+ }
441
+ if (!/^(提醒|定时)\s+/.test(cmd))
442
+ return false;
443
+ const parsed = parseReminderText(cmd, Date.now());
444
+ if (!parsed)
445
+ return false;
446
+ const reminder = {
447
+ id: `r${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
448
+ groupId: String(session.guildId || session.channelId || ''),
449
+ userId: String(session.userId || ''),
450
+ at: parsed.at,
451
+ text: parsed.content,
452
+ createdAt: Date.now(),
453
+ };
454
+ this.addReminder(reminder);
455
+ const confirmation = `好,${this.formatReminderTime(parsed.at)} 提醒你:${parsed.content}`;
456
+ await this.sendReply(session, confirmation);
457
+ try {
458
+ this.ai.recordSelf(session, confirmation);
459
+ }
460
+ catch { /* ignore */ }
461
+ return true;
462
+ }
463
+ async handleReminderRequest(session) {
464
+ if (!session.guildId)
465
+ return false;
466
+ const text = this.extractTextForFilter(session);
467
+ if (!/(提醒|定时|叫我)/.test(text))
468
+ return false;
469
+ const selfId = String(session.bot?.selfId || '');
470
+ const rawContent = String(session.content || '');
471
+ const atBot = !!selfId && new RegExp(`<at\\b[^>]*(?:id|qq)=["']?${selfId}`).test(rawContent);
472
+ if (!atBot && !/^\s*(?:提醒|定时|叫我)/.test(text) && !/^\s*\[bot\]/i.test(rawContent))
473
+ return false;
474
+ const parsed = parseReminderText(text, Date.now());
475
+ if (!parsed)
476
+ return false;
477
+ const reminder = {
478
+ id: `r${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
479
+ groupId: String(session.guildId),
480
+ userId: String(session.userId || ''),
481
+ at: parsed.at,
482
+ text: parsed.content,
483
+ createdAt: Date.now(),
484
+ };
485
+ this.addReminder(reminder);
486
+ const confirmation = `好,${this.formatReminderTime(parsed.at)} 提醒你:${parsed.content}`;
487
+ await this.sendReply(session, confirmation);
488
+ try {
489
+ this.ai.recordSelf(session, confirmation);
490
+ }
491
+ catch { /* ignore */ }
492
+ return true;
493
+ }
494
+ touchIdleTopic(session) {
495
+ const groupId = String(session?.guildId || '');
496
+ const minutes = Number(this.config?.aiIdleTopicMinutes ?? 0);
497
+ if (!groupId || !minutes)
498
+ return;
499
+ try {
500
+ if (!this.ai.resolveEnabled(session))
501
+ return;
502
+ }
503
+ catch { /* ignore */ }
504
+ const old = this._idleTimers.get(groupId);
505
+ if (old)
506
+ clearTimeout(old);
507
+ const timer = setTimeout(() => {
508
+ this.fireIdleTopic(groupId).catch((error) => this._logger.warn(`[idle] ${String(error)}`));
509
+ }, minutes * 60000);
510
+ timer.unref?.();
511
+ this._idleTimers.set(groupId, timer);
512
+ }
513
+ async fireIdleTopic(groupId) {
514
+ this._idleTimers.delete(groupId);
515
+ const hour = new Date().getHours();
516
+ const min = Number(this.config?.aiIdleTopicMinHour ?? 9);
517
+ const max = Number(this.config?.aiIdleTopicMaxHour ?? 23);
518
+ if (hour < min || hour >= max)
519
+ return;
520
+ const cooldown = Math.max(1, Number(this.config?.aiIdleTopicCooldownMinutes ?? 60)) * 60000;
521
+ if (Date.now() - (this._lastIdleTopicAt.get(groupId) || 0) < cooldown)
522
+ return;
523
+ const text = await this.ai.idleTopic(groupId);
524
+ if (!text)
525
+ return;
526
+ await this.sendGroupText(groupId, text);
527
+ this._lastIdleTopicAt.set(groupId, Date.now());
528
+ this._logger.info(`[idle] topic sent group=${groupId} chars=${text.length}`);
529
+ }
530
+ async sendGroupText(groupId, text) {
531
+ const bots = this.ctx?.bots || [];
532
+ const bot = bots.find((b) => b.platform === 'onebot' && b.status !== 'offline')
533
+ || bots.find((b) => b.platform === 'onebot')
534
+ || bots[0];
535
+ if (!bot)
536
+ return;
537
+ await bot.sendMessage(groupId, koishi_1.h.text(text), groupId);
538
+ }
539
+ disposeSchedulers() {
540
+ for (const timer of this._reminderTimers.values())
541
+ clearTimeout(timer);
542
+ for (const timer of this._idleTimers.values())
543
+ clearTimeout(timer);
544
+ this._reminderTimers.clear();
545
+ this._idleTimers.clear();
546
+ }
226
547
  isPlatformAllowed(platform) {
227
548
  if (!platform)
228
549
  return false;
@@ -1696,6 +2017,42 @@ class QQGroupManagerService extends koishi_1.Service {
1696
2017
  extractImages(session) {
1697
2018
  return this.extractImageElements(session);
1698
2019
  }
2020
+ /** 引用消息只带 messageId 时,用 OneBot get_msg 回查图片 */
2021
+ async fetchQuotedImages(session, quote) {
2022
+ const id = String(quote?.id || '');
2023
+ if (!id)
2024
+ return [];
2025
+ const onebot = this.getOneBotApi(session);
2026
+ if (!onebot?.getMsg)
2027
+ return [];
2028
+ try {
2029
+ const msg = await onebot.getMsg(id);
2030
+ const message = msg?.message ?? msg?.data?.message;
2031
+ const elements = [];
2032
+ let content = '';
2033
+ if (Array.isArray(message)) {
2034
+ for (const seg of message) {
2035
+ if (seg?.type === 'image') {
2036
+ elements.push({
2037
+ type: 'image',
2038
+ attrs: {
2039
+ src: seg.data?.url || seg.data?.file || '',
2040
+ file: seg.data?.file || '',
2041
+ },
2042
+ });
2043
+ }
2044
+ }
2045
+ }
2046
+ else if (typeof message === 'string') {
2047
+ content = message;
2048
+ }
2049
+ return this.extractImageElements({ content, elements });
2050
+ }
2051
+ catch (error) {
2052
+ this._logger.warn(`[ai] 引用消息取图失败: ${String(error)}`);
2053
+ return [];
2054
+ }
2055
+ }
1699
2056
  /** 供 AI 引擎把图片引用转成 data URL */
1700
2057
  resolveImage(ref, session) {
1701
2058
  return this.resolveImageReferenceToDataUrl(ref, session);
@@ -2259,6 +2616,8 @@ class QQGroupManagerService extends koishi_1.Service {
2259
2616
  await this.sendCommandMenu(session);
2260
2617
  return true;
2261
2618
  }
2619
+ if (await this.handleReminderCommand(session, rest))
2620
+ return true;
2262
2621
  return false;
2263
2622
  }
2264
2623
  if (name === this.cmdPrefix('cmdMute', '[mute]'))
@@ -2690,6 +3049,8 @@ class QQGroupManagerService extends koishi_1.Service {
2690
3049
  async handleGroupModeration(session) {
2691
3050
  if (!this.isPlatformAllowed(session.platform))
2692
3051
  return;
3052
+ if (session.guildId)
3053
+ this.touchIdleTopic(session);
2693
3054
  // AI 上下文先记录:被管控/被指令拦截的消息也要进上下文(指令类由引擎自行忽略)
2694
3055
  try {
2695
3056
  await this.ai.record(session);
@@ -2772,6 +3133,8 @@ class QQGroupManagerService extends koishi_1.Service {
2772
3133
  catch (error) {
2773
3134
  this._logger.warn(`[repeater] failed: ${String(error)} | ${this.sessionTag(session)}`);
2774
3135
  }
3136
+ if (await this.handleReminderRequest(session))
3137
+ return;
2775
3138
  await this.ai.handle(session);
2776
3139
  }
2777
3140
  /**
@@ -3328,3 +3691,4 @@ class QQGroupManagerService extends koishi_1.Service {
3328
3691
  }
3329
3692
  }
3330
3693
  exports.QQGroupManagerService = QQGroupManagerService;
3694
+ exports.parseReminderText = parseReminderText;
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": "1.2.4",
4
+ "version": "1.2.6",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/src/ai/engine.ts CHANGED
@@ -28,6 +28,7 @@ export interface AiHost {
28
28
  getOneBotApi(session: any): any;
29
29
  toGroupId(session: any): number | null;
30
30
  extractImages(session: any): RenderedImage[];
31
+ fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
31
32
  resolveImage(ref: string, session: any): Promise<string>;
32
33
  sendReply(session: any, text: string): Promise<void>;
33
34
  readMemoryFile(): Promise<string>;
@@ -128,7 +129,7 @@ export class AiEngine {
128
129
 
129
130
  private get selfName(): string {
130
131
  const persona = this.activePersona();
131
- return String(persona?.selfName || this.config.aiAgentName || 'MeowBot').trim() || 'MeowBot';
132
+ return String(persona?.selfName || this.config.aiAgentName || 'bot').trim() || 'bot';
132
133
  }
133
134
 
134
135
  private activePersona(): any {
@@ -396,6 +397,8 @@ export class AiEngine {
396
397
  now: this.now(),
397
398
  lastAttemptAt: state.lastAttemptAt,
398
399
  minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
400
+ lastReplyAt: state.lastReplyAt || 0,
401
+ mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
399
402
  inFlight: state.inFlight,
400
403
  mention,
401
404
  followup,
@@ -524,6 +527,8 @@ export class AiEngine {
524
527
  chars: finalText.length,
525
528
  preview: finalText.slice(0, 60),
526
529
  }, session);
530
+
531
+ await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
527
532
  } catch (error: any) {
528
533
  this.log('ai-reply', {
529
534
  ok: false,
@@ -535,6 +540,38 @@ export class AiEngine {
535
540
  }
536
541
  }
537
542
 
543
+ /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
544
+ chat(request: any) {
545
+ return this.provider.chat(request);
546
+ }
547
+
548
+ /** 群内长时间没人说话时,生成一条主动话题。 */
549
+ async idleTopic(groupId: string): Promise<string> {
550
+ const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
551
+ let sections: string[] = [];
552
+ try {
553
+ sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
554
+ } catch { /* ignore */ }
555
+ const system = [
556
+ `你是 QQ 群 ${groupId} 里的一个普通成员。`,
557
+ '群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
558
+ '不要问“在吗”,不要提“很久没人说话”,不要自我介绍。',
559
+ ...sections,
560
+ ].join('\n');
561
+ const result = await this.provider.chat({
562
+ system,
563
+ user: '现在发一条主动话题。',
564
+ temperature: Number(this.config.aiTemperature ?? 0.8),
565
+ maxTokens: Math.min(300, Number(this.config.aiMaxOutputTokens ?? 400)),
566
+ });
567
+ if (!result.ok || !result.text) return '';
568
+ const raw = String(result.text).trim();
569
+ if (!raw || PASS_RE.test(raw)) return '';
570
+ return clipReply(cleanReply(raw, this.selfName), this.maxReplyChars)
571
+ .replace(/\[表情[::][^\]]*\]/g, '')
572
+ .trim();
573
+ }
574
+
538
575
  private recentImageRecords(state: GroupState, record: ChatRecord, maxAgeMs = 120000): RenderedImage[] {
539
576
  const cutoff = Number(record.at) - maxAgeMs;
540
577
  const candidates = state.records
@@ -562,7 +599,13 @@ export class AiEngine {
562
599
  const own = record.images.length ? record.images : this.host.extractImages(session);
563
600
  // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
564
601
  const fallback = own.length ? [] : this.recentImageRecords(state, record);
565
- const quoted = record.quote ? this.host.extractImages(session?.quote) : [];
602
+ let quoted: RenderedImage[] = record.quote
603
+ ? (record.quote.images?.length ? record.quote.images : this.host.extractImages(session?.quote))
604
+ : [];
605
+ // 引用消息里没解析到图(常见于 quote 只带 messageId):用 get_msg 回查一次
606
+ if (!quoted.length && record.quote?.id && typeof this.host.fetchQuotedImages === 'function') {
607
+ quoted = await this.host.fetchQuotedImages(session, record.quote);
608
+ }
566
609
  const items = pickImages([...own, ...fallback], quoted, maxCount);
567
610
  if (!items.length) return [];
568
611
 
package/src/ai/hooks.ts CHANGED
@@ -17,12 +17,19 @@ export interface AiHookContext {
17
17
  export type PromptSectionProvider = (ctx: AiHookContext) => string | Promise<string>;
18
18
  export type OutputFilter = (text: string, ctx: AiHookContext) => string | null | Promise<string | null>;
19
19
 
20
+ export interface AiAfterReplyContext extends AiHookContext {
21
+ /** 已经发送并写入上下文的最终文本 */
22
+ text: string;
23
+ }
24
+ export type AfterReplyHandler = (ctx: AiAfterReplyContext) => void | Promise<void>;
25
+
20
26
  export class AiHookRegistry {
21
27
  /** 钩子接口版本;外部插件应检查 >= 1 */
22
28
  readonly version = 1;
23
29
 
24
30
  private sections = new Set<PromptSectionProvider>();
25
31
  private filters = new Set<OutputFilter>();
32
+ private afterReplyHandlers = new Set<AfterReplyHandler>();
26
33
 
27
34
  constructor(private logger?: any) {}
28
35
 
@@ -36,6 +43,12 @@ export class AiHookRegistry {
36
43
  return () => this.filters.delete(filter);
37
44
  }
38
45
 
46
+ /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
47
+ registerAfterReply(handler: AfterReplyHandler): () => void {
48
+ this.afterReplyHandlers.add(handler);
49
+ return () => this.afterReplyHandlers.delete(handler);
50
+ }
51
+
39
52
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
40
53
  async collectSections(ctx: AiHookContext): Promise<string[]> {
41
54
  const out: string[] = [];
@@ -64,4 +77,15 @@ export class AiHookRegistry {
64
77
  }
65
78
  return current;
66
79
  }
80
+
81
+ /** 文字回复发送后执行;单个 handler 失败只记日志,不影响其它。 */
82
+ async runAfterReply(ctx: AiAfterReplyContext): Promise<void> {
83
+ for (const handler of this.afterReplyHandlers) {
84
+ try {
85
+ await handler(ctx);
86
+ } catch (error) {
87
+ this.logger?.warn?.(`[ai-hooks] after-reply failed: ${String(error)}`);
88
+ }
89
+ }
90
+ }
67
91
  }
package/src/ai/trigger.ts CHANGED
@@ -16,6 +16,10 @@ export interface TriggerInput {
16
16
  now: number;
17
17
  lastAttemptAt: number;
18
18
  minIntervalMs: number;
19
+ /** 上一次真正发出回复的时间(用于 @ 冷却) */
20
+ lastReplyAt: number;
21
+ /** 被 @ 后两次回复的最小间隔 */
22
+ mentionCooldownMs: number;
19
23
  inFlight: boolean;
20
24
  mention: boolean;
21
25
  followup: boolean;
@@ -31,7 +35,13 @@ export interface TriggerDecision {
31
35
  export function decideTrigger(input: TriggerInput): TriggerDecision {
32
36
  if (input.inFlight) return { fire: false, forced: false, reason: 'in-flight' };
33
37
 
34
- if (input.mention) return { fire: true, forced: true, reason: 'direct-mention' };
38
+ if (input.mention) {
39
+ const cooldown = Math.max(0, Number(input.mentionCooldownMs) || 0);
40
+ if (cooldown > 0 && input.now - (Number(input.lastReplyAt) || 0) < cooldown) {
41
+ return { fire: false, forced: false, reason: 'mention-cooldown' };
42
+ }
43
+ return { fire: true, forced: true, reason: 'direct-mention' };
44
+ }
35
45
  if (input.followup) return { fire: true, forced: true, reason: 'followup' };
36
46
 
37
47
  if (input.minIntervalMs > 0 && input.now - input.lastAttemptAt < input.minIntervalMs) {
package/src/core/text.ts CHANGED
@@ -18,6 +18,10 @@ export interface RenderedQuote {
18
18
  userId: string;
19
19
  name: string;
20
20
  text: string;
21
+ /** 被引用消息里的图片(用于“引用一张图再 @ bot”的场景) */
22
+ images: RenderedImage[];
23
+ /** 被引用消息的 messageId,拿不到图片时可用于 get_msg */
24
+ id: string;
21
25
  }
22
26
 
23
27
  export interface RenderedMessage {
@@ -321,12 +325,31 @@ async function renderQuote(
321
325
  if (!quote) return undefined;
322
326
  const content = String(quote.content ?? '').trim()
323
327
  || (Array.isArray(quote.elements) ? quote.elements.map((el: any) => el?.attrs?.content ?? '').join('') : '');
324
- const text = truncate(stripTags(content), maxChars);
328
+ const images: RenderedImage[] = [];
329
+ const seen = new Set<string>();
330
+ const push = (img: RenderedImage | null) => {
331
+ if (!img) return;
332
+ const key = img.url || img.ref;
333
+ if (!key || seen.has(key)) return;
334
+ seen.add(key);
335
+ images.push(img);
336
+ };
337
+ for (const el of Array.isArray(quote.elements) ? quote.elements : []) {
338
+ const type = String(el?.type ?? '').toLowerCase();
339
+ if (type === 'image' || type === 'img' || type === 'sticker' || type === 'mface') {
340
+ push(imageFromElement(el));
341
+ }
342
+ }
343
+ for (const match of content.matchAll(/\[CQ:image,[^\]]*\]/gi)) push(imageFromCq(match[0]));
344
+ for (const match of content.matchAll(/<img\b[^>]*\/?>/gi)) push(imageFromTag(match[0]));
345
+
346
+ const text = truncate(stripTags(content), maxChars) || (images.length ? '[图片]' : '');
325
347
  if (!text) return undefined;
326
348
  const userId = String(quote.user?.id ?? quote.userId ?? quote.author?.id ?? '');
327
349
  const rawName = quote.user?.name ?? quote.author?.nick ?? quote.author?.name ?? '';
328
350
  const name = String(rawName || (userId ? await resolveName(userId) : '') || '某人');
329
- return { userId, name, text };
351
+ const id = String(quote.id ?? quote.messageId ?? quote.message_id ?? '');
352
+ return { userId, name, text, images, id };
330
353
  }
331
354
 
332
355
  export { truncate, stripTags };
package/src/index.ts CHANGED
@@ -112,7 +112,12 @@ export const Config = Schema.intersect([
112
112
  aiApiKey: Schema.string().role('secret').default('').description('AI 接口密钥(API Key)。'),
113
113
  aiBaseUrl: Schema.string().default('https://api.openai.com/v1').description('接口基础地址(OpenAI 兼容模式需以 /v1 结尾;Gemini 模式可留默认)。'),
114
114
  aiModel: Schema.string().default('gpt-4o-mini').description('模型名称,如 gpt-4o-mini / doubao-1.5-lite / gemini-2.0-flash。'),
115
- aiAgentName: Schema.string().default('MeowBot').description('默认智能体自称。'),
115
+ aiAgentName: Schema.string().default('bot').description('默认智能体自称(可在配置页修改)。'),
116
+ aiMentionCooldownSeconds: Schema.natural().min(0).max(3600).default(5).description('被 @ 后两次回复的最小间隔(秒),防止连续 @ 刷屏。'),
117
+ aiIdleTopicMinutes: Schema.natural().min(0).max(1440).default(120).description('群内无消息多少分钟后主动抛话题;0=关闭。'),
118
+ aiIdleTopicMinHour: Schema.natural().min(0).max(23).default(9).description('主动话题允许的最早小时(0-23)。'),
119
+ aiIdleTopicMaxHour: Schema.natural().min(0).max(24).default(23).description('主动话题允许的最晚小时(不含)。'),
120
+ aiIdleTopicCooldownMinutes: Schema.natural().min(1).max(1440).default(60).description('两次主动话题之间的最小间隔(分钟)。'),
116
121
  aiSystemPrompt: Schema.string().role('textarea').default('你是群聊中的友好机器人,请简洁、自然、符合中文互联网语境地回复。').description('默认系统提示词。'),
117
122
  aiActivePersona: Schema.string().default('').description('启用的人格 ID(为空时使用默认自称与默认提示词)。'),
118
123
  aiPersonas: Schema.array(Schema.object({