@wechatbot/wechatbot 2.1.1 → 2.3.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.
- package/README.md +18 -0
- package/dist/auth/authenticator.d.ts +10 -0
- package/dist/auth/authenticator.d.ts.map +1 -1
- package/dist/auth/authenticator.js +68 -3
- package/dist/auth/authenticator.js.map +1 -1
- package/dist/auth/types.d.ts +7 -0
- package/dist/auth/types.d.ts.map +1 -1
- package/dist/core/client.d.ts +61 -3
- package/dist/core/client.d.ts.map +1 -1
- package/dist/core/client.js +108 -42
- package/dist/core/client.js.map +1 -1
- package/dist/core/errors.d.ts +6 -0
- package/dist/core/errors.d.ts.map +1 -1
- package/dist/core/errors.js +8 -0
- package/dist/core/errors.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/media/downloader.d.ts +3 -1
- package/dist/media/downloader.d.ts.map +1 -1
- package/dist/media/downloader.js +5 -2
- package/dist/media/downloader.js.map +1 -1
- package/dist/media/index.d.ts +1 -1
- package/dist/media/index.d.ts.map +1 -1
- package/dist/media/index.js +1 -1
- package/dist/media/index.js.map +1 -1
- package/dist/media/markdown.d.ts +12 -0
- package/dist/media/markdown.d.ts.map +1 -1
- package/dist/media/markdown.js +17 -0
- package/dist/media/markdown.js.map +1 -1
- package/dist/media/remote.d.ts +3 -0
- package/dist/media/remote.d.ts.map +1 -1
- package/dist/media/remote.js +3 -1
- package/dist/media/remote.js.map +1 -1
- package/dist/media/uploader.d.ts +3 -1
- package/dist/media/uploader.d.ts.map +1 -1
- package/dist/media/uploader.js +5 -2
- package/dist/media/uploader.js.map +1 -1
- package/dist/message/cache.d.ts +30 -0
- package/dist/message/cache.d.ts.map +1 -0
- package/dist/message/cache.js +53 -0
- package/dist/message/cache.js.map +1 -0
- package/dist/message/index.d.ts +2 -0
- package/dist/message/index.d.ts.map +1 -1
- package/dist/message/index.js +2 -0
- package/dist/message/index.js.map +1 -1
- package/dist/message/parser.d.ts.map +1 -1
- package/dist/message/parser.js +10 -2
- package/dist/message/parser.js.map +1 -1
- package/dist/message/partial-quote.d.ts +15 -0
- package/dist/message/partial-quote.d.ts.map +1 -0
- package/dist/message/partial-quote.js +41 -0
- package/dist/message/partial-quote.js.map +1 -0
- package/dist/message/types.d.ts +15 -0
- package/dist/message/types.d.ts.map +1 -1
- package/dist/messaging/sender.d.ts +4 -3
- package/dist/messaging/sender.d.ts.map +1 -1
- package/dist/messaging/sender.js +8 -3
- package/dist/messaging/sender.js.map +1 -1
- package/dist/protocol/api.d.ts +38 -5
- package/dist/protocol/api.d.ts.map +1 -1
- package/dist/protocol/api.js +85 -14
- package/dist/protocol/api.js.map +1 -1
- package/dist/protocol/bot-agent.d.ts +11 -0
- package/dist/protocol/bot-agent.d.ts.map +1 -0
- package/dist/protocol/bot-agent.js +32 -0
- package/dist/protocol/bot-agent.js.map +1 -0
- package/dist/protocol/headers.d.ts +14 -2
- package/dist/protocol/headers.d.ts.map +1 -1
- package/dist/protocol/headers.js +30 -8
- package/dist/protocol/headers.js.map +1 -1
- package/dist/protocol/index.d.ts +1 -0
- package/dist/protocol/index.d.ts.map +1 -1
- package/dist/protocol/index.js +1 -0
- package/dist/protocol/index.js.map +1 -1
- package/dist/protocol/json.d.ts +12 -0
- package/dist/protocol/json.d.ts.map +1 -0
- package/dist/protocol/json.js +69 -0
- package/dist/protocol/json.js.map +1 -0
- package/dist/protocol/types.d.ts +31 -2
- package/dist/protocol/types.d.ts.map +1 -1
- package/dist/protocol/types.js +14 -1
- package/dist/protocol/types.js.map +1 -1
- package/dist/transport/fetch.d.ts +8 -0
- package/dist/transport/fetch.d.ts.map +1 -0
- package/dist/transport/fetch.js +5 -0
- package/dist/transport/fetch.js.map +1 -0
- package/dist/transport/http.d.ts +8 -1
- package/dist/transport/http.d.ts.map +1 -1
- package/dist/transport/http.js +14 -7
- package/dist/transport/http.js.map +1 -1
- package/dist/transport/types.d.ts +2 -0
- package/dist/transport/types.d.ts.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -57,6 +57,24 @@ const bot = new WeChatBot({
|
|
|
57
57
|
})
|
|
58
58
|
```
|
|
59
59
|
|
|
60
|
+
### Proxy
|
|
61
|
+
|
|
62
|
+
Node's built-in `fetch` ignores `HTTPS_PROXY`. To send requests through a proxy:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
// Node 22.21+ / 24.5+: built-in proxy support (process-wide)
|
|
66
|
+
new WeChatBot({ proxy: 'http://127.0.0.1:7890' })
|
|
67
|
+
new WeChatBot({ proxy: true }) // read HTTPS_PROXY / HTTP_PROXY / NO_PROXY
|
|
68
|
+
|
|
69
|
+
// Any Node version: pass your own fetch, e.g. undici with a ProxyAgent
|
|
70
|
+
import { fetch as undiciFetch, ProxyAgent } from 'undici'
|
|
71
|
+
const dispatcher = new ProxyAgent('http://127.0.0.1:7890')
|
|
72
|
+
new WeChatBot({ fetch: (url, init) => undiciFetch(url, { ...init, dispatcher }) })
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
You can also start Node with `NODE_USE_ENV_PROXY=1` and `HTTPS_PROXY` set. The
|
|
76
|
+
custom `fetch` covers the iLink API, the CDN, and `{ url }` downloads.
|
|
77
|
+
|
|
60
78
|
## API Reference
|
|
61
79
|
|
|
62
80
|
### Lifecycle
|
|
@@ -2,6 +2,11 @@ import type { Logger } from '../logger/types.js';
|
|
|
2
2
|
import type { ILinkApi } from '../protocol/api.js';
|
|
3
3
|
import type { Storage } from '../storage/interface.js';
|
|
4
4
|
import type { Credentials, QrLoginCallbacks } from './types.js';
|
|
5
|
+
/**
|
|
6
|
+
* Any status that contains this marker asks for the digits shown on the phone
|
|
7
|
+
* (`need_verifycode`, `confirmed_but_need_verifycode`, …), as upstream does.
|
|
8
|
+
*/
|
|
9
|
+
export declare function statusNeedsVerifyCode(status: string): boolean;
|
|
5
10
|
/**
|
|
6
11
|
* Handles the entire QR login flow with credential persistence.
|
|
7
12
|
* Separated from the main client so it can be tested / replaced independently.
|
|
@@ -34,5 +39,10 @@ export declare class Authenticator {
|
|
|
34
39
|
* - Limits QR refreshes to MAX_QR_REFRESH_COUNT
|
|
35
40
|
*/
|
|
36
41
|
private qrLogin;
|
|
42
|
+
/**
|
|
43
|
+
* Obtain a pairing code from the developer callback, or fall back to a
|
|
44
|
+
* stdin prompt.
|
|
45
|
+
*/
|
|
46
|
+
private promptVerifyCode;
|
|
37
47
|
}
|
|
38
48
|
//# sourceMappingURL=authenticator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authenticator.d.ts","sourceRoot":"","sources":["../../src/auth/authenticator.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"authenticator.d.ts","sourceRoot":"","sources":["../../src/auth/authenticator.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAA;AAChD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAElD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAA;AAEtD,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAK/D;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAE7D;AAKD;;;GAGG;AACH,qBAAa,aAAa;IAItB,OAAO,CAAC,QAAQ,CAAC,GAAG;IACpB,OAAO,CAAC,QAAQ,CAAC,OAAO;IAJ1B,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;gBAGZ,GAAG,EAAE,QAAQ,EACb,OAAO,EAAE,OAAO,EACjC,MAAM,EAAE,MAAM;IAKhB;;OAEG;IACG,eAAe,IAAI,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC;IAIzD;;OAEG;IACG,KAAK,CAAC,OAAO,GAAE;QACnB,KAAK,CAAC,EAAE,OAAO,CAAA;QACf,OAAO,CAAC,EAAE,MAAM,CAAA;QAChB,SAAS,CAAC,EAAE,gBAAgB,CAAA;KACxB,GAAG,OAAO,CAAC,WAAW,CAAC;IAc7B;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAU/B;;;;;OAKG;YACW,OAAO;IA4HrB;;;OAGG;YACW,gBAAgB;CA0B/B"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline/promises';
|
|
1
2
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
2
3
|
import { AuthError } from '../core/errors.js';
|
|
3
4
|
import { DEFAULT_BASE_URL } from '../protocol/types.js';
|
|
@@ -5,6 +6,13 @@ import { STORAGE_KEYS } from '../storage/interface.js';
|
|
|
5
6
|
const QR_POLL_INTERVAL_MS = 2_000;
|
|
6
7
|
/** Maximum number of times to refresh the QR code before giving up. */
|
|
7
8
|
const MAX_QR_REFRESH_COUNT = 3;
|
|
9
|
+
/**
|
|
10
|
+
* Any status that contains this marker asks for the digits shown on the phone
|
|
11
|
+
* (`need_verifycode`, `confirmed_but_need_verifycode`, …), as upstream does.
|
|
12
|
+
*/
|
|
13
|
+
export function statusNeedsVerifyCode(status) {
|
|
14
|
+
return status.includes('need_verifycode');
|
|
15
|
+
}
|
|
8
16
|
/** Fixed API base URL for QR code requests (matches npm package). */
|
|
9
17
|
const FIXED_QR_BASE_URL = 'https://ilinkai.weixin.qq.com';
|
|
10
18
|
/**
|
|
@@ -60,28 +68,40 @@ export class Authenticator {
|
|
|
60
68
|
*/
|
|
61
69
|
async qrLogin(baseUrl, callbacks) {
|
|
62
70
|
let qrRefreshCount = 0;
|
|
71
|
+
// Send known local tokens so the server can answer `binded_redirect`
|
|
72
|
+
// instead of issuing a duplicate session for an already-bound bot.
|
|
73
|
+
const stored = await this.loadCredentials();
|
|
74
|
+
const localTokenList = stored?.token ? [stored.token] : [];
|
|
63
75
|
for (;;) {
|
|
64
76
|
qrRefreshCount++;
|
|
65
77
|
if (qrRefreshCount > MAX_QR_REFRESH_COUNT) {
|
|
66
78
|
throw new AuthError(`QR code expired ${MAX_QR_REFRESH_COUNT} times — login aborted`);
|
|
67
79
|
}
|
|
68
80
|
this.logger.info(`Requesting QR code... (${qrRefreshCount}/${MAX_QR_REFRESH_COUNT})`);
|
|
69
|
-
const qr = await this.api.getQrCode(FIXED_QR_BASE_URL);
|
|
81
|
+
const qr = await this.api.getQrCode(FIXED_QR_BASE_URL, localTokenList);
|
|
70
82
|
// Pass QR URL to developer's callback — display is their responsibility
|
|
71
83
|
if (callbacks?.onQrUrl) {
|
|
72
84
|
callbacks.onQrUrl(qr.qrcode_img_content);
|
|
73
85
|
}
|
|
74
86
|
else {
|
|
75
|
-
|
|
87
|
+
// Warn level: without a callback this line is the only way to get the QR.
|
|
88
|
+
this.logger.warn(`Scan this QR code in WeChat (pass loginCallbacks.onQrUrl to handle it yourself): ${qr.qrcode_img_content}`);
|
|
76
89
|
}
|
|
77
90
|
let lastStatus;
|
|
78
91
|
// Current polling URL; may be updated on IDC redirect
|
|
79
92
|
let currentPollBaseUrl = FIXED_QR_BASE_URL;
|
|
93
|
+
// Pairing code awaiting server verification (pair-code login flow)
|
|
94
|
+
let pendingVerifyCode;
|
|
80
95
|
for (;;) {
|
|
81
|
-
const status = await this.api.pollQrStatus(currentPollBaseUrl, qr.qrcode);
|
|
96
|
+
const status = await this.api.pollQrStatus(currentPollBaseUrl, qr.qrcode, pendingVerifyCode);
|
|
82
97
|
if (status.status !== lastStatus) {
|
|
83
98
|
lastStatus = status.status;
|
|
84
99
|
if (status.status === 'scaned') {
|
|
100
|
+
// A pending pairing code that leads back to `scaned` was accepted
|
|
101
|
+
if (pendingVerifyCode) {
|
|
102
|
+
this.logger.info('Pairing code accepted');
|
|
103
|
+
pendingVerifyCode = undefined;
|
|
104
|
+
}
|
|
85
105
|
this.logger.info('QR scanned — confirm in WeChat');
|
|
86
106
|
callbacks?.onScanned?.();
|
|
87
107
|
}
|
|
@@ -111,6 +131,27 @@ export class Authenticator {
|
|
|
111
131
|
});
|
|
112
132
|
return credentials;
|
|
113
133
|
}
|
|
134
|
+
// Pair-code challenge: ask the user for the digits shown in WeChat
|
|
135
|
+
if (statusNeedsVerifyCode(status.status)) {
|
|
136
|
+
const isRetry = pendingVerifyCode !== undefined;
|
|
137
|
+
pendingVerifyCode = await this.promptVerifyCode(isRetry, callbacks);
|
|
138
|
+
continue; // Re-poll immediately with the code attached
|
|
139
|
+
}
|
|
140
|
+
// Too many wrong pairing codes: server blocked this QR — request a new one
|
|
141
|
+
if (status.status === 'verify_code_blocked') {
|
|
142
|
+
this.logger.warn('Pairing code blocked after repeated mismatches — requesting new QR');
|
|
143
|
+
pendingVerifyCode = undefined;
|
|
144
|
+
break; // Outer loop will request a new QR (counts toward the refresh limit)
|
|
145
|
+
}
|
|
146
|
+
// Already bound to this client: reuse existing local credentials
|
|
147
|
+
if (status.status === 'binded_redirect') {
|
|
148
|
+
if (stored) {
|
|
149
|
+
this.logger.info('Bot already bound to this client — reusing stored credentials');
|
|
150
|
+
return stored;
|
|
151
|
+
}
|
|
152
|
+
throw new AuthError('Server reports this bot is already bound to this client (binded_redirect), ' +
|
|
153
|
+
'but no local credentials were found');
|
|
154
|
+
}
|
|
114
155
|
// IDC redirect: switch polling host
|
|
115
156
|
if (status.status === 'scaned_but_redirect') {
|
|
116
157
|
if (status.redirect_host) {
|
|
@@ -130,5 +171,29 @@ export class Authenticator {
|
|
|
130
171
|
}
|
|
131
172
|
}
|
|
132
173
|
}
|
|
174
|
+
/**
|
|
175
|
+
* Obtain a pairing code from the developer callback, or fall back to a
|
|
176
|
+
* stdin prompt.
|
|
177
|
+
*/
|
|
178
|
+
async promptVerifyCode(isRetry, callbacks) {
|
|
179
|
+
if (callbacks?.onVerifyCode) {
|
|
180
|
+
return callbacks.onVerifyCode(isRetry);
|
|
181
|
+
}
|
|
182
|
+
if (!process.stdin.isTTY) {
|
|
183
|
+
throw new AuthError('WeChat asked for the pairing code shown on the phone, but no ' +
|
|
184
|
+
'loginCallbacks.onVerifyCode was given and stdin is not a terminal. ' +
|
|
185
|
+
'Pass onVerifyCode to supply the code.');
|
|
186
|
+
}
|
|
187
|
+
const prompt = isRetry
|
|
188
|
+
? 'Code mismatch — enter the pairing code shown in WeChat again: '
|
|
189
|
+
: 'Enter the pairing code shown in WeChat on your phone: ';
|
|
190
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
191
|
+
try {
|
|
192
|
+
return (await rl.question(prompt)).trim();
|
|
193
|
+
}
|
|
194
|
+
finally {
|
|
195
|
+
rl.close();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
133
198
|
}
|
|
134
199
|
//# sourceMappingURL=authenticator.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"authenticator.js","sourceRoot":"","sources":["../../src/auth/authenticator.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,IAAI,KAAK,EAAE,MAAM,sBAAsB,CAAA;AAC1D,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAA;AAG7C,OAAO,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAA;AAEvD,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAA;AAGtD,MAAM,mBAAmB,GAAG,KAAK,CAAA;AACjC,uEAAuE;AACvE,MAAM,oBAAoB,GAAG,CAAC,CAAA;AAC9B,qEAAqE;AACrE,MAAM,iBAAiB,GAAG,+BAA+B,CAAA;AAEzD;;;GAGG;AACH,MAAM,OAAO,aAAa;IAIL;IACA;IAJF,MAAM,CAAQ;IAE/B,YACmB,GAAa,EACb,OAAgB,EACjC,MAAc;QAFG,QAAG,GAAH,GAAG,CAAU;QACb,YAAO,GAAP,OAAO,CAAS;QAGjC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC,KAAK,CAAC,MAAM,CAAC,CAAA;IACpC,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,eAAe;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K,CAAC,mCAAmC;gBAC3C,CAAC;gBAED,MAAM,KAAK,CAAC,mBAAmB,CAAC,CAAA;YAClC,CAAC;QACH,CAAC;IACH,CAAC;IAED;;;OAGG;IACK,KAAK,CAAC,gBAAgB,CAC5B,OAAgB,EAChB,SAA4B;QAE5B,IAAI,SAAS,EAAE,YAAY,EAAE,CAAC;YAC5B,OAAO,SAAS,CAAC,YAAY,CAAC,OAAO,CAAC,CAAA;QACxC,CAAC;QAED,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;YACzB,MAAM,IAAI,SAAS,CACjB,+DAA+D;gBAC7D,qEAAqE;gBACrE,uCAAuC,CAC1C,CAAA;QACH,CAAC;QAED,MAAM,MAAM,GAAG,OAAO;YACpB,CAAC,CAAC,gEAAgE;YAClE,CAAC,CAAC,wDAAwD,CAAA;QAC5D,MAAM,EAAE,GAAG,eAAe,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAA;QAC5E,IAAI,CAAC;YACH,OAAO,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,EAAE,CAAA;QAC3C,CAAC;gBAAS,CAAC;YACT,EAAE,CAAC,KAAK,EAAE,CAAA;QACZ,CAAC;IACH,CAAC;CACF"}
|
package/dist/auth/types.d.ts
CHANGED
|
@@ -12,5 +12,12 @@ export interface QrLoginCallbacks {
|
|
|
12
12
|
onScanned?: () => void;
|
|
13
13
|
/** Called when the QR code has expired and a new one will be requested. */
|
|
14
14
|
onExpired?: () => void;
|
|
15
|
+
/**
|
|
16
|
+
* Called when the server requires a pairing code (the digits shown in
|
|
17
|
+
* WeChat on the user's phone). `isRetry` is true when a previously
|
|
18
|
+
* submitted code was rejected. Defaults to a stdin prompt when stdin is a
|
|
19
|
+
* terminal; otherwise login fails with an AuthError.
|
|
20
|
+
*/
|
|
21
|
+
onVerifyCode?: (isRetry: boolean) => string | Promise<string>;
|
|
15
22
|
}
|
|
16
23
|
//# sourceMappingURL=types.d.ts.map
|
package/dist/auth/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,8DAA8D;IAC9D,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAA;IAC/B,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;IACtB,2EAA2E;IAC3E,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/auth/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,WAAW;IAC1B,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;IACf,SAAS,EAAE,MAAM,CAAA;IACjB,MAAM,EAAE,MAAM,CAAA;IACd,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,gBAAgB;IAC/B,8DAA8D;IAC9D,OAAO,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,IAAI,CAAA;IAC/B,wEAAwE;IACxE,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;IACtB,2EAA2E;IAC3E,SAAS,CAAC,EAAE,MAAM,IAAI,CAAA;IACtB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAA;CAC9D"}
|
package/dist/core/client.d.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { MessageBuilder, type IncomingMessage } from '../message/index.js';
|
|
|
6
6
|
import { type Middleware } from '../middleware/index.js';
|
|
7
7
|
import { type CDNMedia } from '../protocol/types.js';
|
|
8
8
|
import { type Storage } from '../storage/index.js';
|
|
9
|
+
import type { FetchFunction } from '../transport/fetch.js';
|
|
9
10
|
export interface WeChatBotOptions {
|
|
10
11
|
/** Base URL for the iLink API (default: https://ilinkai.weixin.qq.com) */
|
|
11
12
|
baseUrl?: string;
|
|
@@ -19,6 +20,57 @@ export interface WeChatBotOptions {
|
|
|
19
20
|
logger?: Logger;
|
|
20
21
|
/** QR login callbacks (for rendering QR codes, etc.) */
|
|
21
22
|
loginCallbacks?: QrLoginCallbacks;
|
|
23
|
+
/**
|
|
24
|
+
* UA-style identifier of the app driving this bot, sent as `base_info.bot_agent`
|
|
25
|
+
* on every API request (e.g. "MyApp/1.2 (prod)"). Invalid values fall back to
|
|
26
|
+
* "WeChatBot/<version>".
|
|
27
|
+
*/
|
|
28
|
+
botAgent?: string;
|
|
29
|
+
/**
|
|
30
|
+
* How many recent messages (received and sent) to keep in memory, keyed by
|
|
31
|
+
* server message ID. Newer WeChat clients send only the ID of a quoted
|
|
32
|
+
* message; the SDK uses this cache to fill `quotedMessage.text`.
|
|
33
|
+
* Default 1000. Set 0 to disable.
|
|
34
|
+
*/
|
|
35
|
+
messageCacheSize?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Deployment route tag, e.g. "10086". Sent as the `SKRouteTag` header and as
|
|
38
|
+
* `_cradle_hostname=g<routeTag>` on every iLink API URL. Leave unset unless
|
|
39
|
+
* WeChat gave you one.
|
|
40
|
+
*/
|
|
41
|
+
routeTag?: string;
|
|
42
|
+
/**
|
|
43
|
+
* Ask WeChat to require the PIN shown on the phone when binding (sends
|
|
44
|
+
* `bot_spam_business_data` with `verify_pin: 1`). Handle the PIN with
|
|
45
|
+
* `loginCallbacks.onVerifyCode`. Default false.
|
|
46
|
+
*/
|
|
47
|
+
verifyPin?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Custom fetch for every HTTP request: iLink API, CDN, and `{ url }` media
|
|
50
|
+
* downloads. Use it to send traffic through a proxy, for example
|
|
51
|
+
* `fetch: (url, init) => undiciFetch(url, { ...init, dispatcher: new ProxyAgent(proxyUrl) })`.
|
|
52
|
+
* Overrides `proxy`.
|
|
53
|
+
*/
|
|
54
|
+
fetch?: FetchFunction;
|
|
55
|
+
/**
|
|
56
|
+
* Send all requests through an HTTP(S) proxy, e.g. "http://127.0.0.1:7890".
|
|
57
|
+
* `true` reads HTTPS_PROXY / HTTP_PROXY / NO_PROXY from the environment.
|
|
58
|
+
* Uses Node's built-in proxy support (`http.setGlobalProxyFromEnv`,
|
|
59
|
+
* Node 22.21+ / 24.5+), which is process-wide. On older Node, set
|
|
60
|
+
* NODE_USE_ENV_PROXY=1 instead, or pass `fetch`.
|
|
61
|
+
*/
|
|
62
|
+
proxy?: string | boolean;
|
|
63
|
+
}
|
|
64
|
+
/** Result of a send. */
|
|
65
|
+
export interface SendResult {
|
|
66
|
+
/**
|
|
67
|
+
* Server-assigned ID of the message, as a string (uint64). For long text
|
|
68
|
+
* split into chunks, the ID of the last chunk. Undefined when the server
|
|
69
|
+
* returned none.
|
|
70
|
+
*/
|
|
71
|
+
messageId?: string;
|
|
72
|
+
/** ID of the separate caption message, when a caption was sent. */
|
|
73
|
+
captionMessageId?: string;
|
|
22
74
|
}
|
|
23
75
|
/**
|
|
24
76
|
* What to send. Exactly one of text/image/file/video/url must be provided.
|
|
@@ -102,6 +154,7 @@ export declare class WeChatBot extends TypedEmitter<BotEventMap> {
|
|
|
102
154
|
readonly uploader: MediaUploader;
|
|
103
155
|
readonly downloader: MediaDownloader;
|
|
104
156
|
private readonly http;
|
|
157
|
+
private readonly fetchFn?;
|
|
105
158
|
private readonly api;
|
|
106
159
|
private readonly auth;
|
|
107
160
|
private readonly parser;
|
|
@@ -110,13 +163,16 @@ export declare class WeChatBot extends TypedEmitter<BotEventMap> {
|
|
|
110
163
|
private readonly poller;
|
|
111
164
|
private readonly sender;
|
|
112
165
|
private readonly typing;
|
|
166
|
+
private readonly messageCache;
|
|
113
167
|
private baseUrl;
|
|
114
168
|
private credentials?;
|
|
115
169
|
private messageHandlers;
|
|
116
170
|
private runPromise;
|
|
171
|
+
private readonly loginCallbacks?;
|
|
117
172
|
constructor(options?: WeChatBotOptions);
|
|
118
173
|
/**
|
|
119
174
|
* Login to WeChat. Uses stored credentials if available, otherwise starts QR flow.
|
|
175
|
+
* `options.callbacks` override the constructor's `loginCallbacks` field by field.
|
|
120
176
|
*/
|
|
121
177
|
login(options?: {
|
|
122
178
|
force?: boolean;
|
|
@@ -165,7 +221,7 @@ export declare class WeChatBot extends TypedEmitter<BotEventMap> {
|
|
|
165
221
|
* // From URL (auto-download, auto-detect type)
|
|
166
222
|
* await bot.reply(msg, { url: 'https://example.com/image.jpg' })
|
|
167
223
|
*/
|
|
168
|
-
reply(message: IncomingMessage, content: SendContent): Promise<
|
|
224
|
+
reply(message: IncomingMessage, content: SendContent): Promise<SendResult>;
|
|
169
225
|
/**
|
|
170
226
|
* Send content to a user by ID.
|
|
171
227
|
* Requires a prior context_token from that user (i.e., they messaged you first).
|
|
@@ -178,11 +234,11 @@ export declare class WeChatBot extends TypedEmitter<BotEventMap> {
|
|
|
178
234
|
* await bot.send(userId, { file: data, fileName: 'doc.pdf' })
|
|
179
235
|
* await bot.send(userId, { url: 'https://example.com/img.png' })
|
|
180
236
|
*/
|
|
181
|
-
send(userId: string, content: SendContent): Promise<
|
|
237
|
+
send(userId: string, content: SendContent): Promise<SendResult>;
|
|
182
238
|
/**
|
|
183
239
|
* Send a pre-built message payload (advanced use with MessageBuilder).
|
|
184
240
|
*/
|
|
185
|
-
sendRaw(payload: ReturnType<MessageBuilder['build']>): Promise<
|
|
241
|
+
sendRaw(payload: ReturnType<MessageBuilder['build']>): Promise<SendResult>;
|
|
186
242
|
/**
|
|
187
243
|
* Download media from an incoming message.
|
|
188
244
|
*
|
|
@@ -244,6 +300,8 @@ export declare class WeChatBot extends TypedEmitter<BotEventMap> {
|
|
|
244
300
|
* Core send implementation. All public send methods route through here.
|
|
245
301
|
*/
|
|
246
302
|
private sendContent;
|
|
303
|
+
/** Send text and remember it in the message cache under its server ID. */
|
|
304
|
+
private sendTrackedText;
|
|
247
305
|
/**
|
|
248
306
|
* Upload buffer to CDN and send as a message item.
|
|
249
307
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/core/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAG5D,OAAO,EAAiB,KAAK,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AACzF,OAAO,EAAgB,KAAK,MAAM,EAAE,KAAK,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAC7E,OAAO,EACL,eAAe,EACf,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,YAAY,EAKlB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,cAAc,EAAiB,KAAK,eAAe,
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/core/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAA;AAG5D,OAAO,EAAiB,KAAK,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AACzF,OAAO,EAAgB,KAAK,MAAM,EAAE,KAAK,QAAQ,EAAE,MAAM,oBAAoB,CAAA;AAC7E,OAAO,EACL,eAAe,EACf,aAAa,EACb,KAAK,aAAa,EAClB,KAAK,YAAY,EAKlB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EAAE,cAAc,EAAiB,KAAK,eAAe,EAA2B,MAAM,qBAAqB,CAAA;AAElH,OAAO,EAAoB,KAAK,U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|
|
4
4
|
import { createLogger } from '../logger/index.js';
|
|
5
5
|
import { MediaDownloader, MediaUploader, categorizeByMime, getMimeFromFilename, downloadFromUrl, silkToWav, } from '../media/index.js';
|
|
6
6
|
import { MessageBuilder, MessageParser } from '../message/index.js';
|
|
7
|
+
import { MessageCache } from '../message/cache.js';
|
|
7
8
|
import { MiddlewareEngine } from '../middleware/index.js';
|
|
8
9
|
import { ContextStore, MessagePoller, MessageSender, TypingService } from '../messaging/index.js';
|
|
9
10
|
import { ILinkApi } from '../protocol/api.js';
|
|
10
11
|
import { DEFAULT_BASE_URL, MediaType } from '../protocol/types.js';
|
|
11
12
|
import { FileStorage, MemoryStorage } from '../storage/index.js';
|
|
12
13
|
import { HttpClient } from '../transport/http.js';
|
|
14
|
+
import * as nodeHttp from 'node:http';
|
|
15
|
+
/**
|
|
16
|
+
* Pick the fetch for a client. A custom `fetch` wins. `proxy` turns on
|
|
17
|
+
* Node's built-in proxy support for the global fetch, process-wide.
|
|
18
|
+
*/
|
|
19
|
+
function resolveClientFetch(options, logger) {
|
|
20
|
+
if (options.fetch)
|
|
21
|
+
return options.fetch;
|
|
22
|
+
if (!options.proxy)
|
|
23
|
+
return undefined;
|
|
24
|
+
const setGlobalProxyFromEnv = nodeHttp.setGlobalProxyFromEnv;
|
|
25
|
+
if (typeof setGlobalProxyFromEnv !== 'function') {
|
|
26
|
+
logger.warn(`The proxy option needs Node 22.21+ or 24.5+ (running ${process.versions.node}). ` +
|
|
27
|
+
'Set NODE_USE_ENV_PROXY=1 with HTTPS_PROXY, or pass a custom fetch.');
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
if (options.proxy === true) {
|
|
31
|
+
setGlobalProxyFromEnv();
|
|
32
|
+
}
|
|
33
|
+
else {
|
|
34
|
+
setGlobalProxyFromEnv({
|
|
35
|
+
HTTP_PROXY: options.proxy,
|
|
36
|
+
HTTPS_PROXY: options.proxy,
|
|
37
|
+
NO_PROXY: process.env.NO_PROXY ?? process.env.no_proxy,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
const MEDIA_CONTENT_TYPE = {
|
|
43
|
+
[MediaType.IMAGE]: 'image',
|
|
44
|
+
[MediaType.VIDEO]: 'video',
|
|
45
|
+
[MediaType.FILE]: 'file',
|
|
46
|
+
[MediaType.VOICE]: 'voice',
|
|
47
|
+
};
|
|
13
48
|
// ═══════════════════════════════════════════════════════════════════════
|
|
14
49
|
// Main Client
|
|
15
50
|
// ═══════════════════════════════════════════════════════════════════════
|
|
@@ -51,6 +86,7 @@ export class WeChatBot extends TypedEmitter {
|
|
|
51
86
|
downloader;
|
|
52
87
|
// ── Internal services ───────────────────────────────────────────────
|
|
53
88
|
http;
|
|
89
|
+
fetchFn;
|
|
54
90
|
api;
|
|
55
91
|
auth;
|
|
56
92
|
parser;
|
|
@@ -59,29 +95,37 @@ export class WeChatBot extends TypedEmitter {
|
|
|
59
95
|
poller;
|
|
60
96
|
sender;
|
|
61
97
|
typing;
|
|
98
|
+
messageCache;
|
|
62
99
|
// ── State ───────────────────────────────────────────────────────────
|
|
63
100
|
baseUrl;
|
|
64
101
|
credentials;
|
|
65
102
|
messageHandlers = [];
|
|
66
103
|
runPromise = null;
|
|
104
|
+
loginCallbacks;
|
|
67
105
|
constructor(options = {}) {
|
|
68
106
|
super();
|
|
69
107
|
// Initialize foundational components
|
|
70
108
|
this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
|
|
109
|
+
this.loginCallbacks = options.loginCallbacks;
|
|
71
110
|
this.logger = options.logger ?? createLogger({ level: options.logLevel ?? 'info' });
|
|
72
111
|
this.storage = resolveStorage(options);
|
|
73
112
|
// Build the layered architecture
|
|
74
|
-
this.
|
|
75
|
-
this.
|
|
113
|
+
this.fetchFn = resolveClientFetch(options, this.logger);
|
|
114
|
+
this.http = new HttpClient({ logger: this.logger, fetch: this.fetchFn });
|
|
115
|
+
this.api = new ILinkApi(this.http, options.botAgent, {
|
|
116
|
+
routeTag: options.routeTag,
|
|
117
|
+
verifyPin: options.verifyPin,
|
|
118
|
+
});
|
|
76
119
|
this.auth = new Authenticator(this.api, this.storage, this.logger);
|
|
77
120
|
this.parser = new MessageParser();
|
|
121
|
+
this.messageCache = new MessageCache(options.messageCacheSize ?? 1000);
|
|
78
122
|
this.middleware = new MiddlewareEngine();
|
|
79
123
|
this.contextStore = new ContextStore(this.storage, this.logger);
|
|
80
124
|
this.poller = new MessagePoller(this.api, this.storage, this.logger);
|
|
81
125
|
this.sender = new MessageSender(this.api, this.contextStore, this.logger);
|
|
82
126
|
this.typing = new TypingService(this.api, this.contextStore, this.logger);
|
|
83
|
-
this.uploader = new MediaUploader(this.api, undefined, this.logger);
|
|
84
|
-
this.downloader = new MediaDownloader(undefined, this.logger);
|
|
127
|
+
this.uploader = new MediaUploader(this.api, undefined, this.logger, this.fetchFn);
|
|
128
|
+
this.downloader = new MediaDownloader(undefined, this.logger, this.fetchFn);
|
|
85
129
|
// Wire up internal events
|
|
86
130
|
this.setupPollerEvents();
|
|
87
131
|
}
|
|
@@ -90,12 +134,13 @@ export class WeChatBot extends TypedEmitter {
|
|
|
90
134
|
// ═══════════════════════════════════════════════════════════════════
|
|
91
135
|
/**
|
|
92
136
|
* Login to WeChat. Uses stored credentials if available, otherwise starts QR flow.
|
|
137
|
+
* `options.callbacks` override the constructor's `loginCallbacks` field by field.
|
|
93
138
|
*/
|
|
94
139
|
async login(options = {}) {
|
|
95
140
|
const creds = await this.auth.login({
|
|
96
141
|
force: options.force,
|
|
97
142
|
baseUrl: this.baseUrl,
|
|
98
|
-
callbacks: options.callbacks,
|
|
143
|
+
callbacks: { ...this.loginCallbacks, ...options.callbacks },
|
|
99
144
|
});
|
|
100
145
|
this.setCredentials(creds);
|
|
101
146
|
this.emit('login', creds);
|
|
@@ -165,8 +210,9 @@ export class WeChatBot extends TypedEmitter {
|
|
|
165
210
|
async reply(message, content) {
|
|
166
211
|
const creds = this.requireCredentials();
|
|
167
212
|
this.contextStore.set(message.userId, message._contextToken);
|
|
168
|
-
await this.sendContent(message.userId, message._contextToken, content);
|
|
213
|
+
const result = await this.sendContent(message.userId, message._contextToken, content);
|
|
169
214
|
this.typing.stopTyping(creds.baseUrl, creds.token, message.userId).catch(() => { });
|
|
215
|
+
return result;
|
|
170
216
|
}
|
|
171
217
|
/**
|
|
172
218
|
* Send content to a user by ID.
|
|
@@ -184,14 +230,14 @@ export class WeChatBot extends TypedEmitter {
|
|
|
184
230
|
const ctx = this.contextStore.get(userId);
|
|
185
231
|
if (!ctx)
|
|
186
232
|
throw new NoContextError(userId);
|
|
187
|
-
|
|
233
|
+
return this.sendContent(userId, ctx, content);
|
|
188
234
|
}
|
|
189
235
|
/**
|
|
190
236
|
* Send a pre-built message payload (advanced use with MessageBuilder).
|
|
191
237
|
*/
|
|
192
238
|
async sendRaw(payload) {
|
|
193
239
|
const creds = this.requireCredentials();
|
|
194
|
-
await this.sender.sendRaw(creds.baseUrl, creds.token, payload);
|
|
240
|
+
return { messageId: await this.sender.sendRaw(creds.baseUrl, creds.token, payload) };
|
|
195
241
|
}
|
|
196
242
|
// ═══════════════════════════════════════════════════════════════════
|
|
197
243
|
// Downloading — one method: download()
|
|
@@ -294,6 +340,10 @@ export class WeChatBot extends TypedEmitter {
|
|
|
294
340
|
this.contextStore.load(),
|
|
295
341
|
this.poller.loadCursor(),
|
|
296
342
|
]);
|
|
343
|
+
// Tell the server we're coming online (non-fatal)
|
|
344
|
+
await this.api.notifyStart(creds.baseUrl, creds.token).catch((error) => {
|
|
345
|
+
this.logger.warn(`notifyStart failed (ignored): ${error instanceof Error ? error.message : String(error)}`);
|
|
346
|
+
});
|
|
297
347
|
this.emit('poll:start');
|
|
298
348
|
this.runPromise = this.poller.start(creds.baseUrl, creds.token);
|
|
299
349
|
try {
|
|
@@ -301,6 +351,12 @@ export class WeChatBot extends TypedEmitter {
|
|
|
301
351
|
}
|
|
302
352
|
finally {
|
|
303
353
|
this.runPromise = null;
|
|
354
|
+
// Tell the server we're going offline (non-fatal).
|
|
355
|
+
// Credentials may have rotated after a mid-poll re-login, so re-read them.
|
|
356
|
+
const current = this.credentials ?? creds;
|
|
357
|
+
await this.api.notifyStop(current.baseUrl, current.token).catch((error) => {
|
|
358
|
+
this.logger.warn(`notifyStop failed (ignored): ${error instanceof Error ? error.message : String(error)}`);
|
|
359
|
+
});
|
|
304
360
|
this.emit('poll:stop');
|
|
305
361
|
}
|
|
306
362
|
}
|
|
@@ -344,17 +400,15 @@ export class WeChatBot extends TypedEmitter {
|
|
|
344
400
|
const creds = this.requireCredentials();
|
|
345
401
|
// String shorthand → text
|
|
346
402
|
if (typeof content === 'string') {
|
|
347
|
-
await this.
|
|
348
|
-
return;
|
|
403
|
+
return { messageId: await this.sendTrackedText(creds, userId, content, contextToken) };
|
|
349
404
|
}
|
|
350
405
|
// { text }
|
|
351
406
|
if ('text' in content) {
|
|
352
|
-
await this.
|
|
353
|
-
return;
|
|
407
|
+
return { messageId: await this.sendTrackedText(creds, userId, content.text, contextToken) };
|
|
354
408
|
}
|
|
355
409
|
// { url } → download then re-route
|
|
356
410
|
if ('url' in content) {
|
|
357
|
-
const result = await downloadFromUrl(content.url, { logger: this.logger });
|
|
411
|
+
const result = await downloadFromUrl(content.url, { logger: this.logger, fetch: this.fetchFn });
|
|
358
412
|
const fileName = content.fileName ?? result.filename;
|
|
359
413
|
return this.sendContent(userId, contextToken, {
|
|
360
414
|
file: result.data,
|
|
@@ -364,43 +418,41 @@ export class WeChatBot extends TypedEmitter {
|
|
|
364
418
|
}
|
|
365
419
|
// { image }
|
|
366
420
|
if ('image' in content) {
|
|
367
|
-
|
|
421
|
+
return this.sendMediaBuffer(creds, userId, contextToken, content.image, MediaType.IMAGE, (builder, result) => {
|
|
368
422
|
builder.image({ media: result.media, midSize: result.encryptedFileSize });
|
|
369
423
|
}, content.caption);
|
|
370
|
-
return;
|
|
371
424
|
}
|
|
372
425
|
// { video }
|
|
373
426
|
if ('video' in content) {
|
|
374
|
-
|
|
427
|
+
return this.sendMediaBuffer(creds, userId, contextToken, content.video, MediaType.VIDEO, (builder, result) => {
|
|
375
428
|
builder.video({ media: result.media, videoSize: result.encryptedFileSize });
|
|
376
429
|
}, content.caption);
|
|
377
|
-
return;
|
|
378
430
|
}
|
|
379
431
|
// { file, fileName } — auto-route by extension
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
caption: content.caption,
|
|
393
|
-
});
|
|
394
|
-
}
|
|
395
|
-
// Generic file
|
|
396
|
-
if (content.caption) {
|
|
397
|
-
await this.sender.sendText(creds.baseUrl, creds.token, userId, content.caption, contextToken);
|
|
398
|
-
}
|
|
399
|
-
await this.sendMediaBuffer(creds, userId, contextToken, content.file, MediaType.FILE, (builder, result) => {
|
|
400
|
-
builder.file({ media: result.media, fileName: content.fileName, size: content.file.length });
|
|
432
|
+
const mime = getMimeFromFilename(content.fileName);
|
|
433
|
+
const category = categorizeByMime(mime);
|
|
434
|
+
if (category === 'image') {
|
|
435
|
+
return this.sendContent(userId, contextToken, {
|
|
436
|
+
image: content.file,
|
|
437
|
+
caption: content.caption,
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
if (category === 'video') {
|
|
441
|
+
return this.sendContent(userId, contextToken, {
|
|
442
|
+
video: content.file,
|
|
443
|
+
caption: content.caption,
|
|
401
444
|
});
|
|
402
|
-
return;
|
|
403
445
|
}
|
|
446
|
+
// Generic file
|
|
447
|
+
return this.sendMediaBuffer(creds, userId, contextToken, content.file, MediaType.FILE, (builder, result) => {
|
|
448
|
+
builder.file({ media: result.media, fileName: content.fileName, size: content.file.length });
|
|
449
|
+
}, content.caption);
|
|
450
|
+
}
|
|
451
|
+
/** Send text and remember it in the message cache under its server ID. */
|
|
452
|
+
async sendTrackedText(creds, userId, text, contextToken) {
|
|
453
|
+
const messageId = await this.sender.sendText(creds.baseUrl, creds.token, userId, text, contextToken);
|
|
454
|
+
this.messageCache.put(messageId, { text, type: 'text', fromBot: true });
|
|
455
|
+
return messageId;
|
|
404
456
|
}
|
|
405
457
|
/**
|
|
406
458
|
* Upload buffer to CDN and send as a message item.
|
|
@@ -411,12 +463,19 @@ export class WeChatBot extends TypedEmitter {
|
|
|
411
463
|
userId,
|
|
412
464
|
mediaType,
|
|
413
465
|
});
|
|
466
|
+
// iLink rejects a text item and a media item in one item_list
|
|
467
|
+
// ("invalid arguments"), so the caption goes first as its own message.
|
|
468
|
+
let captionMessageId;
|
|
469
|
+
if (caption) {
|
|
470
|
+
captionMessageId = await this.sendTrackedText(creds, userId, caption, contextToken);
|
|
471
|
+
}
|
|
414
472
|
const builder = MessageBuilder.to(userId, contextToken);
|
|
415
|
-
if (caption)
|
|
416
|
-
builder.text(caption);
|
|
417
473
|
buildItem(builder, result);
|
|
418
|
-
await this.sender.sendRaw(creds.baseUrl, creds.token, builder.build());
|
|
474
|
+
const messageId = await this.sender.sendRaw(creds.baseUrl, creds.token, builder.build());
|
|
475
|
+
const type = MEDIA_CONTENT_TYPE[mediaType];
|
|
476
|
+
this.messageCache.put(messageId, { text: `[${type}]`, type, fromBot: true });
|
|
419
477
|
this.logger.info('Sent media', { userId, mediaType, size: data.length });
|
|
478
|
+
return { messageId, ...(captionMessageId ? { captionMessageId } : {}) };
|
|
420
479
|
}
|
|
421
480
|
// ═══════════════════════════════════════════════════════════════════
|
|
422
481
|
// Internal wiring
|
|
@@ -431,6 +490,13 @@ export class WeChatBot extends TypedEmitter {
|
|
|
431
490
|
const incoming = this.parser.parse(wire);
|
|
432
491
|
if (!incoming)
|
|
433
492
|
continue;
|
|
493
|
+
// Fill an ID-only quote from the cache, then remember this message
|
|
494
|
+
this.messageCache.resolve(incoming.quotedMessage);
|
|
495
|
+
this.messageCache.put(incoming.messageId, {
|
|
496
|
+
text: incoming.text,
|
|
497
|
+
type: incoming.type,
|
|
498
|
+
fromBot: false,
|
|
499
|
+
});
|
|
434
500
|
// Run through middleware chain
|
|
435
501
|
const ctx = await this.middleware.run(incoming);
|
|
436
502
|
if (ctx.handled)
|