@nestim/koishi-plugin-qq-group-manager 1.2.5 → 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/CHANGELOG.md CHANGED
@@ -2,6 +2,24 @@
2
2
 
3
3
  本文件记录所有值得注意的变更。版本号遵循 [语义化版本](https://semver.org/lang/zh-CN/)。
4
4
 
5
+ ## 1.2.6
6
+
7
+ ### 新增
8
+
9
+ - **定时提醒**:支持 `@bot 18:30提醒我吃饭`、`提醒我明天下午3点开会`、`10分钟后提醒我喝水`,
10
+ 也支持 `[bot] 提醒 18:30 吃饭`;到点会在群里 @ 对方。提醒落盘到
11
+ `data/qqgm-reminders.json`,重启不丢;支持 `[bot] 提醒列表`、`[bot] 取消提醒 <id>`。
12
+ - **群空闲话题**:`aiIdleTopicMinutes`(默认 120,0=关闭)、`aiIdleTopicMinHour`、
13
+ `aiIdleTopicMaxHour`、`aiIdleTopicCooldownMinutes`。群内长时间没人说话时主动抛一个话题,
14
+ 只在开启 AI 的群里生效。
15
+ - **被 @ 回复冷却**:`aiMentionCooldownSeconds`(默认 5 秒),连续 @ 不再每条都回。
16
+ - 默认自称改为 `bot`,删除 MeowBot 默认;`aiAgentName` 仍可在配置页修改。
17
+
18
+ ### 修复
19
+
20
+ - **引用图片**:被引用的消息里有图时,图片会解析并送进视觉模型;引用消息只带
21
+ `messageId` 时用 OneBot `get_msg` 回查,不再回“看不到图”。
22
+
5
23
  ## 1.2.5
6
24
 
7
25
  ### 新增
@@ -21,6 +21,7 @@ export interface AiHost {
21
21
  getOneBotApi(session: any): any;
22
22
  toGroupId(session: any): number | null;
23
23
  extractImages(session: any): RenderedImage[];
24
+ fetchQuotedImages?(session: any, quote: any): Promise<RenderedImage[]>;
24
25
  resolveImage(ref: string, session: any): Promise<string>;
25
26
  sendReply(session: any, text: string): Promise<void>;
26
27
  readMemoryFile(): Promise<string>;
@@ -69,6 +70,8 @@ export declare class AiEngine {
69
70
  handle(session: any): Promise<void>;
70
71
  /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
71
72
  chat(request: any): Promise<ChatResult>;
73
+ /** 群内长时间没人说话时,生成一条主动话题。 */
74
+ idleTopic(groupId: string): Promise<string>;
72
75
  private recentImageRecords;
73
76
  private collectImages;
74
77
  private judge;
package/lib/ai/engine.js CHANGED
@@ -100,7 +100,7 @@ class AiEngine {
100
100
  }
101
101
  get selfName() {
102
102
  const persona = this.activePersona();
103
- return String(persona?.selfName || this.config.aiAgentName || 'MeowBot').trim() || 'MeowBot';
103
+ return String(persona?.selfName || this.config.aiAgentName || 'bot').trim() || 'bot';
104
104
  }
105
105
  activePersona() {
106
106
  const id = String(this.config.aiActivePersona ?? '').trim();
@@ -369,6 +369,8 @@ class AiEngine {
369
369
  now: this.now(),
370
370
  lastAttemptAt: state.lastAttemptAt,
371
371
  minIntervalMs: Math.max(0, Number(this.config.aiMinReplyIntervalSeconds ?? 45)) * 1000,
372
+ lastReplyAt: state.lastReplyAt || 0,
373
+ mentionCooldownMs: Math.max(0, Number(this.config.aiMentionCooldownSeconds ?? 5)) * 1000,
372
374
  inFlight: state.inFlight,
373
375
  mention,
374
376
  followup,
@@ -503,6 +505,35 @@ class AiEngine {
503
505
  chat(request) {
504
506
  return this.provider.chat(request);
505
507
  }
508
+ /** 群内长时间没人说话时,生成一条主动话题。 */
509
+ async idleTopic(groupId) {
510
+ const session = { guildId: groupId, isDirect: false, platform: 'onebot' };
511
+ let sections = [];
512
+ try {
513
+ sections = await this.hooks.collectSections({ session, groupId, mode: 'reply' });
514
+ }
515
+ catch { /* ignore */ }
516
+ const system = [
517
+ `你是 QQ 群 ${groupId} 里的一个普通成员。`,
518
+ '群里已经很久没人说话了。主动抛一个轻松、具体、能接话的话题,一句话。',
519
+ '不要问“在吗”,不要提“很久没人说话”,不要自我介绍。',
520
+ ...sections,
521
+ ].join('\n');
522
+ const result = await this.provider.chat({
523
+ system,
524
+ user: '现在发一条主动话题。',
525
+ temperature: Number(this.config.aiTemperature ?? 0.8),
526
+ maxTokens: Math.min(300, Number(this.config.aiMaxOutputTokens ?? 400)),
527
+ });
528
+ if (!result.ok || !result.text)
529
+ return '';
530
+ const raw = String(result.text).trim();
531
+ if (!raw || PASS_RE.test(raw))
532
+ return '';
533
+ return clipReply(cleanReply(raw, this.selfName), this.maxReplyChars)
534
+ .replace(/\[表情[::][^\]]*\]/g, '')
535
+ .trim();
536
+ }
506
537
  recentImageRecords(state, record, maxAgeMs = 120000) {
507
538
  const cutoff = Number(record.at) - maxAgeMs;
508
539
  const candidates = state.records
@@ -529,7 +560,13 @@ class AiEngine {
529
560
  const own = record.images.length ? record.images : this.host.extractImages(session);
530
561
  // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
531
562
  const fallback = own.length ? [] : this.recentImageRecords(state, record);
532
- const quoted = record.quote ? this.host.extractImages(session?.quote) : [];
563
+ let quoted = record.quote
564
+ ? (record.quote.images?.length ? record.quote.images : this.host.extractImages(session?.quote))
565
+ : [];
566
+ // 引用消息里没解析到图(常见于 quote 只带 messageId):用 get_msg 回查一次
567
+ if (!quoted.length && record.quote?.id && typeof this.host.fetchQuotedImages === 'function') {
568
+ quoted = await this.host.fetchQuotedImages(session, record.quote);
569
+ }
533
570
  const items = (0, vision_1.pickImages)([...own, ...fallback], quoted, maxCount);
534
571
  if (!items.length)
535
572
  return [];
@@ -15,6 +15,10 @@ export interface TriggerInput {
15
15
  now: number;
16
16
  lastAttemptAt: number;
17
17
  minIntervalMs: number;
18
+ /** 上一次真正发出回复的时间(用于 @ 冷却) */
19
+ lastReplyAt: number;
20
+ /** 被 @ 后两次回复的最小间隔 */
21
+ mentionCooldownMs: number;
18
22
  inFlight: boolean;
19
23
  mention: boolean;
20
24
  followup: boolean;
package/lib/ai/trigger.js CHANGED
@@ -13,8 +13,13 @@ exports.decideTrigger = decideTrigger;
13
13
  function decideTrigger(input) {
14
14
  if (input.inFlight)
15
15
  return { fire: false, forced: false, reason: 'in-flight' };
16
- if (input.mention)
16
+ if (input.mention) {
17
+ const cooldown = Math.max(0, Number(input.mentionCooldownMs) || 0);
18
+ if (cooldown > 0 && input.now - (Number(input.lastReplyAt) || 0) < cooldown) {
19
+ return { fire: false, forced: false, reason: 'mention-cooldown' };
20
+ }
17
21
  return { fire: true, forced: true, reason: 'direct-mention' };
22
+ }
18
23
  if (input.followup)
19
24
  return { fire: true, forced: true, reason: 'followup' };
20
25
  if (input.minIntervalMs > 0 && input.now - input.lastAttemptAt < input.minIntervalMs) {
@@ -15,6 +15,10 @@ export interface RenderedQuote {
15
15
  userId: string;
16
16
  name: string;
17
17
  text: string;
18
+ /** 被引用消息里的图片(用于“引用一张图再 @ bot”的场景) */
19
+ images: RenderedImage[];
20
+ /** 被引用消息的 messageId,拿不到图片时可用于 get_msg */
21
+ id: string;
18
22
  }
19
23
  export interface RenderedMessage {
20
24
  /** 已渲染的正文(含 @名字 / [图片] 等占位) */
package/lib/core/text.js CHANGED
@@ -274,11 +274,33 @@ async function renderQuote(quote, resolveName, maxChars) {
274
274
  return undefined;
275
275
  const content = String(quote.content ?? '').trim()
276
276
  || (Array.isArray(quote.elements) ? quote.elements.map((el) => el?.attrs?.content ?? '').join('') : '');
277
- const text = truncate(stripTags(content), maxChars);
277
+ const images = [];
278
+ const seen = new Set();
279
+ const push = (img) => {
280
+ if (!img)
281
+ return;
282
+ const key = img.url || img.ref;
283
+ if (!key || seen.has(key))
284
+ return;
285
+ seen.add(key);
286
+ images.push(img);
287
+ };
288
+ for (const el of Array.isArray(quote.elements) ? quote.elements : []) {
289
+ const type = String(el?.type ?? '').toLowerCase();
290
+ if (type === 'image' || type === 'img' || type === 'sticker' || type === 'mface') {
291
+ push(imageFromElement(el));
292
+ }
293
+ }
294
+ for (const match of content.matchAll(/\[CQ:image,[^\]]*\]/gi))
295
+ push(imageFromCq(match[0]));
296
+ for (const match of content.matchAll(/<img\b[^>]*\/?>/gi))
297
+ push(imageFromTag(match[0]));
298
+ const text = truncate(stripTags(content), maxChars) || (images.length ? '[图片]' : '');
278
299
  if (!text)
279
300
  return undefined;
280
301
  const userId = String(quote.user?.id ?? quote.userId ?? quote.author?.id ?? '');
281
302
  const rawName = quote.user?.name ?? quote.author?.nick ?? quote.author?.name ?? '';
282
303
  const name = String(rawName || (userId ? await resolveName(userId) : '') || '某人');
283
- return { userId, name, text };
304
+ const id = String(quote.id ?? quote.messageId ?? quote.message_id ?? '');
305
+ return { userId, name, text, images, id };
284
306
  }
package/lib/index.d.ts CHANGED
@@ -124,6 +124,11 @@ export declare const Config: Schema<Schemastery.ObjectS<{
124
124
  aiBaseUrl: Schema<string, string>;
125
125
  aiModel: Schema<string, string>;
126
126
  aiAgentName: Schema<string, string>;
127
+ aiMentionCooldownSeconds: Schema<number, number>;
128
+ aiIdleTopicMinutes: Schema<number, number>;
129
+ aiIdleTopicMinHour: Schema<number, number>;
130
+ aiIdleTopicMaxHour: Schema<number, number>;
131
+ aiIdleTopicCooldownMinutes: Schema<number, number>;
127
132
  aiSystemPrompt: Schema<string, string>;
128
133
  aiActivePersona: Schema<string, string>;
129
134
  aiPersonas: Schema<Schemastery.ObjectS<{
@@ -264,6 +269,11 @@ export declare const Config: Schema<Schemastery.ObjectS<{
264
269
  aiBaseUrl: string;
265
270
  aiModel: string;
266
271
  aiAgentName: string;
272
+ aiMentionCooldownSeconds: number;
273
+ aiIdleTopicMinutes: number;
274
+ aiIdleTopicMinHour: number;
275
+ aiIdleTopicMaxHour: number;
276
+ aiIdleTopicCooldownMinutes: number;
267
277
  aiSystemPrompt: string;
268
278
  aiActivePersona: string;
269
279
  aiPersonas: Schemastery.ObjectT<{
package/lib/index.js CHANGED
@@ -115,7 +115,12 @@ exports.Config = koishi_1.Schema.intersect([
115
115
  aiApiKey: koishi_1.Schema.string().role('secret').default('').description('AI 接口密钥(API Key)。'),
116
116
  aiBaseUrl: koishi_1.Schema.string().default('https://api.openai.com/v1').description('接口基础地址(OpenAI 兼容模式需以 /v1 结尾;Gemini 模式可留默认)。'),
117
117
  aiModel: koishi_1.Schema.string().default('gpt-4o-mini').description('模型名称,如 gpt-4o-mini / doubao-1.5-lite / gemini-2.0-flash。'),
118
- aiAgentName: koishi_1.Schema.string().default('MeowBot').description('默认智能体自称。'),
118
+ aiAgentName: koishi_1.Schema.string().default('bot').description('默认智能体自称(可在配置页修改)。'),
119
+ aiMentionCooldownSeconds: koishi_1.Schema.natural().min(0).max(3600).default(5).description('被 @ 后两次回复的最小间隔(秒),防止连续 @ 刷屏。'),
120
+ aiIdleTopicMinutes: koishi_1.Schema.natural().min(0).max(1440).default(120).description('群内无消息多少分钟后主动抛话题;0=关闭。'),
121
+ aiIdleTopicMinHour: koishi_1.Schema.natural().min(0).max(23).default(9).description('主动话题允许的最早小时(0-23)。'),
122
+ aiIdleTopicMaxHour: koishi_1.Schema.natural().min(0).max(24).default(23).description('主动话题允许的最晚小时(不含)。'),
123
+ aiIdleTopicCooldownMinutes: koishi_1.Schema.natural().min(1).max(1440).default(60).description('两次主动话题之间的最小间隔(分钟)。'),
119
124
  aiSystemPrompt: koishi_1.Schema.string().role('textarea').default('你是群聊中的友好机器人,请简洁、自然、符合中文互联网语境地回复。').description('默认系统提示词。'),
120
125
  aiActivePersona: koishi_1.Schema.string().default('').description('启用的人格 ID(为空时使用默认自称与默认提示词)。'),
121
126
  aiPersonas: koishi_1.Schema.array(koishi_1.Schema.object({
package/lib/service.d.ts CHANGED
@@ -56,6 +56,14 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
56
56
  pendingJoinRequestFlags: Map<any, any>;
57
57
  violationRecords: Map<any, any>;
58
58
  _imageDataUrlCache: Map<any, any>;
59
+ /** 定时提醒:id -> reminder */
60
+ _reminders: Map<any, any>;
61
+ /** 定时提醒:id -> timer */
62
+ _reminderTimers: Map<any, any>;
63
+ /** 群空闲话题:groupId -> timer */
64
+ _idleTimers: Map<any, any>;
65
+ /** 上次主动话题时间:groupId -> ts */
66
+ _lastIdleTopicAt: Map<any, any>;
59
67
  /** 记忆库写锁:串行化「读整档→改→整写」,防止并发写互相覆盖 */
60
68
  _memoryWriteLock: Promise<void>;
61
69
  /** 待审入群申请的落盘去抖定时器 */
@@ -110,6 +118,22 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
110
118
  ai: AiEngine;
111
119
  /** 外部插件扩展点:提示词风格段 + 输出过滤(接口版本见 AiHookRegistry.version) */
112
120
  get aiHooks(): import("./ai/hooks").AiHookRegistry;
121
+ reminderFilePath(): any;
122
+ loadReminders(): void;
123
+ saveReminders(): void;
124
+ clearReminderTimer(id: any): void;
125
+ scheduleReminder(reminder: any): void;
126
+ fireReminder(id: any): Promise<void>;
127
+ addReminder(reminder: any): void;
128
+ formatReminderTime(at: any): string;
129
+ sendReminderList(session: any): Promise<void>;
130
+ cancelReminder(session: any, id: any): Promise<void>;
131
+ handleReminderCommand(session: any, rest: any): Promise<boolean>;
132
+ handleReminderRequest(session: any): Promise<boolean>;
133
+ touchIdleTopic(session: any): void;
134
+ fireIdleTopic(groupId: any): Promise<void>;
135
+ sendGroupText(groupId: any, text: any): Promise<void>;
136
+ disposeSchedulers(): void;
113
137
  isPlatformAllowed(platform: any): any;
114
138
  sessionTag(session: any): string;
115
139
  styleText(text: any): any;
@@ -291,6 +315,8 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
291
315
  getOneBotApi(session: any): any;
292
316
  /** 供 AI 引擎抽取图片结构 */
293
317
  extractImages(session: any): any[];
318
+ /** 引用消息只带 messageId 时,用 OneBot get_msg 回查图片 */
319
+ fetchQuotedImages(session: any, quote: any): Promise<any[]>;
294
320
  /** 供 AI 引擎把图片引用转成 data URL */
295
321
  resolveImage(ref: any, session: any): Promise<any>;
296
322
  /** AI 回复发送:优先引用触发消息,失败则退化为纯文本 */
@@ -577,5 +603,10 @@ export class QQGroupManagerService extends koishi_1.Service<any, koishi_1.Contex
577
603
  message: string;
578
604
  }>;
579
605
  }
606
+ /** 解析“提醒/定时”文本;返回 { at, content } 或 null。纯函数,便于测试。 */
607
+ export function parseReminderText(rawText: any, now?: number): {
608
+ at: number;
609
+ content: string;
610
+ };
580
611
  import koishi_1 = require("koishi");
581
612
  import { AiEngine } from "./ai/engine";
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
  /** 待审入群申请的落盘去抖定时器 */
@@ -226,11 +301,249 @@ class QQGroupManagerService extends koishi_1.Service {
226
301
  catch (error) {
227
302
  this._logger.warn(`[join-review] 恢复待审单失败: ${String(error)}`);
228
303
  }
304
+ try {
305
+ this.loadReminders();
306
+ }
307
+ catch (error) {
308
+ this._logger.warn(`[reminder] 恢复待审提醒失败: ${String(error)}`);
309
+ }
310
+ ctx.on('dispose', () => this.disposeSchedulers());
229
311
  }
230
312
  /** 外部插件扩展点:提示词风格段 + 输出过滤(接口版本见 AiHookRegistry.version) */
231
313
  get aiHooks() {
232
314
  return this.ai ? this.ai.hooks : null;
233
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
+ }
234
547
  isPlatformAllowed(platform) {
235
548
  if (!platform)
236
549
  return false;
@@ -1704,6 +2017,42 @@ class QQGroupManagerService extends koishi_1.Service {
1704
2017
  extractImages(session) {
1705
2018
  return this.extractImageElements(session);
1706
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
+ }
1707
2056
  /** 供 AI 引擎把图片引用转成 data URL */
1708
2057
  resolveImage(ref, session) {
1709
2058
  return this.resolveImageReferenceToDataUrl(ref, session);
@@ -2267,6 +2616,8 @@ class QQGroupManagerService extends koishi_1.Service {
2267
2616
  await this.sendCommandMenu(session);
2268
2617
  return true;
2269
2618
  }
2619
+ if (await this.handleReminderCommand(session, rest))
2620
+ return true;
2270
2621
  return false;
2271
2622
  }
2272
2623
  if (name === this.cmdPrefix('cmdMute', '[mute]'))
@@ -2698,6 +3049,8 @@ class QQGroupManagerService extends koishi_1.Service {
2698
3049
  async handleGroupModeration(session) {
2699
3050
  if (!this.isPlatformAllowed(session.platform))
2700
3051
  return;
3052
+ if (session.guildId)
3053
+ this.touchIdleTopic(session);
2701
3054
  // AI 上下文先记录:被管控/被指令拦截的消息也要进上下文(指令类由引擎自行忽略)
2702
3055
  try {
2703
3056
  await this.ai.record(session);
@@ -2780,6 +3133,8 @@ class QQGroupManagerService extends koishi_1.Service {
2780
3133
  catch (error) {
2781
3134
  this._logger.warn(`[repeater] failed: ${String(error)} | ${this.sessionTag(session)}`);
2782
3135
  }
3136
+ if (await this.handleReminderRequest(session))
3137
+ return;
2783
3138
  await this.ai.handle(session);
2784
3139
  }
2785
3140
  /**
@@ -3336,3 +3691,4 @@ class QQGroupManagerService extends koishi_1.Service {
3336
3691
  }
3337
3692
  }
3338
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.5",
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,
@@ -542,6 +545,33 @@ export class AiEngine {
542
545
  return this.provider.chat(request);
543
546
  }
544
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
+
545
575
  private recentImageRecords(state: GroupState, record: ChatRecord, maxAgeMs = 120000): RenderedImage[] {
546
576
  const cutoff = Number(record.at) - maxAgeMs;
547
577
  const candidates = state.records
@@ -569,7 +599,13 @@ export class AiEngine {
569
599
  const own = record.images.length ? record.images : this.host.extractImages(session);
570
600
  // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
571
601
  const fallback = own.length ? [] : this.recentImageRecords(state, record);
572
- 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
+ }
573
609
  const items = pickImages([...own, ...fallback], quoted, maxCount);
574
610
  if (!items.length) return [];
575
611
 
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({
package/src/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
  /** 待审入群申请的落盘去抖定时器 */
@@ -227,11 +302,249 @@ class QQGroupManagerService extends koishi_1.Service {
227
302
  catch (error) {
228
303
  this._logger.warn(`[join-review] 恢复待审单失败: ${String(error)}`);
229
304
  }
305
+ try {
306
+ this.loadReminders();
307
+ }
308
+ catch (error) {
309
+ this._logger.warn(`[reminder] 恢复待审提醒失败: ${String(error)}`);
310
+ }
311
+ ctx.on('dispose', () => this.disposeSchedulers());
230
312
  }
231
313
  /** 外部插件扩展点:提示词风格段 + 输出过滤(接口版本见 AiHookRegistry.version) */
232
314
  get aiHooks() {
233
315
  return this.ai ? this.ai.hooks : null;
234
316
  }
317
+ reminderFilePath() {
318
+ const base = (this.ctx && this.ctx.baseDir) || process.cwd();
319
+ return node_path_1.default.join(base, 'data', 'qqgm-reminders.json');
320
+ }
321
+ loadReminders() {
322
+ const file = this.reminderFilePath();
323
+ if (!node_fs_1.default.existsSync(file))
324
+ return;
325
+ const list = JSON.parse(node_fs_1.default.readFileSync(file, 'utf8'));
326
+ if (!Array.isArray(list))
327
+ return;
328
+ for (const item of list) {
329
+ if (!item || !item.id || !item.groupId || !item.userId || !Number.isFinite(Number(item.at)))
330
+ continue;
331
+ this._reminders.set(item.id, item);
332
+ this.scheduleReminder(item);
333
+ }
334
+ this._logger.info(`[reminder] 恢复 ${this._reminders.size} 条待提醒`);
335
+ }
336
+ saveReminders() {
337
+ try {
338
+ const file = this.reminderFilePath();
339
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(file), { recursive: true });
340
+ node_fs_1.default.writeFileSync(file, JSON.stringify([...this._reminders.values()], null, 2));
341
+ }
342
+ catch (error) {
343
+ this._logger.warn(`[reminder] 保存失败: ${String(error)}`);
344
+ }
345
+ }
346
+ clearReminderTimer(id) {
347
+ const timer = this._reminderTimers.get(id);
348
+ if (timer)
349
+ clearTimeout(timer);
350
+ this._reminderTimers.delete(id);
351
+ }
352
+ scheduleReminder(reminder) {
353
+ this.clearReminderTimer(reminder.id);
354
+ const delay = Math.max(0, Number(reminder.at) - Date.now());
355
+ const max = 2147483647;
356
+ const timer = setTimeout(() => {
357
+ if (delay > max) {
358
+ this.scheduleReminder(reminder);
359
+ return;
360
+ }
361
+ this.fireReminder(reminder.id).catch((error) => this._logger.warn(`[reminder] 触发失败 ${reminder.id}: ${String(error)}`));
362
+ }, Math.min(delay, max));
363
+ timer.unref?.();
364
+ this._reminderTimers.set(reminder.id, timer);
365
+ }
366
+ async fireReminder(id) {
367
+ const reminder = this._reminders.get(id);
368
+ if (!reminder)
369
+ return;
370
+ this._reminders.delete(id);
371
+ this.clearReminderTimer(id);
372
+ this.saveReminders();
373
+ const bots = this.ctx?.bots || [];
374
+ const bot = bots.find((b) => b.platform === 'onebot' && b.status !== 'offline')
375
+ || bots.find((b) => b.platform === 'onebot')
376
+ || bots[0];
377
+ if (!bot) {
378
+ this._logger.warn(`[reminder] 没有可用 bot,跳过 ${id}`);
379
+ return;
380
+ }
381
+ try {
382
+ await bot.sendMessage(reminder.groupId, [koishi_1.h.at(reminder.userId), koishi_1.h.text(` ${reminder.text}`)], reminder.groupId);
383
+ this._logger.info(`[reminder] sent ${id} group=${reminder.groupId} user=${reminder.userId}`);
384
+ }
385
+ catch (error) {
386
+ this._logger.warn(`[reminder] 发送失败 ${id}: ${String(error)}`);
387
+ }
388
+ }
389
+ addReminder(reminder) {
390
+ this._reminders.set(reminder.id, reminder);
391
+ this.saveReminders();
392
+ this.scheduleReminder(reminder);
393
+ }
394
+ formatReminderTime(at) {
395
+ const date = new Date(at);
396
+ const now = new Date();
397
+ const pad = (n) => String(n).padStart(2, '0');
398
+ const day = date.toDateString() === now.toDateString()
399
+ ? '今天'
400
+ : (new Date(now.getTime() + 86400000).toDateString() === date.toDateString()
401
+ ? '明天'
402
+ : `${date.getMonth() + 1}月${date.getDate()}日`);
403
+ return `${day} ${pad(date.getHours())}:${pad(date.getMinutes())}`;
404
+ }
405
+ async sendReminderList(session) {
406
+ const userId = String(session.userId || '');
407
+ const items = [...this._reminders.values()]
408
+ .filter((item) => item.userId === userId)
409
+ .sort((a, b) => a.at - b.at);
410
+ if (!items.length) {
411
+ await this.sendReply(session, '你还没有定时提醒');
412
+ return;
413
+ }
414
+ const lines = items.slice(0, 10).map((item, index) => `${index + 1}. ${this.formatReminderTime(item.at)} ${item.text}`);
415
+ await this.sendReply(session, lines.join('\n'));
416
+ }
417
+ async cancelReminder(session, id) {
418
+ const key = String(id || '').trim();
419
+ const reminder = this._reminders.get(key);
420
+ if (!reminder || reminder.userId !== String(session.userId || '')) {
421
+ await this.sendReply(session, '没找到这条提醒');
422
+ return;
423
+ }
424
+ this._reminders.delete(key);
425
+ this.clearReminderTimer(key);
426
+ this.saveReminders();
427
+ await this.sendReply(session, `已取消:${reminder.text}`);
428
+ }
429
+ async handleReminderCommand(session, rest) {
430
+ const cmd = String(rest || '').trim();
431
+ if (!cmd)
432
+ return false;
433
+ if (/^(提醒|定时)列表$/.test(cmd)) {
434
+ await this.sendReminderList(session);
435
+ return true;
436
+ }
437
+ const cancel = cmd.match(/^(?:取消提醒|取消定时)\s+(\S+)$/);
438
+ if (cancel) {
439
+ await this.cancelReminder(session, cancel[1]);
440
+ return true;
441
+ }
442
+ if (!/^(提醒|定时)\s+/.test(cmd))
443
+ return false;
444
+ const parsed = parseReminderText(cmd, Date.now());
445
+ if (!parsed)
446
+ return false;
447
+ const reminder = {
448
+ id: `r${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
449
+ groupId: String(session.guildId || session.channelId || ''),
450
+ userId: String(session.userId || ''),
451
+ at: parsed.at,
452
+ text: parsed.content,
453
+ createdAt: Date.now(),
454
+ };
455
+ this.addReminder(reminder);
456
+ const confirmation = `好,${this.formatReminderTime(parsed.at)} 提醒你:${parsed.content}`;
457
+ await this.sendReply(session, confirmation);
458
+ try {
459
+ this.ai.recordSelf(session, confirmation);
460
+ }
461
+ catch { /* ignore */ }
462
+ return true;
463
+ }
464
+ async handleReminderRequest(session) {
465
+ if (!session.guildId)
466
+ return false;
467
+ const text = this.extractTextForFilter(session);
468
+ if (!/(提醒|定时|叫我)/.test(text))
469
+ return false;
470
+ const selfId = String(session.bot?.selfId || '');
471
+ const rawContent = String(session.content || '');
472
+ const atBot = !!selfId && new RegExp(`<at\\b[^>]*(?:id|qq)=["']?${selfId}`).test(rawContent);
473
+ if (!atBot && !/^\s*(?:提醒|定时|叫我)/.test(text) && !/^\s*\[bot\]/i.test(rawContent))
474
+ return false;
475
+ const parsed = parseReminderText(text, Date.now());
476
+ if (!parsed)
477
+ return false;
478
+ const reminder = {
479
+ id: `r${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`,
480
+ groupId: String(session.guildId),
481
+ userId: String(session.userId || ''),
482
+ at: parsed.at,
483
+ text: parsed.content,
484
+ createdAt: Date.now(),
485
+ };
486
+ this.addReminder(reminder);
487
+ const confirmation = `好,${this.formatReminderTime(parsed.at)} 提醒你:${parsed.content}`;
488
+ await this.sendReply(session, confirmation);
489
+ try {
490
+ this.ai.recordSelf(session, confirmation);
491
+ }
492
+ catch { /* ignore */ }
493
+ return true;
494
+ }
495
+ touchIdleTopic(session) {
496
+ const groupId = String(session?.guildId || '');
497
+ const minutes = Number(this.config?.aiIdleTopicMinutes ?? 0);
498
+ if (!groupId || !minutes)
499
+ return;
500
+ try {
501
+ if (!this.ai.resolveEnabled(session))
502
+ return;
503
+ }
504
+ catch { /* ignore */ }
505
+ const old = this._idleTimers.get(groupId);
506
+ if (old)
507
+ clearTimeout(old);
508
+ const timer = setTimeout(() => {
509
+ this.fireIdleTopic(groupId).catch((error) => this._logger.warn(`[idle] ${String(error)}`));
510
+ }, minutes * 60000);
511
+ timer.unref?.();
512
+ this._idleTimers.set(groupId, timer);
513
+ }
514
+ async fireIdleTopic(groupId) {
515
+ this._idleTimers.delete(groupId);
516
+ const hour = new Date().getHours();
517
+ const min = Number(this.config?.aiIdleTopicMinHour ?? 9);
518
+ const max = Number(this.config?.aiIdleTopicMaxHour ?? 23);
519
+ if (hour < min || hour >= max)
520
+ return;
521
+ const cooldown = Math.max(1, Number(this.config?.aiIdleTopicCooldownMinutes ?? 60)) * 60000;
522
+ if (Date.now() - (this._lastIdleTopicAt.get(groupId) || 0) < cooldown)
523
+ return;
524
+ const text = await this.ai.idleTopic(groupId);
525
+ if (!text)
526
+ return;
527
+ await this.sendGroupText(groupId, text);
528
+ this._lastIdleTopicAt.set(groupId, Date.now());
529
+ this._logger.info(`[idle] topic sent group=${groupId} chars=${text.length}`);
530
+ }
531
+ async sendGroupText(groupId, text) {
532
+ const bots = this.ctx?.bots || [];
533
+ const bot = bots.find((b) => b.platform === 'onebot' && b.status !== 'offline')
534
+ || bots.find((b) => b.platform === 'onebot')
535
+ || bots[0];
536
+ if (!bot)
537
+ return;
538
+ await bot.sendMessage(groupId, koishi_1.h.text(text), groupId);
539
+ }
540
+ disposeSchedulers() {
541
+ for (const timer of this._reminderTimers.values())
542
+ clearTimeout(timer);
543
+ for (const timer of this._idleTimers.values())
544
+ clearTimeout(timer);
545
+ this._reminderTimers.clear();
546
+ this._idleTimers.clear();
547
+ }
235
548
  isPlatformAllowed(platform) {
236
549
  if (!platform)
237
550
  return false;
@@ -1704,6 +2017,42 @@ class QQGroupManagerService extends koishi_1.Service {
1704
2017
  extractImages(session) {
1705
2018
  return this.extractImageElements(session);
1706
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
+ }
1707
2056
  /** 供 AI 引擎把图片引用转成 data URL */
1708
2057
  resolveImage(ref, session) {
1709
2058
  return this.resolveImageReferenceToDataUrl(ref, session);
@@ -2274,6 +2623,8 @@ class QQGroupManagerService extends koishi_1.Service {
2274
2623
  await this.sendCommandMenu(session);
2275
2624
  return true;
2276
2625
  }
2626
+ if (await this.handleReminderCommand(session, rest))
2627
+ return true;
2277
2628
  return false;
2278
2629
  }
2279
2630
  if (name === this.cmdPrefix('cmdMute', '[mute]'))
@@ -2714,6 +3065,8 @@ class QQGroupManagerService extends koishi_1.Service {
2714
3065
  async handleGroupModeration(session) {
2715
3066
  if (!this.isPlatformAllowed(session.platform))
2716
3067
  return;
3068
+ if (session.guildId)
3069
+ this.touchIdleTopic(session);
2717
3070
  // AI 上下文先记录:被管控/被指令拦截的消息也要进上下文(指令类由引擎自行忽略)
2718
3071
  try {
2719
3072
  await this.ai.record(session);
@@ -2796,6 +3149,8 @@ class QQGroupManagerService extends koishi_1.Service {
2796
3149
  catch (error) {
2797
3150
  this._logger.warn(`[repeater] failed: ${String(error)} | ${this.sessionTag(session)}`);
2798
3151
  }
3152
+ if (await this.handleReminderRequest(session))
3153
+ return;
2799
3154
  await this.ai.handle(session);
2800
3155
  }
2801
3156
  /**
@@ -3352,3 +3707,4 @@ class QQGroupManagerService extends koishi_1.Service {
3352
3707
  }
3353
3708
  }
3354
3709
  exports.QQGroupManagerService = QQGroupManagerService;
3710
+ exports.parseReminderText = parseReminderText;