@kadaliao/dsh-bots 0.3.3 → 0.6.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,300 @@
1
+ /**
2
+ * Telegram transport for chat channels, over the Bot API with `fetch` only:
3
+ * `getMe`, long-polling `getUpdates`, `sendMessage` and `sendChatAction`.
4
+ *
5
+ * Transport only: it knows nothing about bots, pairing or the store
6
+ * (lib/channels.mjs decides what a message means). It never puts the token in
7
+ * a log line, an error or a status; the token is part of every request URL,
8
+ * so every text that could carry it is redacted.
9
+ *
10
+ * `apiBase` defaults to `BOTS_TELEGRAM_API` or https://api.telegram.org, so a
11
+ * local stand-in of the Bot API can be used for testing.
12
+ *
13
+ * @module @kadaliao/dsh-bots/lib/channels/telegram
14
+ */
15
+
16
+ import { redact, splitText } from '../channels.mjs';
17
+
18
+ export const kind = 'telegram';
19
+ export const TEXT_LIMIT = 4096;
20
+
21
+ const DEFAULT_API = 'https://api.telegram.org';
22
+ /** Seconds one getUpdates call waits for news. */
23
+ const POLL_TIMEOUT_S = 40;
24
+ const CONFLICT_RETRY_MS = 30_000;
25
+ const MAX_BACKOFF_MS = 60_000;
26
+
27
+ const TOKEN_REJECTED = 'Telegram rejected the bot token (401 Unauthorized). Copy it again from @BotFather.';
28
+ const CONFLICT = 'Another program is using this bot token (Telegram answered 409 Conflict). Stop it, or create a separate bot with @BotFather for the team.';
29
+
30
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
31
+
32
+ /**
33
+ * @param {{
34
+ * token: string,
35
+ * onMessage: (msg: object) => void,
36
+ * onStatus?: (s: {state: 'connecting'|'connected'|'error'|'stopped', detail?: string, fatal?: boolean}) => void,
37
+ * fetchImpl?: typeof fetch,
38
+ * apiBase?: string,
39
+ * log?: (line: string) => void,
40
+ * pollTimeout?: number, // seconds, for tests
41
+ * sleep?: (ms: number, signal: AbortSignal) => Promise<void>, // for tests
42
+ * }} opts
43
+ */
44
+ export function createConnector(opts) {
45
+ const secret = String(opts?.token ?? '').trim();
46
+ const fetchImpl = opts?.fetchImpl ?? globalThis.fetch;
47
+ const base = String(opts?.apiBase || process.env.BOTS_TELEGRAM_API || DEFAULT_API).replace(/\/+$/, '');
48
+ const pollTimeout = Number.isFinite(opts?.pollTimeout) ? opts.pollTimeout : POLL_TIMEOUT_S;
49
+ const onMessage = typeof opts?.onMessage === 'function' ? opts.onMessage : () => {};
50
+ const clean = (s) => redact(String(s ?? ''), [secret]);
51
+ const log = (line) => {
52
+ try {
53
+ opts?.log?.(clean(line));
54
+ } catch {
55
+ // Logging is a convenience.
56
+ }
57
+ };
58
+ const halt = new AbortController();
59
+ const sleep =
60
+ opts?.sleep ??
61
+ ((ms, signal) =>
62
+ new Promise((resolve) => {
63
+ if (signal.aborted) return resolve();
64
+ const timer = setTimeout(done, ms);
65
+ function done() {
66
+ clearTimeout(timer);
67
+ signal.removeEventListener('abort', done);
68
+ resolve();
69
+ }
70
+ signal.addEventListener('abort', done, { once: true });
71
+ }));
72
+ const wait = (ms) => sleep(ms, halt.signal);
73
+
74
+ let stopped = false;
75
+ let stopping = null;
76
+ let me = null;
77
+ let offset = 0;
78
+ let loop = null;
79
+ let state = 'stopped';
80
+ const status = (s) => {
81
+ state = s.state;
82
+ try {
83
+ opts?.onStatus?.({ state: s.state, ...(s.detail ? { detail: clean(s.detail) } : {}), ...(s.fatal ? { fatal: true } : {}) });
84
+ } catch {
85
+ // The listener's problem.
86
+ }
87
+ };
88
+
89
+ /** One Bot API call. Errors carry `code` (error_code or HTTP status) and `retryAfter`. */
90
+ async function call(method, body, timeoutMs = 30_000, { afterStop = false } = {}) {
91
+ const signal = afterStop ? AbortSignal.timeout(timeoutMs) : AbortSignal.any([halt.signal, AbortSignal.timeout(timeoutMs)]);
92
+ let res;
93
+ let json = null;
94
+ try {
95
+ res = await fetchImpl(`${base}/bot${secret}/${method}`, {
96
+ method: 'POST',
97
+ headers: { 'content-type': 'application/json' },
98
+ body: JSON.stringify(body ?? {}),
99
+ signal,
100
+ });
101
+ try {
102
+ json = await res.json();
103
+ } catch {
104
+ json = null;
105
+ }
106
+ } catch (error) {
107
+ const why = error?.name === 'TimeoutError' || signal.reason?.name === 'TimeoutError' ? 'timed out' : error?.cause?.code ?? error?.cause?.message ?? error?.message ?? 'network error';
108
+ const e = new Error(clean(`could not reach Telegram (${method}: ${why})`));
109
+ e.network = true;
110
+ throw e;
111
+ }
112
+ if (json && json.ok === true) return json.result;
113
+ const description = clean(json?.description ?? `HTTP ${res.status}`);
114
+ const e = new Error(`Telegram ${method}: ${description}`);
115
+ e.code = Number(json?.error_code ?? res.status) || 0;
116
+ e.description = description;
117
+ if (json?.parameters?.retry_after !== undefined) e.retryAfter = Number(json.parameters.retry_after) || 1;
118
+ throw e;
119
+ }
120
+
121
+ /** A call that waits out 429 Too Many Requests a few times. */
122
+ async function polite(method, body) {
123
+ for (let attempt = 0; ; attempt += 1) {
124
+ try {
125
+ return await call(method, body);
126
+ } catch (error) {
127
+ if (error.code !== 429 || attempt >= 4 || stopped) throw error;
128
+ await wait(Math.min(60, error.retryAfter ?? 1) * 1000);
129
+ }
130
+ }
131
+ }
132
+
133
+ const chatIdOf = (id) => (/^-?\d+$/.test(String(id)) ? Number(id) : String(id));
134
+
135
+ /** A Bot API message as a channel message, or null when it is not for us. */
136
+ function toMessage(m) {
137
+ if (!m || typeof m !== 'object' || typeof m.text !== 'string' || m.text.trim() === '') return null;
138
+ const from = m.from;
139
+ if (!from || from.is_bot || String(from.id) === String(me?.id)) return null;
140
+ const chat = m.chat ?? {};
141
+ const isDirect = chat.type === 'private';
142
+ const username = String(me?.username ?? '');
143
+ const at = `@${username.toLowerCase()}`;
144
+ const text = m.text;
145
+ let mentioned = isDirect;
146
+ for (const e of Array.isArray(m.entities) ? m.entities : []) {
147
+ const part = text.slice(e.offset, e.offset + e.length).toLowerCase();
148
+ if (username && e.type === 'mention' && part === at) mentioned = true;
149
+ if (username && e.type === 'bot_command' && part.endsWith(at)) mentioned = true;
150
+ if (e.type === 'text_mention' && String(e.user?.id) === String(me?.id)) mentioned = true;
151
+ }
152
+ if (me && String(m.reply_to_message?.from?.id ?? '') === String(me.id)) mentioned = true;
153
+ const stripped = username ? text.replace(new RegExp(`@${escapeRe(username)}\\b`, 'gi'), '') : text;
154
+ const body = stripped
155
+ .replace(/[ \t]{2,}/g, ' ')
156
+ .replace(/ +([,,.。!?!?::])/g, '$1')
157
+ .replace(/^[ \t,,::]+/, '')
158
+ .trim();
159
+ const name = [from.first_name, from.last_name].filter(Boolean).join(' ').trim() || (from.username ? `@${from.username}` : String(from.id));
160
+ return {
161
+ chatId: String(chat.id),
162
+ messageId: String(m.message_id),
163
+ userId: String(from.id),
164
+ userName: name,
165
+ text: body,
166
+ isDirect,
167
+ mentioned,
168
+ ...(isDirect ? {} : { chatTitle: String(chat.title ?? '') }),
169
+ };
170
+ }
171
+
172
+ async function poll() {
173
+ let failures = 0;
174
+ let webhookCleared = false;
175
+ while (!stopped) {
176
+ let updates;
177
+ try {
178
+ updates = await call('getUpdates', { offset, timeout: pollTimeout, allowed_updates: ['message'] }, (pollTimeout + 15) * 1000);
179
+ } catch (error) {
180
+ if (stopped) break;
181
+ if (error.code === 401 || error.code === 404) {
182
+ status({ state: 'error', detail: TOKEN_REJECTED, fatal: true });
183
+ log(`telegram: ${error.message}; stopped polling`);
184
+ break;
185
+ }
186
+ if (error.code === 409) {
187
+ // A webhook set elsewhere blocks polling; this token now belongs to the team.
188
+ if (/webhook/i.test(error.description ?? '') && !webhookCleared) {
189
+ webhookCleared = true;
190
+ try {
191
+ await call('deleteWebhook', { drop_pending_updates: false });
192
+ log('telegram: removed the webhook set for this bot so it can poll');
193
+ continue;
194
+ } catch (e) {
195
+ log(`telegram: deleteWebhook: ${e.message}`);
196
+ }
197
+ }
198
+ status({ state: 'error', detail: CONFLICT });
199
+ await wait(CONFLICT_RETRY_MS);
200
+ continue;
201
+ }
202
+ if (error.code === 429) {
203
+ await wait(Math.min(60, error.retryAfter ?? 5) * 1000);
204
+ continue;
205
+ }
206
+ failures += 1;
207
+ const ms = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(failures - 1, 6));
208
+ // One dropped poll is a blip (reconnecting); more in a row is an outage worth showing.
209
+ status({ state: failures === 1 ? 'connecting' : 'error', detail: `${error.message}; retrying in ${Math.round(ms / 1000)} s` });
210
+ log(`telegram: ${error.message}`);
211
+ await wait(ms);
212
+ continue;
213
+ }
214
+ if (stopped) break;
215
+ if (failures > 0 || state !== 'connected') status({ state: 'connected' });
216
+ failures = 0;
217
+ for (const update of Array.isArray(updates) ? updates : []) {
218
+ if (Number.isInteger(update?.update_id)) offset = Math.max(offset, update.update_id + 1);
219
+ const msg = toMessage(update?.message);
220
+ if (!msg) continue;
221
+ try {
222
+ onMessage(msg);
223
+ } catch (error) {
224
+ log(`telegram: a message handler failed: ${error?.message ?? error}`);
225
+ }
226
+ }
227
+ }
228
+ }
229
+
230
+ return {
231
+ /** Check the token with getMe, then poll in the background. */
232
+ async start() {
233
+ if (stopped) throw new Error('the connector was stopped');
234
+ if (!secret) {
235
+ status({ state: 'error', detail: 'no bot token', fatal: true });
236
+ throw Object.assign(new Error('no bot token'), { fatal: true });
237
+ }
238
+ status({ state: 'connecting' });
239
+ for (let attempt = 0; ; attempt += 1) {
240
+ try {
241
+ me = await call('getMe', {}, 20_000);
242
+ break;
243
+ } catch (error) {
244
+ if (stopped) throw new Error('the connector was stopped');
245
+ if (error.code === 401 || error.code === 404) {
246
+ status({ state: 'error', detail: TOKEN_REJECTED, fatal: true });
247
+ throw Object.assign(new Error(TOKEN_REJECTED), { fatal: true });
248
+ }
249
+ const ms = error.code === 429 ? Math.min(60, error.retryAfter ?? 5) * 1000 : Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(attempt, 6));
250
+ status({ state: 'error', detail: `${error.message}; retrying in ${Math.round(ms / 1000)} s` });
251
+ await wait(ms);
252
+ if (stopped) throw new Error('the connector was stopped');
253
+ }
254
+ }
255
+ status({ state: 'connected' });
256
+ loop = poll().catch((error) => {
257
+ if (!stopped) {
258
+ status({ state: 'error', detail: error?.message ?? String(error) });
259
+ log(`telegram: polling ended: ${error?.message ?? error}`);
260
+ }
261
+ });
262
+ return { id: String(me?.id ?? ''), username: String(me?.username ?? ''), name: String(me?.first_name ?? me?.username ?? '') };
263
+ },
264
+
265
+ /**
266
+ * Stop polling; idempotent, nothing reconnects afterwards. Telegram forgets
267
+ * updates only when a later getUpdates confirms them, so the last batch is
268
+ * confirmed on the way out (best effort): a restart does not get it again.
269
+ */
270
+ stop() {
271
+ if (stopping) return stopping;
272
+ stopped = true;
273
+ halt.abort();
274
+ stopping = Promise.resolve(loop)
275
+ .catch(() => {})
276
+ .then(() => (offset > 0 ? call('getUpdates', { offset, timeout: 0, limit: 1 }, 3000, { afterStop: true }).catch(() => {}) : undefined))
277
+ .then(() => status({ state: 'stopped' }));
278
+ return stopping;
279
+ },
280
+
281
+ /** Send plain text, in parts of at most TEXT_LIMIT; the first part answers `replyTo`. */
282
+ async send(chatId, text, sendOpts = {}) {
283
+ let first = true;
284
+ for (const part of splitText(text, TEXT_LIMIT)) {
285
+ const replyTo = first && sendOpts?.replyTo && /^\d+$/.test(String(sendOpts.replyTo)) ? Number(sendOpts.replyTo) : null;
286
+ await polite('sendMessage', {
287
+ chat_id: chatIdOf(chatId),
288
+ text: part,
289
+ ...(replyTo ? { reply_parameters: { message_id: replyTo, allow_sending_without_reply: true } } : {}),
290
+ });
291
+ first = false;
292
+ }
293
+ },
294
+
295
+ /** "typing…" in the chat for about five seconds. */
296
+ async typing(chatId) {
297
+ await call('sendChatAction', { chat_id: chatIdOf(chatId), action: 'typing' }, 10_000);
298
+ },
299
+ };
300
+ }