dsh-message-gateway 0.1.31 → 0.1.33
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/client.js +144 -8
- package/lib/client.js.map +2 -2
- package/lib/index.js +516 -46
- package/lib/index.js.map +4 -4
- package/package.json +4 -2
package/lib/index.js
CHANGED
|
@@ -8,6 +8,322 @@ var __export = (target, all) => {
|
|
|
8
8
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
+
// src/host/wechat-ilink-bridge.ts
|
|
12
|
+
var wechat_ilink_bridge_exports = {};
|
|
13
|
+
__export(wechat_ilink_bridge_exports, {
|
|
14
|
+
WechatIlinkBridge: () => WechatIlinkBridge
|
|
15
|
+
});
|
|
16
|
+
import crypto from "node:crypto";
|
|
17
|
+
var ILINK_BASE_URL, ILINK_APP_ID, ILINK_CLIENT_VERSION, WechatIlinkBridge;
|
|
18
|
+
var init_wechat_ilink_bridge = __esm({
|
|
19
|
+
"src/host/wechat-ilink-bridge.ts"() {
|
|
20
|
+
"use strict";
|
|
21
|
+
ILINK_BASE_URL = "https://ilinkai.weixin.qq.com";
|
|
22
|
+
ILINK_APP_ID = "bot";
|
|
23
|
+
ILINK_CLIENT_VERSION = (2 & 255) << 16 | (4 & 255) << 8 | 8 & 255;
|
|
24
|
+
WechatIlinkBridge = class _WechatIlinkBridge {
|
|
25
|
+
stopped = false;
|
|
26
|
+
pollController = null;
|
|
27
|
+
syncBuf = "";
|
|
28
|
+
cred;
|
|
29
|
+
callbacks;
|
|
30
|
+
status = { state: "idle", detail: "", connectedAt: null };
|
|
31
|
+
constructor(cred, callbacks) {
|
|
32
|
+
this.cred = cred;
|
|
33
|
+
this.callbacks = callbacks;
|
|
34
|
+
}
|
|
35
|
+
setStatus(state, detail = "") {
|
|
36
|
+
this.status = {
|
|
37
|
+
state,
|
|
38
|
+
detail,
|
|
39
|
+
connectedAt: state === "connected" ? this.status.connectedAt ?? Date.now() : null
|
|
40
|
+
};
|
|
41
|
+
this.callbacks.onStatus(this.status);
|
|
42
|
+
}
|
|
43
|
+
static randomWechatUin() {
|
|
44
|
+
const uint32 = crypto.randomBytes(4).readUInt32BE(0);
|
|
45
|
+
return Buffer.from(String(uint32), "utf-8").toString("base64");
|
|
46
|
+
}
|
|
47
|
+
static buildHeaders(token) {
|
|
48
|
+
const headers = {
|
|
49
|
+
"Content-Type": "application/json",
|
|
50
|
+
"iLink-App-Id": ILINK_APP_ID,
|
|
51
|
+
"iLink-App-ClientVersion": String(ILINK_CLIENT_VERSION),
|
|
52
|
+
"X-WECHAT-UIN": _WechatIlinkBridge.randomWechatUin()
|
|
53
|
+
};
|
|
54
|
+
if (token?.trim()) {
|
|
55
|
+
headers["Authorization"] = `Bearer ${token.trim()}`;
|
|
56
|
+
headers["AuthorizationType"] = "ilink_bot_token";
|
|
57
|
+
}
|
|
58
|
+
return headers;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* 生成微信扫码登录二维码。
|
|
62
|
+
* 返回 qrcode key 与完整二维码展示图片/扫码 URL。
|
|
63
|
+
*/
|
|
64
|
+
static async getLoginQr() {
|
|
65
|
+
const url = `${ILINK_BASE_URL}/ilink/bot/get_bot_qrcode?bot_type=3`;
|
|
66
|
+
const resp = await fetch(url, {
|
|
67
|
+
method: "POST",
|
|
68
|
+
headers: _WechatIlinkBridge.buildHeaders(),
|
|
69
|
+
body: JSON.stringify({ local_token_list: [] }),
|
|
70
|
+
signal: AbortSignal.timeout(15e3)
|
|
71
|
+
});
|
|
72
|
+
if (!resp.ok) {
|
|
73
|
+
throw new Error(`get_bot_qrcode failed: HTTP ${resp.status}`);
|
|
74
|
+
}
|
|
75
|
+
const data = await resp.json();
|
|
76
|
+
const qrcode = data.qrcode;
|
|
77
|
+
const rawTarget = data.qrcode_img_content || `https://ilinkai.weixin.qq.com/ilink/bot/get_qrcode_img?qrcode=${encodeURIComponent(qrcode)}`;
|
|
78
|
+
let qrcodeUrl = rawTarget;
|
|
79
|
+
try {
|
|
80
|
+
const QRCode = await import("qrcode");
|
|
81
|
+
qrcodeUrl = await QRCode.toDataURL(rawTarget, { width: 220, margin: 1 });
|
|
82
|
+
} catch (e) {
|
|
83
|
+
console.warn("[dsh-message-gateway] QRCode.toDataURL error", e);
|
|
84
|
+
}
|
|
85
|
+
return { qrcode, qrcodeUrl };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* 轮询扫码状态。
|
|
89
|
+
*/
|
|
90
|
+
static async pollQrStatus(qrcode) {
|
|
91
|
+
const url = `${ILINK_BASE_URL}/ilink/bot/get_qrcode_status?qrcode=${encodeURIComponent(qrcode)}`;
|
|
92
|
+
const resp = await fetch(url, {
|
|
93
|
+
method: "GET",
|
|
94
|
+
headers: _WechatIlinkBridge.buildHeaders(),
|
|
95
|
+
signal: AbortSignal.timeout(35e3)
|
|
96
|
+
});
|
|
97
|
+
if (!resp.ok) {
|
|
98
|
+
return { status: "wait" };
|
|
99
|
+
}
|
|
100
|
+
const data = await resp.json();
|
|
101
|
+
return {
|
|
102
|
+
status: data.status,
|
|
103
|
+
botToken: data.bot_token,
|
|
104
|
+
baseUrl: data.baseurl || ILINK_BASE_URL,
|
|
105
|
+
botId: data.ilink_bot_id,
|
|
106
|
+
userId: data.ilink_user_id
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* 启动长轮询消息监听。
|
|
111
|
+
*/
|
|
112
|
+
start() {
|
|
113
|
+
if (this.status.state === "connected") return;
|
|
114
|
+
this.stopped = false;
|
|
115
|
+
const label = this.cred.nickname || this.cred.userId ? `@${this.cred.nickname || this.cred.userId}` : "\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA";
|
|
116
|
+
this.setStatus("connected", label);
|
|
117
|
+
console.log("[dsh-message-gateway] wechat ilink bridge started for", label);
|
|
118
|
+
void this.pollLoop();
|
|
119
|
+
}
|
|
120
|
+
async pollLoop() {
|
|
121
|
+
const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
|
|
122
|
+
while (!this.stopped) {
|
|
123
|
+
try {
|
|
124
|
+
this.pollController = new AbortController();
|
|
125
|
+
const timeoutId = setTimeout(() => this.pollController?.abort(), 35e3);
|
|
126
|
+
const resp = await fetch(`${baseUrl}/ilink/bot/getupdates`, {
|
|
127
|
+
method: "POST",
|
|
128
|
+
headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
|
|
129
|
+
body: JSON.stringify({
|
|
130
|
+
get_updates_buf: this.syncBuf,
|
|
131
|
+
base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
|
|
132
|
+
}),
|
|
133
|
+
signal: this.pollController.signal
|
|
134
|
+
});
|
|
135
|
+
clearTimeout(timeoutId);
|
|
136
|
+
if (!resp.ok) {
|
|
137
|
+
if (resp.status === 401 || resp.status === 403) {
|
|
138
|
+
this.setStatus("error", "Token \u5DF2\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u626B\u7801");
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
await new Promise((r) => setTimeout(r, 3e3));
|
|
142
|
+
continue;
|
|
143
|
+
}
|
|
144
|
+
const data = await resp.json();
|
|
145
|
+
if (data.get_updates_buf) {
|
|
146
|
+
this.syncBuf = data.get_updates_buf;
|
|
147
|
+
}
|
|
148
|
+
const msgs = data.msgs ?? [];
|
|
149
|
+
for (const msg of msgs) {
|
|
150
|
+
if (msg.message_type !== 1) continue;
|
|
151
|
+
this.handleInboundMessage(msg);
|
|
152
|
+
}
|
|
153
|
+
} catch (err) {
|
|
154
|
+
if (this.stopped) break;
|
|
155
|
+
const isAbort = err instanceof Error && err.name === "AbortError";
|
|
156
|
+
if (!isAbort) {
|
|
157
|
+
console.warn("[dsh-message-gateway] wechat getupdates error, retrying in 2s:", err);
|
|
158
|
+
await new Promise((r) => setTimeout(r, 2e3));
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* 处理单条从微信拉取到的消息。
|
|
165
|
+
*/
|
|
166
|
+
handleInboundMessage(msg) {
|
|
167
|
+
const fromUser = String(msg.from_user_id ?? "");
|
|
168
|
+
if (!fromUser) return;
|
|
169
|
+
let text = "";
|
|
170
|
+
if (Array.isArray(msg.item_list)) {
|
|
171
|
+
for (const item of msg.item_list) {
|
|
172
|
+
if (item.type === 1 && item.text_item?.text) {
|
|
173
|
+
text += (text ? "\n" : "") + String(item.text_item.text).trim();
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (!text) return;
|
|
178
|
+
const contextToken = msg.context_token ?? "";
|
|
179
|
+
const sessionId = msg.session_id || fromUser;
|
|
180
|
+
const frame = {
|
|
181
|
+
fromUser,
|
|
182
|
+
contextToken,
|
|
183
|
+
sessionId,
|
|
184
|
+
msgId: msg.message_id
|
|
185
|
+
};
|
|
186
|
+
let typingTimer = null;
|
|
187
|
+
let typingTicket = "";
|
|
188
|
+
const startTyping = async () => {
|
|
189
|
+
try {
|
|
190
|
+
typingTicket = await this.getTypingTicket(fromUser, contextToken);
|
|
191
|
+
if (typingTicket) {
|
|
192
|
+
await this.sendTypingIndicator(fromUser, typingTicket);
|
|
193
|
+
typingTimer = setInterval(() => {
|
|
194
|
+
void this.sendTypingIndicator(fromUser, typingTicket);
|
|
195
|
+
}, 4500);
|
|
196
|
+
}
|
|
197
|
+
} catch (err) {
|
|
198
|
+
console.warn("[dsh-message-gateway] wechat startTyping failed", err);
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
void startTyping();
|
|
202
|
+
const sink = {
|
|
203
|
+
stream: (_f, _streamId, content, finish) => {
|
|
204
|
+
if (finish) {
|
|
205
|
+
if (typingTimer) {
|
|
206
|
+
clearInterval(typingTimer);
|
|
207
|
+
typingTimer = null;
|
|
208
|
+
}
|
|
209
|
+
if (content.trim()) {
|
|
210
|
+
void this.sendMessage(fromUser, content, contextToken);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
ack: false
|
|
215
|
+
};
|
|
216
|
+
const identity = {
|
|
217
|
+
key: `wechat:${sessionId}`,
|
|
218
|
+
frame,
|
|
219
|
+
sink,
|
|
220
|
+
chatType: msg.group_id ? "group" : "single"
|
|
221
|
+
};
|
|
222
|
+
this.callbacks.onText(text, identity);
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* 获取微信用户的 typing_ticket(打字态凭证)。
|
|
226
|
+
*/
|
|
227
|
+
async getTypingTicket(userId, contextToken) {
|
|
228
|
+
const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
|
|
229
|
+
try {
|
|
230
|
+
const resp = await fetch(`${baseUrl}/ilink/bot/getconfig`, {
|
|
231
|
+
method: "POST",
|
|
232
|
+
headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
|
|
233
|
+
body: JSON.stringify({
|
|
234
|
+
ilink_user_id: userId,
|
|
235
|
+
context_token: contextToken || "",
|
|
236
|
+
base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
|
|
237
|
+
}),
|
|
238
|
+
signal: AbortSignal.timeout(8e3)
|
|
239
|
+
});
|
|
240
|
+
if (!resp.ok) return "";
|
|
241
|
+
const data = await resp.json();
|
|
242
|
+
return data.typing_ticket ?? "";
|
|
243
|
+
} catch {
|
|
244
|
+
return "";
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* 向微信客户端发送「对方正在输入…」指示。
|
|
249
|
+
*/
|
|
250
|
+
async sendTypingIndicator(toUserId, typingTicket) {
|
|
251
|
+
if (!typingTicket) return false;
|
|
252
|
+
const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
|
|
253
|
+
try {
|
|
254
|
+
const resp = await fetch(`${baseUrl}/ilink/bot/sendtyping`, {
|
|
255
|
+
method: "POST",
|
|
256
|
+
headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
|
|
257
|
+
body: JSON.stringify({
|
|
258
|
+
ilink_user_id: toUserId,
|
|
259
|
+
typing_ticket: typingTicket,
|
|
260
|
+
base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
|
|
261
|
+
}),
|
|
262
|
+
signal: AbortSignal.timeout(6e3)
|
|
263
|
+
});
|
|
264
|
+
if (!resp.ok) return false;
|
|
265
|
+
const data = await resp.json();
|
|
266
|
+
return data.ret === 0;
|
|
267
|
+
} catch {
|
|
268
|
+
return false;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* 发送回复消息回微信用户。
|
|
273
|
+
*/
|
|
274
|
+
async sendMessage(toUserId, content, contextToken) {
|
|
275
|
+
const baseUrl = this.cred.baseUrl || ILINK_BASE_URL;
|
|
276
|
+
const clientId = `dsh-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
277
|
+
try {
|
|
278
|
+
const resp = await fetch(`${baseUrl}/ilink/bot/sendmessage`, {
|
|
279
|
+
method: "POST",
|
|
280
|
+
headers: _WechatIlinkBridge.buildHeaders(this.cred.botToken),
|
|
281
|
+
body: JSON.stringify({
|
|
282
|
+
msg: {
|
|
283
|
+
from_user_id: "",
|
|
284
|
+
to_user_id: toUserId,
|
|
285
|
+
client_id: clientId,
|
|
286
|
+
message_type: 2,
|
|
287
|
+
// BOT
|
|
288
|
+
message_state: 2,
|
|
289
|
+
// FINISH
|
|
290
|
+
context_token: contextToken || "",
|
|
291
|
+
item_list: [
|
|
292
|
+
{
|
|
293
|
+
type: 1,
|
|
294
|
+
// TEXT
|
|
295
|
+
text_item: { text: content }
|
|
296
|
+
}
|
|
297
|
+
]
|
|
298
|
+
},
|
|
299
|
+
base_info: { channel_version: "2.4.8", bot_agent: "DSH-Message-Gateway" }
|
|
300
|
+
}),
|
|
301
|
+
signal: AbortSignal.timeout(15e3)
|
|
302
|
+
});
|
|
303
|
+
if (!resp.ok) {
|
|
304
|
+
console.error("[dsh-message-gateway] wechat sendmessage failed:", resp.status);
|
|
305
|
+
return false;
|
|
306
|
+
}
|
|
307
|
+
const data = await resp.json();
|
|
308
|
+
return data.ret === 0;
|
|
309
|
+
} catch (err) {
|
|
310
|
+
console.error("[dsh-message-gateway] wechat sendmessage error:", err);
|
|
311
|
+
return false;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
/**
|
|
315
|
+
* 停止微信长轮询连接。
|
|
316
|
+
*/
|
|
317
|
+
stop() {
|
|
318
|
+
this.stopped = true;
|
|
319
|
+
this.pollController?.abort();
|
|
320
|
+
this.pollController = null;
|
|
321
|
+
this.setStatus("idle");
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
}
|
|
325
|
+
});
|
|
326
|
+
|
|
11
327
|
// src/host/gateway-store.ts
|
|
12
328
|
var gateway_store_exports = {};
|
|
13
329
|
__export(gateway_store_exports, {
|
|
@@ -458,6 +774,67 @@ var WecomBridge = class {
|
|
|
458
774
|
}
|
|
459
775
|
};
|
|
460
776
|
|
|
777
|
+
// src/host/proxy.ts
|
|
778
|
+
import { ProxyAgent, fetch as undiciFetch } from "undici";
|
|
779
|
+
var cachedProxyUrl = void 0;
|
|
780
|
+
async function getProxyUrl() {
|
|
781
|
+
if (cachedProxyUrl !== void 0) return cachedProxyUrl;
|
|
782
|
+
const envProxy = process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY || process.env.all_proxy || process.env.ALL_PROXY;
|
|
783
|
+
if (envProxy) {
|
|
784
|
+
cachedProxyUrl = envProxy;
|
|
785
|
+
return cachedProxyUrl;
|
|
786
|
+
}
|
|
787
|
+
const commonPorts = [7890, 7897, 10808, 10809, 1087];
|
|
788
|
+
const net = await import("node:net");
|
|
789
|
+
for (const port of commonPorts) {
|
|
790
|
+
const isUp = await new Promise((resolve) => {
|
|
791
|
+
const socket = net.connect({ host: "127.0.0.1", port, timeout: 500 });
|
|
792
|
+
socket.once("connect", () => {
|
|
793
|
+
socket.destroy();
|
|
794
|
+
resolve(true);
|
|
795
|
+
});
|
|
796
|
+
socket.once("error", () => resolve(false));
|
|
797
|
+
socket.once("timeout", () => {
|
|
798
|
+
socket.destroy();
|
|
799
|
+
resolve(false);
|
|
800
|
+
});
|
|
801
|
+
});
|
|
802
|
+
if (isUp) {
|
|
803
|
+
cachedProxyUrl = `http://127.0.0.1:${port}`;
|
|
804
|
+
console.log(`[dsh-message-gateway] auto-detected local proxy on port ${port}`);
|
|
805
|
+
return cachedProxyUrl;
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
cachedProxyUrl = null;
|
|
809
|
+
return null;
|
|
810
|
+
}
|
|
811
|
+
async function getProxyDispatcher() {
|
|
812
|
+
const proxyUrl = await getProxyUrl();
|
|
813
|
+
if (proxyUrl) {
|
|
814
|
+
return new ProxyAgent(proxyUrl);
|
|
815
|
+
}
|
|
816
|
+
return void 0;
|
|
817
|
+
}
|
|
818
|
+
async function smartFetch(url, init) {
|
|
819
|
+
const urlStr = String(url);
|
|
820
|
+
const isOverseas = /discord\.com|telegram\.org|api\.openai\.com/i.test(urlStr);
|
|
821
|
+
if (isOverseas) {
|
|
822
|
+
const dispatcher = await getProxyDispatcher();
|
|
823
|
+
if (dispatcher) {
|
|
824
|
+
const res2 = await undiciFetch(urlStr, { ...init, dispatcher });
|
|
825
|
+
return {
|
|
826
|
+
status: res2.status,
|
|
827
|
+
json: () => res2.json()
|
|
828
|
+
};
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
const res = await fetch(url, init);
|
|
832
|
+
return {
|
|
833
|
+
status: res.status,
|
|
834
|
+
json: () => res.json()
|
|
835
|
+
};
|
|
836
|
+
}
|
|
837
|
+
|
|
461
838
|
// src/host/telegram-bridge.ts
|
|
462
839
|
var EDIT_INTERVAL_MS = 1200;
|
|
463
840
|
var MSG_LIMIT = 4096;
|
|
@@ -491,11 +868,13 @@ var TelegramBridge = class {
|
|
|
491
868
|
const controller = new AbortController();
|
|
492
869
|
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
493
870
|
try {
|
|
871
|
+
const dispatcher = await getProxyDispatcher();
|
|
494
872
|
const response = await fetch(`https://api.telegram.org/bot${this.token}/${method}`, {
|
|
495
873
|
method: "POST",
|
|
496
874
|
headers: { "content-type": "application/json" },
|
|
497
875
|
body: JSON.stringify(params),
|
|
498
|
-
signal: controller.signal
|
|
876
|
+
signal: controller.signal,
|
|
877
|
+
...dispatcher ? { dispatcher } : {}
|
|
499
878
|
});
|
|
500
879
|
const body = await response.json();
|
|
501
880
|
if (body.ok === true) return body.result;
|
|
@@ -648,6 +1027,7 @@ var TelegramBridge = class {
|
|
|
648
1027
|
};
|
|
649
1028
|
|
|
650
1029
|
// src/host/discord-bridge.ts
|
|
1030
|
+
import { WebSocket as UndiciWebSocket } from "undici";
|
|
651
1031
|
var GATEWAY_URL = "wss://gateway.discord.gg/?v=10&encoding=json";
|
|
652
1032
|
var REST = "https://discord.com/api/v10";
|
|
653
1033
|
var INTENTS = 1 << 0 | 1 << 9 | 1 << 12 | 1 << 15;
|
|
@@ -681,26 +1061,33 @@ var DiscordBridge = class {
|
|
|
681
1061
|
}
|
|
682
1062
|
connect() {
|
|
683
1063
|
if (this.stopped) return;
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
this.clearHeartbeat();
|
|
698
|
-
this.ws = null;
|
|
699
|
-
if (!this.stopped) {
|
|
700
|
-
console.warn("[dsh-message-gateway] discord gateway closed, reconnect in 3s");
|
|
701
|
-
setTimeout(() => this.connect(), 3e3);
|
|
1064
|
+
void (async () => {
|
|
1065
|
+
let ws;
|
|
1066
|
+
try {
|
|
1067
|
+
const dispatcher = await getProxyDispatcher();
|
|
1068
|
+
if (dispatcher) {
|
|
1069
|
+
ws = new UndiciWebSocket(GATEWAY_URL, { dispatcher });
|
|
1070
|
+
} else {
|
|
1071
|
+
ws = new WebSocket(GATEWAY_URL);
|
|
1072
|
+
}
|
|
1073
|
+
} catch (error) {
|
|
1074
|
+
console.error("[dsh-message-gateway] discord ws create failed", error);
|
|
1075
|
+
this.setStatus("error", "ws create failed");
|
|
1076
|
+
return;
|
|
702
1077
|
}
|
|
703
|
-
|
|
1078
|
+
this.ws = ws;
|
|
1079
|
+
ws.onopen = () => console.log("[dsh-message-gateway] discord gateway open");
|
|
1080
|
+
ws.onmessage = (event) => this.onMessage(String(event.data));
|
|
1081
|
+
ws.onerror = () => console.warn("[dsh-message-gateway] discord gateway ws error");
|
|
1082
|
+
ws.onclose = () => {
|
|
1083
|
+
this.clearHeartbeat();
|
|
1084
|
+
this.ws = null;
|
|
1085
|
+
if (!this.stopped) {
|
|
1086
|
+
console.warn("[dsh-message-gateway] discord gateway closed, reconnect in 3s");
|
|
1087
|
+
setTimeout(() => this.connect(), 3e3);
|
|
1088
|
+
}
|
|
1089
|
+
};
|
|
1090
|
+
})();
|
|
704
1091
|
}
|
|
705
1092
|
onMessage(raw) {
|
|
706
1093
|
let payload;
|
|
@@ -723,8 +1110,10 @@ var DiscordBridge = class {
|
|
|
723
1110
|
}
|
|
724
1111
|
case 0: {
|
|
725
1112
|
if (payload.t === "READY") {
|
|
726
|
-
|
|
727
|
-
|
|
1113
|
+
const user = payload.d?.user;
|
|
1114
|
+
const name = user?.username ? `@${user.username}` : "\u5DF2\u8FDE\u63A5";
|
|
1115
|
+
this.setStatus("connected", name);
|
|
1116
|
+
console.log("[dsh-message-gateway] discord READY", name);
|
|
728
1117
|
} else if (payload.t === "MESSAGE_CREATE") {
|
|
729
1118
|
this.handleMessage(payload.d);
|
|
730
1119
|
}
|
|
@@ -737,7 +1126,7 @@ var DiscordBridge = class {
|
|
|
737
1126
|
}
|
|
738
1127
|
}
|
|
739
1128
|
sendOp(op, d) {
|
|
740
|
-
if (this.ws === null || this.ws.readyState !==
|
|
1129
|
+
if (this.ws === null || this.ws.readyState !== 1) return;
|
|
741
1130
|
this.ws.send(JSON.stringify({ op, d }));
|
|
742
1131
|
}
|
|
743
1132
|
identify() {
|
|
@@ -762,17 +1151,14 @@ var DiscordBridge = class {
|
|
|
762
1151
|
const controller = new AbortController();
|
|
763
1152
|
const timer = setTimeout(() => controller.abort(), 15e3);
|
|
764
1153
|
try {
|
|
765
|
-
const response = await
|
|
1154
|
+
const response = await smartFetch(`${REST}${path}`, {
|
|
766
1155
|
method,
|
|
767
1156
|
headers: { authorization: `Bot ${this.token}`, "content-type": "application/json" },
|
|
768
1157
|
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
769
1158
|
signal: controller.signal
|
|
770
1159
|
});
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
return null;
|
|
774
|
-
}
|
|
775
|
-
return await response.json();
|
|
1160
|
+
const data = await response.json();
|
|
1161
|
+
return data;
|
|
776
1162
|
} catch (error) {
|
|
777
1163
|
console.warn("[dsh-message-gateway] discord rest failed", method, path, String(error));
|
|
778
1164
|
return null;
|
|
@@ -2124,6 +2510,7 @@ var DingTalkBridge = class {
|
|
|
2124
2510
|
};
|
|
2125
2511
|
|
|
2126
2512
|
// src/host/bridge-manager.ts
|
|
2513
|
+
init_wechat_ilink_bridge();
|
|
2127
2514
|
var DEFAULT_MAX_CHAT_AGENTS = 40;
|
|
2128
2515
|
var STREAM_PUSH_INTERVAL = 600;
|
|
2129
2516
|
var ACK_HEARTBEAT_INTERVAL = 4e3;
|
|
@@ -2375,6 +2762,8 @@ var BridgeManager = class {
|
|
|
2375
2762
|
this.feishu = null;
|
|
2376
2763
|
this.dingtalk?.stop();
|
|
2377
2764
|
this.dingtalk = null;
|
|
2765
|
+
this.wechat?.stop();
|
|
2766
|
+
this.wechat = null;
|
|
2378
2767
|
this.finishAllPending();
|
|
2379
2768
|
const entries = [...this.agents.values()];
|
|
2380
2769
|
this.agents.clear();
|
|
@@ -2842,6 +3231,29 @@ ${secret}`;
|
|
|
2842
3231
|
email = null;
|
|
2843
3232
|
feishu = null;
|
|
2844
3233
|
dingtalk = null;
|
|
3234
|
+
wechat = null;
|
|
3235
|
+
/** 启动微信智能机器人桥(腾讯 iLink 官方协议长轮询)。 */
|
|
3236
|
+
startWechat(cred) {
|
|
3237
|
+
this.wechat?.stop();
|
|
3238
|
+
const ilinkCred = {
|
|
3239
|
+
botToken: cred.botToken ?? "",
|
|
3240
|
+
baseUrl: cred.baseUrl,
|
|
3241
|
+
botId: cred.botId,
|
|
3242
|
+
userId: cred.userId,
|
|
3243
|
+
nickname: cred.nickname
|
|
3244
|
+
};
|
|
3245
|
+
const bridge = new WechatIlinkBridge(ilinkCred, {
|
|
3246
|
+
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3247
|
+
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
3248
|
+
});
|
|
3249
|
+
this.wechat = bridge;
|
|
3250
|
+
bridge.start();
|
|
3251
|
+
}
|
|
3252
|
+
/** 停止微信桥。 */
|
|
3253
|
+
stopWechat() {
|
|
3254
|
+
this.wechat?.stop();
|
|
3255
|
+
this.wechat = null;
|
|
3256
|
+
}
|
|
2845
3257
|
/** 启动 DingTalk 桥(企业自建应用 Stream 模式 WebSocket 长连接)。 */
|
|
2846
3258
|
startDingTalk(cred) {
|
|
2847
3259
|
this.dingtalk?.stop();
|
|
@@ -2986,6 +3398,7 @@ ${secret}`;
|
|
|
2986
3398
|
if (id === "email") return this.email?.status ?? { state: "idle", detail: "", connectedAt: null };
|
|
2987
3399
|
if (id === "feishu") return this.feishu?.status ?? { state: "idle", detail: "", connectedAt: null };
|
|
2988
3400
|
if (id === "dingtalk") return this.dingtalk?.status ?? { state: "idle", detail: "", connectedAt: null };
|
|
3401
|
+
if (id === "wechat") return this.wechat?.status ?? { state: "idle", detail: "", connectedAt: null };
|
|
2989
3402
|
return { state: "idle", detail: "", connectedAt: null };
|
|
2990
3403
|
}
|
|
2991
3404
|
/** 将桥状态并入存储状态。 */
|
|
@@ -3061,7 +3474,8 @@ ${secret}`;
|
|
|
3061
3474
|
bridgeLine("QQ", this.bridgeStatus("qq")),
|
|
3062
3475
|
bridgeLine("Email", this.bridgeStatus("email")),
|
|
3063
3476
|
bridgeLine("Feishu", this.bridgeStatus("feishu")),
|
|
3064
|
-
bridgeLine("DingTalk", this.bridgeStatus("dingtalk"))
|
|
3477
|
+
bridgeLine("DingTalk", this.bridgeStatus("dingtalk")),
|
|
3478
|
+
bridgeLine("WeChat", this.bridgeStatus("wechat"))
|
|
3065
3479
|
];
|
|
3066
3480
|
reply(lines.join("\n"));
|
|
3067
3481
|
return true;
|
|
@@ -3167,10 +3581,7 @@ var PLATFORMS = [
|
|
|
3167
3581
|
icon: "\u{1F49A}",
|
|
3168
3582
|
testable: false,
|
|
3169
3583
|
hintKey: "platform.wechat.hint",
|
|
3170
|
-
fields: [
|
|
3171
|
-
{ key: "gatewayUrl", labelKey: "field.gatewayUrl", placeholderKey: "field.gatewayUrl.ph", kind: "text" },
|
|
3172
|
-
{ key: "token", labelKey: "field.token", placeholderKey: "field.secret.ph", kind: "secret" }
|
|
3173
|
-
]
|
|
3584
|
+
fields: []
|
|
3174
3585
|
},
|
|
3175
3586
|
{
|
|
3176
3587
|
id: "wechat-mp",
|
|
@@ -3272,7 +3683,7 @@ async function httpJson(url, init) {
|
|
|
3272
3683
|
const controller = new AbortController();
|
|
3273
3684
|
const timer = setTimeout(() => controller.abort(), 12e3);
|
|
3274
3685
|
try {
|
|
3275
|
-
const response = await
|
|
3686
|
+
const response = await smartFetch(url, { ...init, signal: controller.signal });
|
|
3276
3687
|
let body = null;
|
|
3277
3688
|
try {
|
|
3278
3689
|
body = await response.json();
|
|
@@ -3783,10 +4194,10 @@ async function buildView(manager) {
|
|
|
3783
4194
|
for (const def of PLATFORMS) {
|
|
3784
4195
|
const stored = store.statuses[def.id];
|
|
3785
4196
|
const configured = store.platforms[def.id] !== void 0;
|
|
3786
|
-
let state = stored?.state ??
|
|
3787
|
-
let detail = stored?.detail ?? "";
|
|
3788
|
-
let testedAt = stored?.testedAt ?? null;
|
|
3789
|
-
if (def.id === "wecom-aibot" || def.id === "telegram" || def.id === "discord" || def.id === "qq" || def.id === "email" || def.id === "feishu" || def.id === "dingtalk") {
|
|
4197
|
+
let state = configured ? stored?.state ?? "none" : def.id === "webhooks" ? "manual" : "none";
|
|
4198
|
+
let detail = configured ? stored?.detail ?? "" : "";
|
|
4199
|
+
let testedAt = configured ? stored?.testedAt ?? null : null;
|
|
4200
|
+
if (configured && (def.id === "wecom-aibot" || def.id === "telegram" || def.id === "discord" || def.id === "qq" || def.id === "email" || def.id === "feishu" || def.id === "dingtalk" || def.id === "wechat")) {
|
|
3790
4201
|
const merged = manager.mergeStatus(stored, def.id);
|
|
3791
4202
|
state = merged.state;
|
|
3792
4203
|
detail = merged.detail;
|
|
@@ -4119,6 +4530,49 @@ function registerGatewayRoutes(ctx, manager) {
|
|
|
4119
4530
|
json(res, { ok: true, value: await buildView(manager) });
|
|
4120
4531
|
return;
|
|
4121
4532
|
}
|
|
4533
|
+
if (path === "/gateway/wechat/qr") {
|
|
4534
|
+
try {
|
|
4535
|
+
const { WechatIlinkBridge: WechatIlinkBridge2 } = await Promise.resolve().then(() => (init_wechat_ilink_bridge(), wechat_ilink_bridge_exports));
|
|
4536
|
+
const qr = await WechatIlinkBridge2.getLoginQr();
|
|
4537
|
+
json(res, { ok: true, value: qr });
|
|
4538
|
+
} catch (e) {
|
|
4539
|
+
json(res, { ok: false, error: { code: "internal", message: e instanceof Error ? e.message : String(e) } });
|
|
4540
|
+
}
|
|
4541
|
+
return;
|
|
4542
|
+
}
|
|
4543
|
+
if (path === "/gateway/wechat/qr-status") {
|
|
4544
|
+
const body = payload;
|
|
4545
|
+
const qrcode = body?.qrcode ?? "";
|
|
4546
|
+
if (!qrcode) {
|
|
4547
|
+
json(res, { ok: false, error: { code: "internal", message: "missing qrcode" } });
|
|
4548
|
+
return;
|
|
4549
|
+
}
|
|
4550
|
+
try {
|
|
4551
|
+
const { WechatIlinkBridge: WechatIlinkBridge2 } = await Promise.resolve().then(() => (init_wechat_ilink_bridge(), wechat_ilink_bridge_exports));
|
|
4552
|
+
const status = await WechatIlinkBridge2.pollQrStatus(qrcode);
|
|
4553
|
+
if (status.status === "confirmed" && status.botToken) {
|
|
4554
|
+
const store = await loadStore();
|
|
4555
|
+
const cred = {
|
|
4556
|
+
botToken: status.botToken,
|
|
4557
|
+
baseUrl: status.baseUrl ?? "",
|
|
4558
|
+
botId: status.botId ?? "",
|
|
4559
|
+
userId: status.userId ?? ""
|
|
4560
|
+
};
|
|
4561
|
+
store.platforms.wechat = cred;
|
|
4562
|
+
store.statuses.wechat = {
|
|
4563
|
+
state: "connected",
|
|
4564
|
+
detail: status.userId ? `@${status.userId}` : "\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA",
|
|
4565
|
+
testedAt: Date.now()
|
|
4566
|
+
};
|
|
4567
|
+
await saveStore(store);
|
|
4568
|
+
manager.startWechat(cred);
|
|
4569
|
+
}
|
|
4570
|
+
json(res, { ok: true, value: status });
|
|
4571
|
+
} catch (e) {
|
|
4572
|
+
json(res, { ok: false, error: { code: "internal", message: e instanceof Error ? e.message : String(e) } });
|
|
4573
|
+
}
|
|
4574
|
+
return;
|
|
4575
|
+
}
|
|
4122
4576
|
if (path === "/gateway/save" || path === "/gateway/delete" || path === "/gateway/test") {
|
|
4123
4577
|
const platform = payload?.platform;
|
|
4124
4578
|
if (typeof platform !== "string") {
|
|
@@ -4137,6 +4591,7 @@ function registerGatewayRoutes(ctx, manager) {
|
|
|
4137
4591
|
if (platform === "email") manager.stopEmail();
|
|
4138
4592
|
if (platform === "feishu") manager.stopFeishu();
|
|
4139
4593
|
if (platform === "dingtalk") manager.stopDingTalk();
|
|
4594
|
+
if (platform === "wechat") manager.stopWechat();
|
|
4140
4595
|
json(res, { ok: true, value: await buildView(manager) });
|
|
4141
4596
|
return;
|
|
4142
4597
|
}
|
|
@@ -4193,20 +4648,30 @@ function registerGatewayRoutes(ctx, manager) {
|
|
|
4193
4648
|
manager.stopDingTalk();
|
|
4194
4649
|
}
|
|
4195
4650
|
}
|
|
4651
|
+
if (platform === "wechat") {
|
|
4652
|
+
if (credentials2.botToken !== void 0 && credentials2.botToken !== "") {
|
|
4653
|
+
manager.startWechat(credentials2);
|
|
4654
|
+
} else {
|
|
4655
|
+
manager.stopWechat();
|
|
4656
|
+
}
|
|
4657
|
+
}
|
|
4196
4658
|
json(res, { ok: true, value: await buildView(manager) });
|
|
4197
4659
|
return;
|
|
4198
4660
|
}
|
|
4199
4661
|
const submitted = extractCredentials(platform, payload);
|
|
4200
4662
|
const hasSubmitted = Object.keys(submitted).length > 0;
|
|
4663
|
+
const isConfigured = store.platforms[platform] !== void 0;
|
|
4201
4664
|
const credentials = hasSubmitted ? submitted : store.platforms[platform] ?? {};
|
|
4202
4665
|
const result = await testPlatform(platform, credentials);
|
|
4203
|
-
|
|
4204
|
-
|
|
4205
|
-
|
|
4206
|
-
|
|
4207
|
-
|
|
4208
|
-
|
|
4209
|
-
|
|
4666
|
+
if (isConfigured && !hasSubmitted) {
|
|
4667
|
+
const stored = {
|
|
4668
|
+
state: result.ok ? "connected" : "error",
|
|
4669
|
+
detail: result.detail,
|
|
4670
|
+
testedAt: Date.now()
|
|
4671
|
+
};
|
|
4672
|
+
store.statuses[platform] = stored;
|
|
4673
|
+
await saveStore(store);
|
|
4674
|
+
}
|
|
4210
4675
|
json(res, { ok: true, value: { ok: result.ok, detail: result.detail } });
|
|
4211
4676
|
return;
|
|
4212
4677
|
}
|
|
@@ -4295,6 +4760,11 @@ function apply(ctx, config = Config({})) {
|
|
|
4295
4760
|
manager.startDingTalk(dingtalk);
|
|
4296
4761
|
console.log("[dsh-message-gateway] dingtalk bridge auto-started");
|
|
4297
4762
|
}
|
|
4763
|
+
const wechat = store.platforms.wechat;
|
|
4764
|
+
if (wechat !== void 0 && wechat.botToken !== "" && wechat.botToken !== void 0) {
|
|
4765
|
+
manager.startWechat(wechat);
|
|
4766
|
+
console.log("[dsh-message-gateway] wechat bridge auto-started");
|
|
4767
|
+
}
|
|
4298
4768
|
});
|
|
4299
4769
|
const disposeRoutes = registerGatewayRoutes(ctx, manager);
|
|
4300
4770
|
let disposeTools;
|