@nestim/koishi-plugin-qq-group-manager 1.2.5 → 1.2.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/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}. [${item.id}] ${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;