koishi-plugin-rina-qq-bridge 0.1.0 → 0.1.2

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/lib/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Bot, Context, h, Service } from 'koishi';
2
2
  import { Config as ConfigSchema, Config as PluginConfig, QqMentionMode, QqUrlMode } from './config';
3
- import { MemberMatchReport } from './matcher';
3
+ import { GroupMatchReport, MemberMatchReport } from './matcher';
4
4
  import { MappingSource, RinaQqGroupMap, RinaQqUserMap } from './model';
5
5
  export type Config = PluginConfig;
6
6
  export declare const Config: import("schemastery")<ConfigSchema>;
@@ -31,6 +31,7 @@ declare module 'koishi' {
31
31
  }
32
32
  export declare function isPlainNumericId(value: string): boolean;
33
33
  export declare function defangUrl(url: string): string;
34
+ export declare function formatErrorDetail(error: unknown): string;
34
35
  export declare class RinaQqBridge extends Service<Config> {
35
36
  static inject: string[];
36
37
  static Config: import("schemastery")<ConfigSchema>;
@@ -81,6 +82,11 @@ export declare class RinaQqBridge extends Service<Config> {
81
82
  resolveUserOpenId(botSelfId: string, qqOrOpenId: string): Promise<string | undefined>;
82
83
  resolveQqNumber(botSelfId: string, memberOpenId: string): Promise<string | undefined>;
83
84
  refreshGroupMetadata(bot: Bot, groupOpenId: string, force?: boolean): Promise<void>;
85
+ /**
86
+ * Automatically matches unmapped QQ groups in `rina_qq_group_map` against
87
+ * OneBot's `get_group_list` using `group_name + member_count`.
88
+ */
89
+ autoMatchGroupsWithOneBot(botSelfId?: string, onebotBot?: Bot, apply?: boolean): Promise<GroupMatchReport>;
84
90
  checkProactiveState(bot: Bot, groupOpenId: string, force?: boolean): Promise<ProactiveState>;
85
91
  /**
86
92
  * Official beta API: GET /v2/groups/{group_openid}/members
package/lib/index.js CHANGED
@@ -24,6 +24,7 @@ __export(src_exports, {
24
24
  RinaQqBridge: () => RinaQqBridge,
25
25
  defangUrl: () => defangUrl,
26
26
  default: () => src_default,
27
+ formatErrorDetail: () => formatErrorDetail,
27
28
  inject: () => inject,
28
29
  isPlainNumericId: () => isPlainNumericId,
29
30
  name: () => name
@@ -36,9 +37,11 @@ var import_koishi = require("koishi");
36
37
  function registerCommands(ctx, bridge) {
37
38
  ctx.command("qq映射状态", "查看当前群与用户的 ID、映射关系以及 QQ 群主动推送状态").alias("qq信息").action(async ({ session }) => {
38
39
  if (!session) return "请在会话中使用该指令。";
40
+ const appId = String(session.bot?.config?.id ?? "").trim();
39
41
  const lines = [
40
42
  `平台:${session.platform}`,
41
43
  `机器人 selfId:${session.selfId}`,
44
+ ...appId && appId !== session.selfId ? [`机器人 AppID:${appId}`] : [],
42
45
  `频道/群 ID:${session.channelId || "无"}`,
43
46
  `用户 ID:${session.userId || "无"}`
44
47
  ];
@@ -126,6 +129,37 @@ function registerCommands(ctx, bridge) {
126
129
  }
127
130
  return sections.join("\n\n");
128
131
  });
132
+ ctx.command("qq同步群", "按群名称+群人数自动将已登记的 QQ 官方群与 OneBot 群列表批量匹配(无需在每个群发指令)").option("dryRun", "-d 仅预览匹配结果,不写入数据库").option("refresh", "-r 匹配前先刷新所有已知 QQ 官方群的群名与人数").action(async ({ session, options }) => {
133
+ const qqBot = session?.platform === "qq" ? session.bot : ctx.bots.find((b) => b.platform === "qq");
134
+ const onebotBot = ctx.bots.find((b) => b.platform === "onebot");
135
+ if (!onebotBot) return "未找到在线的 OneBot 机器人(platform=onebot),无法拉取 OneBot 群列表。";
136
+ if (options?.refresh && qqBot) {
137
+ const known = await bridge.listGroupMappings(qqBot.selfId);
138
+ for (const group of known) {
139
+ await bridge.refreshGroupMetadata(qqBot, group.groupOpenId, true);
140
+ }
141
+ }
142
+ const report = await bridge.autoMatchGroupsWithOneBot(qqBot?.selfId, onebotBot, !options?.dryRun);
143
+ const lines = [
144
+ `【群名+人数批量匹配${options?.dryRun ? "(预览模式)" : "(已自动写入)"}】`,
145
+ `已登记 QQ 群:${report.totalQqGroups} | OneBot 群:${report.totalOneBotGroups} | 已有映射:${report.alreadyMapped}`,
146
+ `本次唯一匹配:${report.matched.length} | 同名冲突待确认:${report.conflicts.length} | 未匹配:${report.unmatchedQq}`
147
+ ];
148
+ if (report.matched.length) {
149
+ lines.push("", "匹配结果:");
150
+ for (const item of report.matched.slice(0, 20)) {
151
+ lines.push(`- 群 ${item.onebotGroup.groupId} ↔ ${item.qqGroup.groupOpenId}(${item.qqGroup.groupName})[${item.reasons.join("、")}]`);
152
+ }
153
+ }
154
+ if (report.conflicts.length) {
155
+ lines.push("", "同名冲突(需在 dataview 手动核对):");
156
+ for (const conflict of report.conflicts.slice(0, 10)) {
157
+ const cands = conflict.candidates.map((c) => `${c.onebotGroup.groupId}(${c.onebotGroup.memberCount}人)`).join(" / ");
158
+ lines.push(`- ${conflict.qqGroup.groupOpenId}(${conflict.qqGroup.groupName},${conflict.qqGroup.memberCount}人)候选:${cands}`);
159
+ }
160
+ }
161
+ return lines.join("\n");
162
+ });
129
163
  ctx.command("qq同步成员", "调用官方内测接口(每页30条游标分页)同步当前 QQ 群成员列表").action(async ({ session }) => {
130
164
  if (!session || session.isDirect || !session.channelId) return "请在目标 QQ 群中使用该指令。";
131
165
  if (session.platform !== "qq") return "该指令仅用于 QQ 官方适配器(platform=qq)。";
@@ -244,6 +278,116 @@ function parseRfc3339ToUnixSec(value) {
244
278
  return { iso: "", ts: 0 };
245
279
  }
246
280
  __name(parseRfc3339ToUnixSec, "parseRfc3339ToUnixSec");
281
+ async function fetchOneBotGroupList(bot) {
282
+ const internal = bot.internal;
283
+ let rawList;
284
+ if (typeof internal?.getGroupList === "function") {
285
+ rawList = await internal.getGroupList();
286
+ } else if (typeof internal?.get_group_list === "function") {
287
+ rawList = await internal.get_group_list();
288
+ } else if (typeof bot.getGuildList === "function") {
289
+ const res = await bot.getGuildList();
290
+ const items = Array.isArray(res?.data) ? res.data : [];
291
+ return items.map((g) => ({
292
+ groupId: String(g?.id ?? "").trim(),
293
+ groupName: String(g?.name ?? "").trim(),
294
+ memberCount: Number(g?.memberCount ?? g?.member_count ?? 0) || 0
295
+ })).filter((g) => !!g.groupId);
296
+ }
297
+ if (!Array.isArray(rawList)) {
298
+ throw new Error("OneBot 适配器未返回有效的群列表(get_group_list)");
299
+ }
300
+ return rawList.map((item) => ({
301
+ groupId: String(item?.group_id ?? "").trim(),
302
+ groupName: String(item?.group_name ?? "").trim(),
303
+ memberCount: Number(item?.member_count ?? 0) || 0
304
+ })).filter((g) => !!g.groupId);
305
+ }
306
+ __name(fetchOneBotGroupList, "fetchOneBotGroupList");
307
+ function matchGroupsWithOneBotList(qqGroups, onebotGroups) {
308
+ const mappedCodes = /* @__PURE__ */ new Set();
309
+ const unmappedQq = [];
310
+ let alreadyMapped = 0;
311
+ for (const g of qqGroups) {
312
+ if (g.groupCode) {
313
+ alreadyMapped++;
314
+ mappedCodes.add(g.groupCode);
315
+ } else {
316
+ unmappedQq.push(g);
317
+ }
318
+ }
319
+ const availableOneBot = onebotGroups.filter((g) => !mappedCodes.has(g.groupId));
320
+ const perQqCandidates = /* @__PURE__ */ new Map();
321
+ for (const qqGroup of unmappedQq) {
322
+ const qqName = normalizeName(qqGroup.groupName);
323
+ if (!qqName) continue;
324
+ const candidates = [];
325
+ for (const ob of availableOneBot) {
326
+ const obName = normalizeName(ob.groupName);
327
+ if (!obName || qqName !== obName) continue;
328
+ let score = 100;
329
+ const reasons = ["群名称一致"];
330
+ if (qqGroup.memberCount > 0 && ob.memberCount > 0) {
331
+ const diff = Math.abs(qqGroup.memberCount - ob.memberCount);
332
+ if (diff <= 3) {
333
+ score += 50;
334
+ reasons.push(`群人数一致(Δ${diff})`);
335
+ } else if (diff <= 10) {
336
+ score += 20;
337
+ reasons.push(`群人数相近(Δ${diff})`);
338
+ } else {
339
+ score -= 30;
340
+ reasons.push(`群人数差异较大(Δ${diff})`);
341
+ }
342
+ }
343
+ if (score >= 80) {
344
+ candidates.push({ onebotGroup: ob, score, reasons });
345
+ }
346
+ }
347
+ if (candidates.length) {
348
+ candidates.sort((a, b) => b.score - a.score);
349
+ const topScore = candidates[0].score;
350
+ perQqCandidates.set(qqGroup.groupOpenId, candidates.filter((c) => c.score >= topScore - 15));
351
+ }
352
+ }
353
+ const onebotClaimers = /* @__PURE__ */ new Map();
354
+ for (const [openId, list] of perQqCandidates) {
355
+ if (list.length === 1) {
356
+ const gid = list[0].onebotGroup.groupId;
357
+ const arr = onebotClaimers.get(gid) ?? [];
358
+ arr.push(openId);
359
+ onebotClaimers.set(gid, arr);
360
+ }
361
+ }
362
+ const matched = [];
363
+ const conflicts = [];
364
+ for (const qqGroup of unmappedQq) {
365
+ const list = perQqCandidates.get(qqGroup.groupOpenId);
366
+ if (!list?.length) continue;
367
+ if (list.length === 1) {
368
+ const claimers = onebotClaimers.get(list[0].onebotGroup.groupId) ?? [];
369
+ if (claimers.length === 1) {
370
+ matched.push({
371
+ qqGroup,
372
+ onebotGroup: list[0].onebotGroup,
373
+ score: list[0].score,
374
+ reasons: list[0].reasons
375
+ });
376
+ continue;
377
+ }
378
+ }
379
+ conflicts.push({ qqGroup, candidates: list });
380
+ }
381
+ return {
382
+ totalQqGroups: qqGroups.length,
383
+ totalOneBotGroups: onebotGroups.length,
384
+ alreadyMapped,
385
+ matched,
386
+ conflicts,
387
+ unmatchedQq: unmappedQq.length - matched.length - conflicts.length
388
+ };
389
+ }
390
+ __name(matchGroupsWithOneBotList, "matchGroupsWithOneBotList");
247
391
  async function fetchOneBotGroupMembers(bot, groupCode) {
248
392
  const internal = bot.internal;
249
393
  let rawList;
@@ -643,6 +787,22 @@ function defangUrl(url) {
643
787
  return url.replace(/^https?:\/\//i, "").replace(/^([^/?#]+)/, (host) => host.replace(/\./g, "·"));
644
788
  }
645
789
  __name(defangUrl, "defangUrl");
790
+ function formatErrorDetail(error) {
791
+ if (!error) return String(error);
792
+ if (Array.isArray(error.errors) && error.errors.length) {
793
+ return error.errors.map((item) => formatErrorDetail(item)).join(" | ");
794
+ }
795
+ const resp = error.response;
796
+ if (resp) {
797
+ const status = resp.status ?? "";
798
+ const data = typeof resp.data === "string" ? resp.data : JSON.stringify(resp.data);
799
+ const trace = typeof resp.headers?.get === "function" ? resp.headers.get("x-tps-trace-id") : resp.headers?.["x-tps-trace-id"];
800
+ return `HTTP ${status} ${data}${trace ? ` (trace=${trace})` : ""}`.trim();
801
+ }
802
+ if (error instanceof Error) return error.message || error.name;
803
+ return String(error);
804
+ }
805
+ __name(formatErrorDetail, "formatErrorDetail");
646
806
  var RinaQqBridge = class extends import_koishi4.Service {
647
807
  static {
648
808
  __name(this, "RinaQqBridge");
@@ -723,6 +883,14 @@ var RinaQqBridge = class extends import_koishi4.Service {
723
883
  });
724
884
  }
725
885
  });
886
+ ctx.on("login-updated", (session) => {
887
+ if (!config.enableDualBotPairing) return;
888
+ if (session.bot?.platform === "onebot" && session.bot.status === 1) {
889
+ void this.autoMatchGroupsWithOneBot(void 0, session.bot, true).catch((error) => {
890
+ if (this.config.debug) this.log.debug(`OneBot 上线自动匹配群列表跳过:${String(error)}`);
891
+ });
892
+ }
893
+ });
726
894
  registerCommands(ctx, this);
727
895
  }
728
896
  async recordQqMessageMetadata(session) {
@@ -948,6 +1116,43 @@ var RinaQqBridge = class extends import_koishi4.Service {
948
1116
  source: "message"
949
1117
  });
950
1118
  }
1119
+ if (this.config.enableDualBotPairing && groupName) {
1120
+ const current = await this.getGroupByOpenId(bot.selfId, groupOpenId);
1121
+ if (!current?.groupCode) {
1122
+ const onebot = this.ctx.bots.find((b) => b.platform === "onebot");
1123
+ if (onebot) {
1124
+ void this.autoMatchGroupsWithOneBot(bot.selfId, onebot, true).catch((error) => {
1125
+ if (this.config.debug) this.log.debug(`自动匹配群名失败:${String(error)}`);
1126
+ });
1127
+ }
1128
+ }
1129
+ }
1130
+ }
1131
+ /**
1132
+ * Automatically matches unmapped QQ groups in `rina_qq_group_map` against
1133
+ * OneBot's `get_group_list` using `group_name + member_count`.
1134
+ */
1135
+ async autoMatchGroupsWithOneBot(botSelfId, onebotBot, apply = true) {
1136
+ const ob = onebotBot ?? this.ctx.bots.find((b) => b.platform === "onebot");
1137
+ if (!ob) {
1138
+ throw new Error("未找到在线的 OneBot 机器人(platform=onebot),无法拉取群列表。");
1139
+ }
1140
+ const qqGroups = await this.listGroupMappings(botSelfId);
1141
+ const onebotGroups = await fetchOneBotGroupList(ob);
1142
+ const report = matchGroupsWithOneBotList(qqGroups, onebotGroups);
1143
+ if (apply && report.matched.length) {
1144
+ for (const item of report.matched) {
1145
+ await this.upsertGroupMapping({
1146
+ botSelfId: item.qqGroup.botSelfId,
1147
+ groupOpenId: item.qqGroup.groupOpenId,
1148
+ groupCode: item.onebotGroup.groupId,
1149
+ groupName: item.qqGroup.groupName || item.onebotGroup.groupName,
1150
+ source: "group-list-match"
1151
+ });
1152
+ this.log.info(`群名+人数自动匹配成功:群 ${item.onebotGroup.groupId} ↔ ${item.qqGroup.groupOpenId}(${item.qqGroup.groupName})`);
1153
+ }
1154
+ }
1155
+ return report;
951
1156
  }
952
1157
  async checkProactiveState(bot, groupOpenId, force = false) {
953
1158
  if (bot.platform !== "qq") return { checked: false };
@@ -1132,18 +1337,30 @@ var RinaQqBridge = class extends import_koishi4.Service {
1132
1337
  const mimeType = options.mimeType || "image/png";
1133
1338
  const combine = options.combineImageAndText !== false;
1134
1339
  if (options.image && options.text && combine) {
1135
- await bot.sendMessage(resolvedChannelId, [
1136
- import_koishi4.h.image(options.image, mimeType),
1137
- import_koishi4.h.text(options.text)
1138
- ]);
1139
- return;
1340
+ try {
1341
+ await bot.sendMessage(resolvedChannelId, [
1342
+ import_koishi4.h.image(options.image, mimeType),
1343
+ import_koishi4.h.text(options.text)
1344
+ ]);
1345
+ return;
1346
+ } catch (error) {
1347
+ this.log.warn(`QQ 群 ${channelId}(${resolvedChannelId})图文合发失败(${formatErrorDetail(error)}),自动降级为先发文字再发图片。`);
1348
+ }
1140
1349
  }
1141
1350
  if (options.text) {
1142
1351
  const content = options.markdown ? (0, import_koishi4.h)("qq:markdown", {}, [import_koishi4.h.text(options.text)]) : import_koishi4.h.text(options.text);
1143
1352
  await bot.sendMessage(resolvedChannelId, content);
1144
1353
  }
1145
1354
  if (options.image) {
1146
- await bot.sendMessage(resolvedChannelId, import_koishi4.h.image(options.image, mimeType));
1355
+ try {
1356
+ await bot.sendMessage(resolvedChannelId, import_koishi4.h.image(options.image, mimeType));
1357
+ } catch (error) {
1358
+ if (options.text) {
1359
+ this.log.warn(`QQ 群 ${channelId}(${resolvedChannelId})图片发送失败(文字已送达):${formatErrorDetail(error)}`);
1360
+ } else {
1361
+ throw error;
1362
+ }
1363
+ }
1147
1364
  }
1148
1365
  return;
1149
1366
  }
@@ -1161,6 +1378,7 @@ var src_default = RinaQqBridge;
1161
1378
  Config,
1162
1379
  RinaQqBridge,
1163
1380
  defangUrl,
1381
+ formatErrorDetail,
1164
1382
  inject,
1165
1383
  isPlainNumericId,
1166
1384
  name
package/lib/matcher.d.ts CHANGED
@@ -1,5 +1,32 @@
1
1
  import { Bot } from 'koishi';
2
- import { RinaQqUserMap } from './model';
2
+ import { RinaQqGroupMap, RinaQqUserMap } from './model';
3
+ export interface OneBotGroupInfo {
4
+ groupId: string;
5
+ groupName: string;
6
+ memberCount: number;
7
+ }
8
+ export interface GroupMatchCandidate {
9
+ qqGroup: RinaQqGroupMap;
10
+ onebotGroup: OneBotGroupInfo;
11
+ score: number;
12
+ reasons: string[];
13
+ }
14
+ export interface GroupMatchConflict {
15
+ qqGroup: RinaQqGroupMap;
16
+ candidates: Array<{
17
+ onebotGroup: OneBotGroupInfo;
18
+ score: number;
19
+ reasons: string[];
20
+ }>;
21
+ }
22
+ export interface GroupMatchReport {
23
+ totalQqGroups: number;
24
+ totalOneBotGroups: number;
25
+ alreadyMapped: number;
26
+ matched: GroupMatchCandidate[];
27
+ conflicts: GroupMatchConflict[];
28
+ unmatchedQq: number;
29
+ }
3
30
  export interface OneBotGroupMember {
4
31
  userId: string;
5
32
  nickname: string;
@@ -37,6 +64,17 @@ export declare function parseRfc3339ToUnixSec(value?: string | number): {
37
64
  iso: string;
38
65
  ts: number;
39
66
  };
67
+ /**
68
+ * Fetches group list from a OneBot adapter instance (`get_group_list`),
69
+ * capturing plain `group_id`, `group_name`, and `member_count`.
70
+ */
71
+ export declare function fetchOneBotGroupList(bot: Bot): Promise<OneBotGroupInfo[]>;
72
+ /**
73
+ * Matches unmapped QQ official groups (with `groupName` and `memberCount` from
74
+ * `GET /v2/groups/{group_openid}/info`) against OneBot's `get_group_list`.
75
+ * Enforces strict global 1-to-1 uniqueness so identically named groups go to `conflicts`.
76
+ */
77
+ export declare function matchGroupsWithOneBotList(qqGroups: RinaQqGroupMap[], onebotGroups: OneBotGroupInfo[]): GroupMatchReport;
40
78
  /**
41
79
  * Fetches group member list from a OneBot adapter instance, prioritizing raw
42
80
  * `get_group_member_list` (which always includes `join_time`, `nickname`, `card`, `role`).
package/lib/model.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Context } from 'koishi';
2
- export type MappingSource = 'guild-added' | 'message' | 'mention' | 'member-add' | 'admin-bind' | 'self-bind' | 'dual-bot-pair' | 'member-sync' | 'member-list-match';
2
+ export type MappingSource = 'guild-added' | 'message' | 'mention' | 'member-add' | 'admin-bind' | 'self-bind' | 'dual-bot-pair' | 'group-list-match' | 'member-sync' | 'member-list-match';
3
3
  export interface RinaQqGroupMap {
4
4
  id: number;
5
5
  botSelfId: string;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-rina-qq-bridge",
3
3
  "description": "QQ 官方群接口适配辅助、群号/QQ号与 OpenID 映射及双 Bot 只读指纹配对服务",
4
- "version": "0.1.0",
4
+ "version": "0.1.2",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [
package/readme.md CHANGED
@@ -4,8 +4,9 @@
4
4
 
5
5
  ## 功能
6
6
 
7
- 1. **多通道自动采集 OpenID**:
8
- - `GROUP_ADD_ROBOT`(进群事件):自动登记 `group_openid` 并调用 `getGuildInfo` / `getGuildBotState` 补全群名、人数与主动消息权限状态;
7
+ 1. **多通道自动采集与免指令群匹配**:
8
+ - `GROUP_ADD_ROBOT`(进群事件):自动登记 `group_openid` 并调用 `getGuildInfo` / `getGuildBotState` 补全群名、人数与主动消息权限状态;若 OneBot 同时在线,立即自动按 **群名 + 群人数** 与 OneBot `get_group_list` 完成 `群号 ↔ group_openid` 唯一匹配,**无需在每个群发绑定指令**;
9
+ - `qq同步群 [-r] [-d]`:可在私聊或控制台沙盒一键对所有已知群批量执行群名+人数匹配;
9
10
  - `GROUP_AT_MESSAGE_CREATE` / `GROUP_MESSAGE_CREATE`:自动采集消息发送者与 `mentions` 中所有被 `@` 成员的 `member_openid`、昵称、头像、群角色与 `union_openid`;
10
11
  - `GROUP_MEMBER_ADD`(新成员入群):自动记录新入群成员的 `member_openid` 与精确 `joined_at` 入群时间。
11
12
  2. **双 Bot 只读自动指纹配对**:过渡期同时挂载 OneBot(只收不发)与官方 QQ Bot(开启全量消息)时,自动按“时间窗口 + 归一化纯文本指纹 + 唯一性确认”建立 `群号 ↔ group_openid` 与 `QQ号 ↔ member_openid` 映射。