dsh-message-gateway 0.1.1 → 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.js CHANGED
@@ -490,11 +490,9 @@ var DiscordBridge = class {
490
490
 
491
491
  // src/host/qq-bridge.ts
492
492
  var TOKEN_URL = "https://bots.qq.com/app/getAppAccessToken";
493
- var REST2 = "https://api.sgroup.qq.com";
494
- var GATEWAY = "wss://api.sgroup.qq.com/?v=1&encoding=json";
495
- var INTENTS2 = 1 << 9 | 1 << 12 | 1 << 30;
496
- var EDIT_INTERVAL_MS3 = 1200;
497
- var MSG_LIMIT3 = 2e3;
493
+ var BASE = "https://api.bot.qq.com";
494
+ var INTENTS2 = 1 << 25;
495
+ var DEDUP_CAP = 64;
498
496
  var QQBridge = class {
499
497
  constructor(appId, secret, callbacks) {
500
498
  this.appId = appId;
@@ -506,22 +504,20 @@ var QQBridge = class {
506
504
  heartbeat = null;
507
505
  seq = null;
508
506
  accessToken = null;
509
- /** streamId → 已发送消息(用于渐进编辑)。 */
510
- streams = /* @__PURE__ */ new Map();
511
- /** streamId → 最新待推送内容(流式合并,单 worker 消费)。 */
512
- state = /* @__PURE__ */ new Map();
513
- working = /* @__PURE__ */ new Set();
507
+ /** streamId → 已发出(单条定稿消息,防重复发送)。 */
508
+ sent = /* @__PURE__ */ new Set();
509
+ recentMsgIds = /* @__PURE__ */ new Set();
514
510
  status = { state: "idle", detail: "", connectedAt: null };
515
511
  setStatus(state, detail = "") {
516
512
  this.status = { state, detail, connectedAt: state === "connected" ? Date.now() : this.status.connectedAt };
517
513
  this.callbacks.onStatus(this.status);
518
514
  }
519
- /** 启动:先取 access_token,再连网关。 */
515
+ /** 启动:先取 access_token,再取 WSS 接入点,最后连网关。 */
520
516
  start() {
521
517
  if (!this.stopped && this.ws !== null) return;
522
518
  this.stopped = false;
523
519
  this.setStatus("connecting", "access token");
524
- void this.getAccessToken().then((token) => {
520
+ void this.getAccessToken().then(async (token) => {
525
521
  if (this.stopped) return;
526
522
  if (token === null) {
527
523
  this.setStatus("error", "access token failed");
@@ -529,7 +525,13 @@ var QQBridge = class {
529
525
  }
530
526
  this.accessToken = token;
531
527
  this.setStatus("connecting", "gateway");
532
- this.connect();
528
+ const url = await this.getGatewayUrl();
529
+ if (this.stopped) return;
530
+ if (url === null) {
531
+ this.setStatus("error", "gateway url failed");
532
+ return;
533
+ }
534
+ this.connect(url);
533
535
  });
534
536
  }
535
537
  async getAccessToken() {
@@ -555,18 +557,42 @@ var QQBridge = class {
555
557
  clearTimeout(timer);
556
558
  }
557
559
  }
558
- connect() {
560
+ /** 获取通用 WSS 接入点(官方推荐先调接口拿地址,避免写死)。 */
561
+ async getGatewayUrl() {
562
+ const controller = new AbortController();
563
+ const timer = setTimeout(() => controller.abort(), 15e3);
564
+ try {
565
+ const response = await fetch(`${BASE}/gateway`, {
566
+ headers: { authorization: `QQBot ${this.accessToken ?? ""}` },
567
+ signal: controller.signal
568
+ });
569
+ if (!response.ok) {
570
+ console.warn("[dsh-message-gateway] qq gateway url", response.status);
571
+ return null;
572
+ }
573
+ const body = await response.json();
574
+ if (typeof body.url === "string" && body.url !== "") return body.url;
575
+ console.warn("[dsh-message-gateway] qq gateway url missing", JSON.stringify(body).slice(0, 120));
576
+ return null;
577
+ } catch (error) {
578
+ console.warn("[dsh-message-gateway] qq gateway url error", String(error));
579
+ return null;
580
+ } finally {
581
+ clearTimeout(timer);
582
+ }
583
+ }
584
+ connect(url) {
559
585
  if (this.stopped) return;
560
586
  let ws;
561
587
  try {
562
- ws = new WebSocket(GATEWAY);
588
+ ws = new WebSocket(url);
563
589
  } catch (error) {
564
590
  console.error("[dsh-message-gateway] qq ws create failed", error);
565
591
  this.setStatus("error", "ws create failed");
566
592
  return;
567
593
  }
568
594
  this.ws = ws;
569
- ws.onopen = () => console.log("[dsh-message-gateway] qq gateway open");
595
+ ws.onopen = () => console.log("[dsh-message-gateway] qq gateway open", url);
570
596
  ws.onmessage = (event) => this.onMessage(String(event.data));
571
597
  ws.onerror = () => console.warn("[dsh-message-gateway] qq gateway ws error");
572
598
  ws.onclose = () => {
@@ -574,7 +600,13 @@ var QQBridge = class {
574
600
  this.ws = null;
575
601
  if (!this.stopped) {
576
602
  console.warn("[dsh-message-gateway] qq gateway closed, reconnect in 3s");
577
- setTimeout(() => this.connect(), 3e3);
603
+ setTimeout(() => {
604
+ if (this.stopped) return;
605
+ void this.getGatewayUrl().then((u) => {
606
+ if (this.stopped || u === null) return;
607
+ this.connect(u);
608
+ });
609
+ }, 3e3);
578
610
  }
579
611
  };
580
612
  }
@@ -601,15 +633,24 @@ var QQBridge = class {
601
633
  if (payload.t === "READY") {
602
634
  this.setStatus("connected", "qq");
603
635
  console.log("[dsh-message-gateway] qq READY");
604
- } else if (payload.t === "MESSAGE_CREATE" || payload.t === "DIRECT_MESSAGE_CREATE") {
605
- this.handleMessage(payload.d);
636
+ } else if (payload.t === "C2C_MESSAGE_CREATE") {
637
+ this.handleMessage(payload.d, "c2c");
638
+ } else if (payload.t === "GROUP_AT_MESSAGE_CREATE") {
639
+ this.handleMessage(payload.d, "group");
606
640
  }
607
641
  break;
608
642
  }
643
+ case 9: {
644
+ console.warn("[dsh-message-gateway] qq identify rejected (INVALID_SESSION) \u2014 \u8BF7\u786E\u8BA4\u63A7\u5236\u53F0\u4E8B\u4EF6\u8BA2\u9605\u4E3A WebSocket \u957F\u8FDE\u63A5");
645
+ this.ws?.close();
646
+ break;
647
+ }
609
648
  case 7: {
610
649
  this.ws?.close();
611
650
  break;
612
651
  }
652
+ case 11:
653
+ break;
613
654
  }
614
655
  }
615
656
  sendOp(op, d) {
@@ -618,7 +659,7 @@ var QQBridge = class {
618
659
  }
619
660
  identify() {
620
661
  this.sendOp(2, {
621
- token: this.accessToken,
662
+ token: `QQBot ${this.accessToken ?? ""}`,
622
663
  intents: INTENTS2,
623
664
  shard: [0, 1]
624
665
  });
@@ -638,17 +679,18 @@ var QQBridge = class {
638
679
  const controller = new AbortController();
639
680
  const timer = setTimeout(() => controller.abort(), 15e3);
640
681
  try {
641
- const response = await fetch(`${REST2}${path}`, {
682
+ const response = await fetch(`${BASE}${path}`, {
642
683
  method,
643
684
  headers: {
644
- authorization: `Bot ${this.accessToken ?? ""}`,
685
+ authorization: `QQBot ${this.accessToken ?? ""}`,
645
686
  "content-type": "application/json"
646
687
  },
647
688
  body: body === void 0 ? void 0 : JSON.stringify(body),
648
689
  signal: controller.signal
649
690
  });
650
691
  if (!response.ok) {
651
- console.warn("[dsh-message-gateway] qq rest", method, path, response.status);
692
+ const text = (await response.text()).slice(0, 200);
693
+ console.warn("[dsh-message-gateway] qq rest", method, path, response.status, text);
652
694
  return null;
653
695
  }
654
696
  return await response.json();
@@ -659,70 +701,54 @@ var QQBridge = class {
659
701
  clearTimeout(timer);
660
702
  }
661
703
  }
662
- handleMessage(d) {
704
+ /** 单聊/群聊消息分发(content 群聊已去 @前缀)。 */
705
+ handleMessage(d, scene) {
663
706
  const author = d.author;
664
707
  if (author?.bot === true) return;
665
708
  const text = typeof d.content === "string" ? d.content.trim() : "";
666
709
  if (text === "") return;
667
- const channelId = String(d.channel_id ?? "");
668
- if (channelId === "") return;
669
- const guildId = String(d.guild_id ?? "");
670
- const frame = { channelId, messageId: String(d.id ?? ""), guildId };
710
+ const msgId = String(d.id ?? "");
711
+ if (msgId === "") return;
712
+ if (this.recentMsgIds.has(msgId)) return;
713
+ this.recentMsgIds.add(msgId);
714
+ if (this.recentMsgIds.size > DEDUP_CAP) {
715
+ const first = this.recentMsgIds.values().next().value;
716
+ if (first !== void 0) this.recentMsgIds.delete(first);
717
+ }
718
+ const openid = scene === "c2c" ? author?.user_openid ?? "" : String(d.group_openid ?? "");
719
+ if (openid === "") return;
720
+ const frame = { openid, msgId, scene };
671
721
  const sink = {
722
+ // 单聊/群聊回复不支持就地编辑(群聊明确不支持流式),ack 关闭:
723
+ // 只发一条最终消息,避免「正在处理… + 回复」两条。
724
+ ack: false,
672
725
  stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
673
726
  };
674
727
  const identity = {
675
- key: `qq:${channelId}`,
728
+ key: scene === "c2c" ? `qq:c2c:${openid}` : `qq:group:${openid}`,
676
729
  frame,
677
730
  sink,
678
- chatType: guildId === "" ? "single" : "group"
731
+ chatType: scene === "c2c" ? "single" : "group"
679
732
  };
680
- console.log("[dsh-message-gateway] qq text", { channelId, text: text.slice(0, 60) });
733
+ console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60) });
681
734
  this.callbacks.onText(text, identity);
682
735
  }
683
- /** 流式回复:状态合并 + 单 worker——首次被动回复,随后 PATCH 渐进更新(限频)。 */
736
+ /** 回复:finish 时一次发出(带 msg_id 被动回复;幂等防重发)。 */
684
737
  async streamReply(frame, streamId, content, finish) {
685
- const prev = this.state.get(streamId);
686
- this.state.set(streamId, { content, finish: finish || (prev?.finish ?? false) });
687
- if (this.working.has(streamId)) return;
688
- this.working.add(streamId);
689
- try {
690
- for (let guard = 0; guard < 200; guard += 1) {
691
- const current = this.state.get(streamId);
692
- if (current === void 0) break;
693
- const text = (current.content === "" ? " " : current.content).slice(0, MSG_LIMIT3);
694
- const existing = this.streams.get(streamId);
695
- if (existing === void 0) {
696
- if (current.content === "" && !current.finish) break;
697
- const result = await this.rest("POST", `/channels/${frame.channelId}/messages`, {
698
- content: text,
699
- msg_type: 0,
700
- msg_id: frame.messageId
701
- });
702
- if (result?.id === void 0) break;
703
- this.streams.set(streamId, { channelId: frame.channelId, messageId: result.id, lastEdit: Date.now() });
704
- if (current.finish || this.state.get(streamId).content === current.content) break;
705
- continue;
706
- }
707
- const wait = EDIT_INTERVAL_MS3 - (Date.now() - existing.lastEdit);
708
- if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
709
- existing.lastEdit = Date.now();
710
- await this.rest("PATCH", `/channels/${existing.channelId}/messages/${existing.messageId}`, { content: text });
711
- if (current.finish || this.state.get(streamId).content === current.content) break;
712
- }
713
- } catch (error) {
714
- console.error("[dsh-message-gateway] qq reply failed", error);
715
- } finally {
716
- this.working.delete(streamId);
717
- }
738
+ if (!finish) return;
739
+ if (this.sent.has(streamId)) return;
740
+ this.sent.add(streamId);
741
+ const text = content.trim() === "" ? "\uFF08\u7A7A\u56DE\u590D\uFF09" : content.slice(0, 2e3);
742
+ const path = frame.scene === "c2c" ? `/v2/users/${encodeURIComponent(frame.openid)}/messages` : `/v2/groups/${encodeURIComponent(frame.openid)}/messages`;
743
+ const result = await this.rest("POST", path, { content: text, msg_type: 0, msg_id: frame.msgId });
744
+ if (result === null) this.sent.delete(streamId);
718
745
  }
719
746
  /** 停止网关连接。 */
720
747
  stop() {
721
748
  this.stopped = true;
722
749
  this.clearHeartbeat();
723
- this.streams.clear();
724
- this.state.clear();
725
- this.working.clear();
750
+ this.sent.clear();
751
+ this.recentMsgIds.clear();
726
752
  this.ws?.close();
727
753
  this.ws = null;
728
754
  this.accessToken = null;
@@ -1698,7 +1724,7 @@ var BridgeManager = class {
1698
1724
  return { state: "error", detail: live.detail, testedAt: stored?.testedAt ?? null };
1699
1725
  }
1700
1726
  if (live.state === "connecting") {
1701
- return { state: stored?.state ?? "none", detail: "\u8FDE\u63A5\u4E2D\u2026", testedAt: stored?.testedAt ?? null };
1727
+ return { state: "connecting", detail: live.detail || "\u8FDE\u63A5\u4E2D\u2026", testedAt: stored?.testedAt ?? null };
1702
1728
  }
1703
1729
  return stored ?? { state: "none", detail: "", testedAt: null };
1704
1730
  }