loopzero-gateway-telegram 0.1.0 → 0.2.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/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Bot, Context } from 'grammy';
2
- import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from 'loopzero-gateway';
2
+ import { BasePlatformAdapter, AdapterCapabilities, OutboundMessage, SendResult, FileUploadCapability, ButtonCapability, StreamingPreviewCapability, MessageEvent, GatewayConfigurationError, GatewayConfigurationErrorOptions, TelegramMessageEvent } from 'loopzero-gateway';
3
3
 
4
4
  /**
5
5
  * `TelegramAdapter` — wraps grammy in the `loopzero-gateway`
@@ -81,8 +81,21 @@ declare class TelegramAdapter extends BasePlatformAdapter {
81
81
  readonly supportsAttachments = true;
82
82
  /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
83
83
  protected readonly attachmentKinds: readonly ["image", "audio"];
84
+ /** Telegram sends a file through `sendDocument`: any media type, up to 50 MiB. */
85
+ readonly fileUpload: FileUploadCapability;
86
+ /**
87
+ * Telegram shows rows of buttons under a message as an inline keyboard: URL buttons, and
88
+ * `web_app` buttons that open a Mini App in a private chat. A `callback` button is refused until
89
+ * the adapter receives `callback_query` updates.
90
+ */
91
+ readonly buttonSupport: ButtonCapability;
84
92
  /** Telegram edits a sent message's text through `editMessageText`. */
85
93
  readonly supportsEdit = true;
94
+ /**
95
+ * A streamed reply is previewed by editing one message. Telegram allows about one message per
96
+ * second in a chat, and an edit of up to 4096 characters is one `editMessageText`.
97
+ */
98
+ readonly streamingPreview: StreamingPreviewCapability;
86
99
  /**
87
100
  * Replace the text of a message this bot sent, through `editMessageText`.
88
101
  *
@@ -107,12 +120,21 @@ declare class TelegramAdapter extends BasePlatformAdapter {
107
120
  */
108
121
  private gateMention;
109
122
  /**
110
- * The event with the voice note's audio when the message has one (B-715, ADR D1).
123
+ * The event with the voice note's audio when the message has one (B-715, ADR D1), or with the
124
+ * audio file's when it carries one instead (`message.audio`, OC-103). A message holds at most
125
+ * one of the two.
111
126
  *
112
127
  * The audio is deferred: no request leaves here, so a `pre_inbound` hook that refuses the event
113
- * costs no download. An unreadable voice rejects `audio.read()` and writes the reason to stderr.
128
+ * costs no download. An unreadable voice or audio file rejects `audio.read()` and writes the
129
+ * reason to stderr.
114
130
  */
115
131
  private withVoice;
132
+ /**
133
+ * The event with the message's document as `files`, when it has one. Deferred like the voice
134
+ * note: no request leaves here. An unreadable document rejects `read()` and writes the reason
135
+ * to stderr.
136
+ */
137
+ private withDocument;
116
138
  /**
117
139
  * Deliver an event that arrived out of band — the ingest `onInbound` had no counterpart for (#83).
118
140
  *
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { Bot, GrammyError, HttpError, InputFile } from 'grammy';
2
- import { BasePlatformAdapter, GatewayConfigurationError } from 'loopzero-gateway';
2
+ import { BasePlatformAdapter, GatewayConfigurationError, readFileAttachment, refuseFileAttachment } from 'loopzero-gateway';
3
3
 
4
4
  // src/adapter.ts
5
5
 
@@ -27,6 +27,84 @@ function stripBotMention(text, botUsername) {
27
27
  return text.replace(regex, "").trim();
28
28
  }
29
29
 
30
+ // src/inline-keyboard.ts
31
+ var TELEGRAM_BUTTONS = { actionKinds: ["url", "web_app"] };
32
+ function refusal(code, message) {
33
+ return { ok: false, error: { code, message } };
34
+ }
35
+ function absoluteUrl(value) {
36
+ if (typeof value !== "string") return void 0;
37
+ try {
38
+ return new URL(value);
39
+ } catch {
40
+ return void 0;
41
+ }
42
+ }
43
+ function urlButton(label, url, at) {
44
+ if (absoluteUrl(url) === void 0) {
45
+ return refusal("invalid_buttons", `the URL of ${at} is not an absolute URL`);
46
+ }
47
+ return { text: label, url };
48
+ }
49
+ function webAppButton(label, url, at, channelType) {
50
+ if (channelType !== "dm") {
51
+ return refusal(
52
+ "buttons_unsupported",
53
+ "telegram adapter sends a web_app button only in a private chat"
54
+ );
55
+ }
56
+ if (absoluteUrl(url)?.protocol !== "https:") {
57
+ return refusal("invalid_buttons", `the web_app URL of ${at} must be an absolute https: URL`);
58
+ }
59
+ return { text: label, web_app: { url } };
60
+ }
61
+ function toInlineButton(button, at, channelType) {
62
+ if (typeof button?.label !== "string" || button.label.trim() === "") {
63
+ return refusal("invalid_buttons", `${at} has no label`);
64
+ }
65
+ const action = button.action;
66
+ switch (action?.kind) {
67
+ case "url":
68
+ return urlButton(button.label, action.url, at);
69
+ case "web_app":
70
+ return webAppButton(button.label, action.url, at, channelType);
71
+ case "callback":
72
+ return refusal("buttons_unsupported", "telegram adapter cannot send a callback button");
73
+ default:
74
+ return refusal("invalid_buttons", `${at} has no known action kind`);
75
+ }
76
+ }
77
+ function keyboardRow(buttons, row, channelType) {
78
+ if (!Array.isArray(buttons) || buttons.length === 0) {
79
+ return refusal("invalid_buttons", `button row ${row + 1} is empty`);
80
+ }
81
+ const line = [];
82
+ for (const [column, button] of buttons.entries()) {
83
+ const mapped = toInlineButton(button, `button ${column + 1} of row ${row + 1}`, channelType);
84
+ if ("ok" in mapped) return mapped;
85
+ line.push(mapped);
86
+ }
87
+ return line;
88
+ }
89
+ function inlineKeyboardOf(out) {
90
+ const rows = out.buttons;
91
+ if (rows == null || rows.length === 0) return {};
92
+ if (out.attachments != null && out.attachments.length !== 0) {
93
+ return refusal("buttons_unsupported", "telegram adapter cannot send buttons with attachments");
94
+ }
95
+ if (!Array.isArray(rows)) return refusal("invalid_buttons", "buttons is not a list of rows");
96
+ const keyboard = [];
97
+ for (const [row, buttons] of rows.entries()) {
98
+ const line = keyboardRow(buttons, row, out.channel.type);
99
+ if (!Array.isArray(line)) return line;
100
+ keyboard.push(line);
101
+ }
102
+ return { reply_markup: { inline_keyboard: keyboard } };
103
+ }
104
+ function isRefusal(value) {
105
+ return "ok" in value;
106
+ }
107
+
30
108
  // src/parse-inbound.ts
31
109
  function buildEvent(chat, msg, from, raw) {
32
110
  let channelType;
@@ -111,6 +189,7 @@ var MAX_VOICE_BYTES = 20 * 1024 * 1024;
111
189
  var READ_TIMEOUT_MS = 3e4;
112
190
  var DEFAULT_API_BASE = "https://api.telegram.org";
113
191
  var DEFAULT_MEDIA_TYPE = "audio/ogg";
192
+ var DEFAULT_AUDIO_FILE_MEDIA_TYPE = "audio/mpeg";
114
193
  var VoiceReadError = class extends Error {
115
194
  constructor(reason) {
116
195
  super(`voice not read: ${reason}`);
@@ -119,27 +198,51 @@ var VoiceReadError = class extends Error {
119
198
  reason;
120
199
  name = "VoiceReadError";
121
200
  };
201
+ var AudioReadError = class extends Error {
202
+ constructor(reason) {
203
+ super(`audio not read: ${reason}`);
204
+ this.reason = reason;
205
+ }
206
+ reason;
207
+ name = "AudioReadError";
208
+ };
122
209
  function deferVoice(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
123
210
  const voice = ctx.message?.voice ?? {};
211
+ return deferMessageAudio(ctx, voice, DEFAULT_MEDIA_TYPE, token, {
212
+ onFailure,
213
+ toError: (reason) => new VoiceReadError(reason),
214
+ fetchImpl,
215
+ apiBase
216
+ });
217
+ }
218
+ function deferAudioFile(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
219
+ const audio = ctx.message?.audio ?? {};
220
+ return deferMessageAudio(ctx, audio, DEFAULT_AUDIO_FILE_MEDIA_TYPE, token, {
221
+ onFailure,
222
+ toError: (reason) => new AudioReadError(reason),
223
+ fetchImpl,
224
+ apiBase
225
+ });
226
+ }
227
+ function deferMessageAudio(ctx, fields, defaultMediaType, token, settings) {
124
228
  let pending;
125
229
  const fetchBytes = async () => {
126
- const result = await readVoice(ctx, token, fetchImpl, apiBase);
230
+ const result = await readMessageFile(ctx, fields, token, settings.fetchImpl, settings.apiBase);
127
231
  if ("reason" in result) {
128
- onFailure(result.reason);
129
- throw new VoiceReadError(result.reason);
232
+ settings.onFailure(result.reason);
233
+ throw settings.toError(result.reason);
130
234
  }
131
- return result.audio.data;
235
+ return result.data;
132
236
  };
133
237
  return {
134
238
  read: () => pending ??= fetchBytes(),
135
- ...typeof voice.file_size === "number" ? { size: voice.file_size } : {},
136
- ...voiceDetails(voice)
239
+ ...typeof fields.file_size === "number" ? { size: fields.file_size } : {},
240
+ ...audioDetails(fields, defaultMediaType)
137
241
  };
138
242
  }
139
- async function readVoice(ctx, token, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
140
- const voice = ctx.message?.voice ?? {};
141
- if (typeof voice.file_id !== "string") return { reason: "no_file_id" };
142
- if (typeof voice.file_size === "number" && voice.file_size > MAX_VOICE_BYTES) {
243
+ async function readMessageFile(ctx, fields, token, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
244
+ if (typeof fields.file_id !== "string") return { reason: "no_file_id" };
245
+ if (typeof fields.file_size === "number" && fields.file_size > MAX_VOICE_BYTES) {
143
246
  return { reason: "too_large" };
144
247
  }
145
248
  const controller = new AbortController();
@@ -150,15 +253,15 @@ async function readVoice(ctx, token, fetchImpl = fetch, apiBase = DEFAULT_API_BA
150
253
  const url = `${apiBase}/file/bot${token}/${path}`;
151
254
  const bytes = await download(url, fetchImpl, controller.signal);
152
255
  if (!(bytes instanceof Uint8Array)) return bytes;
153
- return { audio: { data: bytes } };
256
+ return { data: bytes };
154
257
  } finally {
155
258
  clearTimeout(timer);
156
259
  }
157
260
  }
158
- function voiceDetails(voice) {
261
+ function audioDetails(voice, defaultMediaType) {
159
262
  const duration = voice.duration;
160
263
  return {
161
- mediaType: typeof voice.mime_type === "string" ? voice.mime_type : DEFAULT_MEDIA_TYPE,
264
+ mediaType: typeof voice.mime_type === "string" ? voice.mime_type : defaultMediaType,
162
265
  durationSeconds: typeof duration === "number" && Number.isFinite(duration) ? duration : 0
163
266
  };
164
267
  }
@@ -215,6 +318,39 @@ async function readChunks(reader) {
215
318
  return bytes;
216
319
  }
217
320
 
321
+ // src/read-document.ts
322
+ var UNKNOWN_MEDIA_TYPE = "application/octet-stream";
323
+ var DocumentReadError = class extends Error {
324
+ constructor(reason) {
325
+ super(`document not read: ${reason}`);
326
+ this.reason = reason;
327
+ }
328
+ reason;
329
+ name = "DocumentReadError";
330
+ };
331
+ function deferDocument(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
332
+ const document = ctx.message?.document;
333
+ if (document === void 0 || document === null) return void 0;
334
+ let pending;
335
+ const fetchBytes = async () => {
336
+ const result = await readMessageFile(ctx, document, token, fetchImpl, apiBase);
337
+ if ("reason" in result) {
338
+ onFailure(result.reason);
339
+ throw new DocumentReadError(result.reason);
340
+ }
341
+ return result.data;
342
+ };
343
+ return {
344
+ read: () => {
345
+ pending ??= fetchBytes();
346
+ return pending;
347
+ },
348
+ mediaType: typeof document.mime_type === "string" ? document.mime_type : UNKNOWN_MEDIA_TYPE,
349
+ ...typeof document.file_size === "number" ? { size: document.file_size } : {},
350
+ ...typeof document.file_name === "string" ? { filename: document.file_name } : {}
351
+ };
352
+ }
353
+
218
354
  // src/refuse-attachments.ts
219
355
  function refuseAttachments(out) {
220
356
  if (out.attachments == null || out.attachments.length === 0) return void 0;
@@ -357,6 +493,7 @@ function markerIndexes(text, needle) {
357
493
  var CAPTION_LIMIT = 1024;
358
494
  var MAX_PHOTO_BYTES = 10 * 1024 * 1024;
359
495
  var MAX_AUDIO_BYTES = 50 * 1024 * 1024;
496
+ var TELEGRAM_FILE_UPLOAD = { maxBytes: MAX_AUDIO_BYTES };
360
497
  var KIND_LIMITS = {
361
498
  image: { maxBytes: MAX_PHOTO_BYTES, label: "an image", bound: "10 MiB" },
362
499
  audio: { maxBytes: MAX_AUDIO_BYTES, label: "an audio", bound: "50 MiB" }
@@ -373,11 +510,13 @@ async function sendPhotos(api, out) {
373
510
  error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
374
511
  };
375
512
  }
376
- const refusal = validateAttachments(out.attachments);
377
- if (refusal !== void 0) return refusal;
513
+ const refusal2 = validateAttachments(out.attachments);
514
+ if (refusal2 !== void 0) return refusal2;
515
+ const payloads = await payloadsOf(out.attachments);
516
+ if ("error" in payloads) return { ok: false, error: payloads.error };
378
517
  const shared = sharedOptions(out);
379
518
  try {
380
- let lastId = await sendEachAttachment(api, chatId, out, shared);
519
+ let lastId = await sendEachAttachment(api, chatId, out, payloads, shared);
381
520
  if (out.text.length > CAPTION_LIMIT) {
382
521
  for (const chunk of splitForTelegram(out.text)) {
383
522
  lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts))).message_id;
@@ -388,15 +527,33 @@ async function sendPhotos(api, out) {
388
527
  return mapSendError(err);
389
528
  }
390
529
  }
391
- async function sendEachAttachment(api, chatId, out, shared) {
392
- const attachments = out.attachments;
530
+ async function payloadsOf(attachments) {
531
+ const payloads = [];
532
+ for (const attachment of attachments) {
533
+ if (attachment.kind !== "file") {
534
+ payloads.push({
535
+ kind: attachment.kind,
536
+ bytes: attachment.data,
537
+ filename: attachment.filename
538
+ });
539
+ continue;
540
+ }
541
+ const read = await readFileAttachment(attachment, TELEGRAM_FILE_UPLOAD.maxBytes);
542
+ if (!read.ok) return { error: read.error };
543
+ payloads.push({ kind: "file", bytes: read.bytes, filename: attachment.filename });
544
+ }
545
+ return payloads;
546
+ }
547
+ async function sendEachAttachment(api, chatId, out, payloads, shared) {
393
548
  const caption = captionOf(out.text);
394
549
  let lastId = 0;
395
- for (const [index, attachment] of attachments.entries()) {
550
+ for (const [index, payload] of payloads.entries()) {
396
551
  const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
397
552
  const msg = await withPlainFallback(options, (opts) => {
398
- const file = new InputFile(attachment.data, attachment.filename);
399
- return attachment.kind === "audio" ? api.sendVoice(chatId, file, opts) : api.sendPhoto(chatId, file, opts);
553
+ const file = new InputFile(payload.bytes, payload.filename);
554
+ if (payload.kind === "audio") return api.sendVoice(chatId, file, opts);
555
+ if (payload.kind === "file") return api.sendDocument(chatId, file, opts);
556
+ return api.sendPhoto(chatId, file, opts);
400
557
  });
401
558
  lastId = msg.message_id;
402
559
  }
@@ -445,8 +602,8 @@ function validateAttachments(attachments) {
445
602
  );
446
603
  }
447
604
  for (const attachment of attachments) {
448
- const refusal = validateAttachment(attachment);
449
- if (refusal !== void 0) return refusal;
605
+ const refusal2 = validateAttachment(attachment);
606
+ if (refusal2 !== void 0) return refusal2;
450
607
  }
451
608
  return void 0;
452
609
  }
@@ -454,10 +611,13 @@ function validateAttachment(attachment) {
454
611
  if (typeof attachment !== "object" || attachment === null) {
455
612
  return refuse("invalid_attachment", "an attachment is not an object");
456
613
  }
614
+ if (attachment.kind === "file") {
615
+ return refuseFileAttachment(attachment, TELEGRAM_FILE_UPLOAD, "telegram");
616
+ }
457
617
  if (attachment.kind !== "image" && attachment.kind !== "audio") {
458
618
  return refuse(
459
619
  "attachments_unsupported",
460
- "telegram adapter sends only image and audio attachments"
620
+ "telegram adapter sends only image, audio and file attachments"
461
621
  );
462
622
  }
463
623
  const limit = KIND_LIMITS[attachment.kind];
@@ -616,6 +776,8 @@ var TelegramAdapter = class extends BasePlatformAdapter {
616
776
  }
617
777
  // 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.
618
778
  async sendMessage(out) {
779
+ const keyboard = inlineKeyboardOf(out);
780
+ if (isRefusal(keyboard)) return keyboard;
619
781
  if (hasAttachments(out)) return sendPhotos(this.bot.api, out);
620
782
  if (out.text.length === 0) {
621
783
  return { ok: false, error: { code: "empty_text", message: "text is empty" } };
@@ -631,10 +793,12 @@ var TelegramAdapter = class extends BasePlatformAdapter {
631
793
  const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
632
794
  const chunks = splitForTelegram(out.text);
633
795
  let lastId;
634
- for (const chunk of chunks) {
796
+ for (const [index, chunk] of chunks.entries()) {
635
797
  try {
636
798
  const msg = await withPlainFallback(
637
799
  {
800
+ // The keyboard belongs under the whole reply, so only the last part carries it.
801
+ ...index === chunks.length - 1 ? keyboard : {},
638
802
  ...parseMode !== void 0 ? { parse_mode: parseMode } : {},
639
803
  ...threadId !== void 0 ? { message_thread_id: threadId } : {},
640
804
  ...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
@@ -652,8 +816,24 @@ var TelegramAdapter = class extends BasePlatformAdapter {
652
816
  supportsAttachments = true;
653
817
  /** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
654
818
  attachmentKinds = ["image", "audio"];
819
+ /** Telegram sends a file through `sendDocument`: any media type, up to 50 MiB. */
820
+ fileUpload = TELEGRAM_FILE_UPLOAD;
821
+ /**
822
+ * Telegram shows rows of buttons under a message as an inline keyboard: URL buttons, and
823
+ * `web_app` buttons that open a Mini App in a private chat. A `callback` button is refused until
824
+ * the adapter receives `callback_query` updates.
825
+ */
826
+ buttonSupport = TELEGRAM_BUTTONS;
655
827
  /** Telegram edits a sent message's text through `editMessageText`. */
656
828
  supportsEdit = true;
829
+ /**
830
+ * A streamed reply is previewed by editing one message. Telegram allows about one message per
831
+ * second in a chat, and an edit of up to 4096 characters is one `editMessageText`.
832
+ */
833
+ streamingPreview = {
834
+ minUpdateIntervalMs: 1e3,
835
+ maxCharsPerMessage: () => TELEGRAM_MAX_MESSAGE
836
+ };
657
837
  /**
658
838
  * Replace the text of a message this bot sent, through `editMessageText`.
659
839
  *
@@ -669,6 +849,8 @@ var TelegramAdapter = class extends BasePlatformAdapter {
669
849
  return refuseAttachments(out) ?? this.editText(messageId, out);
670
850
  }
671
851
  async editText(messageId, out) {
852
+ const keyboard = inlineKeyboardOf(out);
853
+ if (isRefusal(keyboard)) return keyboard;
672
854
  if (out.text.length === 0) {
673
855
  return { ok: false, error: { code: "empty_text", message: "text is empty" } };
674
856
  }
@@ -692,12 +874,10 @@ var TelegramAdapter = class extends BasePlatformAdapter {
692
874
  const parts = splitForTelegram(out.text);
693
875
  if (parts.length !== 1) return editPartsRefusal(parts.length);
694
876
  try {
695
- await this.bot.api.editMessageText(
696
- chatIdNum,
697
- id,
698
- parts[0],
699
- parseModeOptions(out.format)
700
- );
877
+ await this.bot.api.editMessageText(chatIdNum, id, parts[0], {
878
+ ...parseModeOptions(out.format),
879
+ ...keyboard
880
+ });
701
881
  } catch (err) {
702
882
  if (!isNotModified(err)) return mapSendError(err);
703
883
  }
@@ -749,7 +929,9 @@ var TelegramAdapter = class extends BasePlatformAdapter {
749
929
  if (normalized === void 0) return;
750
930
  const event = this.gateMention(normalized);
751
931
  if (event === void 0) return;
752
- await this.dispatchEvent(this.withVoice(ctx, event));
932
+ await this.dispatchEvent(
933
+ this.withDocument(ctx, this.withVoice(ctx, event))
934
+ );
753
935
  }
754
936
  /**
755
937
  * Marks whether the bot was addressed and applies the `requireMention` gate, shared by the
@@ -779,27 +961,63 @@ var TelegramAdapter = class extends BasePlatformAdapter {
779
961
  return { ...event, addressed };
780
962
  }
781
963
  /**
782
- * The event with the voice note's audio when the message has one (B-715, ADR D1).
964
+ * The event with the voice note's audio when the message has one (B-715, ADR D1), or with the
965
+ * audio file's when it carries one instead (`message.audio`, OC-103). A message holds at most
966
+ * one of the two.
783
967
  *
784
968
  * The audio is deferred: no request leaves here, so a `pre_inbound` hook that refuses the event
785
- * costs no download. An unreadable voice rejects `audio.read()` and writes the reason to stderr.
969
+ * costs no download. An unreadable voice or audio file rejects `audio.read()` and writes the
970
+ * reason to stderr.
786
971
  */
787
972
  withVoice(ctx, event) {
788
973
  const voice = ctx.message?.voice;
789
- if (voice === void 0 || typeof voice.file_id !== "string") {
790
- if (voice !== void 0) process.stderr.write("[telegram] voice not read: no_file_id\n");
974
+ if (voice !== void 0) {
975
+ if (typeof voice.file_id !== "string") {
976
+ process.stderr.write("[telegram] voice not read: no_file_id\n");
977
+ return event;
978
+ }
979
+ const audio2 = deferVoice(
980
+ ctx,
981
+ this.bot.token,
982
+ (reason) => process.stderr.write(`[telegram] voice not read: ${reason}
983
+ `),
984
+ void 0,
985
+ this.apiBase
986
+ );
987
+ return { ...event, audio: audio2 };
988
+ }
989
+ const audioFile = ctx.message?.audio;
990
+ if (audioFile === void 0) return event;
991
+ if (typeof audioFile.file_id !== "string") {
992
+ process.stderr.write("[telegram] audio not read: no_file_id\n");
791
993
  return event;
792
994
  }
793
- const audio = deferVoice(
995
+ const audio = deferAudioFile(
794
996
  ctx,
795
997
  this.bot.token,
796
- (reason) => process.stderr.write(`[telegram] voice not read: ${reason}
998
+ (reason) => process.stderr.write(`[telegram] audio not read: ${reason}
797
999
  `),
798
1000
  void 0,
799
1001
  this.apiBase
800
1002
  );
801
1003
  return { ...event, audio };
802
1004
  }
1005
+ /**
1006
+ * The event with the message's document as `files`, when it has one. Deferred like the voice
1007
+ * note: no request leaves here. An unreadable document rejects `read()` and writes the reason
1008
+ * to stderr.
1009
+ */
1010
+ withDocument(ctx, event) {
1011
+ const file = deferDocument(
1012
+ ctx,
1013
+ this.bot.token,
1014
+ (reason) => process.stderr.write(`[telegram] document not read: ${reason}
1015
+ `),
1016
+ void 0,
1017
+ this.apiBase
1018
+ );
1019
+ return file === void 0 ? event : { ...event, files: [file] };
1020
+ }
803
1021
  /**
804
1022
  * Dispatch a pre-built event to the current handler, honouring EC-H replace
805
1023
  * semantics.