qq-bot-roost 1.1.1 → 1.1.3

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.
@@ -20,6 +20,7 @@ import { syncNickname } from '../services/nickname.js';
20
20
  import { INTENTS, INTENT_META, EVENTS } from '../events.js';
21
21
  import { CHANNEL_DAILY_ACTIVE } from '../outbound.js';
22
22
  import { registerMedia } from './media.js';
23
+ import { splitQuery } from '../search-query.js';
23
24
  import { registerOps } from './ops.js';
24
25
  import { registerDev } from './dev.js';
25
26
  import { sendOut, receivedAtOf, isChatKind, CHAT_KINDS } from './dispatch.js';
@@ -267,6 +268,157 @@ export function createMethods({ runtime: R, getState, log = () => {}, extBridge
267
268
  });
268
269
  });
269
270
 
271
+ /**
272
+ * 围绕某条消息的前后文(按 `seq`)。
273
+ *
274
+ * 模型搜到一条之后想看「当时到底怎么聊的」,但它手里只有 `seq`——
275
+ * 所以先用 `bySeq` 定位这条(拿到 chatId),再取邻文。等价于面板上
276
+ * 「点一条看上下文」。
277
+ *
278
+ * **`anchor` 会一起返回**:宿主侧要靠 `anchor.userId` 判「非特权用户是不是
279
+ * 在翻别人的对话」——这个判断不能只在框架里做一半,因为「谁能看谁」是
280
+ * 会话身份的事,只有宿主知道。
281
+ */
282
+ def('ledger.around', 'read', '取某条消息的前后文(按 seq)', async (p) => {
283
+ if (!R.ledger) throw notReady('账本未就绪');
284
+ const seq = Math.max(1, Number(p.seq) || 0);
285
+ if (!seq) throw bad('要给 seq(搜索结果里每条都带)');
286
+
287
+ const anchor = R.ledger.bySeq?.(seq) ?? null;
288
+ if (!anchor) throw bad(`账本里没有 seq=${seq} 这条记录`);
289
+
290
+ /**
291
+ * `before` / `after`:缺省或非法(负数、NaN)都退默认 3;`0` 是合法值
292
+ * (表示「只要后面 / 只要前面」),上限 20。
293
+ */
294
+ const clampAround = (v, dft = 3) => {
295
+ const n = Number(v);
296
+ if (!Number.isFinite(n) || n < 0) return dft;
297
+ return Math.min(20, Math.floor(n));
298
+ };
299
+ const before = clampAround(p.before);
300
+ const after = clampAround(p.after);
301
+ const items = R.ledger.timeline?.({
302
+ chatId: anchor.chatId,
303
+ anchorSeq: seq,
304
+ before,
305
+ after,
306
+ }) ?? [];
307
+
308
+ return {
309
+ anchor: {
310
+ seq: anchor.seq,
311
+ chatId: anchor.chatId,
312
+ kind: anchor.kind,
313
+ userId: anchor.userId,
314
+ at: anchor.at,
315
+ },
316
+ items,
317
+ };
318
+ });
319
+
320
+ /**
321
+ * 跨会话搜索账本。
322
+ *
323
+ * 宿主(dsh-roost)拿它给模型做「翻以前说过什么」——这是**唯一**能让模型
324
+ * 接触到任意历史消息的口子,所以两件事必须在这里做对:
325
+ *
326
+ * · 参数一律白名单化:`terms` 最多 8 个、`openids` 最多 20 个、`limit` 封顶 200;
327
+ * · **权限不在这里判**。host 协议是本地受信进程(token + read scope),
328
+ * 它天然能读全库;「一个人只能查自己」是**宿主侧**按会话里的发送者身份
329
+ * 收窄的(见 dsh-roost 的 `search-scope.js`)。这里如果也判一遍,
330
+ * 就会变成「两个地方各有一套规则」,迟早分叉。
331
+ *
332
+ * `person` 容三种输入(openid / QQ号 / 昵称),解析口径与面板一致:
333
+ * QQ 号只有绑定过才反查得到 openid,没绑过就当昵称去碰运气。
334
+ */
335
+ def('ledger.search', 'read', '跨会话搜索账本(关键词 / 发言人 / 类型 / 时间)', async (p) => {
336
+ if (!R.ledger) throw notReady('账本未就绪');
337
+
338
+ const terms = (Array.isArray(p.terms) ? p.terms : [])
339
+ .map((x) => str(x).trim())
340
+ .filter(Boolean)
341
+ .slice(0, 8);
342
+ /** 只给了 `q`(一整句)时用同一套词法拆:剥疑问词、单字丢弃 */
343
+ const q = str(p.q).trim();
344
+ const finalTerms = terms.length ? terms : splitQuery(q);
345
+
346
+ const openids = (Array.isArray(p.openids) ? p.openids : [])
347
+ .map((x) => str(x).trim())
348
+ .filter(Boolean)
349
+ .slice(0, 20);
350
+ let name = str(p.name).trim();
351
+
352
+ const person = str(p.person).trim();
353
+ if (person) {
354
+ if (/^[0-9A-Za-z_-]{16,}$/.test(person) && /[A-Za-z]/.test(person)) {
355
+ openids.push(person);
356
+ } else if (/^\d{5,12}$/.test(person)) {
357
+ const opid = R.identity?.openidOf?.(R.id, person) ?? '';
358
+ if (opid) openids.push(String(opid));
359
+ else name = person;
360
+ } else {
361
+ name = person;
362
+ }
363
+ }
364
+
365
+ const kind = str(p.kind).trim();
366
+ /** 只支持单会话精确匹配:多会话由宿主各查一次再合并,别在这里做笛卡尔积 */
367
+ const chatId = str(p.chatId).trim();
368
+ const since = Math.max(0, Number(p.since) || 0);
369
+ const beforeSeq = Math.max(0, Number(p.beforeSeq) || 0);
370
+ const limit = Math.max(1, Math.min(200, Number(p.limit) || 20));
371
+
372
+ /**
373
+ * 只给了「什么 / 怎么 / 吗」这类词时,拆完一个关键词都不剩。
374
+ *
375
+ * 这时候**不能**当成「没有关键词」去跑:SQL 里只剩 `bot_id = ?`,
376
+ * 返回的是最新 N 条,模型会以为「搜到了」——面板上已经踩过这个坑。
377
+ * 直接回空列表 + 说明。
378
+ */
379
+ if (q && !finalTerms.length && !openids.length && !name && !kind && !chatId) {
380
+ return {
381
+ items: [],
382
+ terms: [],
383
+ relaxed: false,
384
+ hasMore: false,
385
+ note: '关键词里没有可检索的内容(全是疑问词/语气词),换个实义词试试',
386
+ };
387
+ }
388
+
389
+ const base = {
390
+ terms: finalTerms,
391
+ openids,
392
+ name,
393
+ kind,
394
+ since,
395
+ beforeSeq,
396
+ limit,
397
+ withPeople: true,
398
+ };
399
+
400
+ const run = (extra) => R.ledger.search({ ...base, ...extra });
401
+
402
+ let rows = run({ chatId, mode: 'and' });
403
+ let relaxed = false;
404
+ /** 多词全中 0 条时放宽成任一命中,和面板同一条策略 */
405
+ if (!rows.length && finalTerms.length > 1) {
406
+ rows = run({ chatId, mode: 'or' });
407
+ relaxed = rows.length > 0;
408
+ }
409
+
410
+ return {
411
+ items: rows.map((r) => ({
412
+ ...r,
413
+ openid: String(r.userId ?? ''),
414
+ chatName: r.kind === 'group' ? String(R.groupName?.(r.chatId) ?? '') : '',
415
+ })),
416
+ terms: finalTerms,
417
+ relaxed,
418
+ hasMore: rows.length >= limit,
419
+ };
420
+ });
421
+
270
422
  /* ---------------- 官方 API 全量透传 ---------------- */
271
423
 
272
424
  def('qq.methods', 'read', '列出 qq.call 可透传的方法、风险档与所需 scope', async () => ({
@@ -565,6 +717,34 @@ export function createMethods({ runtime: R, getState, log = () => {}, extBridge
565
717
  return out;
566
718
  };
567
719
 
720
+ /**
721
+ * 最近在这个机器人这儿说过话的人(内存索引)。
722
+ *
723
+ * 为什么需要:群成员资料本应「公开」,但官方 `getUserInfo` 要求**好友关系**
724
+ * (非好友回 `40184001`),而群成员绝大多数不是好友——只看官方接口的话,
725
+ * 「刚才那位是谁」永远查不到。`recentPeople` 是框架在每条消息上攒下来的
726
+ * (昵称 / 群名片 / 头像 / QQ号),正好补这个洞。
727
+ *
728
+ * 只读、只含「说过话的人」、不落盘:重启后为空,有人说话又会填上。
729
+ */
730
+ def('people.list', 'read', '最近说过话的人(昵称/群名片/头像/QQ号),给宿主认人用', async (p) => {
731
+ const limit = Math.min(Math.max(Number(p.limit) || 200, 1), 200);
732
+ const list = R.listRecentPeople ? R.listRecentPeople(limit) : [];
733
+ return {
734
+ people: (Array.isArray(list) ? list : []).map((x) => ({
735
+ openid: str(x.openid),
736
+ name: str(x.name),
737
+ card: str(x.card),
738
+ nickname: str(x.nickname),
739
+ avatar: str(x.avatar),
740
+ uin: str(x.uin),
741
+ unionOpenid: str(x.unionOpenid),
742
+ scope: str(x.scope),
743
+ at: Number(x.at) || 0,
744
+ })),
745
+ };
746
+ });
747
+
568
748
  def('group.info', 'read', '群信息 + 机器人在群里的角色 + 能不能管(没内邀也能读公开信息)', async (p) => {
569
749
  if (!R.api) throw notReady('官方接口未就绪');
570
750
  const groupOpenid = str(p.groupOpenid).trim();
@@ -581,7 +761,17 @@ export function createMethods({ runtime: R, getState, log = () => {}, extBridge
581
761
  return {
582
762
  groupOpenid,
583
763
  name: str(info?.group_name ?? info?.name),
584
- memberCount: Number(info?.member_count ?? info?.max_member_count) || 0,
764
+ /**
765
+ * 官方字段是 `group_member_num`(2026-11-16 文档)。
766
+ * 以前这里读 `member_count` / `max_member_count`——两个都不存在,
767
+ * 所以群人数**恒为 0**:面板和模型问「这个群多少人」永远答 0,
768
+ * 不报错、也不缺字段,属于最难发现的那种错。
769
+ */
770
+ memberCount: Number(info?.group_member_num ?? info?.member_count ?? 0) || 0,
771
+ /** 简介 / 分类 / 标签:2026-11-16 起群信息接口才给,用来回答「这是个什么群」 */
772
+ memo: str(info?.group_finger_memo),
773
+ classText: str(info?.group_class_text),
774
+ tags: Array.isArray(info?.group_tags) ? info.group_tags.map(String).filter(Boolean) : [],
585
775
  role: manage.role ?? null,
586
776
  canManage: manage.ok === true,
587
777
  manageReason: str(manage.reason),
package/src/host/ops.js CHANGED
@@ -18,6 +18,8 @@
18
18
  import fs from 'node:fs/promises';
19
19
  import path from 'node:path';
20
20
  import { DIRS } from '../paths.js';
21
+ /** 二维码:扫码登录和面板画「资料卡链接」共用同一套实现,不各写一份 */
22
+ import { toSvg as qrToSvg } from '../qq/qrsvg.js';
21
23
  import { saveBotConfig } from '../config.js';
22
24
  import { FILE_TYPE } from '../api.js';
23
25
  import {
@@ -188,6 +190,20 @@ export function registerOps(def, { R, err, log = () => {} }) {
188
190
  stats: R.delivery?.stats?.() ?? { available: false },
189
191
  }));
190
192
 
193
+ /**
194
+ * 把一段短文本画成二维码 SVG。
195
+ *
196
+ * 只在服务端画:前端(DSH 插件)只有一个 client.js 入口,塞 QR 库既占体积
197
+ * 又要改加载方式。`src/qq/qrsvg.js` 本来就在给扫码登录用,这里把它暴露出来,
198
+ * 面板画「机器人资料卡链接」就不用再实现一遍。
199
+ */
200
+ def('qr.svg', 'read', '把一段短文本画成二维码 SVG(登录码、资料卡链接共用一套实现)', async (p) => {
201
+ const text = str(p.text).trim();
202
+ if (!text) throw err.bad('要给 text');
203
+ if (text.length > 300) throw err.bad('文本太长(最多 300 字)');
204
+ return { svg: qrToSvg(text) };
205
+ }),
206
+
191
207
  def('roles.resolve', 'read', '算发送者权限档位 bucket/level/role(ai-chat senderInfo 等价)', async (p) => {
192
208
  const userId = str(p.userId).trim();
193
209
  if (!userId) throw err.bad('要给 userId(openid)');
@@ -33,6 +33,11 @@ export function serializeMessage(msg, { groupName = '' } = {}) {
33
33
  groupUin: msg.groupUin ?? '',
34
34
  groupIdentityId: msg.groupIdentityId ?? '',
35
35
  groupAliases: Array.isArray(msg.groupAliases) ? msg.groupAliases : [],
36
+ /**
37
+ * 官方 2026-11-16 新加的跨应用群标识,**只透传**。它换不出对方机器人的
38
+ * openid,发消息只认 `groupId`;跨机器人关联走 identity 的群号绑定。
39
+ */
40
+ unionGroupId: msg.unionGroupId ?? '',
36
41
  name: groupName,
37
42
  },
38
43
  sender: {
@@ -40,7 +45,17 @@ export function serializeMessage(msg, { groupName = '' } = {}) {
40
45
  uin: msg.uin ?? '',
41
46
  identityId: msg.identityId ?? '',
42
47
  aliases: Array.isArray(msg.userAliases) ? msg.userAliases : [],
48
+ /**
49
+ * 显示名(群聊取群内昵称)。`nickname` / `card` 两个原始值也带上:
50
+ * 客户端要「群名片」和「QQ 昵称」分开显示时,用 name 是分不出来的。
51
+ */
43
52
  name: msg.userName ?? '',
53
+ nickname: msg.userNickname ?? '',
54
+ card: msg.userCard ?? '',
55
+ /** 头像原图 URL;官方没给就是空串(别拼默认头像,那是猜) */
56
+ avatar: msg.userAvatar ?? '',
57
+ /** 跨应用统一用户 id,绑了 3 方应用才有 */
58
+ unionOpenid: msg.unionUserId ?? '',
44
59
  isBot: msg.raw?.author?.bot === true,
45
60
  },
46
61
  msgId: msg.id ?? '',
package/src/ledger.js CHANGED
@@ -41,6 +41,21 @@ import { probeSqlite, openDatabase } from './storage/db.js';
41
41
  import { migrateEvents } from './storage/events-schema.js';
42
42
  import { SENSITIVE_KEY } from './runtime.js';
43
43
 
44
+ /**
45
+ * 账本行的固定列。
46
+ *
47
+ * `payload` 不在里面:那是整包报文,面板列表不需要。要发言人头像/昵称时
48
+ * 单独用 `AUTHOR_COLS` 把它用 `json_extract` 拆成三列——一页 50 条每条
49
+ * 几十 KB 的报文全都读上来太浪费。
50
+ */
51
+ const EVENT_COLS = 'seq, id, kind, chat_id, user_id, user_name, content, at, time_basis, msg_idx, quoted, trace, plugin, bot_id';
52
+
53
+ /** 从 `payload.author` 里取的三个展示字段(昵称 / 群名片 / 头像) */
54
+ const AUTHOR_COLS = `,
55
+ json_extract(payload, '$.author.avatar') AS author_avatar,
56
+ json_extract(payload, '$.author.member_nickname') AS author_card,
57
+ json_extract(payload, '$.author.username') AS author_nickname`;
58
+
44
59
  const log = createLogger('ledger');
45
60
 
46
61
  /** 每次滚动删最多删多少行。分批是为了不长时间锁库,收消息会卡 */
@@ -457,26 +472,191 @@ export class EventLedger {
457
472
  return this.db.prepare('SELECT * FROM events WHERE id = ?').get(String(id ?? '')) ?? null;
458
473
  }
459
474
 
460
- /** 某会话最近的若干条,按时间正序返回 */
461
- recent({ chatId, limit = 50, beforeSeq } = {}) {
475
+ /**
476
+ * 按 `seq` 取一条(带发言人字段)。
477
+ *
478
+ * 为什么需要它:模型搜到一条之后想看「前后还说了什么」,但 `timeline()`
479
+ * 要 `chatId`,而模型手里只有 `seq`。先按 seq 定位这条,才能知道它在哪个
480
+ * 会话里,再去取邻文。
481
+ *
482
+ * @param {number} seq
483
+ * @returns {object|null}
484
+ */
485
+ bySeq(seq) {
486
+ if (!this.available || this.closed || !this.db) return null;
487
+ const n = Number(seq) || 0;
488
+ if (n <= 0) return null;
489
+ try {
490
+ const r = this.db
491
+ .prepare(`SELECT ${EVENT_COLS}${AUTHOR_COLS} FROM events WHERE bot_id = ? AND seq = ?`)
492
+ .get(this.botId, n);
493
+ return r ? { ...mapRow(r), ...authorFieldsOf(r) } : null;
494
+ } catch {
495
+ return null;
496
+ }
497
+ }
498
+
499
+ /**
500
+ * 这个会话里**最近一个有名字的发言人**(`user_name` 非空)。
501
+ *
502
+ * 面板会话列表要显示人名而不是 openid。不能直接取「最近一条」——机器人自己
503
+ * 的回复(出站)没有 `user_name`,一段对话的最后一条往往就是出站,取到的是空串。
504
+ * 所以按 `seq` 倒序找第一条有名字的。
505
+ *
506
+ * @param {string} chatId 会话 openid(私聊就是对方 openid)
507
+ * @returns {string} 没有就空串
508
+ */
509
+ lastNameOf(chatId) {
510
+ if (!this.available || this.closed || !chatId) return '';
511
+ try {
512
+ const row = this.db
513
+ .prepare(
514
+ `SELECT user_name FROM events
515
+ WHERE bot_id = ? AND chat_id = ? AND user_name IS NOT NULL AND user_name != ''
516
+ ORDER BY seq DESC LIMIT 1`,
517
+ )
518
+ .get(this.botId, String(chatId));
519
+ return String(row?.user_name ?? '');
520
+ } catch {
521
+ return '';
522
+ }
523
+ }
524
+
525
+ /**
526
+ * 某会话最近的若干条,按时间正序返回。
527
+ *
528
+ * @param {object} p
529
+ * @param {string} p.chatId
530
+ * @param {number} [p.limit]
531
+ * @param {number} [p.beforeSeq]
532
+ * @param {boolean} [p.withPeople] 带上发言人的头像 / QQ 昵称 / 群昵称
533
+ * (面板账本要显示「谁说的」,只有 `user_name` 分不出群名片和 QQ 昵称)
534
+ */
535
+ recent({ chatId, limit = 50, beforeSeq, withPeople = false } = {}) {
462
536
  if (!this.available || this.closed || !chatId) return [];
463
537
  const lim = Math.min(Math.max(Number(limit) || 50, 1), 500);
538
+ const people = withPeople ? AUTHOR_COLS : '';
464
539
  const rows = beforeSeq
465
540
  ? this.db
466
541
  .prepare(
467
- `SELECT seq, id, kind, chat_id, user_id, user_name, content, at, time_basis, msg_idx, quoted, trace, plugin, bot_id
542
+ `SELECT ${EVENT_COLS}${people}
468
543
  FROM events WHERE bot_id = ? AND chat_id = ? AND seq < ?
469
544
  ORDER BY seq DESC LIMIT ?`,
470
545
  )
471
546
  .all(this.botId, String(chatId), Number(beforeSeq), lim)
472
547
  : this.db
473
548
  .prepare(
474
- `SELECT seq, id, kind, chat_id, user_id, user_name, content, at, time_basis, msg_idx, quoted, trace, plugin, bot_id
549
+ `SELECT ${EVENT_COLS}${people}
475
550
  FROM events WHERE bot_id = ? AND chat_id = ?
476
551
  ORDER BY seq DESC LIMIT ?`,
477
552
  )
478
553
  .all(this.botId, String(chatId), lim);
479
- return rows.reverse().map(mapRow);
554
+
555
+ return rows.reverse().map((r) => {
556
+ const row = mapRow(r);
557
+ if (!withPeople) return row;
558
+ return { ...row, ...authorFieldsOf(r) };
559
+ });
560
+ }
561
+
562
+ /**
563
+ * 全局查询:按关键词 / 发言人 / 类型 / 时间筛账本。
564
+ *
565
+ * 「发言人」这一维要容三类输入:openid(精确)、QQ 号(server 层先反查成
566
+ * openid 列表)、昵称(模糊)。所以这里收的是**已经解析好的** `openids` +
567
+ * `name`,解析(尤其 QQ 号反查绑定)放在 server 层,这边只管拼 SQL。
568
+ *
569
+ * 排序是 `seq DESC`(最新在前):查询场景是「找最近提到某事的那次」,
570
+ * 和账本页「按时间往下读」正好相反,所以**不 reverse**。
571
+ *
572
+ * @param {object} p
573
+ * @param {string[]} [p.terms] 正文关键词(`splitQuery` 拆好的词)
574
+ * @param {'and'|'or'} [p.mode] 多个词是「全都要有」还是「任一」(先 and,空了再 or)
575
+ * @param {string[]} [p.openids] 发言人 openid(精确,多个是 OR)
576
+ * @param {string} [p.name] 发言人昵称(模糊)
577
+ * @param {string} [p.chatId] 限定会话(精确)
578
+ * @param {string} [p.kind] group / c2c / guild / dm
579
+ * @param {number} [p.since] 起始时间(毫秒)
580
+ * @param {number} [p.beforeSeq] 翻页游标(上一页最后一条的 seq)
581
+ * @param {number} [p.limit]
582
+ * @param {boolean} [p.withPeople]
583
+ */
584
+ search({
585
+ terms = [], mode = 'and', openids = [], name = '', chatId = '', kind = '',
586
+ since = 0, beforeSeq = 0, limit = 50, withPeople = true,
587
+ } = {}) {
588
+ if (!this.available || this.closed || !this.db) return [];
589
+ const lim = Math.min(Math.max(Number(limit) || 50, 1), 200);
590
+ const where = ['bot_id = ?'];
591
+ const args = [this.botId];
592
+
593
+ /** LIKE 里的 `%` `_` 要转义,否则用户搜「100%」会变成「匹配一切」 */
594
+ const like = (s) => `%${String(s).replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
595
+
596
+ const list = (Array.isArray(terms) ? terms : [])
597
+ .map((t) => String(t ?? '').trim())
598
+ .filter(Boolean)
599
+ .slice(0, 8);
600
+ if (list.length) {
601
+ const cls = list.map(() => "content LIKE ? ESCAPE '\\'");
602
+ where.push(`(${cls.join(mode === 'or' ? ' OR ' : ' AND ')})`);
603
+ args.push(...list.map(like));
604
+ }
605
+
606
+ const room = String(chatId ?? '').trim();
607
+ if (room) {
608
+ where.push('chat_id = ?');
609
+ args.push(room);
610
+ }
611
+
612
+ const k = String(kind ?? '').trim();
613
+ if (k) {
614
+ where.push('kind = ?');
615
+ args.push(k);
616
+ }
617
+
618
+ const from = Number(since) || 0;
619
+ if (from > 0) {
620
+ where.push('at >= ?');
621
+ args.push(from);
622
+ }
623
+
624
+ const ids = [...new Set((Array.isArray(openids) ? openids : []).map((x) => String(x ?? '').trim()).filter(Boolean))];
625
+ const nm = String(name ?? '').trim();
626
+ if (ids.length) {
627
+ const ph = ids.map(() => '?').join(',');
628
+ if (nm) {
629
+ where.push(`(user_id IN (${ph}) OR user_name LIKE ? ESCAPE '\\')`);
630
+ args.push(...ids, like(nm));
631
+ } else {
632
+ where.push(`user_id IN (${ph})`);
633
+ args.push(...ids);
634
+ }
635
+ } else if (nm) {
636
+ where.push("user_name LIKE ? ESCAPE '\\'");
637
+ args.push(like(nm));
638
+ }
639
+
640
+ const cursor = Number(beforeSeq) || 0;
641
+ if (cursor > 0) {
642
+ where.push('seq < ?');
643
+ args.push(cursor);
644
+ }
645
+
646
+ const people = withPeople ? AUTHOR_COLS : '';
647
+ try {
648
+ const rows = this.db
649
+ .prepare(`SELECT ${EVENT_COLS}${people} FROM events WHERE ${where.join(' AND ')} ORDER BY seq DESC LIMIT ?`)
650
+ .all(...args, lim);
651
+ return rows.map((r) => {
652
+ const row = mapRow(r);
653
+ if (!withPeople) return row;
654
+ return { ...row, ...authorFieldsOf(r) };
655
+ });
656
+ } catch (e) {
657
+ log.warn(`账本查询失败:${e.message}`);
658
+ return [];
659
+ }
480
660
  }
481
661
 
482
662
  /**
@@ -938,6 +1118,23 @@ function mapRow(r) {
938
1118
  };
939
1119
  }
940
1120
 
1121
+ /**
1122
+ * 把 `AUTHOR_COLS` 查出来的三列摊成展示字段。
1123
+ *
1124
+ * 老账本 / 出站行没有 `author`(`json_extract` 返回 NULL),一律给空串——
1125
+ * 前端据此回退到 `user_name`,不会拿到 undefined。
1126
+ */
1127
+ function authorFieldsOf(r) {
1128
+ return {
1129
+ /** 头像原图 URL;前端自己换小尺寸,不受这里的 s=640 影响 */
1130
+ avatar: String(r?.author_avatar ?? ''),
1131
+ /** 群名片 / 群内昵称 */
1132
+ card: String(r?.author_card ?? ''),
1133
+ /** QQ 昵称 */
1134
+ nickname: String(r?.author_nickname ?? ''),
1135
+ };
1136
+ }
1137
+
941
1138
  /**
942
1139
  * @param {object} p
943
1140
  * @param {string} p.file
package/src/message.js CHANGED
@@ -52,6 +52,42 @@ function stripMention(content) {
52
52
  .trim();
53
53
  }
54
54
 
55
+ /**
56
+ * 说话人昵称 / 头像的取值。
57
+ *
58
+ * 2026-11-16 官方补齐了事件里的昵称与头像:
59
+ * · 单聊:`author.username` 以前经常是空串,现在稳定下发
60
+ * · 群聊:新增 `author.member_nickname`(**群内昵称**,和 QQ 昵称不是一回事)
61
+ * · 两种场景都带 `author.avatar`
62
+ *
63
+ * 群聊里说话人该显示群内昵称,所以 `userName` 按 member_nickname → username 取。
64
+ * QQ 昵称另外挂在 `userNickname` 上——OneBot 的 nickname / card 要靠它俩分开,
65
+ * 以前两个字段同值,客户端改群名片永远对不上。
66
+ *
67
+ * 驼峰/下划线两套都认,是防「文档写的键名和实测不一致」;都没有就是空串,
68
+ * 不影响消息本身。
69
+ */
70
+ export function personCard(author) {
71
+ const a = author && typeof author === 'object' ? author : {};
72
+ return String(a.member_nickname ?? a.memberNickname ?? a.card ?? '').trim();
73
+ }
74
+
75
+ export function personNickname(author) {
76
+ const a = author && typeof author === 'object' ? author : {};
77
+ return String(a.username ?? a.nickname ?? '').trim();
78
+ }
79
+
80
+ /** 显示名:群内昵称优先,其次 QQ 昵称 */
81
+ export function personName(author) {
82
+ return personCard(author) || personNickname(author);
83
+ }
84
+
85
+ /** 头像原图 URL(官方给的是 qlogo 地址);拿不到是空串 */
86
+ export function personAvatar(author) {
87
+ const a = author && typeof author === 'object' ? author : {};
88
+ return String(a.avatar ?? a.avatar_url ?? a.avatarUrl ?? '').trim();
89
+ }
90
+
55
91
  /**
56
92
  * 图文卡片(`msg_type=8`)的官方硬约束,发之前先查一遍。
57
93
  *
@@ -232,7 +268,10 @@ export function parseElements(list, depth = 0) {
232
268
  author: author
233
269
  ? {
234
270
  id: String(author.member_openid ?? author.user_openid ?? author.id ?? ''),
235
- name: String(author.username ?? ''),
271
+ name: personName(author),
272
+ card: personCard(author),
273
+ nickname: personNickname(author),
274
+ avatar: personAvatar(author),
236
275
  isBot: Boolean(author.bot),
237
276
  }
238
277
  : null,
@@ -267,7 +306,16 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
267
306
  */
268
307
  let guildId = '';
269
308
  let channelId = '';
270
- const userName = d.author?.username ?? '';
309
+ /**
310
+ * 说话人的三个名字,别混:
311
+ * · `userName` 显示名(群内昵称优先)—— 插件要「喊人」时用它
312
+ * · `userNickname` QQ 昵称 —— OneBot 的 `nickname`
313
+ * · `userCard` 群名片/群内昵称 —— OneBot 的 `card`
314
+ */
315
+ const userName = personName(d.author);
316
+ const userNickname = personNickname(d.author);
317
+ const userCard = personCard(d.author);
318
+ const userAvatar = personAvatar(d.author);
271
319
  if (kind === 'group') {
272
320
  groupId = d.group_openid ?? '';
273
321
  userId = d.author?.member_openid ?? d.author?.id ?? '';
@@ -345,7 +393,21 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
345
393
  eventMeta: EVENTS[eventName] ?? null,
346
394
  groupId,
347
395
  userId,
396
+ /** 显示名:群聊取群内昵称,单聊取 QQ 昵称(2026-11-16 官方开始下发) */
348
397
  userName,
398
+ /** QQ 昵称(群聊里可能和 `userCard` 不同) */
399
+ userNickname,
400
+ /** 群名片/群内昵称;单聊与频道为空串 */
401
+ userCard,
402
+ /** 头像原图 URL;官方没给就是空串 */
403
+ userAvatar,
404
+ /**
405
+ * 官方 2026-11-16 新加的跨应用标识,**只透传、不做适配**:
406
+ * 只有同一开发者 + 绑了同一个 3 方应用才有值,且换不出对方的 openid。
407
+ * 跨机器人的身份/群关联一律走 `identity` 的「QQ号/群号 ↔ openid」绑定。
408
+ */
409
+ unionUserId: String(d?.author?.union_openid ?? ''),
410
+ unionGroupId: String(d?.union_group_openid ?? ''),
349
411
  chatId,
350
412
  /** 频道维度(群/单聊为空串):guildId 是频道 ID,channelId 是子频道 ID */
351
413
  guildId,
@@ -390,7 +452,7 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
390
452
  id: m?.id ?? m?.member_openid ?? m?.user_openid ?? '',
391
453
  isBot: Boolean(m?.is_you || m?.bot),
392
454
  // 昵称带上:禁言/踢人成功时能回「已禁言 张三」,比一串 openid 好认
393
- name: String(m?.username ?? '').trim(),
455
+ name: personName(m),
394
456
  }))
395
457
  .filter((m) => m.id);
396
458
  const fromText = mentionsFromContent(d?.content).map((id) => ({ id, isBot: false, name: '' }));
@@ -417,7 +479,7 @@ export function buildMessage(eventName, d, { api, cfg, outbound, session, traceI
417
479
  .map((m) => ({
418
480
  id: m?.id ?? m?.member_openid ?? m?.user_openid ?? '',
419
481
  isBot: Boolean(m?.is_you || m?.bot),
420
- name: String(m?.username ?? '').trim(),
482
+ name: personName(m),
421
483
  }))
422
484
  .filter((m) => m.id);
423
485
  const fromText = mentionsFromContent(d?.content).map((id) => ({ id, isBot: false, name: '' }));