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/CHANGELOG.md +9 -0
- package/README.md +43 -2
- package/dist/index.cjs +256 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -3
- package/dist/index.d.ts +25 -3
- package/dist/index.js +257 -39
- package/dist/index.js.map +1 -1
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 31c4c2d: Send `file` attachments through `sendDocument` (any media type, up to 50 MiB, from bytes or a `Blob`), in the same order and caption rule as photos and voice notes, and read a polled message's `document` as `event.files`, downloaded on demand through `getFile` (up to 20 MB). `capabilities.attachments` is now `["image", "audio", "file"]`.
|
|
8
|
+
- 414ebff: Read a polled message's audio file (`message.audio`, a recording or music file sent as audio rather than as a voice note) as `event.audio`, the same field a voice note fills. It is downloaded only when `audio.read()` is called, through `getFile`, up to 20 MB and under the 30 s deadline voice notes use. A file with no media type is labelled `audio/mpeg`. A failed read rejects with an error naming the reason, never the download URL, which holds the bot token, and writes `[telegram] audio not read: <reason>` to stderr.
|
|
9
|
+
- 414ebff: Send `OutboundMessage.buttons` as an inline keyboard: URL buttons, and `web_app` buttons that open a Telegram Mini App in a private chat. The keyboard goes on the last part of a split text and is kept by an edit. A `web_app` button in a group, a `callback` button (the adapter does not receive `callback_query` yet) and buttons with attachments are refused as `buttons_unsupported`; a blank label, a URL that is not absolute or a `web_app` URL that is not HTTPS as `invalid_buttons`, all before any request. `capabilities.buttons` is `{ actionKinds: ["url", "web_app"] }` (#4).
|
|
10
|
+
- fd8af16: Declare `streamingPreview` (one edit a second, 4096 characters a message), so `ctx.stream()` edits a reply in place as it arrives (OC-49). The `loopzero-gateway` peer floor rises to 0.2.0.
|
|
11
|
+
|
|
3
12
|
## 0.15.0
|
|
4
13
|
|
|
5
14
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -100,6 +100,45 @@ shows OGG/Opus, MP3 and M4A as a voice bubble; other audio is delivered as a fil
|
|
|
100
100
|
Attachments need `loopzero-gateway` 0.13.0 or later: an older core's `ctx.reply` does not carry
|
|
101
101
|
them to the adapter, so install both together.
|
|
102
102
|
|
|
103
|
+
## Files
|
|
104
|
+
|
|
105
|
+
**Sending.** An attachment with `kind: "file"` (a document with a `filename`, a `mediaType` and its
|
|
106
|
+
bytes or a `Blob`, such as `fs.openAsBlob(path)`) goes out through `sendDocument`, in the same path
|
|
107
|
+
and order as images and voice notes, with the same caption rule. Any media type is taken, up to
|
|
108
|
+
50 MiB (Bot API "Sending files": 50 MB for files other than photos); a larger file is refused as
|
|
109
|
+
`attachment_too_large`, and a file with no name or no bytes as `invalid_attachment`, before any
|
|
110
|
+
request. Every file is read before the first request, so a source that fails to read sends
|
|
111
|
+
nothing. `capabilities.files` is `{ maxBytes: 52428800 }`. Files need `loopzero-gateway` 0.2.0.
|
|
112
|
+
|
|
113
|
+
**Reading.** A polled message with a `document` (a file sent as a file, including a photo sent
|
|
114
|
+
uncompressed) reaches hooks and the handler with `event.files`: one entry with the document's
|
|
115
|
+
`filename`, `mediaType` (`application/octet-stream` when Telegram reports none) and `size`, and
|
|
116
|
+
`read()`, which fetches the bytes on its first call through `getFile` and the file server. The
|
|
117
|
+
read is bounded at 20 MB (`getFile`'s limit); a failure rejects with `document not read: <reason>`
|
|
118
|
+
and never carries the download URL. A document delivered through a webhook carries no `files`,
|
|
119
|
+
for the same reason as a voice note: only the polled path holds the token.
|
|
120
|
+
|
|
121
|
+
## Buttons and Mini Apps
|
|
122
|
+
|
|
123
|
+
`OutboundMessage.buttons` goes out as `reply_markup.inline_keyboard`, one keyboard row per row, on
|
|
124
|
+
the last message when a long text is split. Two action kinds are sent:
|
|
125
|
+
|
|
126
|
+
- `url`: a URL button. The URL must be absolute.
|
|
127
|
+
- `web_app`: a button that opens a Telegram Mini App, which receives the signed `initData` the app
|
|
128
|
+
verifies. Telegram allows it only in a private chat, so in a group it is refused as
|
|
129
|
+
`buttons_unsupported`; its URL must be HTTPS, or it is refused as `invalid_buttons`.
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
await ctx.reply("Open the panel.", {
|
|
133
|
+
buttons: [[{ label: "Open panel", action: { kind: "web_app", url: "https://panel.example/app" } }]],
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
A `callback` button is refused as `buttons_unsupported`: the adapter does not receive
|
|
138
|
+
`callback_query` updates yet, so its press would reach nobody. Buttons together with attachments
|
|
139
|
+
are refused the same way. An edit keeps its buttons through `editMessageText`'s `reply_markup`.
|
|
140
|
+
Every refusal is made before any request. Buttons need `loopzero-gateway` 0.2.0.
|
|
141
|
+
|
|
103
142
|
## Group messages: `requireMention`
|
|
104
143
|
|
|
105
144
|
With `requireMention: true`, a group or supergroup message reaches the handler only if it mentions
|
|
@@ -147,8 +186,10 @@ boolean or `"true"`/`"false"`.
|
|
|
147
186
|
## Capabilities
|
|
148
187
|
|
|
149
188
|
`adapter.capabilities` reports `edit`, `typing` and `reactions` as `true` and
|
|
150
|
-
`attachments: ["image", "audio"]
|
|
151
|
-
|
|
189
|
+
`attachments: ["image", "audio", "file"]`, with `files: { maxBytes: 52428800 }` and
|
|
190
|
+
`buttons: { actionKinds: ["url", "web_app"] }`. It also reports `maxMessageChars: 4096` (the splitter limit)
|
|
191
|
+
and `threads: true`. `streamingPreview` lets `ctx.stream()` edit a reply as it arrives, at most
|
|
192
|
+
once a second. See `loopzero-gateway` for the field meanings.
|
|
152
193
|
|
|
153
194
|
## Helpers
|
|
154
195
|
|
package/dist/index.cjs
CHANGED
|
@@ -29,6 +29,84 @@ function stripBotMention(text, botUsername) {
|
|
|
29
29
|
return text.replace(regex, "").trim();
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
+
// src/inline-keyboard.ts
|
|
33
|
+
var TELEGRAM_BUTTONS = { actionKinds: ["url", "web_app"] };
|
|
34
|
+
function refusal(code, message) {
|
|
35
|
+
return { ok: false, error: { code, message } };
|
|
36
|
+
}
|
|
37
|
+
function absoluteUrl(value) {
|
|
38
|
+
if (typeof value !== "string") return void 0;
|
|
39
|
+
try {
|
|
40
|
+
return new URL(value);
|
|
41
|
+
} catch {
|
|
42
|
+
return void 0;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function urlButton(label, url, at) {
|
|
46
|
+
if (absoluteUrl(url) === void 0) {
|
|
47
|
+
return refusal("invalid_buttons", `the URL of ${at} is not an absolute URL`);
|
|
48
|
+
}
|
|
49
|
+
return { text: label, url };
|
|
50
|
+
}
|
|
51
|
+
function webAppButton(label, url, at, channelType) {
|
|
52
|
+
if (channelType !== "dm") {
|
|
53
|
+
return refusal(
|
|
54
|
+
"buttons_unsupported",
|
|
55
|
+
"telegram adapter sends a web_app button only in a private chat"
|
|
56
|
+
);
|
|
57
|
+
}
|
|
58
|
+
if (absoluteUrl(url)?.protocol !== "https:") {
|
|
59
|
+
return refusal("invalid_buttons", `the web_app URL of ${at} must be an absolute https: URL`);
|
|
60
|
+
}
|
|
61
|
+
return { text: label, web_app: { url } };
|
|
62
|
+
}
|
|
63
|
+
function toInlineButton(button, at, channelType) {
|
|
64
|
+
if (typeof button?.label !== "string" || button.label.trim() === "") {
|
|
65
|
+
return refusal("invalid_buttons", `${at} has no label`);
|
|
66
|
+
}
|
|
67
|
+
const action = button.action;
|
|
68
|
+
switch (action?.kind) {
|
|
69
|
+
case "url":
|
|
70
|
+
return urlButton(button.label, action.url, at);
|
|
71
|
+
case "web_app":
|
|
72
|
+
return webAppButton(button.label, action.url, at, channelType);
|
|
73
|
+
case "callback":
|
|
74
|
+
return refusal("buttons_unsupported", "telegram adapter cannot send a callback button");
|
|
75
|
+
default:
|
|
76
|
+
return refusal("invalid_buttons", `${at} has no known action kind`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function keyboardRow(buttons, row, channelType) {
|
|
80
|
+
if (!Array.isArray(buttons) || buttons.length === 0) {
|
|
81
|
+
return refusal("invalid_buttons", `button row ${row + 1} is empty`);
|
|
82
|
+
}
|
|
83
|
+
const line = [];
|
|
84
|
+
for (const [column, button] of buttons.entries()) {
|
|
85
|
+
const mapped = toInlineButton(button, `button ${column + 1} of row ${row + 1}`, channelType);
|
|
86
|
+
if ("ok" in mapped) return mapped;
|
|
87
|
+
line.push(mapped);
|
|
88
|
+
}
|
|
89
|
+
return line;
|
|
90
|
+
}
|
|
91
|
+
function inlineKeyboardOf(out) {
|
|
92
|
+
const rows = out.buttons;
|
|
93
|
+
if (rows == null || rows.length === 0) return {};
|
|
94
|
+
if (out.attachments != null && out.attachments.length !== 0) {
|
|
95
|
+
return refusal("buttons_unsupported", "telegram adapter cannot send buttons with attachments");
|
|
96
|
+
}
|
|
97
|
+
if (!Array.isArray(rows)) return refusal("invalid_buttons", "buttons is not a list of rows");
|
|
98
|
+
const keyboard = [];
|
|
99
|
+
for (const [row, buttons] of rows.entries()) {
|
|
100
|
+
const line = keyboardRow(buttons, row, out.channel.type);
|
|
101
|
+
if (!Array.isArray(line)) return line;
|
|
102
|
+
keyboard.push(line);
|
|
103
|
+
}
|
|
104
|
+
return { reply_markup: { inline_keyboard: keyboard } };
|
|
105
|
+
}
|
|
106
|
+
function isRefusal(value) {
|
|
107
|
+
return "ok" in value;
|
|
108
|
+
}
|
|
109
|
+
|
|
32
110
|
// src/parse-inbound.ts
|
|
33
111
|
function buildEvent(chat, msg, from, raw) {
|
|
34
112
|
let channelType;
|
|
@@ -113,6 +191,7 @@ var MAX_VOICE_BYTES = 20 * 1024 * 1024;
|
|
|
113
191
|
var READ_TIMEOUT_MS = 3e4;
|
|
114
192
|
var DEFAULT_API_BASE = "https://api.telegram.org";
|
|
115
193
|
var DEFAULT_MEDIA_TYPE = "audio/ogg";
|
|
194
|
+
var DEFAULT_AUDIO_FILE_MEDIA_TYPE = "audio/mpeg";
|
|
116
195
|
var VoiceReadError = class extends Error {
|
|
117
196
|
constructor(reason) {
|
|
118
197
|
super(`voice not read: ${reason}`);
|
|
@@ -121,27 +200,51 @@ var VoiceReadError = class extends Error {
|
|
|
121
200
|
reason;
|
|
122
201
|
name = "VoiceReadError";
|
|
123
202
|
};
|
|
203
|
+
var AudioReadError = class extends Error {
|
|
204
|
+
constructor(reason) {
|
|
205
|
+
super(`audio not read: ${reason}`);
|
|
206
|
+
this.reason = reason;
|
|
207
|
+
}
|
|
208
|
+
reason;
|
|
209
|
+
name = "AudioReadError";
|
|
210
|
+
};
|
|
124
211
|
function deferVoice(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
|
|
125
212
|
const voice = ctx.message?.voice ?? {};
|
|
213
|
+
return deferMessageAudio(ctx, voice, DEFAULT_MEDIA_TYPE, token, {
|
|
214
|
+
onFailure,
|
|
215
|
+
toError: (reason) => new VoiceReadError(reason),
|
|
216
|
+
fetchImpl,
|
|
217
|
+
apiBase
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
function deferAudioFile(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
|
|
221
|
+
const audio = ctx.message?.audio ?? {};
|
|
222
|
+
return deferMessageAudio(ctx, audio, DEFAULT_AUDIO_FILE_MEDIA_TYPE, token, {
|
|
223
|
+
onFailure,
|
|
224
|
+
toError: (reason) => new AudioReadError(reason),
|
|
225
|
+
fetchImpl,
|
|
226
|
+
apiBase
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
function deferMessageAudio(ctx, fields, defaultMediaType, token, settings) {
|
|
126
230
|
let pending;
|
|
127
231
|
const fetchBytes = async () => {
|
|
128
|
-
const result = await
|
|
232
|
+
const result = await readMessageFile(ctx, fields, token, settings.fetchImpl, settings.apiBase);
|
|
129
233
|
if ("reason" in result) {
|
|
130
|
-
onFailure(result.reason);
|
|
131
|
-
throw
|
|
234
|
+
settings.onFailure(result.reason);
|
|
235
|
+
throw settings.toError(result.reason);
|
|
132
236
|
}
|
|
133
|
-
return result.
|
|
237
|
+
return result.data;
|
|
134
238
|
};
|
|
135
239
|
return {
|
|
136
240
|
read: () => pending ??= fetchBytes(),
|
|
137
|
-
...typeof
|
|
138
|
-
...
|
|
241
|
+
...typeof fields.file_size === "number" ? { size: fields.file_size } : {},
|
|
242
|
+
...audioDetails(fields, defaultMediaType)
|
|
139
243
|
};
|
|
140
244
|
}
|
|
141
|
-
async function
|
|
142
|
-
|
|
143
|
-
if (typeof
|
|
144
|
-
if (typeof voice.file_size === "number" && voice.file_size > MAX_VOICE_BYTES) {
|
|
245
|
+
async function readMessageFile(ctx, fields, token, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
|
|
246
|
+
if (typeof fields.file_id !== "string") return { reason: "no_file_id" };
|
|
247
|
+
if (typeof fields.file_size === "number" && fields.file_size > MAX_VOICE_BYTES) {
|
|
145
248
|
return { reason: "too_large" };
|
|
146
249
|
}
|
|
147
250
|
const controller = new AbortController();
|
|
@@ -152,15 +255,15 @@ async function readVoice(ctx, token, fetchImpl = fetch, apiBase = DEFAULT_API_BA
|
|
|
152
255
|
const url = `${apiBase}/file/bot${token}/${path}`;
|
|
153
256
|
const bytes = await download(url, fetchImpl, controller.signal);
|
|
154
257
|
if (!(bytes instanceof Uint8Array)) return bytes;
|
|
155
|
-
return {
|
|
258
|
+
return { data: bytes };
|
|
156
259
|
} finally {
|
|
157
260
|
clearTimeout(timer);
|
|
158
261
|
}
|
|
159
262
|
}
|
|
160
|
-
function
|
|
263
|
+
function audioDetails(voice, defaultMediaType) {
|
|
161
264
|
const duration = voice.duration;
|
|
162
265
|
return {
|
|
163
|
-
mediaType: typeof voice.mime_type === "string" ? voice.mime_type :
|
|
266
|
+
mediaType: typeof voice.mime_type === "string" ? voice.mime_type : defaultMediaType,
|
|
164
267
|
durationSeconds: typeof duration === "number" && Number.isFinite(duration) ? duration : 0
|
|
165
268
|
};
|
|
166
269
|
}
|
|
@@ -217,6 +320,39 @@ async function readChunks(reader) {
|
|
|
217
320
|
return bytes;
|
|
218
321
|
}
|
|
219
322
|
|
|
323
|
+
// src/read-document.ts
|
|
324
|
+
var UNKNOWN_MEDIA_TYPE = "application/octet-stream";
|
|
325
|
+
var DocumentReadError = class extends Error {
|
|
326
|
+
constructor(reason) {
|
|
327
|
+
super(`document not read: ${reason}`);
|
|
328
|
+
this.reason = reason;
|
|
329
|
+
}
|
|
330
|
+
reason;
|
|
331
|
+
name = "DocumentReadError";
|
|
332
|
+
};
|
|
333
|
+
function deferDocument(ctx, token, onFailure, fetchImpl = fetch, apiBase = DEFAULT_API_BASE) {
|
|
334
|
+
const document = ctx.message?.document;
|
|
335
|
+
if (document === void 0 || document === null) return void 0;
|
|
336
|
+
let pending;
|
|
337
|
+
const fetchBytes = async () => {
|
|
338
|
+
const result = await readMessageFile(ctx, document, token, fetchImpl, apiBase);
|
|
339
|
+
if ("reason" in result) {
|
|
340
|
+
onFailure(result.reason);
|
|
341
|
+
throw new DocumentReadError(result.reason);
|
|
342
|
+
}
|
|
343
|
+
return result.data;
|
|
344
|
+
};
|
|
345
|
+
return {
|
|
346
|
+
read: () => {
|
|
347
|
+
pending ??= fetchBytes();
|
|
348
|
+
return pending;
|
|
349
|
+
},
|
|
350
|
+
mediaType: typeof document.mime_type === "string" ? document.mime_type : UNKNOWN_MEDIA_TYPE,
|
|
351
|
+
...typeof document.file_size === "number" ? { size: document.file_size } : {},
|
|
352
|
+
...typeof document.file_name === "string" ? { filename: document.file_name } : {}
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
|
|
220
356
|
// src/refuse-attachments.ts
|
|
221
357
|
function refuseAttachments(out) {
|
|
222
358
|
if (out.attachments == null || out.attachments.length === 0) return void 0;
|
|
@@ -359,6 +495,7 @@ function markerIndexes(text, needle) {
|
|
|
359
495
|
var CAPTION_LIMIT = 1024;
|
|
360
496
|
var MAX_PHOTO_BYTES = 10 * 1024 * 1024;
|
|
361
497
|
var MAX_AUDIO_BYTES = 50 * 1024 * 1024;
|
|
498
|
+
var TELEGRAM_FILE_UPLOAD = { maxBytes: MAX_AUDIO_BYTES };
|
|
362
499
|
var KIND_LIMITS = {
|
|
363
500
|
image: { maxBytes: MAX_PHOTO_BYTES, label: "an image", bound: "10 MiB" },
|
|
364
501
|
audio: { maxBytes: MAX_AUDIO_BYTES, label: "an audio", bound: "50 MiB" }
|
|
@@ -375,11 +512,13 @@ async function sendPhotos(api, out) {
|
|
|
375
512
|
error: { code: "invalid_channel", message: `channel.id "${out.channel.id}" not numeric` }
|
|
376
513
|
};
|
|
377
514
|
}
|
|
378
|
-
const
|
|
379
|
-
if (
|
|
515
|
+
const refusal2 = validateAttachments(out.attachments);
|
|
516
|
+
if (refusal2 !== void 0) return refusal2;
|
|
517
|
+
const payloads = await payloadsOf(out.attachments);
|
|
518
|
+
if ("error" in payloads) return { ok: false, error: payloads.error };
|
|
380
519
|
const shared = sharedOptions(out);
|
|
381
520
|
try {
|
|
382
|
-
let lastId = await sendEachAttachment(api, chatId, out, shared);
|
|
521
|
+
let lastId = await sendEachAttachment(api, chatId, out, payloads, shared);
|
|
383
522
|
if (out.text.length > CAPTION_LIMIT) {
|
|
384
523
|
for (const chunk of splitForTelegram(out.text)) {
|
|
385
524
|
lastId = (await withPlainFallback(shared, (opts) => api.sendMessage(chatId, chunk, opts))).message_id;
|
|
@@ -390,15 +529,33 @@ async function sendPhotos(api, out) {
|
|
|
390
529
|
return mapSendError(err);
|
|
391
530
|
}
|
|
392
531
|
}
|
|
393
|
-
async function
|
|
394
|
-
const
|
|
532
|
+
async function payloadsOf(attachments) {
|
|
533
|
+
const payloads = [];
|
|
534
|
+
for (const attachment of attachments) {
|
|
535
|
+
if (attachment.kind !== "file") {
|
|
536
|
+
payloads.push({
|
|
537
|
+
kind: attachment.kind,
|
|
538
|
+
bytes: attachment.data,
|
|
539
|
+
filename: attachment.filename
|
|
540
|
+
});
|
|
541
|
+
continue;
|
|
542
|
+
}
|
|
543
|
+
const read = await loopzeroGateway.readFileAttachment(attachment, TELEGRAM_FILE_UPLOAD.maxBytes);
|
|
544
|
+
if (!read.ok) return { error: read.error };
|
|
545
|
+
payloads.push({ kind: "file", bytes: read.bytes, filename: attachment.filename });
|
|
546
|
+
}
|
|
547
|
+
return payloads;
|
|
548
|
+
}
|
|
549
|
+
async function sendEachAttachment(api, chatId, out, payloads, shared) {
|
|
395
550
|
const caption = captionOf(out.text);
|
|
396
551
|
let lastId = 0;
|
|
397
|
-
for (const [index,
|
|
552
|
+
for (const [index, payload] of payloads.entries()) {
|
|
398
553
|
const options = { ...shared, ...index === 0 ? firstPhotoOptions(out, caption) : {} };
|
|
399
554
|
const msg = await withPlainFallback(options, (opts) => {
|
|
400
|
-
const file = new grammy.InputFile(
|
|
401
|
-
|
|
555
|
+
const file = new grammy.InputFile(payload.bytes, payload.filename);
|
|
556
|
+
if (payload.kind === "audio") return api.sendVoice(chatId, file, opts);
|
|
557
|
+
if (payload.kind === "file") return api.sendDocument(chatId, file, opts);
|
|
558
|
+
return api.sendPhoto(chatId, file, opts);
|
|
402
559
|
});
|
|
403
560
|
lastId = msg.message_id;
|
|
404
561
|
}
|
|
@@ -447,8 +604,8 @@ function validateAttachments(attachments) {
|
|
|
447
604
|
);
|
|
448
605
|
}
|
|
449
606
|
for (const attachment of attachments) {
|
|
450
|
-
const
|
|
451
|
-
if (
|
|
607
|
+
const refusal2 = validateAttachment(attachment);
|
|
608
|
+
if (refusal2 !== void 0) return refusal2;
|
|
452
609
|
}
|
|
453
610
|
return void 0;
|
|
454
611
|
}
|
|
@@ -456,10 +613,13 @@ function validateAttachment(attachment) {
|
|
|
456
613
|
if (typeof attachment !== "object" || attachment === null) {
|
|
457
614
|
return refuse("invalid_attachment", "an attachment is not an object");
|
|
458
615
|
}
|
|
616
|
+
if (attachment.kind === "file") {
|
|
617
|
+
return loopzeroGateway.refuseFileAttachment(attachment, TELEGRAM_FILE_UPLOAD, "telegram");
|
|
618
|
+
}
|
|
459
619
|
if (attachment.kind !== "image" && attachment.kind !== "audio") {
|
|
460
620
|
return refuse(
|
|
461
621
|
"attachments_unsupported",
|
|
462
|
-
"telegram adapter sends only image and
|
|
622
|
+
"telegram adapter sends only image, audio and file attachments"
|
|
463
623
|
);
|
|
464
624
|
}
|
|
465
625
|
const limit = KIND_LIMITS[attachment.kind];
|
|
@@ -618,6 +778,8 @@ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
618
778
|
}
|
|
619
779
|
// 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.
|
|
620
780
|
async sendMessage(out) {
|
|
781
|
+
const keyboard = inlineKeyboardOf(out);
|
|
782
|
+
if (isRefusal(keyboard)) return keyboard;
|
|
621
783
|
if (hasAttachments(out)) return sendPhotos(this.bot.api, out);
|
|
622
784
|
if (out.text.length === 0) {
|
|
623
785
|
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
@@ -633,10 +795,12 @@ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
633
795
|
const threadId = out.channel.topicId !== void 0 ? Number(out.channel.topicId) : void 0;
|
|
634
796
|
const chunks = splitForTelegram(out.text);
|
|
635
797
|
let lastId;
|
|
636
|
-
for (const chunk of chunks) {
|
|
798
|
+
for (const [index, chunk] of chunks.entries()) {
|
|
637
799
|
try {
|
|
638
800
|
const msg = await withPlainFallback(
|
|
639
801
|
{
|
|
802
|
+
// The keyboard belongs under the whole reply, so only the last part carries it.
|
|
803
|
+
...index === chunks.length - 1 ? keyboard : {},
|
|
640
804
|
...parseMode !== void 0 ? { parse_mode: parseMode } : {},
|
|
641
805
|
...threadId !== void 0 ? { message_thread_id: threadId } : {},
|
|
642
806
|
...out.replyTo !== void 0 ? { reply_parameters: { message_id: Number(out.replyTo) } } : {}
|
|
@@ -654,8 +818,24 @@ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
654
818
|
supportsAttachments = true;
|
|
655
819
|
/** Telegram sends images through `sendPhoto` and audio through `sendVoice`. */
|
|
656
820
|
attachmentKinds = ["image", "audio"];
|
|
821
|
+
/** Telegram sends a file through `sendDocument`: any media type, up to 50 MiB. */
|
|
822
|
+
fileUpload = TELEGRAM_FILE_UPLOAD;
|
|
823
|
+
/**
|
|
824
|
+
* Telegram shows rows of buttons under a message as an inline keyboard: URL buttons, and
|
|
825
|
+
* `web_app` buttons that open a Mini App in a private chat. A `callback` button is refused until
|
|
826
|
+
* the adapter receives `callback_query` updates.
|
|
827
|
+
*/
|
|
828
|
+
buttonSupport = TELEGRAM_BUTTONS;
|
|
657
829
|
/** Telegram edits a sent message's text through `editMessageText`. */
|
|
658
830
|
supportsEdit = true;
|
|
831
|
+
/**
|
|
832
|
+
* A streamed reply is previewed by editing one message. Telegram allows about one message per
|
|
833
|
+
* second in a chat, and an edit of up to 4096 characters is one `editMessageText`.
|
|
834
|
+
*/
|
|
835
|
+
streamingPreview = {
|
|
836
|
+
minUpdateIntervalMs: 1e3,
|
|
837
|
+
maxCharsPerMessage: () => TELEGRAM_MAX_MESSAGE
|
|
838
|
+
};
|
|
659
839
|
/**
|
|
660
840
|
* Replace the text of a message this bot sent, through `editMessageText`.
|
|
661
841
|
*
|
|
@@ -671,6 +851,8 @@ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
671
851
|
return refuseAttachments(out) ?? this.editText(messageId, out);
|
|
672
852
|
}
|
|
673
853
|
async editText(messageId, out) {
|
|
854
|
+
const keyboard = inlineKeyboardOf(out);
|
|
855
|
+
if (isRefusal(keyboard)) return keyboard;
|
|
674
856
|
if (out.text.length === 0) {
|
|
675
857
|
return { ok: false, error: { code: "empty_text", message: "text is empty" } };
|
|
676
858
|
}
|
|
@@ -694,12 +876,10 @@ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
694
876
|
const parts = splitForTelegram(out.text);
|
|
695
877
|
if (parts.length !== 1) return editPartsRefusal(parts.length);
|
|
696
878
|
try {
|
|
697
|
-
await this.bot.api.editMessageText(
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
parseModeOptions(out.format)
|
|
702
|
-
);
|
|
879
|
+
await this.bot.api.editMessageText(chatIdNum, id, parts[0], {
|
|
880
|
+
...parseModeOptions(out.format),
|
|
881
|
+
...keyboard
|
|
882
|
+
});
|
|
703
883
|
} catch (err) {
|
|
704
884
|
if (!isNotModified(err)) return mapSendError(err);
|
|
705
885
|
}
|
|
@@ -751,7 +931,9 @@ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
751
931
|
if (normalized === void 0) return;
|
|
752
932
|
const event = this.gateMention(normalized);
|
|
753
933
|
if (event === void 0) return;
|
|
754
|
-
await this.dispatchEvent(
|
|
934
|
+
await this.dispatchEvent(
|
|
935
|
+
this.withDocument(ctx, this.withVoice(ctx, event))
|
|
936
|
+
);
|
|
755
937
|
}
|
|
756
938
|
/**
|
|
757
939
|
* Marks whether the bot was addressed and applies the `requireMention` gate, shared by the
|
|
@@ -781,27 +963,63 @@ var TelegramAdapter = class extends loopzeroGateway.BasePlatformAdapter {
|
|
|
781
963
|
return { ...event, addressed };
|
|
782
964
|
}
|
|
783
965
|
/**
|
|
784
|
-
* The event with the voice note's audio when the message has one (B-715, ADR D1)
|
|
966
|
+
* The event with the voice note's audio when the message has one (B-715, ADR D1), or with the
|
|
967
|
+
* audio file's when it carries one instead (`message.audio`, OC-103). A message holds at most
|
|
968
|
+
* one of the two.
|
|
785
969
|
*
|
|
786
970
|
* The audio is deferred: no request leaves here, so a `pre_inbound` hook that refuses the event
|
|
787
|
-
* costs no download. An unreadable voice rejects `audio.read()` and writes the
|
|
971
|
+
* costs no download. An unreadable voice or audio file rejects `audio.read()` and writes the
|
|
972
|
+
* reason to stderr.
|
|
788
973
|
*/
|
|
789
974
|
withVoice(ctx, event) {
|
|
790
975
|
const voice = ctx.message?.voice;
|
|
791
|
-
if (voice
|
|
792
|
-
if (voice !==
|
|
976
|
+
if (voice !== void 0) {
|
|
977
|
+
if (typeof voice.file_id !== "string") {
|
|
978
|
+
process.stderr.write("[telegram] voice not read: no_file_id\n");
|
|
979
|
+
return event;
|
|
980
|
+
}
|
|
981
|
+
const audio2 = deferVoice(
|
|
982
|
+
ctx,
|
|
983
|
+
this.bot.token,
|
|
984
|
+
(reason) => process.stderr.write(`[telegram] voice not read: ${reason}
|
|
985
|
+
`),
|
|
986
|
+
void 0,
|
|
987
|
+
this.apiBase
|
|
988
|
+
);
|
|
989
|
+
return { ...event, audio: audio2 };
|
|
990
|
+
}
|
|
991
|
+
const audioFile = ctx.message?.audio;
|
|
992
|
+
if (audioFile === void 0) return event;
|
|
993
|
+
if (typeof audioFile.file_id !== "string") {
|
|
994
|
+
process.stderr.write("[telegram] audio not read: no_file_id\n");
|
|
793
995
|
return event;
|
|
794
996
|
}
|
|
795
|
-
const audio =
|
|
997
|
+
const audio = deferAudioFile(
|
|
796
998
|
ctx,
|
|
797
999
|
this.bot.token,
|
|
798
|
-
(reason) => process.stderr.write(`[telegram]
|
|
1000
|
+
(reason) => process.stderr.write(`[telegram] audio not read: ${reason}
|
|
799
1001
|
`),
|
|
800
1002
|
void 0,
|
|
801
1003
|
this.apiBase
|
|
802
1004
|
);
|
|
803
1005
|
return { ...event, audio };
|
|
804
1006
|
}
|
|
1007
|
+
/**
|
|
1008
|
+
* The event with the message's document as `files`, when it has one. Deferred like the voice
|
|
1009
|
+
* note: no request leaves here. An unreadable document rejects `read()` and writes the reason
|
|
1010
|
+
* to stderr.
|
|
1011
|
+
*/
|
|
1012
|
+
withDocument(ctx, event) {
|
|
1013
|
+
const file = deferDocument(
|
|
1014
|
+
ctx,
|
|
1015
|
+
this.bot.token,
|
|
1016
|
+
(reason) => process.stderr.write(`[telegram] document not read: ${reason}
|
|
1017
|
+
`),
|
|
1018
|
+
void 0,
|
|
1019
|
+
this.apiBase
|
|
1020
|
+
);
|
|
1021
|
+
return file === void 0 ? event : { ...event, files: [file] };
|
|
1022
|
+
}
|
|
805
1023
|
/**
|
|
806
1024
|
* Dispatch a pre-built event to the current handler, honouring EC-H replace
|
|
807
1025
|
* semantics.
|