koishi-plugin-group-analysis-mx 1.8.2 → 1.9.0

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.
@@ -624,6 +624,9 @@ class AnalysisService extends koishi_1.Service {
624
624
  const recordId = (0, utils_1.buildPersonaRecordId)(session.platform, session.selfId, userId);
625
625
  let avatar;
626
626
  let user;
627
+ // 优先使用消息事件缓存下来的群昵称/头像(QQ 官方新事件已提供)
628
+ const memberProfile = this.ctx.group_analysis_message?.getMemberProfile?.(
629
+ session.guildId || session.channelId, userId);
627
630
  try {
628
631
  user = await bot.getGuildMember(session.channelId || session.guildId, userId);
629
632
  }
@@ -635,7 +638,8 @@ class AnalysisService extends koishi_1.Service {
635
638
  platform: session.platform,
636
639
  selfId: session.selfId,
637
640
  userId,
638
- username: user?.nick || user?.name || user?.user?.name || userId
641
+ username: memberProfile?.nickname ||
642
+ user?.nick || user?.name || user?.user?.name || userId
639
643
  });
640
644
  let displayName = cache.record.username;
641
645
  const cacheExpired = (0, utils_1.isCacheExpiredByDays)(cache.record.lastAnalysisAt, this.config.personaCacheLifetimeDays);
@@ -662,6 +666,13 @@ class AnalysisService extends koishi_1.Service {
662
666
  cache.pendingMessages = 0;
663
667
  }
664
668
  const profile = cache.parsedPersona;
669
+ if (memberProfile?.nickname) {
670
+ displayName = memberProfile.nickname;
671
+ cache.record.username = memberProfile.nickname;
672
+ }
673
+ if (memberProfile?.avatar) {
674
+ avatar = memberProfile.avatar;
675
+ }
665
676
  if (user) {
666
677
  // Koishi Universal.GuildMember 结构:{ user: { id, name, avatar }, name, ... }
667
678
  avatar = user.avatar || user.user?.avatar;
@@ -708,7 +719,13 @@ class AnalysisService extends koishi_1.Service {
708
719
  await session.send(message);
709
720
  }
710
721
  async resolveGroupNickname(bot, guildId, userId) {
711
- if (!bot?.getGuildMember || !guildId || !userId)
722
+ if (!guildId || !userId)
723
+ return null;
724
+ // 优先用消息事件里带的群昵称(QQ 官方新事件已提供 member_nickname)
725
+ const cachedProfile = this.ctx.group_analysis_message?.getMemberProfile?.(guildId, String(userId));
726
+ if (cachedProfile?.nickname)
727
+ return cachedProfile.nickname;
728
+ if (!bot?.getGuildMember)
712
729
  return null;
713
730
  const key = `${bot.selfId}:${guildId}:${userId}`;
714
731
  const cached = this._groupNicknameCache.get(key);
@@ -719,7 +736,8 @@ class AnalysisService extends koishi_1.Service {
719
736
  }
720
737
  try {
721
738
  const info = await bot.getGuildMember(guildId, userId);
722
- const name = (info?.name || info?.user?.name || '').trim();
739
+ // 新接口/适配器可能提供群内昵称字段,优先于个人昵称
740
+ const name = (info?.member_nickname || info?.memberNickname || info?.name || info?.user?.name || '').trim();
723
741
  this._groupNicknameCache.set(key, {
724
742
  name: name || null,
725
743
  expireAt: Date.now() + (name ? 3600_000 : 60_000)
@@ -866,12 +884,11 @@ class AnalysisService extends koishi_1.Service {
866
884
  this.ctx.logger.error('金句分析失败:', quotesResult.reason);
867
885
  // Final statistics
868
886
  const sortedUsers = users.sort((a, b) => b.messageCount - a.messageCount);
869
- // 群名片解析:官方 QQ bot 消息作者名是"个人昵称",群名片需通过 getGuildMember 获取。
870
- // 只对活跃的 top 用户调用,且带缓存避免重复请求。
871
887
  const botForAvatar = this._getBot(selfId);
872
888
  const guildIdForNick = target?.guildId;
873
889
  const groupNicknameMap = new Map();
874
- if (botForAvatar?.getGuildMember && guildIdForNick) {
890
+ // 群名片解析:优先用消息事件自带的群昵称,其次回退 getGuildMember
891
+ if (guildIdForNick) {
875
892
  const topUsers = sortedUsers.slice(0, Math.max(this.config.maxUsersInReport * 2, 20));
876
893
  await Promise.all(topUsers.map(async (u) => {
877
894
  const gname = await this.resolveGroupNickname(botForAvatar, guildIdForNick, String(u.userId));
@@ -7,6 +7,8 @@ const cqcode_1 = require("../onebot/cqcode");
7
7
  class MessageService extends koishi_1.Service {
8
8
  config;
9
9
  messageCache = new Map();
10
+ /** QQ 官方事件带来的成员资料缓存(群昵称/头像),key = guildId:userId */
11
+ memberProfiles = new Map();
10
12
  cacheSize = 1000;
11
13
  cacheExpiration = 1000 * 60 * 24; // 1 days
12
14
  messageHandlers = [];
@@ -28,6 +30,19 @@ class MessageService extends koishi_1.Service {
28
30
  onUserMessage(handler) {
29
31
  this.messageHandlers.push(handler);
30
32
  }
33
+ /**
34
+ * 读取事件中缓存的群成员资料(群昵称/头像)。
35
+ * QQ 官方 bot 获取群成员信息的接口常受权限限制,这里优先用消息事件自带的字段。
36
+ */
37
+ getMemberProfile(guildId, userId) {
38
+ if (!guildId || !userId)
39
+ return null;
40
+ const profile = this.memberProfiles.get(`${guildId}:${userId}`);
41
+ if (!profile)
42
+ return null;
43
+ // 缓存 6 小时,过期后仍可作为弱兜底返回,但标记 stale
44
+ return { ...profile, stale: Date.now() - profile.updatedAt > 6 * 60 * 60 * 1000 };
45
+ }
31
46
  setupDatabase() {
32
47
  this.ctx.database.extend('group_analysis_messages', {
33
48
  id: 'string',
@@ -66,6 +81,16 @@ class MessageService extends koishi_1.Service {
66
81
  }
67
82
  async handleMessage(session) {
68
83
  // 黑名单只限制用户画像(见 handleIncomingMessageForPersona),消息本身仍需入库供群分析统计
84
+ // QQ 官方机器人新事件直接带群昵称和头像,先缓存(即使该条消息因无文字被跳过,资料也应留存)
85
+ const qqMember = (0, utils_1.extractQQGroupMember)(session);
86
+ if (qqMember && (qqMember.nickname || qqMember.avatar)) {
87
+ const scope = session.guildId || session.channelId || '0';
88
+ this.memberProfiles.set(`${scope}:${qqMember.userId || session.userId}`, {
89
+ nickname: qqMember.nickname || '',
90
+ avatar: qqMember.avatar || '',
91
+ updatedAt: Date.now()
92
+ });
93
+ }
69
94
  // 清洗掉官方 bot 的原始表情/协议标签,只保留正常文字
70
95
  const cleanContent = (0, utils_1.cleanContent)(session.content);
71
96
  // 腾讯官方 bot 的签名等非聊天垃圾内容,不记录
@@ -84,9 +109,13 @@ class MessageService extends koishi_1.Service {
84
109
  channelId: session.channelId || '0',
85
110
  guildId: session.guildId || '0',
86
111
  userId: session.userId,
87
- avatarUrl: session.event.user?.avatar || '',
112
+ avatarUrl: (qqMember && qqMember.avatar) || session.event.user?.avatar || '',
88
113
  // 用户昵称可能存在事件缺失(如官方 QQ bot 作者未返回 username),做多级兜底
89
- username: session.username || session.event?.user?.name || session.userId || '未知用户',
114
+ username: (qqMember && qqMember.nickname) ||
115
+ session.username ||
116
+ session.event?.user?.name ||
117
+ session.userId ||
118
+ '未知用户',
90
119
  content: cleanContent,
91
120
  timestamp: new Date(session.timestamp),
92
121
  messageId: session.messageId
package/lib/utils.js CHANGED
@@ -27,6 +27,7 @@ exports.isCacheExpiredByMinutes = isCacheExpiredByMinutes;
27
27
  exports.buildGroupAnalysisCacheKey = buildGroupAnalysisCacheKey;
28
28
  exports.buildMessagePersistenceKey = buildMessagePersistenceKey;
29
29
  exports.isNapCatBot = isNapCatBot;
30
+ exports.extractQQGroupMember = extractQQGroupMember;
30
31
  exports.isJunkMessage = isJunkMessage;
31
32
  exports.isForwardedChatRecord = isForwardedChatRecord;
32
33
  exports.cleanContent = cleanContent;
@@ -373,6 +374,38 @@ async function isNapCatBot(bot) {
373
374
  const name = versionInfo.data['app_name'].toLowerCase();
374
375
  return { isRunningNapCat: name.includes('napcat'), botAppName: name };
375
376
  }
377
+ /**
378
+ * 从 QQ 官方机器人原始事件中提取发送者资料。
379
+ * 2026-10 起官方在群消息事件里新增 author.member_nickname(群内昵称)与 author.avatar,
380
+ * 这两项比 username(个人昵称)和 openid 头像模板更准确,优先使用。
381
+ * 原始 payload 由 Koishi QQ 适配器保存在 session.event._data。
382
+ */
383
+ function extractQQGroupMember(session) {
384
+ if (!session || session.platform !== 'qq')
385
+ return null;
386
+ const raw = session.event?._data;
387
+ // 适配器有两种形态:内部事件 _data 直接是事件体,消息会话 _data 是 { op, t, d } 派发载荷
388
+ const payload = raw && typeof raw === 'object' && raw.d && typeof raw.d === 'object' ? raw.d : raw;
389
+ const author = payload?.author;
390
+ if (!author || typeof author !== 'object')
391
+ return null;
392
+ const memberNickname = String(author.member_nickname || '').trim();
393
+ const username = String(author.username || '').trim();
394
+ const avatar = String(author.avatar || '').trim();
395
+ const memberOpenid = String(author.member_openid || author.id || '').trim();
396
+ const unionGroupOpenid = String(payload?.union_group_openid || '').trim();
397
+ if (!memberNickname && !username && !avatar)
398
+ return null;
399
+ return {
400
+ userId: memberOpenid,
401
+ // 群内昵称优先,其次个人昵称
402
+ nickname: memberNickname || username || '',
403
+ username,
404
+ memberNickname,
405
+ avatar,
406
+ unionGroupOpenid
407
+ };
408
+ }
376
409
  /**
377
410
  * 判断消息是否为 QQ“合并转发/聊天记录”卡片。
378
411
  * 官方适配器没有解析 102 类型的聊天记录,只把卡片预览文字当成普通文本,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-group-analysis-mx",
3
3
  "description": "群聊分析插件 - 生成精美群聊统计报告,支持 AI 话题总结(独立版,不依赖 ChatLuna)",
4
- "version": "1.8.2",
4
+ "version": "1.9.0",
5
5
  "main": "lib/index.js",
6
6
  "module": "lib/index.mjs",
7
7
  "typings": "lib/index.d.ts",
@@ -66,4 +66,5 @@
66
66
 
67
67
 
68
68
 
69
+
69
70