@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/CHANGELOG.md CHANGED
@@ -2,6 +2,33 @@
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
+
23
+ ## 1.2.5
24
+
25
+ ### 新增
26
+
27
+ - **`aiHooks.registerAfterReply`**:文字回复发送并写入上下文后触发,参数带最终文本。
28
+ 用于追加表情包等“文字之后”的动作,保证先文字、后图片。
29
+ - **root 暴露 `qqgmAiRuntime`**:`{ config, hooks, chat }`。私聊等外部插件可以复用
30
+ 同一个模型 provider 与同一套 style/meme 扩展点,不必重复配置 API Key。
31
+
5
32
  ## 1.2.4
6
33
 
7
34
  ### 修复
@@ -12,7 +12,7 @@
12
12
  * - 允许模型用 <pass/> 主动放弃,放弃也重置计数,避免每条消息都空转调用。
13
13
  */
14
14
  import { AiState, ChatRecord } from './state';
15
- import { ChatProvider } from './provider';
15
+ import { ChatProvider, ChatResult } from './provider';
16
16
  import { RenderedImage } from '../core/text';
17
17
  import { AiHookRegistry } from './hooks';
18
18
  export interface AiHost {
@@ -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>;
@@ -67,6 +68,10 @@ export declare class AiEngine {
67
68
  private getFollowup;
68
69
  private loadMemories;
69
70
  handle(session: any): Promise<void>;
71
+ /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
72
+ chat(request: any): Promise<ChatResult>;
73
+ /** 群内长时间没人说话时,生成一条主动话题。 */
74
+ idleTopic(groupId: string): Promise<string>;
70
75
  private recentImageRecords;
71
76
  private collectImages;
72
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,
@@ -486,6 +488,7 @@ class AiEngine {
486
488
  chars: finalText.length,
487
489
  preview: finalText.slice(0, 60),
488
490
  }, session);
491
+ await this.hooks.runAfterReply({ ...hookCtx, text: finalText });
489
492
  }
490
493
  catch (error) {
491
494
  this.log('ai-reply', {
@@ -498,6 +501,39 @@ class AiEngine {
498
501
  state.inFlight = false;
499
502
  }
500
503
  }
504
+ /** 供外部插件(如私聊插件)复用同一个模型 provider。 */
505
+ chat(request) {
506
+ return this.provider.chat(request);
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
+ }
501
537
  recentImageRecords(state, record, maxAgeMs = 120000) {
502
538
  const cutoff = Number(record.at) - maxAgeMs;
503
539
  const candidates = state.records
@@ -524,7 +560,13 @@ class AiEngine {
524
560
  const own = record.images.length ? record.images : this.host.extractImages(session);
525
561
  // 用户常见的“先发图,再单独 @ 一句”:当前消息没有图,回看同一用户最近 2 分钟内的图
526
562
  const fallback = own.length ? [] : this.recentImageRecords(state, record);
527
- 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
+ }
528
570
  const items = (0, vision_1.pickImages)([...own, ...fallback], quoted, maxCount);
529
571
  if (!items.length)
530
572
  return [];
package/lib/ai/hooks.d.ts CHANGED
@@ -14,17 +14,27 @@ export interface AiHookContext {
14
14
  }
15
15
  export type PromptSectionProvider = (ctx: AiHookContext) => string | Promise<string>;
16
16
  export type OutputFilter = (text: string, ctx: AiHookContext) => string | null | Promise<string | null>;
17
+ export interface AiAfterReplyContext extends AiHookContext {
18
+ /** 已经发送并写入上下文的最终文本 */
19
+ text: string;
20
+ }
21
+ export type AfterReplyHandler = (ctx: AiAfterReplyContext) => void | Promise<void>;
17
22
  export declare class AiHookRegistry {
18
23
  private logger?;
19
24
  /** 钩子接口版本;外部插件应检查 >= 1 */
20
25
  readonly version = 1;
21
26
  private sections;
22
27
  private filters;
28
+ private afterReplyHandlers;
23
29
  constructor(logger?: any);
24
30
  registerPromptSection(provider: PromptSectionProvider): () => void;
25
31
  registerOutputFilter(filter: OutputFilter): () => void;
32
+ /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
33
+ registerAfterReply(handler: AfterReplyHandler): () => void;
26
34
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
27
35
  collectSections(ctx: AiHookContext): Promise<string[]>;
28
36
  /** 依次执行输出过滤器;返回 null 表示丢弃本条回复。 */
29
37
  applyFilters(text: string, ctx: AiHookContext): Promise<string | null>;
38
+ /** 文字回复发送后执行;单个 handler 失败只记日志,不影响其它。 */
39
+ runAfterReply(ctx: AiAfterReplyContext): Promise<void>;
30
40
  }
package/lib/ai/hooks.js CHANGED
@@ -16,6 +16,7 @@ class AiHookRegistry {
16
16
  version = 1;
17
17
  sections = new Set();
18
18
  filters = new Set();
19
+ afterReplyHandlers = new Set();
19
20
  constructor(logger) {
20
21
  this.logger = logger;
21
22
  }
@@ -27,6 +28,11 @@ class AiHookRegistry {
27
28
  this.filters.add(filter);
28
29
  return () => this.filters.delete(filter);
29
30
  }
31
+ /** 文字回复已发送后触发;用于追加表情包等后续动作。 */
32
+ registerAfterReply(handler) {
33
+ this.afterReplyHandlers.add(handler);
34
+ return () => this.afterReplyHandlers.delete(handler);
35
+ }
30
36
  /** 汇总所有风格段;单个 provider 失败只记日志,不影响其它。 */
31
37
  async collectSections(ctx) {
32
38
  const out = [];
@@ -58,5 +64,16 @@ class AiHookRegistry {
58
64
  }
59
65
  return current;
60
66
  }
67
+ /** 文字回复发送后执行;单个 handler 失败只记日志,不影响其它。 */
68
+ async runAfterReply(ctx) {
69
+ for (const handler of this.afterReplyHandlers) {
70
+ try {
71
+ await handler(ctx);
72
+ }
73
+ catch (error) {
74
+ this.logger?.warn?.(`[ai-hooks] after-reply failed: ${String(error)}`);
75
+ }
76
+ }
77
+ }
61
78
  }
62
79
  exports.AiHookRegistry = AiHookRegistry;
@@ -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";