@theokit/gateway-telegram 0.4.0 → 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.
- package/CHANGELOG.md +123 -0
- package/README.md +40 -0
- package/dist/index.cjs +416 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +24 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +417 -40
- package/dist/index.js.map +1 -1
- package/package.json +5 -2
package/dist/index.cjs
CHANGED
|
@@ -84,6 +84,101 @@ function parseInbound(payload) {
|
|
|
84
84
|
);
|
|
85
85
|
}
|
|
86
86
|
|
|
87
|
+
// src/read-voice.ts
|
|
88
|
+
var MAX_VOICE_BYTES = 20 * 1024 * 1024;
|
|
89
|
+
var READ_TIMEOUT_MS = 3e4;
|
|
90
|
+
var DEFAULT_MEDIA_TYPE = "audio/ogg";
|
|
91
|
+
async function readVoice(ctx, token, fetchImpl = fetch) {
|
|
92
|
+
const voice = ctx.message?.voice ?? {};
|
|
93
|
+
if (typeof voice.file_id !== "string") return { reason: "no_file_id" };
|
|
94
|
+
if (typeof voice.file_size === "number" && voice.file_size > MAX_VOICE_BYTES) {
|
|
95
|
+
return { reason: "too_large" };
|
|
96
|
+
}
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const timer = setTimeout(() => controller.abort(), READ_TIMEOUT_MS);
|
|
99
|
+
try {
|
|
100
|
+
const path = await filePath(ctx, controller.signal);
|
|
101
|
+
if (typeof path !== "string") return path;
|
|
102
|
+
const url = `https://api.telegram.org/file/bot${token}/${path}`;
|
|
103
|
+
const bytes = await download(url, fetchImpl, controller.signal);
|
|
104
|
+
if (!(bytes instanceof Uint8Array)) return bytes;
|
|
105
|
+
return { audio: { data: bytes, ...voiceDetails(voice) } };
|
|
106
|
+
} finally {
|
|
107
|
+
clearTimeout(timer);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function voiceDetails(voice) {
|
|
111
|
+
const duration = voice.duration;
|
|
112
|
+
return {
|
|
113
|
+
mediaType: typeof voice.mime_type === "string" ? voice.mime_type : DEFAULT_MEDIA_TYPE,
|
|
114
|
+
durationSeconds: typeof duration === "number" && Number.isFinite(duration) ? duration : 0
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
async function filePath(ctx, signal) {
|
|
118
|
+
let file;
|
|
119
|
+
try {
|
|
120
|
+
file = await ctx.getFile(signal);
|
|
121
|
+
} catch {
|
|
122
|
+
return { reason: signal.aborted ? "timeout" : "get_file_failed" };
|
|
123
|
+
}
|
|
124
|
+
return file.file_path ?? { reason: "no_file_path" };
|
|
125
|
+
}
|
|
126
|
+
async function download(url, fetchImpl, signal) {
|
|
127
|
+
try {
|
|
128
|
+
const response = await fetchImpl(url, { signal });
|
|
129
|
+
if (!response.ok) return { reason: `download_status_${response.status}` };
|
|
130
|
+
if (response.body === null) return { reason: "download_failed" };
|
|
131
|
+
return await readBounded(response.body, signal);
|
|
132
|
+
} catch {
|
|
133
|
+
return { reason: signal.aborted ? "timeout" : "download_failed" };
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async function readBounded(body, signal) {
|
|
137
|
+
const reader = body.getReader();
|
|
138
|
+
const cancel = () => void reader.cancel().catch(() => void 0);
|
|
139
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
140
|
+
try {
|
|
141
|
+
const chunks = await readChunks(reader);
|
|
142
|
+
if (signal.aborted) return { reason: "timeout" };
|
|
143
|
+
return chunks ?? { reason: "too_large" };
|
|
144
|
+
} finally {
|
|
145
|
+
signal.removeEventListener("abort", cancel);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async function readChunks(reader) {
|
|
149
|
+
const chunks = [];
|
|
150
|
+
let total = 0;
|
|
151
|
+
for (; ; ) {
|
|
152
|
+
const { done, value } = await reader.read();
|
|
153
|
+
if (done) break;
|
|
154
|
+
total += value.length;
|
|
155
|
+
if (total > MAX_VOICE_BYTES) {
|
|
156
|
+
await reader.cancel();
|
|
157
|
+
return void 0;
|
|
158
|
+
}
|
|
159
|
+
chunks.push(value);
|
|
160
|
+
}
|
|
161
|
+
const bytes = new Uint8Array(total);
|
|
162
|
+
let offset = 0;
|
|
163
|
+
for (const chunk of chunks) {
|
|
164
|
+
bytes.set(chunk, offset);
|
|
165
|
+
offset += chunk.length;
|
|
166
|
+
}
|
|
167
|
+
return bytes;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// src/refuse-attachments.ts
|
|
171
|
+
function refuseAttachments(out) {
|
|
172
|
+
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
173
|
+
return {
|
|
174
|
+
ok: false,
|
|
175
|
+
error: {
|
|
176
|
+
code: "attachments_unsupported",
|
|
177
|
+
message: "telegram adapter cannot attach to an edit"
|
|
178
|
+
}
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
87
182
|
// src/split.ts
|
|
88
183
|
var TELEGRAM_MAX_MESSAGE = 4096;
|
|
89
184
|
var SAFE_CHUNK = 4e3;
|
|
@@ -96,40 +191,261 @@ function splitForTelegram(text) {
|
|
|
96
191
|
parts.push(remaining);
|
|
97
192
|
break;
|
|
98
193
|
}
|
|
99
|
-
let boundary = remaining
|
|
100
|
-
|
|
101
|
-
if (
|
|
194
|
+
let boundary = findBoundary(remaining);
|
|
195
|
+
const afterRow = takeRowSafe(parts, remaining, boundary);
|
|
196
|
+
if (afterRow !== void 0) {
|
|
197
|
+
remaining = afterRow;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
102
200
|
const rawChunk = remaining.slice(0, boundary);
|
|
103
201
|
const balanced = balanceMarkdownPairs(rawChunk);
|
|
104
202
|
const chunk = balanced.length > 0 ? balanced : rawChunk;
|
|
105
203
|
boundary = chunk.length;
|
|
106
|
-
|
|
107
|
-
|
|
204
|
+
const [piece, reopen] = closeFence(chunk);
|
|
205
|
+
parts.push(piece);
|
|
206
|
+
remaining = reopen + remaining.slice(boundary).replace(/^\n+/, "");
|
|
108
207
|
}
|
|
109
208
|
return parts;
|
|
110
209
|
}
|
|
210
|
+
function findBoundary(remaining) {
|
|
211
|
+
let boundary = remaining.lastIndexOf("\n\n", SAFE_CHUNK);
|
|
212
|
+
if (boundary < SAFE_CHUNK / 2) boundary = remaining.lastIndexOf("\n", SAFE_CHUNK);
|
|
213
|
+
return boundary < SAFE_CHUNK / 2 ? SAFE_CHUNK : boundary;
|
|
214
|
+
}
|
|
215
|
+
function takeRowSafe(parts, remaining, boundary) {
|
|
216
|
+
const moved = rowSafeCut(remaining, boundary, SAFE_CHUNK);
|
|
217
|
+
if (moved === void 0) return void 0;
|
|
218
|
+
const [piece, reopen] = closeFence(remaining.slice(0, moved.end));
|
|
219
|
+
parts.push(piece);
|
|
220
|
+
return reopen + remaining.slice(moved.start);
|
|
221
|
+
}
|
|
222
|
+
var isLineEnd = (ch) => ch === "\n" || ch === "\r";
|
|
223
|
+
function rowSafeCut(text, cut, window) {
|
|
224
|
+
const start = tableRowStart(text, cut);
|
|
225
|
+
if (start === void 0 || rowLength(text, start, cut, window) > window) return void 0;
|
|
226
|
+
let end = start;
|
|
227
|
+
while (end > 0 && isLineEnd(text[end - 1])) end -= 1;
|
|
228
|
+
return end > 0 ? { end, start } : void 0;
|
|
229
|
+
}
|
|
230
|
+
function tableRowStart(text, cut) {
|
|
231
|
+
if (cut >= text.length || isLineEnd(text[cut])) return void 0;
|
|
232
|
+
let start = cut;
|
|
233
|
+
while (start > 0 && !isLineEnd(text[start - 1])) start -= 1;
|
|
234
|
+
return start > 0 && /^[^\S\r\n]*\|/.test(text.slice(start, cut + 1)) ? start : void 0;
|
|
235
|
+
}
|
|
236
|
+
function rowLength(text, start, cut, window) {
|
|
237
|
+
let rowEnd = cut;
|
|
238
|
+
while (rowEnd < text.length && rowEnd - start <= window && !isLineEnd(text[rowEnd])) rowEnd += 1;
|
|
239
|
+
return rowEnd - start;
|
|
240
|
+
}
|
|
241
|
+
var FENCE_LINE = /^ {0,3}(`{3,}|~{3,})(.*)$/;
|
|
242
|
+
var MAX_INFO = 40;
|
|
243
|
+
function fencedRanges(text) {
|
|
244
|
+
const ranges = [];
|
|
245
|
+
let open;
|
|
246
|
+
let pos = 0;
|
|
247
|
+
for (const line of text.split("\n")) {
|
|
248
|
+
open = stepFence(open, line, pos, ranges);
|
|
249
|
+
pos += line.length + 1;
|
|
250
|
+
}
|
|
251
|
+
if (open !== void 0) ranges.push([open.start, text.length]);
|
|
252
|
+
return ranges;
|
|
253
|
+
}
|
|
254
|
+
function stepFence(open, line, pos, ranges) {
|
|
255
|
+
const m = FENCE_LINE.exec(line.replace(/\r$/, ""));
|
|
256
|
+
const marker = m?.[1];
|
|
257
|
+
if (marker === void 0) return open;
|
|
258
|
+
if (open === void 0) return { fence: { marker, info: (m?.[2] ?? "").trim() }, start: pos };
|
|
259
|
+
if (!closesFence(open.fence, marker, m?.[2] ?? "")) return open;
|
|
260
|
+
ranges.push([open.start, pos + line.length]);
|
|
261
|
+
return void 0;
|
|
262
|
+
}
|
|
263
|
+
function closesFence(fence, marker, rest) {
|
|
264
|
+
return marker[0] === fence.marker[0] && marker.length >= fence.marker.length && rest.trim() === "";
|
|
265
|
+
}
|
|
266
|
+
function openFenceAt(text) {
|
|
267
|
+
const last = fencedRanges(text).at(-1);
|
|
268
|
+
if (last === void 0 || last[1] !== text.length) return void 0;
|
|
269
|
+
const lines = text.slice(last[0]).split("\n");
|
|
270
|
+
const opener = FENCE_LINE.exec(lines[0] ?? "");
|
|
271
|
+
const closer = lines.length > 1 ? FENCE_LINE.exec((lines.at(-1) ?? "").replace(/\r$/, "")) : null;
|
|
272
|
+
if (opener?.[1] === void 0) return void 0;
|
|
273
|
+
const fence = { marker: opener[1], info: (opener[2] ?? "").trim().slice(0, MAX_INFO) };
|
|
274
|
+
if (closer?.[1] !== void 0 && closesFence(fence, closer[1], closer[2] ?? "")) return void 0;
|
|
275
|
+
return fence;
|
|
276
|
+
}
|
|
277
|
+
function closeFence(chunk) {
|
|
278
|
+
const open = openFenceAt(chunk);
|
|
279
|
+
if (open === void 0) return [chunk, ""];
|
|
280
|
+
return [`${chunk}
|
|
281
|
+
${open.marker}`, `${open.marker}${open.info}
|
|
282
|
+
`];
|
|
283
|
+
}
|
|
111
284
|
function balanceMarkdownPairs(chunk) {
|
|
112
285
|
const markers = ["**", "__", "~~", "`"];
|
|
113
286
|
let out = chunk;
|
|
114
287
|
for (const m of markers) {
|
|
115
|
-
const
|
|
116
|
-
if (
|
|
117
|
-
|
|
118
|
-
out = out.slice(0, lastIdx).trimEnd();
|
|
288
|
+
const outside = markerIndexes(out, m);
|
|
289
|
+
if (outside.length % 2 === 1) {
|
|
290
|
+
out = out.slice(0, outside[outside.length - 1]).trimEnd();
|
|
119
291
|
}
|
|
120
292
|
}
|
|
121
293
|
return out;
|
|
122
294
|
}
|
|
123
|
-
function
|
|
124
|
-
|
|
295
|
+
function markerIndexes(text, needle) {
|
|
296
|
+
const ranges = fencedRanges(text);
|
|
297
|
+
const found = [];
|
|
125
298
|
let pos = 0;
|
|
126
299
|
while (true) {
|
|
127
|
-
const
|
|
128
|
-
if (
|
|
129
|
-
|
|
130
|
-
|
|
300
|
+
const at = text.indexOf(needle, pos);
|
|
301
|
+
if (at === -1) break;
|
|
302
|
+
pos = at + needle.length;
|
|
303
|
+
if (!ranges.some(([a, b]) => at >= a && at < b)) found.push(at);
|
|
131
304
|
}
|
|
132
|
-
return
|
|
305
|
+
return found;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
// src/send-photos.ts
|
|
309
|
+
var CAPTION_LIMIT = 1024;
|
|
310
|
+
var MAX_PHOTO_BYTES = 10 * 1024 * 1024;
|
|
311
|
+
var MAX_AUDIO_BYTES = 50 * 1024 * 1024;
|
|
312
|
+
var KIND_LIMITS = {
|
|
313
|
+
image: { maxBytes: MAX_PHOTO_BYTES, label: "an image", bound: "10 MiB" },
|
|
314
|
+
audio: { maxBytes: MAX_AUDIO_BYTES, label: "an audio", bound: "50 MiB" }
|
|
315
|
+
};
|
|
316
|
+
var MAX_PHOTOS_PER_SEND = 10;
|
|
317
|
+
function hasAttachments(out) {
|
|
318
|
+
return out.attachments != null && out.attachments.length !== 0;
|
|
319
|
+
}
|
|
320
|
+
async function sendPhotos(api, out) {
|
|
321
|
+
const chatId = Number(out.channel.id);
|
|
322
|
+
if (Number.isNaN(chatId)) {
|
|
323
|
+
return {
|
|
324
|
+
ok: false,
|
|
325
|
+
error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
const refusal = validateAttachments(out.attachments);
|
|
329
|
+
if (refusal !== void 0) return refusal;
|
|
330
|
+
const shared = sharedOptions(out);
|
|
331
|
+
try {
|
|
332
|
+
let lastId = await sendEachAttachment(api, chatId, out, shared);
|
|
333
|
+
if (out.text.length > CAPTION_LIMIT) {
|
|
334
|
+
for (const chunk of splitForTelegram(out.text)) {
|
|
335
|
+
lastId = (await api.sendMessage(chatId, chunk, shared)).message_id;
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
return { ok: true, messageId: String(lastId) };
|
|
339
|
+
} catch (err) {
|
|
340
|
+
return mapSendError(err);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
async function sendEachAttachment(api, chatId, out, shared) {
|
|
344
|
+
const attachments = out.attachments;
|
|
345
|
+
const caption = captionOf(out.text);
|
|
346
|
+
let lastId = 0;
|
|
347
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
348
|
+
const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
|
|
349
|
+
const file = new grammy.InputFile(attachment.data, attachment.filename);
|
|
350
|
+
const msg = attachment.kind === "audio" ? await api.sendVoice(chatId, file, options) : await api.sendPhoto(chatId, file, options);
|
|
351
|
+
lastId = msg.message_id;
|
|
352
|
+
}
|
|
353
|
+
return lastId;
|
|
354
|
+
}
|
|
355
|
+
function captionOf(text) {
|
|
356
|
+
return text.length >= 1 && text.length <= CAPTION_LIMIT ? text : void 0;
|
|
357
|
+
}
|
|
358
|
+
function firstPhotoOptions(out, caption) {
|
|
359
|
+
return {
|
|
360
|
+
...caption !== void 0 ? { caption } : {},
|
|
361
|
+
...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
function sharedOptions(out) {
|
|
365
|
+
const parseMode = mapFormat(out.format);
|
|
366
|
+
const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
|
|
367
|
+
return {
|
|
368
|
+
...parseMode !== void 0 ? { parse_mode: parseMode } : {},
|
|
369
|
+
...threadId !== void 0 ? { message_thread_id: threadId } : {}
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
function validateAttachments(attachments) {
|
|
373
|
+
if (!Array.isArray(attachments)) {
|
|
374
|
+
return refuse("invalid_attachment", "attachments is not a list");
|
|
375
|
+
}
|
|
376
|
+
if (attachments.length > MAX_PHOTOS_PER_SEND) {
|
|
377
|
+
return refuse(
|
|
378
|
+
"invalid_attachment",
|
|
379
|
+
`telegram adapter sends at most ${MAX_PHOTOS_PER_SEND} attachments at once, got ${attachments.length}`
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
for (const attachment of attachments) {
|
|
383
|
+
const refusal = validateAttachment(attachment);
|
|
384
|
+
if (refusal !== void 0) return refusal;
|
|
385
|
+
}
|
|
386
|
+
return void 0;
|
|
387
|
+
}
|
|
388
|
+
function validateAttachment(attachment) {
|
|
389
|
+
if (typeof attachment !== "object" || attachment === null) {
|
|
390
|
+
return refuse("invalid_attachment", "an attachment is not an object");
|
|
391
|
+
}
|
|
392
|
+
if (attachment.kind !== "image" && attachment.kind !== "audio") {
|
|
393
|
+
return refuse(
|
|
394
|
+
"attachments_unsupported",
|
|
395
|
+
"telegram adapter sends only image and audio attachments"
|
|
396
|
+
);
|
|
397
|
+
}
|
|
398
|
+
const limit = KIND_LIMITS[attachment.kind];
|
|
399
|
+
if (!(attachment.data instanceof Uint8Array) || attachment.data.length === 0) {
|
|
400
|
+
return refuse("invalid_attachment", `${limit.label} attachment has no bytes`);
|
|
401
|
+
}
|
|
402
|
+
if (attachment.data.length > limit.maxBytes) {
|
|
403
|
+
return refuse(
|
|
404
|
+
"invalid_attachment",
|
|
405
|
+
`${limit.label} attachment is ${attachment.data.length} bytes; Telegram takes at most ${limit.bound}`
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
return mediaTypeRefusal(attachment);
|
|
409
|
+
}
|
|
410
|
+
function mediaTypeRefusal(attachment) {
|
|
411
|
+
if (attachment.kind !== "audio") return void 0;
|
|
412
|
+
const mediaType = typeof attachment.mediaType === "string" ? attachment.mediaType : "";
|
|
413
|
+
if (mediaType.toLowerCase().startsWith("audio/")) return void 0;
|
|
414
|
+
return refuse("invalid_attachment", `an audio attachment has media type "${mediaType}"`);
|
|
415
|
+
}
|
|
416
|
+
function refuse(code, message) {
|
|
417
|
+
return { ok: false, error: { code, message } };
|
|
418
|
+
}
|
|
419
|
+
function mapFormat(format) {
|
|
420
|
+
if (format === "markdown") return "Markdown";
|
|
421
|
+
if (format === "html") return "HTML";
|
|
422
|
+
return void 0;
|
|
423
|
+
}
|
|
424
|
+
function parseModeOptions(format) {
|
|
425
|
+
const parseMode = mapFormat(format);
|
|
426
|
+
return parseMode !== void 0 ? { parse_mode: parseMode } : {};
|
|
427
|
+
}
|
|
428
|
+
function mapSendError(err) {
|
|
429
|
+
if (err instanceof grammy.GrammyError) {
|
|
430
|
+
const description = err.description.toLowerCase();
|
|
431
|
+
if (description.includes("rate limit") || err.error_code === 429) {
|
|
432
|
+
return { ok: false, error: { code: "rate_limited", message: err.description } };
|
|
433
|
+
}
|
|
434
|
+
if (description.includes("forbidden") || err.error_code === 403) {
|
|
435
|
+
return { ok: false, error: { code: "no_permission", message: err.description } };
|
|
436
|
+
}
|
|
437
|
+
if (description.includes("parse")) {
|
|
438
|
+
return { ok: false, error: { code: "markdown_error", message: err.description } };
|
|
439
|
+
}
|
|
440
|
+
return {
|
|
441
|
+
ok: false,
|
|
442
|
+
error: { code: `telegram_${err.error_code}`, message: err.description }
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
if (err instanceof grammy.HttpError) {
|
|
446
|
+
return { ok: false, error: { code: "network_error", message: err.message } };
|
|
447
|
+
}
|
|
448
|
+
return { ok: false, error: { code: "unknown", message: err.message } };
|
|
133
449
|
}
|
|
134
450
|
|
|
135
451
|
// src/adapter.ts
|
|
@@ -194,8 +510,9 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
194
510
|
this.startPromise = void 0;
|
|
195
511
|
}
|
|
196
512
|
}
|
|
197
|
-
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.
|
|
513
|
+
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: photo dispatch (send-photos.ts) + validation + parse_mode mapping + thread option + chunk loop + error mapping are all single-responsibility branches inline; splitting hurts readability more than the score.
|
|
198
514
|
async sendMessage(out) {
|
|
515
|
+
if (hasAttachments(out)) return sendPhotos(this.bot.api, out);
|
|
199
516
|
if (out.text.length === 0) {
|
|
200
517
|
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
201
518
|
}
|
|
@@ -224,6 +541,59 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
224
541
|
}
|
|
225
542
|
return { ok: true, ...lastId !== void 0 ? { messageId: lastId } : {} };
|
|
226
543
|
}
|
|
544
|
+
/** Telegram sends each image of `out.attachments` through `sendPhoto` (B-674). */
|
|
545
|
+
supportsAttachments = true;
|
|
546
|
+
/** Telegram edits a sent message's text through `editMessageText`. */
|
|
547
|
+
supportsEdit = true;
|
|
548
|
+
/**
|
|
549
|
+
* Replace the text of a message this bot sent, through `editMessageText`.
|
|
550
|
+
*
|
|
551
|
+
* Refuses, with no request, an outbound carrying attachments (`attachments_unsupported`: no
|
|
552
|
+
* Telegram edit adds an image), empty text, a message id that is not a safe positive integer,
|
|
553
|
+
* and a non-numeric channel, in that order; empty text and the channel are `sendMessage`'s own
|
|
554
|
+
* checks. A text `splitForTelegram` would cut in two is refused as `edit_too_long`: an edit
|
|
555
|
+
* replaces one message. Telegram's "message is not modified" refusal is answered as a success,
|
|
556
|
+
* because the message already shows the text; a caller that treated it as a failure would send
|
|
557
|
+
* the same text again as a second message.
|
|
558
|
+
*/
|
|
559
|
+
async editMessage(messageId, out) {
|
|
560
|
+
return refuseAttachments(out) ?? this.editText(messageId, out);
|
|
561
|
+
}
|
|
562
|
+
async editText(messageId, out) {
|
|
563
|
+
if (out.text.length === 0) {
|
|
564
|
+
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
565
|
+
}
|
|
566
|
+
const id = parseMessageId(messageId);
|
|
567
|
+
if (id === void 0) {
|
|
568
|
+
return {
|
|
569
|
+
ok: false,
|
|
570
|
+
error: {
|
|
571
|
+
code: "invalid_message_id",
|
|
572
|
+
message: `message id "${messageId}" is not a positive integer`
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
const chatIdNum = Number(out.channel.id);
|
|
577
|
+
if (Number.isNaN(chatIdNum)) {
|
|
578
|
+
return {
|
|
579
|
+
ok: false,
|
|
580
|
+
error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
const parts = splitForTelegram(out.text);
|
|
584
|
+
if (parts.length !== 1) return editPartsRefusal(parts.length);
|
|
585
|
+
try {
|
|
586
|
+
await this.bot.api.editMessageText(
|
|
587
|
+
chatIdNum,
|
|
588
|
+
id,
|
|
589
|
+
parts[0],
|
|
590
|
+
parseModeOptions(out.format)
|
|
591
|
+
);
|
|
592
|
+
} catch (err) {
|
|
593
|
+
if (!isNotModified(err)) return mapSendError(err);
|
|
594
|
+
}
|
|
595
|
+
return { ok: true, messageId };
|
|
596
|
+
}
|
|
227
597
|
onInbound(handler) {
|
|
228
598
|
this.handler = handler;
|
|
229
599
|
return () => {
|
|
@@ -247,7 +617,21 @@ var TelegramAdapter = class extends gateway.BasePlatformAdapter {
|
|
|
247
617
|
}
|
|
248
618
|
const event = normalizeEvent(ctx);
|
|
249
619
|
if (event === void 0) return;
|
|
250
|
-
await this.dispatchEvent(event);
|
|
620
|
+
await this.dispatchEvent(await this.withVoice(ctx, event));
|
|
621
|
+
}
|
|
622
|
+
/**
|
|
623
|
+
* The event with the voice note's audio when the message has one (B-715, ADR D1).
|
|
624
|
+
*
|
|
625
|
+
* An unreadable voice leaves the event as it was and writes the reason to stderr: the message is
|
|
626
|
+
* delivered either way, as it was before voice notes were read.
|
|
627
|
+
*/
|
|
628
|
+
async withVoice(ctx, event) {
|
|
629
|
+
if (ctx.message?.voice === void 0) return event;
|
|
630
|
+
const read = await readVoice(ctx, this.bot.token);
|
|
631
|
+
if ("audio" in read) return { ...event, audio: read.audio };
|
|
632
|
+
process.stderr.write(`[telegram] voice not read: ${read.reason}
|
|
633
|
+
`);
|
|
634
|
+
return event;
|
|
251
635
|
}
|
|
252
636
|
/**
|
|
253
637
|
* Dispatch a pre-built event to the current handler, honouring EC-H replace
|
|
@@ -289,32 +673,25 @@ function normalizeEvent(ctx) {
|
|
|
289
673
|
if (chat === void 0 || msg === void 0) return void 0;
|
|
290
674
|
return buildEvent(chat, msg, ctx.from, ctx);
|
|
291
675
|
}
|
|
292
|
-
function
|
|
293
|
-
if (
|
|
294
|
-
|
|
295
|
-
return void 0;
|
|
676
|
+
function parseMessageId(messageId) {
|
|
677
|
+
if (!/^\d+$/.test(messageId)) return void 0;
|
|
678
|
+
const id = Number(messageId);
|
|
679
|
+
return Number.isSafeInteger(id) && id > 0 ? id : void 0;
|
|
296
680
|
}
|
|
297
|
-
function
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
}
|
|
303
|
-
if (description.includes("forbidden") || err.error_code === 403) {
|
|
304
|
-
return { ok: false, error: { code: "no_permission", message: err.description } };
|
|
305
|
-
}
|
|
306
|
-
if (description.includes("parse")) {
|
|
307
|
-
return { ok: false, error: { code: "markdown_error", message: err.description } };
|
|
308
|
-
}
|
|
681
|
+
function isNotModified(err) {
|
|
682
|
+
return err instanceof grammy.GrammyError && err.description.toLowerCase().includes("message is not modified");
|
|
683
|
+
}
|
|
684
|
+
function editPartsRefusal(partCount) {
|
|
685
|
+
if (partCount > 1) {
|
|
309
686
|
return {
|
|
310
687
|
ok: false,
|
|
311
|
-
error: {
|
|
688
|
+
error: {
|
|
689
|
+
code: "edit_too_long",
|
|
690
|
+
message: `text needs ${partCount} Telegram messages; an edit replaces one`
|
|
691
|
+
}
|
|
312
692
|
};
|
|
313
693
|
}
|
|
314
|
-
|
|
315
|
-
return { ok: false, error: { code: "network_error", message: err.message } };
|
|
316
|
-
}
|
|
317
|
-
return { ok: false, error: { code: "unknown", message: err.message } };
|
|
694
|
+
return { ok: false, error: { code: "empty_text", message: "text reduced to zero parts" } };
|
|
318
695
|
}
|
|
319
696
|
var ConfigurationError = class extends gateway.GatewayConfigurationError {
|
|
320
697
|
name = "ConfigurationError";
|