@kadaliao/dsh-bots 0.3.3 → 0.4.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.
@@ -0,0 +1,590 @@
1
+ /**
2
+ * Discord transport for bot chat channels: a Gateway (API v10) connection for
3
+ * inbound messages and the REST API for replies and the typing indicator.
4
+ *
5
+ * Transport only: it knows nothing about bots, pairing or the store. Messages
6
+ * from humans arrive normalised through `onMessage` (the caller decides which
7
+ * ones to answer); `send` splits long replies at Discord's 2000-character limit.
8
+ *
9
+ * - Heartbeats on the Hello interval, the first one jittered. A beat that goes
10
+ * unacknowledged means a dead connection: the session resumes on a new socket.
11
+ * - Reconnect (op 7), Invalid Session (op 9) and dropped connections resume when
12
+ * Discord allows it and identify again otherwise, with exponential backoff
13
+ * (1 s … 60 s) while the network is down.
14
+ * - A bad token (HTTP 401 / close 4004), a missing Message Content intent (4014)
15
+ * and the other unrecoverable close codes (4010–4013) are fatal: no reconnects.
16
+ * - The token never appears in log lines, thrown errors or status details.
17
+ *
18
+ * @module @kadaliao/dsh-bots/lib/channels/discord
19
+ */
20
+
21
+ export const kind = 'discord';
22
+ export const TEXT_LIMIT = 2000;
23
+
24
+ /** GUILDS | GUILD_MESSAGES | DIRECT_MESSAGES | MESSAGE_CONTENT */
25
+ export const INTENTS = (1 << 0) | (1 << 9) | (1 << 12) | (1 << 15);
26
+
27
+ const API_BASE = 'https://discord.com/api/v10';
28
+ const USER_AGENT = 'DiscordBot (https://github.com/kadaliao/dsh-plugins, 0.4)';
29
+ const GATEWAY_QUERY = '/?v=10&encoding=json';
30
+ const MIN_BACKOFF = 1000;
31
+ const MAX_BACKOFF = 60_000;
32
+ const RATE_LIMIT_RETRIES = 3;
33
+ const MAX_RETRY_WAIT = 60_000;
34
+ /** Any close code but 1000/1001 keeps the session resumable. */
35
+ const RESUME_CLOSE = 4000;
36
+ const FENCE = '```';
37
+ const CLOSE_FENCE = `\n${FENCE}`;
38
+
39
+ const INVALID_TOKEN = 'Discord rejected the bot token (invalid bot token). Copy it again from the Developer Portal: your app → Bot → Reset Token.';
40
+ const FATAL_CLOSE = {
41
+ 4004: INVALID_TOKEN,
42
+ 4010: 'Discord rejected the connection (close 4010: invalid shard).',
43
+ 4011: 'Discord requires sharding for this bot (close 4011): it is in too many servers for one connection.',
44
+ 4012: 'Discord rejected the gateway version (close 4012).',
45
+ 4013: 'Discord rejected the requested intents (close 4013: invalid intents).',
46
+ 4014: 'Discord refused the Message Content intent (close 4014). In the Developer Portal open your app → Bot → Privileged Gateway Intents, turn on Message Content Intent, save, then reconnect the channel.',
47
+ };
48
+ /** The session is gone: start a new one instead of resuming. */
49
+ const REIDENTIFY_CLOSE = new Set([4007, 4009]);
50
+
51
+ const escapeRe = (s) => String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
52
+
53
+ /**
54
+ * Reconnect delay for the n-th consecutive failure (0-based): doubles from 1 s,
55
+ * capped at 60 s, ±20 % jitter.
56
+ * @param {number} attempt
57
+ * @param {() => number} [random]
58
+ */
59
+ export function backoffDelay(attempt, random = Math.random) {
60
+ const base = Math.min(MAX_BACKOFF, MIN_BACKOFF * 2 ** Math.max(0, attempt));
61
+ return Math.round(Math.min(MAX_BACKOFF, Math.max(MIN_BACKOFF, base * (0.8 + 0.4 * random()))));
62
+ }
63
+
64
+ /**
65
+ * A `MESSAGE_CREATE` payload as a channel message, or null when it is not a
66
+ * human's text message (bots, webhooks, the bot itself, system messages, empty).
67
+ * @param {object} d the event payload
68
+ * @param {string} botId the bot's own user id
69
+ * @param {string[]} [botRoleIds] the bot's managed role in this guild (people often @ the role by mistake)
70
+ */
71
+ export function normalizeMessage(d, botId, botRoleIds = []) {
72
+ const author = d?.author;
73
+ if (!author?.id || !botId) return null;
74
+ if (author.bot || author.system || d.webhook_id || author.id === botId) return null;
75
+ if (d.type != null && d.type !== 0 && d.type !== 19) return null; // default and reply only
76
+ const raw = typeof d.content === 'string' ? d.content : '';
77
+ if (!raw.trim()) return null;
78
+ const isDirect = !d.guild_id;
79
+ const roles = (botRoleIds ?? []).map(String);
80
+ const mentioned = isDirect
81
+ || (Array.isArray(d.mentions) && d.mentions.some((u) => u?.id === botId))
82
+ || d.referenced_message?.author?.id === botId
83
+ || (Array.isArray(d.mention_roles) && d.mention_roles.some((r) => roles.includes(String(r))))
84
+ || raw.includes(`<@${botId}>`) || raw.includes(`<@!${botId}>`);
85
+ let text = raw.replace(new RegExp(`<@!?${escapeRe(botId)}>\\s*`, 'g'), '');
86
+ if (roles.length) text = text.replace(new RegExp(`<@&(?:${roles.map(escapeRe).join('|')})>\\s*`, 'g'), '');
87
+ text = text.trim();
88
+ if (!text) return null;
89
+ return {
90
+ chatId: String(d.channel_id),
91
+ messageId: String(d.id),
92
+ userId: String(author.id),
93
+ userName: String(d.member?.nick ?? author.global_name ?? author.username ?? author.id),
94
+ text,
95
+ isDirect,
96
+ mentioned,
97
+ };
98
+ }
99
+
100
+ /** Whether `s` ends inside a ``` block, where that block opened, and its language tag. */
101
+ function fenceState(s) {
102
+ let open = false;
103
+ let at = -1;
104
+ let lang = '';
105
+ for (let i = s.indexOf(FENCE); i !== -1; i = s.indexOf(FENCE, i + FENCE.length)) {
106
+ open = !open;
107
+ if (open) {
108
+ at = i;
109
+ lang = /^([\w+#.-]{1,16})?(?=\n|$)/.exec(s.slice(i + FENCE.length, i + FENCE.length + 18))?.[1] ?? '';
110
+ }
111
+ }
112
+ return { open, at, lang };
113
+ }
114
+
115
+ /** Where to cut `s` so the head is at most `budget` long: a late newline, a late space, any newline, any space, or a hard cut. */
116
+ function cutPoint(s, budget) {
117
+ const win = s.slice(0, budget + 1); // a separator right at the budget is dropped, so it may sit there
118
+ const half = budget / 2;
119
+ const nl = win.lastIndexOf('\n');
120
+ const sp = win.lastIndexOf(' ');
121
+ if (nl >= half) return { cut: nl, skip: 1 };
122
+ if (sp >= half) return { cut: sp, skip: 1 };
123
+ if (nl > 0) return { cut: nl, skip: 1 };
124
+ if (sp > 0) return { cut: sp, skip: 1 };
125
+ let cut = Math.max(1, budget);
126
+ const code = s.charCodeAt(cut - 1);
127
+ if (cut > 1 && code >= 0xd800 && code <= 0xdbff) cut -= 1; // don't split a surrogate pair
128
+ return { cut, skip: 0 };
129
+ }
130
+
131
+ /**
132
+ * Split a reply into Discord-sized messages. Cuts prefer the last newline, then
133
+ * the last space; a cut inside a ``` block closes it at the end of the chunk
134
+ * and reopens it (same language) at the start of the next. Never yields an
135
+ * empty or whitespace-only chunk.
136
+ * @param {string} text
137
+ * @param {number} [limit]
138
+ * @returns {string[]}
139
+ */
140
+ export function splitMessage(text, limit = TEXT_LIMIT) {
141
+ let rest = String(text ?? '').replace(/\r\n?/g, '\n');
142
+ const out = [];
143
+ let reopen = '';
144
+ while (rest) {
145
+ if (!reopen) rest = rest.replace(/^\n+/, '');
146
+ if (!rest) break;
147
+ if (reopen.length + rest.length <= limit) {
148
+ if (rest.trim()) out.push(reopen + rest.trimEnd());
149
+ break;
150
+ }
151
+ const budget = Math.max(1, limit - reopen.length - CLOSE_FENCE.length);
152
+ let { cut, skip } = cutPoint(rest, budget);
153
+ let chunk = reopen + rest.slice(0, cut);
154
+ let fence = fenceState(chunk);
155
+ if (fence.open && fence.at > reopen.length && !chunk.slice(fence.at + FENCE.length + fence.lang.length).trim()) {
156
+ // The chunk would end on a bare opening fence: start the next one with it instead.
157
+ cut = fence.at - reopen.length;
158
+ skip = 0;
159
+ chunk = reopen + rest.slice(0, cut);
160
+ fence = fenceState(chunk);
161
+ }
162
+ if (chunk.slice(reopen.length).trim()) out.push(fence.open ? `${chunk.trimEnd()}${CLOSE_FENCE}` : chunk.trimEnd());
163
+ reopen = fence.open ? `${FENCE}${fence.lang}\n` : '';
164
+ rest = rest.slice(cut + skip);
165
+ }
166
+ return out;
167
+ }
168
+
169
+ /** Seconds to wait from a 429 (JSON `retry_after` or the `Retry-After` header), in ms. */
170
+ function retryAfterMs(data, headers) {
171
+ const sec = Number(data?.retry_after ?? headers?.get?.('retry-after'));
172
+ return Number.isFinite(sec) && sec >= 0 ? Math.min(MAX_RETRY_WAIT, Math.ceil(sec * 1000)) : 1000;
173
+ }
174
+
175
+ async function readJson(res) {
176
+ try {
177
+ const t = await res.text();
178
+ return t ? JSON.parse(t) : null;
179
+ } catch {
180
+ return null;
181
+ }
182
+ }
183
+
184
+ /**
185
+ * @typedef {object} ChannelMessage
186
+ * @property {string} chatId
187
+ * @property {string} messageId
188
+ * @property {string} userId
189
+ * @property {string} userName
190
+ * @property {string} text the bot's own mention removed, trimmed
191
+ * @property {boolean} isDirect a 1:1 DM with the bot
192
+ * @property {boolean} mentioned @mentioned or replied to; always true in a DM
193
+ * @property {string} [chatTitle] `Server #channel`, when the channel is known
194
+ */
195
+
196
+ /**
197
+ * @param {object} opts
198
+ * @param {string} opts.token the bot token (a pasted `Bot ` prefix is dropped)
199
+ * @param {(msg: ChannelMessage) => void} opts.onMessage
200
+ * @param {(s: { state: 'connecting'|'connected'|'error'|'stopped', detail?: string, fatal?: boolean }) => void} [opts.onStatus]
201
+ * @param {typeof fetch} [opts.fetchImpl]
202
+ * @param {typeof WebSocket} [opts.WebSocketImpl]
203
+ * @param {string} [opts.apiBase]
204
+ * @param {(line: string) => void} [opts.log]
205
+ * @param {typeof setTimeout} [opts.setTimeoutImpl] for tests
206
+ * @param {typeof clearTimeout} [opts.clearTimeoutImpl] for tests
207
+ * @param {() => number} [opts.random] for tests (heartbeat and backoff jitter)
208
+ */
209
+ export function createConnector(opts = {}) {
210
+ const {
211
+ onMessage = () => {},
212
+ onStatus,
213
+ fetchImpl = globalThis.fetch,
214
+ WebSocketImpl = globalThis.WebSocket,
215
+ log: logImpl,
216
+ setTimeoutImpl = setTimeout,
217
+ clearTimeoutImpl = clearTimeout,
218
+ random = Math.random,
219
+ } = opts;
220
+ const token = String(opts.token ?? '').trim().replace(/^Bot\s+/i, '');
221
+ const apiBase = String(opts.apiBase || API_BASE).replace(/\/+$/, '');
222
+
223
+ /** Belt and braces: no string leaves this module with the token in it. */
224
+ const scrub = (v) => {
225
+ const s = String(v ?? '');
226
+ return token.length >= 8 ? s.split(token).join('[token]') : s;
227
+ };
228
+ const log = (line) => {
229
+ try { logImpl?.(scrub(line)); } catch { /* a broken logger must not break the connection */ }
230
+ };
231
+ const status = (state, detail, fatal = false) => {
232
+ const s = { state };
233
+ if (detail) s.detail = scrub(detail);
234
+ if (state === 'error') s.fatal = fatal;
235
+ try { onStatus?.(s); } catch (e) { log(`discord: onStatus threw: ${e?.message ?? e}`); }
236
+ };
237
+ const guard = (fn) => (...args) => {
238
+ try { fn(...args); } catch (e) { log(`discord: ${e?.message ?? e}`); }
239
+ };
240
+
241
+ // --- REST ---------------------------------------------------------------------------
242
+
243
+ const sleepers = new Set();
244
+ const sleep = (ms) => new Promise((resolve, reject) => {
245
+ const entry = { reject };
246
+ entry.timer = setTimeoutImpl(() => { sleepers.delete(entry); resolve(); }, ms);
247
+ sleepers.add(entry);
248
+ });
249
+
250
+ async function api(method, path, body, retries = RATE_LIMIT_RETRIES) {
251
+ const headers = { Authorization: `Bot ${token}`, 'User-Agent': USER_AGENT };
252
+ if (body !== undefined) headers['Content-Type'] = 'application/json';
253
+ for (let attempt = 0; ; attempt += 1) {
254
+ let res;
255
+ try {
256
+ res = await fetchImpl(`${apiBase}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
257
+ } catch (e) {
258
+ throw new Error(scrub(`Discord ${method} ${path} failed: ${e?.message ?? e}`));
259
+ }
260
+ const data = await readJson(res);
261
+ if (res.status === 429 && attempt < retries) {
262
+ const wait = retryAfterMs(data, res.headers);
263
+ log(`discord: rate limited on ${method} ${path}, retrying in ${wait} ms`);
264
+ await sleep(wait);
265
+ continue;
266
+ }
267
+ if (!res.ok) {
268
+ const why = [data?.message, data?.code ? `(code ${data.code})` : ''].filter(Boolean).join(' ');
269
+ const err = new Error(scrub(`Discord ${method} ${path} failed: HTTP ${res.status}${why ? ` ${why}` : ''}`));
270
+ err.status = res.status;
271
+ if (data?.code) err.code = data.code;
272
+ throw err;
273
+ }
274
+ return data;
275
+ }
276
+ }
277
+
278
+ async function gatewayBase() {
279
+ let data;
280
+ try {
281
+ data = await api('GET', '/gateway/bot', undefined, 0);
282
+ } catch (e) {
283
+ if (e.status === 401) throw Object.assign(new Error(INVALID_TOKEN), { fatal: true });
284
+ throw e;
285
+ }
286
+ if (typeof data?.url !== 'string' || !/^wss?:\/\//.test(data.url)) throw new Error('Discord returned no gateway URL');
287
+ if (data.session_start_limit?.remaining === 0) log('discord: daily session start limit reached; Discord may refuse to identify until it resets');
288
+ return data.url;
289
+ }
290
+
291
+ // --- Gateway ------------------------------------------------------------------------
292
+
293
+ let ws = null;
294
+ let gatewayUrl = '';
295
+ let resumeUrl = '';
296
+ let sessionId = '';
297
+ let seq = null;
298
+ let me = null;
299
+ let attempts = 0;
300
+ let healthy = false;
301
+ let stopped = false;
302
+ let dead = false;
303
+ let startPromise = null;
304
+ let pending = null;
305
+ let hbTimer = null;
306
+ let acked = true;
307
+ let reconnectTimer = null;
308
+ const guildNames = new Map();
309
+ const channels = new Map(); // id → { guildId, name }
310
+ const botRoles = new Map(); // guild id → the bot's managed role ids
311
+
312
+ const halted = () => stopped || dead;
313
+ const cancel = (h) => { if (h != null) clearTimeoutImpl(h); };
314
+
315
+ function sendFrame(sock, frame) {
316
+ try { sock.send(JSON.stringify(frame)); } catch (e) { log(`discord: could not send op ${frame.op}: ${e?.message ?? e}`); }
317
+ }
318
+ const identifyFrame = () => ({ op: 2, d: { token, intents: INTENTS, properties: { os: process.platform, browser: 'dsh-bots', device: 'dsh-bots' } } });
319
+ const resumeFrame = () => ({ op: 6, d: { token, session_id: sessionId, seq } });
320
+
321
+ function stopHeartbeat() {
322
+ cancel(hbTimer);
323
+ hbTimer = null;
324
+ }
325
+
326
+ function startHeartbeat(sock, interval) {
327
+ stopHeartbeat();
328
+ acked = true;
329
+ const beat = guard(() => {
330
+ hbTimer = null;
331
+ if (sock !== ws) return;
332
+ if (!acked) return reconnectSoon('resume', 0, 'heartbeat not acknowledged; resuming on a new connection');
333
+ acked = false;
334
+ sendFrame(sock, { op: 1, d: seq });
335
+ hbTimer = setTimeoutImpl(beat, interval);
336
+ });
337
+ hbTimer = setTimeoutImpl(beat, Math.round(interval * random()));
338
+ }
339
+
340
+ /** Forget the current socket (its events are ignored from now on) and close it. */
341
+ function detach(code) {
342
+ const sock = ws;
343
+ ws = null;
344
+ stopHeartbeat();
345
+ if (sock) try { sock.close(code); } catch { /* already closed */ }
346
+ }
347
+
348
+ function schedule(mode, delay) {
349
+ cancel(reconnectTimer);
350
+ reconnectTimer = setTimeoutImpl(guard(() => { reconnectTimer = null; run(mode); }), delay);
351
+ }
352
+
353
+ /** Discord asked for it (op 7 / op 9) or the socket went quiet: reconnect without backoff. */
354
+ function reconnectSoon(mode, delay, why) {
355
+ log(`discord: ${why}`);
356
+ detach(RESUME_CLOSE);
357
+ schedule(mode, delay);
358
+ }
359
+
360
+ /** Something failed: reconnect with backoff. The first drop after a good connection reads as `connecting`, repeats as `error`. */
361
+ function retry(why, mode) {
362
+ detach(RESUME_CLOSE);
363
+ const delay = backoffDelay(attempts, random);
364
+ attempts += 1;
365
+ const detail = `${why}; reconnecting in ${Math.max(1, Math.round(delay / 1000))} s`;
366
+ log(`discord: ${detail}`);
367
+ status(healthy ? 'connecting' : 'error', detail);
368
+ healthy = false;
369
+ schedule(mode, delay);
370
+ }
371
+
372
+ function fail(detail) {
373
+ if (halted()) return;
374
+ dead = true;
375
+ cancel(reconnectTimer);
376
+ reconnectTimer = null;
377
+ detach(1000);
378
+ log(`discord: ${detail}`);
379
+ status('error', detail, true);
380
+ if (pending) {
381
+ const err = Object.assign(new Error(scrub(detail)), { fatal: true });
382
+ pending.reject(err);
383
+ pending = null;
384
+ }
385
+ }
386
+
387
+ function connected(detail) {
388
+ attempts = 0;
389
+ healthy = true;
390
+ status('connected', detail);
391
+ if (pending && me) {
392
+ pending.resolve({ ...me });
393
+ pending = null;
394
+ }
395
+ }
396
+
397
+ const run = (mode) => { open(mode).catch((e) => log(`discord: ${e?.message ?? e}`)); };
398
+
399
+ async function open(mode) {
400
+ if (halted()) return;
401
+ if (mode === 'resume' && !(sessionId && resumeUrl)) mode = 'identify';
402
+ status('connecting', mode === 'resume' ? 'Resuming the Discord session' : 'Connecting to Discord');
403
+ let base = mode === 'resume' ? resumeUrl : gatewayUrl;
404
+ if (!base) {
405
+ try {
406
+ base = gatewayUrl = await gatewayBase();
407
+ } catch (e) {
408
+ if (halted()) return;
409
+ if (e.fatal) return fail(e.message);
410
+ return retry(e.message, 'identify');
411
+ }
412
+ if (halted()) return;
413
+ }
414
+ let sock;
415
+ try {
416
+ sock = new WebSocketImpl(`${base.replace(/\/+$/, '')}${GATEWAY_QUERY}`);
417
+ } catch (e) {
418
+ return retry(`Could not open the Discord gateway: ${e?.message ?? e}`, mode);
419
+ }
420
+ ws = sock;
421
+ sock.addEventListener('message', guard((ev) => onFrame(sock, mode, ev?.data)));
422
+ sock.addEventListener('close', guard((ev) => onClose(sock, ev?.code, ev?.reason)));
423
+ sock.addEventListener('error', guard(() => { if (sock === ws) log('discord: gateway socket error'); }));
424
+ }
425
+
426
+ function onFrame(sock, mode, data) {
427
+ if (sock !== ws) return;
428
+ let p;
429
+ try {
430
+ p = JSON.parse(typeof data === 'string' ? data : Buffer.from(data).toString('utf8'));
431
+ } catch {
432
+ return log('discord: ignored an unreadable gateway frame');
433
+ }
434
+ if (typeof p?.s === 'number') seq = p.s;
435
+ switch (p?.op) {
436
+ case 0: return dispatch(p.t, p.d);
437
+ case 1: return sendFrame(sock, { op: 1, d: seq });
438
+ case 7: return reconnectSoon('resume', 0, 'Discord asked to reconnect; resuming');
439
+ case 9: return invalidSession(p.d === true);
440
+ case 10:
441
+ startHeartbeat(sock, Number(p.d?.heartbeat_interval) || 41_250);
442
+ return sendFrame(sock, mode === 'resume' ? resumeFrame() : identifyFrame());
443
+ case 11:
444
+ acked = true;
445
+ return undefined;
446
+ default: return undefined;
447
+ }
448
+ }
449
+
450
+ function invalidSession(resumable) {
451
+ if (resumable && sessionId) return reconnectSoon('resume', 0, 'Discord invalidated the session; resuming');
452
+ sessionId = '';
453
+ resumeUrl = '';
454
+ seq = null;
455
+ return reconnectSoon('identify', Math.round(1000 + random() * 4000), 'Discord invalidated the session; identifying again');
456
+ }
457
+
458
+ function onClose(sock, code, reason) {
459
+ if (sock !== ws) return;
460
+ ws = null;
461
+ stopHeartbeat();
462
+ if (halted()) return;
463
+ if (FATAL_CLOSE[code]) return fail(FATAL_CLOSE[code]);
464
+ if (REIDENTIFY_CLOSE.has(code)) {
465
+ sessionId = '';
466
+ resumeUrl = '';
467
+ seq = null;
468
+ return retry(`Discord ended the session (close ${code})`, 'identify');
469
+ }
470
+ return retry(`Discord connection closed (${code ?? 'no code'}${reason ? `: ${reason}` : ''})`, 'resume');
471
+ }
472
+
473
+ function rememberChannel(c, guildId = c?.guild_id) {
474
+ if (c?.id && c.name && guildId) channels.set(c.id, { guildId, name: c.name });
475
+ }
476
+ function rememberGuild(g) {
477
+ if (!g?.id || g.unavailable) return;
478
+ if (g.name) guildNames.set(g.id, g.name);
479
+ for (const c of g.channels ?? []) rememberChannel(c, g.id);
480
+ for (const c of g.threads ?? []) rememberChannel(c, g.id);
481
+ if (Array.isArray(g.roles) && me) botRoles.set(g.id, g.roles.filter((r) => r?.tags?.bot_id === me.id).map((r) => r.id));
482
+ }
483
+ function forgetGuild(id) {
484
+ guildNames.delete(id);
485
+ botRoles.delete(id);
486
+ for (const [cid, c] of channels) if (c.guildId === id) channels.delete(cid);
487
+ }
488
+ function titleOf(channelId) {
489
+ const c = channels.get(channelId);
490
+ if (!c) return undefined;
491
+ const g = guildNames.get(c.guildId);
492
+ return g ? `${g} #${c.name}` : `#${c.name}`;
493
+ }
494
+
495
+ function deliver(d) {
496
+ if (!me) return;
497
+ const msg = normalizeMessage(d, me.id, botRoles.get(d?.guild_id));
498
+ if (!msg) return;
499
+ const title = msg.isDirect ? undefined : titleOf(msg.chatId);
500
+ if (title) msg.chatTitle = title;
501
+ try {
502
+ const r = onMessage(msg);
503
+ if (r && typeof r.catch === 'function') r.catch((e) => log(`discord: onMessage failed: ${e?.message ?? e}`));
504
+ } catch (e) {
505
+ log(`discord: onMessage threw: ${e?.message ?? e}`);
506
+ }
507
+ }
508
+
509
+ function dispatch(t, d) {
510
+ switch (t) {
511
+ case 'READY': {
512
+ sessionId = String(d?.session_id ?? '');
513
+ resumeUrl = String(d?.resume_gateway_url ?? '');
514
+ const u = d?.user ?? {};
515
+ me = { id: String(u.id ?? ''), username: String(u.username ?? ''), name: String(u.global_name || u.username || '') };
516
+ return connected(`Signed in as ${me.username}`);
517
+ }
518
+ case 'RESUMED': return connected(me ? `Signed in as ${me.username}` : 'Session resumed');
519
+ case 'MESSAGE_CREATE': return deliver(d);
520
+ case 'GUILD_CREATE':
521
+ case 'GUILD_UPDATE': return rememberGuild(d);
522
+ case 'GUILD_DELETE': return d?.unavailable ? undefined : forgetGuild(d?.id);
523
+ case 'CHANNEL_CREATE':
524
+ case 'CHANNEL_UPDATE':
525
+ case 'THREAD_CREATE':
526
+ case 'THREAD_UPDATE': return rememberChannel(d);
527
+ case 'CHANNEL_DELETE':
528
+ case 'THREAD_DELETE': return void channels.delete(d?.id);
529
+ default: return undefined;
530
+ }
531
+ }
532
+
533
+ // --- Public -------------------------------------------------------------------------
534
+
535
+ /** Connect and resolve with the bot's identity once Discord says READY. Transient failures keep retrying; fatal ones reject. */
536
+ function start() {
537
+ if (stopped) return Promise.reject(new Error('This Discord connector is stopped; create a new one'));
538
+ if (startPromise) return startPromise;
539
+ startPromise = new Promise((resolve, reject) => { pending = { resolve, reject }; });
540
+ startPromise.catch(() => {}); // the caller may not await it; a fatal error is also reported through onStatus
541
+ if (!token) fail('No Discord bot token. Paste the token from the Developer Portal: your app → Bot.');
542
+ else if (typeof WebSocketImpl !== 'function') fail('This runtime has no WebSocket');
543
+ else if (typeof fetchImpl !== 'function') fail('This runtime has no fetch');
544
+ else run('identify');
545
+ return startPromise;
546
+ }
547
+
548
+ /** Close the connection for good: no reconnects, no timers, pending rate-limit waits are cancelled. */
549
+ async function stop() {
550
+ if (stopped) return;
551
+ stopped = true;
552
+ cancel(reconnectTimer);
553
+ reconnectTimer = null;
554
+ detach(1000);
555
+ for (const s of sleepers) {
556
+ clearTimeoutImpl(s.timer);
557
+ s.reject(new Error('Discord connector stopped'));
558
+ }
559
+ sleepers.clear();
560
+ if (pending) {
561
+ pending.reject(new Error('Discord connector stopped before it connected'));
562
+ pending = null;
563
+ }
564
+ status('stopped');
565
+ }
566
+
567
+ /** Post `text` to a channel, split at the 2000-character limit; `replyTo` threads the first chunk under that message. */
568
+ async function send(chatId, text, sendOpts = {}) {
569
+ if (stopped) throw new Error('Discord connector is stopped');
570
+ const path = `/channels/${encodeURIComponent(String(chatId))}/messages`;
571
+ const chunks = splitMessage(text);
572
+ for (let i = 0; i < chunks.length; i += 1) {
573
+ const body = { content: chunks[i], allowed_mentions: { parse: [] } };
574
+ if (i === 0 && sendOpts?.replyTo) body.message_reference = { message_id: String(sendOpts.replyTo), fail_if_not_exists: false };
575
+ await api('POST', path, body);
576
+ }
577
+ }
578
+
579
+ /** Show "bot is typing…" for about ten seconds. Failures are logged and ignored. */
580
+ async function typing(chatId) {
581
+ if (stopped) return;
582
+ try {
583
+ await api('POST', `/channels/${encodeURIComponent(String(chatId))}/typing`, undefined, 0);
584
+ } catch (e) {
585
+ log(`discord: typing indicator failed: ${e?.message ?? e}`);
586
+ }
587
+ }
588
+
589
+ return { start, stop, send, typing };
590
+ }