@zerodot/telegram 0.0.0-stage → 1.0.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/LICENSE +661 -0
- package/dist/index.mjs +1195 -0
- package/package.json +45 -3
- package/telegram.svg +1 -0
- package/README.md +0 -3
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,1195 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { FORM_FIELD_TYPES, defineNode, fileIcon, mimeTypeOf, readBinary, toBinary } from "@zerodot/node-sdk";
|
|
3
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
4
|
+
// src/api.ts
|
|
5
|
+
const TELEGRAM_CREDENTIAL = "telegram.bot";
|
|
6
|
+
const DEFAULT_BASE_URL = "https://api.telegram.org";
|
|
7
|
+
/** The token and the API address of a credential. */
|
|
8
|
+
function telegramAccess(credential) {
|
|
9
|
+
if (!credential || credential.type !== "telegram.bot") throw new Error("The node needs a Telegram bot credential");
|
|
10
|
+
const { accessToken, baseUrl } = credential.data;
|
|
11
|
+
if (typeof accessToken !== "string" || accessToken.length === 0) throw new Error("The credential has no \"accessToken\"");
|
|
12
|
+
return {
|
|
13
|
+
accessToken,
|
|
14
|
+
baseUrl: (typeof baseUrl === "string" && baseUrl !== "" ? baseUrl : DEFAULT_BASE_URL).replace(/\/+$/, "")
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
/** One Bot API call. The error text never has the token, because the token is in the URL. */
|
|
18
|
+
async function callTelegram(access, method, body, options) {
|
|
19
|
+
const isForm = body instanceof FormData;
|
|
20
|
+
const response = await fetch(`${access.baseUrl}/bot${access.accessToken}/${method}`, {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: isForm ? void 0 : { "content-type": "application/json" },
|
|
23
|
+
body: isForm ? body : JSON.stringify(body),
|
|
24
|
+
signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)])
|
|
25
|
+
});
|
|
26
|
+
const answer = await response.json().catch(() => null);
|
|
27
|
+
if (!answer?.ok) throw new Error(`Telegram ${method} failed (${response.status}): ${answer?.description ?? "no answer"}`);
|
|
28
|
+
return answer;
|
|
29
|
+
}
|
|
30
|
+
/** Bot API files are at most 20 MB. */
|
|
31
|
+
const MAX_DOWNLOAD_BYTES = 20971520;
|
|
32
|
+
/** The bytes of a file that `getFile` named. The error text never has the token. */
|
|
33
|
+
async function downloadTelegramFile(access, filePath, options) {
|
|
34
|
+
let response;
|
|
35
|
+
try {
|
|
36
|
+
response = await fetch(`${access.baseUrl}/file/bot${access.accessToken}/${filePath}`, { signal: AbortSignal.any([options.signal, AbortSignal.timeout(options.timeoutMs)]) });
|
|
37
|
+
} catch {
|
|
38
|
+
throw new Error("Telegram file download failed");
|
|
39
|
+
}
|
|
40
|
+
if (!response.ok) throw new Error(`Telegram file download failed (${response.status})`);
|
|
41
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
42
|
+
if (bytes.byteLength > MAX_DOWNLOAD_BYTES) throw new Error("The Telegram file is too large");
|
|
43
|
+
return bytes;
|
|
44
|
+
}
|
|
45
|
+
// src/icon.ts
|
|
46
|
+
const TELEGRAM_ICON = fileIcon(import.meta.url, "../telegram.svg");
|
|
47
|
+
// src/credential.ts
|
|
48
|
+
const TIMEOUT_MS = 1e4;
|
|
49
|
+
const text = (value) => typeof value === "string" && value !== "" ? value : void 0;
|
|
50
|
+
const telegramCredential = {
|
|
51
|
+
type: TELEGRAM_CREDENTIAL,
|
|
52
|
+
label: "Telegram bot",
|
|
53
|
+
fields: z.object({
|
|
54
|
+
accessToken: z.string().min(1).meta({ placeholder: "123456:ABC-DEF…" }),
|
|
55
|
+
baseUrl: z.url().optional().meta({ placeholder: "https://api.telegram.org" })
|
|
56
|
+
}),
|
|
57
|
+
secretFields: ["accessToken"],
|
|
58
|
+
icon: "Send",
|
|
59
|
+
iconUrl: TELEGRAM_ICON,
|
|
60
|
+
async test({ data }) {
|
|
61
|
+
const token = text(data.accessToken);
|
|
62
|
+
if (!token) throw new Error("The credential has no \"accessToken\"");
|
|
63
|
+
const base = (text(data.baseUrl) ?? "https://api.telegram.org").replace(/\/+$/, "");
|
|
64
|
+
const response = await fetch(`${base}/bot${token}/getMe`, { signal: AbortSignal.timeout(TIMEOUT_MS) });
|
|
65
|
+
if (response.status === 401 || response.status === 404) throw new Error("Telegram did not accept the token");
|
|
66
|
+
if (!response.ok) throw new Error(`Telegram answered with status ${response.status}`);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
// src/config.ts
|
|
70
|
+
const RESOURCES = [
|
|
71
|
+
"message",
|
|
72
|
+
"chat",
|
|
73
|
+
"callback",
|
|
74
|
+
"file"
|
|
75
|
+
];
|
|
76
|
+
const OPERATIONS = [
|
|
77
|
+
"sendMessage",
|
|
78
|
+
"editMessageText",
|
|
79
|
+
"deleteMessage",
|
|
80
|
+
"pinChatMessage",
|
|
81
|
+
"unpinChatMessage",
|
|
82
|
+
"sendPhoto",
|
|
83
|
+
"sendVideo",
|
|
84
|
+
"sendAudio",
|
|
85
|
+
"sendDocument",
|
|
86
|
+
"sendAnimation",
|
|
87
|
+
"sendSticker",
|
|
88
|
+
"sendLocation",
|
|
89
|
+
"sendMediaGroup",
|
|
90
|
+
"sendChatAction",
|
|
91
|
+
"sendAndWait",
|
|
92
|
+
"get",
|
|
93
|
+
"administrators",
|
|
94
|
+
"member",
|
|
95
|
+
"leave",
|
|
96
|
+
"setTitle",
|
|
97
|
+
"setDescription",
|
|
98
|
+
"answerQuery",
|
|
99
|
+
"answerInlineQuery"
|
|
100
|
+
];
|
|
101
|
+
/** Operations of each resource. `get` is in `chat` and in `file`. */
|
|
102
|
+
const OPERATIONS_OF = {
|
|
103
|
+
message: [
|
|
104
|
+
"sendMessage",
|
|
105
|
+
"editMessageText",
|
|
106
|
+
"deleteMessage",
|
|
107
|
+
"pinChatMessage",
|
|
108
|
+
"unpinChatMessage",
|
|
109
|
+
"sendPhoto",
|
|
110
|
+
"sendVideo",
|
|
111
|
+
"sendAudio",
|
|
112
|
+
"sendDocument",
|
|
113
|
+
"sendAnimation",
|
|
114
|
+
"sendSticker",
|
|
115
|
+
"sendLocation",
|
|
116
|
+
"sendMediaGroup",
|
|
117
|
+
"sendChatAction",
|
|
118
|
+
"sendAndWait"
|
|
119
|
+
],
|
|
120
|
+
chat: [
|
|
121
|
+
"get",
|
|
122
|
+
"administrators",
|
|
123
|
+
"member",
|
|
124
|
+
"leave",
|
|
125
|
+
"setTitle",
|
|
126
|
+
"setDescription"
|
|
127
|
+
],
|
|
128
|
+
callback: ["answerQuery", "answerInlineQuery"],
|
|
129
|
+
file: ["get"]
|
|
130
|
+
};
|
|
131
|
+
const CHAT_ACTIONS = [
|
|
132
|
+
"typing",
|
|
133
|
+
"find_location",
|
|
134
|
+
"record_audio",
|
|
135
|
+
"record_video",
|
|
136
|
+
"record_video_note",
|
|
137
|
+
"upload_audio",
|
|
138
|
+
"upload_document",
|
|
139
|
+
"upload_photo",
|
|
140
|
+
"upload_video",
|
|
141
|
+
"upload_video_note"
|
|
142
|
+
];
|
|
143
|
+
const id = z.union([z.string(), z.number()]);
|
|
144
|
+
const button = z.object({
|
|
145
|
+
text: z.string(),
|
|
146
|
+
additionalFields: z.record(z.string(), z.unknown()).optional()
|
|
147
|
+
});
|
|
148
|
+
/** The "fixed collection" shape: rows.row.buttons. */
|
|
149
|
+
const keyboard = z.object({ rows: z.array(z.object({ row: z.object({ buttons: z.array(button) }) })).default([]) });
|
|
150
|
+
const mediaItem = z.object({
|
|
151
|
+
type: z.enum(["photo", "video"]),
|
|
152
|
+
media: z.string(),
|
|
153
|
+
additionalFields: z.object({
|
|
154
|
+
caption: z.string(),
|
|
155
|
+
parse_mode: z.enum([
|
|
156
|
+
"Markdown",
|
|
157
|
+
"MarkdownV2",
|
|
158
|
+
"HTML"
|
|
159
|
+
])
|
|
160
|
+
}).partial().optional()
|
|
161
|
+
});
|
|
162
|
+
const additionalFields = z.object({
|
|
163
|
+
caption: z.string(),
|
|
164
|
+
disable_notification: z.boolean(),
|
|
165
|
+
disable_web_page_preview: z.boolean(),
|
|
166
|
+
duration: z.number(),
|
|
167
|
+
fileName: z.string(),
|
|
168
|
+
height: z.number(),
|
|
169
|
+
parse_mode: z.enum([
|
|
170
|
+
"Markdown",
|
|
171
|
+
"MarkdownV2",
|
|
172
|
+
"HTML"
|
|
173
|
+
]),
|
|
174
|
+
performer: z.string(),
|
|
175
|
+
reply_to_message_id: z.number(),
|
|
176
|
+
message_thread_id: z.number(),
|
|
177
|
+
title: z.string(),
|
|
178
|
+
thumb: z.string(),
|
|
179
|
+
width: z.number(),
|
|
180
|
+
cache_time: z.number(),
|
|
181
|
+
show_alert: z.boolean(),
|
|
182
|
+
text: z.string(),
|
|
183
|
+
url: z.string(),
|
|
184
|
+
mimeType: z.string()
|
|
185
|
+
}).partial().catchall(z.unknown());
|
|
186
|
+
const forOperations = (...operations) => ({ showWhen: { operation: operations } });
|
|
187
|
+
const SEND_FILE = [
|
|
188
|
+
"sendPhoto",
|
|
189
|
+
"sendVideo",
|
|
190
|
+
"sendAudio",
|
|
191
|
+
"sendDocument",
|
|
192
|
+
"sendAnimation",
|
|
193
|
+
"sendSticker"
|
|
194
|
+
];
|
|
195
|
+
const WITH_ADDITIONAL = [
|
|
196
|
+
"sendMessage",
|
|
197
|
+
"editMessageText",
|
|
198
|
+
...SEND_FILE,
|
|
199
|
+
"sendLocation",
|
|
200
|
+
"sendMediaGroup",
|
|
201
|
+
"pinChatMessage",
|
|
202
|
+
"answerQuery",
|
|
203
|
+
"answerInlineQuery"
|
|
204
|
+
];
|
|
205
|
+
const WITH_MARKUP = [
|
|
206
|
+
"sendMessage",
|
|
207
|
+
...SEND_FILE,
|
|
208
|
+
"sendLocation"
|
|
209
|
+
];
|
|
210
|
+
const telegramConfig = z.object({
|
|
211
|
+
resource: z.enum(RESOURCES).default("message").meta({
|
|
212
|
+
labels: {
|
|
213
|
+
message: "Message",
|
|
214
|
+
chat: "Chat",
|
|
215
|
+
callback: "Callback",
|
|
216
|
+
file: "File"
|
|
217
|
+
},
|
|
218
|
+
hints: {
|
|
219
|
+
message: "Send, edit, delete, or pin messages",
|
|
220
|
+
chat: "Get or change a chat, a channel, or a group",
|
|
221
|
+
callback: "Answer a button press or an inline query",
|
|
222
|
+
file: "Get a file that Telegram has"
|
|
223
|
+
}
|
|
224
|
+
}),
|
|
225
|
+
operation: z.enum(OPERATIONS).default("sendMessage").meta({
|
|
226
|
+
labels: {
|
|
227
|
+
sendMessage: "Send Message",
|
|
228
|
+
editMessageText: "Edit Message Text",
|
|
229
|
+
deleteMessage: "Delete Message",
|
|
230
|
+
pinChatMessage: "Pin Message",
|
|
231
|
+
unpinChatMessage: "Unpin Message",
|
|
232
|
+
sendPhoto: "Send Photo",
|
|
233
|
+
sendVideo: "Send Video",
|
|
234
|
+
sendAudio: "Send Audio",
|
|
235
|
+
sendDocument: "Send Document",
|
|
236
|
+
sendAnimation: "Send Animation",
|
|
237
|
+
sendSticker: "Send Sticker",
|
|
238
|
+
sendLocation: "Send Location",
|
|
239
|
+
sendMediaGroup: "Send Media Group",
|
|
240
|
+
sendChatAction: "Send Chat Action",
|
|
241
|
+
sendAndWait: "Send and Wait for Response",
|
|
242
|
+
get: "Get",
|
|
243
|
+
administrators: "Get Administrators",
|
|
244
|
+
member: "Get Member",
|
|
245
|
+
leave: "Leave",
|
|
246
|
+
setTitle: "Set Title",
|
|
247
|
+
setDescription: "Set Description",
|
|
248
|
+
answerQuery: "Answer Query",
|
|
249
|
+
answerInlineQuery: "Answer Inline Query"
|
|
250
|
+
},
|
|
251
|
+
hints: {
|
|
252
|
+
sendMessage: "Send a text message",
|
|
253
|
+
editMessageText: "Change the text of a message",
|
|
254
|
+
deleteMessage: "Delete a message from a chat",
|
|
255
|
+
pinChatMessage: "Pin a message in a chat",
|
|
256
|
+
unpinChatMessage: "Unpin a message in a chat",
|
|
257
|
+
sendPhoto: "Send a photo",
|
|
258
|
+
sendVideo: "Send a video",
|
|
259
|
+
sendAudio: "Send an audio file",
|
|
260
|
+
sendDocument: "Send a document",
|
|
261
|
+
sendAnimation: "Send a GIF or a short video without sound",
|
|
262
|
+
sendSticker: "Send a sticker",
|
|
263
|
+
sendLocation: "Send a point on the map",
|
|
264
|
+
sendMediaGroup: "Send photos and videos as one album",
|
|
265
|
+
sendChatAction: "Show a status such as typing",
|
|
266
|
+
sendAndWait: "Send a message and pause the workflow until the user answers",
|
|
267
|
+
get: "Get a chat, or a file",
|
|
268
|
+
administrators: "Get the administrators of a chat",
|
|
269
|
+
member: "Get one member of a chat",
|
|
270
|
+
leave: "Make the bot leave a chat",
|
|
271
|
+
setTitle: "Change the title of a chat",
|
|
272
|
+
setDescription: "Change the description of a chat",
|
|
273
|
+
answerQuery: "Answer a button press",
|
|
274
|
+
answerInlineQuery: "Answer an inline query"
|
|
275
|
+
}
|
|
276
|
+
}),
|
|
277
|
+
chatId: id.optional().meta({
|
|
278
|
+
...forOperations("sendMessage", "editMessageText", "deleteMessage", "pinChatMessage", "unpinChatMessage", ...SEND_FILE, "sendLocation", "sendMediaGroup", "sendChatAction", "sendAndWait", "get", "administrators", "member", "leave", "setTitle", "setDescription"),
|
|
279
|
+
showWhen: {
|
|
280
|
+
resource: ["message", "chat"],
|
|
281
|
+
operation: [
|
|
282
|
+
"sendMessage",
|
|
283
|
+
"editMessageText",
|
|
284
|
+
"deleteMessage",
|
|
285
|
+
"pinChatMessage",
|
|
286
|
+
"unpinChatMessage",
|
|
287
|
+
...SEND_FILE,
|
|
288
|
+
"sendLocation",
|
|
289
|
+
"sendMediaGroup",
|
|
290
|
+
"sendChatAction",
|
|
291
|
+
"sendAndWait",
|
|
292
|
+
"get",
|
|
293
|
+
"administrators",
|
|
294
|
+
"member",
|
|
295
|
+
"leave",
|
|
296
|
+
"setTitle",
|
|
297
|
+
"setDescription"
|
|
298
|
+
]
|
|
299
|
+
},
|
|
300
|
+
description: "Unique identifier of the target chat, or @channelusername"
|
|
301
|
+
}),
|
|
302
|
+
messageId: id.optional().meta(forOperations("editMessageText", "deleteMessage", "pinChatMessage", "unpinChatMessage")),
|
|
303
|
+
messageType: z.enum(["message", "inlineMessage"]).optional().meta({
|
|
304
|
+
...forOperations("editMessageText"),
|
|
305
|
+
labels: {
|
|
306
|
+
message: "Message",
|
|
307
|
+
inlineMessage: "Inline Message"
|
|
308
|
+
},
|
|
309
|
+
hints: {
|
|
310
|
+
message: "A message in a chat",
|
|
311
|
+
inlineMessage: "A message that was sent through inline mode"
|
|
312
|
+
}
|
|
313
|
+
}),
|
|
314
|
+
inlineMessageId: z.string().optional().meta(forOperations("editMessageText")),
|
|
315
|
+
userId: id.optional().meta(forOperations("member")),
|
|
316
|
+
title: z.string().optional().meta(forOperations("setTitle")),
|
|
317
|
+
description: z.string().optional().meta(forOperations("setDescription")),
|
|
318
|
+
queryId: z.string().optional().meta(forOperations("answerQuery", "answerInlineQuery")),
|
|
319
|
+
results: z.string().optional().meta({
|
|
320
|
+
...forOperations("answerInlineQuery"),
|
|
321
|
+
description: "A JSON array of results for the inline query"
|
|
322
|
+
}),
|
|
323
|
+
fileId: z.string().optional().meta({ showWhen: {
|
|
324
|
+
resource: ["file"],
|
|
325
|
+
operation: ["get"]
|
|
326
|
+
} }),
|
|
327
|
+
download: z.boolean().default(false).meta({
|
|
328
|
+
showWhen: {
|
|
329
|
+
resource: ["file"],
|
|
330
|
+
operation: ["get"]
|
|
331
|
+
},
|
|
332
|
+
description: "Add the file as binary data to the output"
|
|
333
|
+
}),
|
|
334
|
+
binaryData: z.boolean().default(false).meta({
|
|
335
|
+
...forOperations(...SEND_FILE),
|
|
336
|
+
description: "Upload the binary data of the input instead of a URL or a file_id"
|
|
337
|
+
}),
|
|
338
|
+
binaryPropertyName: z.string().default("data").meta({
|
|
339
|
+
showWhen: { binaryData: [true] },
|
|
340
|
+
description: "The property of `binary` in the input that holds the file"
|
|
341
|
+
}),
|
|
342
|
+
message: z.string().optional().meta({
|
|
343
|
+
...forOperations("sendAndWait"),
|
|
344
|
+
description: "The message to send, with the buttons"
|
|
345
|
+
}),
|
|
346
|
+
responseType: z.enum([
|
|
347
|
+
"approval",
|
|
348
|
+
"freeText",
|
|
349
|
+
"customForm"
|
|
350
|
+
]).default("approval").meta({
|
|
351
|
+
...forOperations("sendAndWait"),
|
|
352
|
+
title: "Response Type",
|
|
353
|
+
labels: {
|
|
354
|
+
approval: "Approval",
|
|
355
|
+
freeText: "Free Text",
|
|
356
|
+
customForm: "Custom Form"
|
|
357
|
+
},
|
|
358
|
+
hints: {
|
|
359
|
+
approval: "The user presses an approve or decline button",
|
|
360
|
+
freeText: "The user writes an answer in text",
|
|
361
|
+
customForm: "The user fills in a form with the fields that you set"
|
|
362
|
+
}
|
|
363
|
+
}),
|
|
364
|
+
approvalOptions: z.object({
|
|
365
|
+
approvalType: z.enum(["single", "double"]).default("single"),
|
|
366
|
+
approveLabel: z.string().default("Approve"),
|
|
367
|
+
disapproveLabel: z.string().default("Decline")
|
|
368
|
+
}).partial().optional().meta({ showWhen: {
|
|
369
|
+
operation: ["sendAndWait"],
|
|
370
|
+
responseType: ["approval"]
|
|
371
|
+
} }),
|
|
372
|
+
formFields: z.array(z.object({
|
|
373
|
+
fieldLabel: z.string(),
|
|
374
|
+
fieldType: z.enum(FORM_FIELD_TYPES).optional(),
|
|
375
|
+
placeholder: z.string().optional(),
|
|
376
|
+
requiredField: z.boolean().optional(),
|
|
377
|
+
fieldOptions: z.object({ values: z.array(z.object({ option: z.string() })) }).optional()
|
|
378
|
+
})).optional().meta({ showWhen: {
|
|
379
|
+
operation: ["sendAndWait"],
|
|
380
|
+
responseType: ["customForm"]
|
|
381
|
+
} }),
|
|
382
|
+
options: z.object({
|
|
383
|
+
messageButtonLabel: z.string(),
|
|
384
|
+
responseFormTitle: z.string(),
|
|
385
|
+
responseFormDescription: z.string(),
|
|
386
|
+
responseFormButtonLabel: z.string(),
|
|
387
|
+
limitWaitTimeHours: z.number().min(.01).max(720)
|
|
388
|
+
}).partial().optional().meta({
|
|
389
|
+
...forOperations("sendAndWait"),
|
|
390
|
+
description: "limitWaitTimeHours: how long to wait for an answer. Default 168 (7 days)."
|
|
391
|
+
}),
|
|
392
|
+
text: z.string().optional().meta({
|
|
393
|
+
...forOperations("sendMessage", "editMessageText"),
|
|
394
|
+
ui: "textarea"
|
|
395
|
+
}),
|
|
396
|
+
file: z.string().optional().meta({
|
|
397
|
+
...forOperations(...SEND_FILE),
|
|
398
|
+
description: "A public URL, or the file_id of a file that Telegram has"
|
|
399
|
+
}),
|
|
400
|
+
action: z.enum(CHAT_ACTIONS).optional().meta({
|
|
401
|
+
...forOperations("sendChatAction"),
|
|
402
|
+
labels: {
|
|
403
|
+
typing: "Typing a Message",
|
|
404
|
+
find_location: "Selecting a Location",
|
|
405
|
+
record_audio: "Recording Audio",
|
|
406
|
+
record_video: "Recording Video",
|
|
407
|
+
record_video_note: "Recording Video Note",
|
|
408
|
+
upload_audio: "Uploading Audio",
|
|
409
|
+
upload_document: "Uploading Document",
|
|
410
|
+
upload_photo: "Uploading Photo",
|
|
411
|
+
upload_video: "Uploading Video",
|
|
412
|
+
upload_video_note: "Uploading Video Note"
|
|
413
|
+
},
|
|
414
|
+
hints: {
|
|
415
|
+
typing: "Show that the bot writes text",
|
|
416
|
+
find_location: "Show that the bot picks a location",
|
|
417
|
+
record_audio: "Show that the bot records a voice message",
|
|
418
|
+
record_video: "Show that the bot records a video",
|
|
419
|
+
record_video_note: "Show that the bot records a round video",
|
|
420
|
+
upload_audio: "Show that the bot sends audio",
|
|
421
|
+
upload_document: "Show that the bot sends a document",
|
|
422
|
+
upload_photo: "Show that the bot sends a photo",
|
|
423
|
+
upload_video: "Show that the bot sends a video",
|
|
424
|
+
upload_video_note: "Show that the bot sends a round video"
|
|
425
|
+
}
|
|
426
|
+
}),
|
|
427
|
+
latitude: z.number().optional().meta(forOperations("sendLocation")),
|
|
428
|
+
longitude: z.number().optional().meta(forOperations("sendLocation")),
|
|
429
|
+
media: z.object({ media: z.array(mediaItem) }).optional().meta(forOperations("sendMediaGroup")),
|
|
430
|
+
replyMarkup: z.enum([
|
|
431
|
+
"none",
|
|
432
|
+
"inlineKeyboard",
|
|
433
|
+
"replyKeyboard",
|
|
434
|
+
"replyKeyboardRemove",
|
|
435
|
+
"forceReply"
|
|
436
|
+
]).default("none").meta({
|
|
437
|
+
...forOperations(...WITH_MARKUP, "editMessageText"),
|
|
438
|
+
title: "Reply Markup",
|
|
439
|
+
labels: {
|
|
440
|
+
none: "None",
|
|
441
|
+
inlineKeyboard: "Inline Keyboard",
|
|
442
|
+
replyKeyboard: "Reply Keyboard",
|
|
443
|
+
replyKeyboardRemove: "Reply Keyboard Remove",
|
|
444
|
+
forceReply: "Force Reply"
|
|
445
|
+
},
|
|
446
|
+
hints: {
|
|
447
|
+
none: "No buttons",
|
|
448
|
+
inlineKeyboard: "Buttons under the message",
|
|
449
|
+
replyKeyboard: "Buttons that replace the keyboard of the user",
|
|
450
|
+
replyKeyboardRemove: "Remove the reply keyboard",
|
|
451
|
+
forceReply: "Make the user reply to the message"
|
|
452
|
+
}
|
|
453
|
+
}),
|
|
454
|
+
inlineKeyboard: keyboard.optional().meta({ showWhen: { replyMarkup: ["inlineKeyboard"] } }),
|
|
455
|
+
replyKeyboard: keyboard.optional().meta({ showWhen: { replyMarkup: ["replyKeyboard"] } }),
|
|
456
|
+
replyKeyboardOptions: z.object({
|
|
457
|
+
resize_keyboard: z.boolean(),
|
|
458
|
+
one_time_keyboard: z.boolean(),
|
|
459
|
+
selective: z.boolean()
|
|
460
|
+
}).partial().optional().meta({ showWhen: { replyMarkup: ["replyKeyboard"] } }),
|
|
461
|
+
replyKeyboardRemove: z.object({
|
|
462
|
+
remove_keyboard: z.boolean(),
|
|
463
|
+
selective: z.boolean()
|
|
464
|
+
}).partial().optional().meta({ showWhen: { replyMarkup: ["replyKeyboardRemove"] } }),
|
|
465
|
+
forceReply: z.object({
|
|
466
|
+
force_reply: z.boolean(),
|
|
467
|
+
selective: z.boolean()
|
|
468
|
+
}).partial().optional().meta({ showWhen: { replyMarkup: ["forceReply"] } }),
|
|
469
|
+
additionalFields: additionalFields.default({}).meta(forOperations(...WITH_ADDITIONAL)),
|
|
470
|
+
timeoutMs: z.number().int().min(1).max(3e5).default(3e4)
|
|
471
|
+
}).superRefine((config, context) => {
|
|
472
|
+
if (!OPERATIONS_OF[config.resource].includes(config.operation)) context.addIssue({
|
|
473
|
+
code: "custom",
|
|
474
|
+
path: ["operation"],
|
|
475
|
+
message: `"${config.operation}" is not an operation of "${config.resource}"`
|
|
476
|
+
});
|
|
477
|
+
});
|
|
478
|
+
// src/request.ts
|
|
479
|
+
const FILE_FIELD = {
|
|
480
|
+
sendPhoto: "photo",
|
|
481
|
+
sendVideo: "video",
|
|
482
|
+
sendAudio: "audio",
|
|
483
|
+
sendDocument: "document",
|
|
484
|
+
sendAnimation: "animation",
|
|
485
|
+
sendSticker: "sticker"
|
|
486
|
+
};
|
|
487
|
+
const URL_IN_TEXT = /(https?|ftp|file):\/\/\S+|www\.\S+|\S+\.\S+/;
|
|
488
|
+
function keyboardRows(keyboard) {
|
|
489
|
+
return (keyboard?.rows ?? []).map(({ row }) => row.buttons.map(({ text, additionalFields }) => ({
|
|
490
|
+
text,
|
|
491
|
+
...additionalFields
|
|
492
|
+
})));
|
|
493
|
+
}
|
|
494
|
+
/** Adds the optional fields of a request, without an attribution footer. */
|
|
495
|
+
function addAdditionalFields(body, config) {
|
|
496
|
+
const { operation } = config;
|
|
497
|
+
const fields = { ...config.additionalFields };
|
|
498
|
+
if (operation === "sendMessage") {
|
|
499
|
+
fields.parse_mode ??= "Markdown";
|
|
500
|
+
if (!URL_IN_TEXT.test(String(body.text ?? ""))) body.disable_web_page_preview = true;
|
|
501
|
+
fields.disable_web_page_preview ??= true;
|
|
502
|
+
}
|
|
503
|
+
Object.assign(body, fields);
|
|
504
|
+
if (operation === "sendMediaGroup") return;
|
|
505
|
+
const { replyMarkup } = config;
|
|
506
|
+
if (replyMarkup === "none") return;
|
|
507
|
+
if (replyMarkup === "inlineKeyboard") body.reply_markup = { inline_keyboard: keyboardRows(config.inlineKeyboard) };
|
|
508
|
+
else if (replyMarkup === "replyKeyboard") body.reply_markup = {
|
|
509
|
+
keyboard: keyboardRows(config.replyKeyboard),
|
|
510
|
+
...config.replyKeyboardOptions
|
|
511
|
+
};
|
|
512
|
+
else if (replyMarkup === "forceReply") body.reply_markup = { ...config.forceReply };
|
|
513
|
+
else body.reply_markup = { ...config.replyKeyboardRemove };
|
|
514
|
+
}
|
|
515
|
+
/** The Bot API call for a config. It throws when a field that the operation needs is empty. */
|
|
516
|
+
function buildRequest(config) {
|
|
517
|
+
const { resource, operation } = config;
|
|
518
|
+
const need = (name, value) => {
|
|
519
|
+
if (value === void 0 || value === "") throw new Error(`Telegram ${resource}.${operation} needs "${name}"`);
|
|
520
|
+
return value;
|
|
521
|
+
};
|
|
522
|
+
const chat = () => need("chatId", config.chatId);
|
|
523
|
+
const body = {};
|
|
524
|
+
if (resource === "callback") {
|
|
525
|
+
if (operation === "answerQuery") {
|
|
526
|
+
body.callback_query_id = need("queryId", config.queryId);
|
|
527
|
+
Object.assign(body, config.additionalFields);
|
|
528
|
+
return {
|
|
529
|
+
method: "answerCallbackQuery",
|
|
530
|
+
body
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
body.inline_query_id = need("queryId", config.queryId);
|
|
534
|
+
body.results = need("results", config.results);
|
|
535
|
+
Object.assign(body, config.additionalFields);
|
|
536
|
+
return {
|
|
537
|
+
method: "answerInlineQuery",
|
|
538
|
+
body
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
if (resource === "chat") {
|
|
542
|
+
body.chat_id = chat();
|
|
543
|
+
switch (operation) {
|
|
544
|
+
case "get": return {
|
|
545
|
+
method: "getChat",
|
|
546
|
+
body
|
|
547
|
+
};
|
|
548
|
+
case "administrators": return {
|
|
549
|
+
method: "getChatAdministrators",
|
|
550
|
+
body
|
|
551
|
+
};
|
|
552
|
+
case "leave": return {
|
|
553
|
+
method: "leaveChat",
|
|
554
|
+
body
|
|
555
|
+
};
|
|
556
|
+
case "member":
|
|
557
|
+
body.user_id = need("userId", config.userId);
|
|
558
|
+
return {
|
|
559
|
+
method: "getChatMember",
|
|
560
|
+
body
|
|
561
|
+
};
|
|
562
|
+
case "setDescription":
|
|
563
|
+
body.description = need("description", config.description);
|
|
564
|
+
return {
|
|
565
|
+
method: "setChatDescription",
|
|
566
|
+
body
|
|
567
|
+
};
|
|
568
|
+
case "setTitle":
|
|
569
|
+
body.title = need("title", config.title);
|
|
570
|
+
return {
|
|
571
|
+
method: "setChatTitle",
|
|
572
|
+
body
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
throw new Error(`"${operation}" is not an operation of "chat"`);
|
|
576
|
+
}
|
|
577
|
+
if (resource === "file") {
|
|
578
|
+
body.file_id = need("fileId", config.fileId);
|
|
579
|
+
return {
|
|
580
|
+
method: "getFile",
|
|
581
|
+
body
|
|
582
|
+
};
|
|
583
|
+
}
|
|
584
|
+
switch (operation) {
|
|
585
|
+
case "editMessageText":
|
|
586
|
+
if (config.messageType === "inlineMessage") body.inline_message_id = need("inlineMessageId", config.inlineMessageId);
|
|
587
|
+
else {
|
|
588
|
+
body.chat_id = chat();
|
|
589
|
+
body.message_id = need("messageId", config.messageId);
|
|
590
|
+
}
|
|
591
|
+
body.text = need("text", config.text);
|
|
592
|
+
addAdditionalFields(body, config);
|
|
593
|
+
return {
|
|
594
|
+
method: "editMessageText",
|
|
595
|
+
body
|
|
596
|
+
};
|
|
597
|
+
case "deleteMessage":
|
|
598
|
+
case "unpinChatMessage":
|
|
599
|
+
body.chat_id = chat();
|
|
600
|
+
body.message_id = need("messageId", config.messageId);
|
|
601
|
+
return {
|
|
602
|
+
method: operation,
|
|
603
|
+
body
|
|
604
|
+
};
|
|
605
|
+
case "pinChatMessage":
|
|
606
|
+
body.chat_id = chat();
|
|
607
|
+
body.message_id = need("messageId", config.messageId);
|
|
608
|
+
if (config.additionalFields.disable_notification) body.disable_notification = true;
|
|
609
|
+
return {
|
|
610
|
+
method: "pinChatMessage",
|
|
611
|
+
body
|
|
612
|
+
};
|
|
613
|
+
case "sendChatAction":
|
|
614
|
+
body.chat_id = chat();
|
|
615
|
+
body.action = need("action", config.action);
|
|
616
|
+
return {
|
|
617
|
+
method: "sendChatAction",
|
|
618
|
+
body
|
|
619
|
+
};
|
|
620
|
+
case "sendLocation":
|
|
621
|
+
body.chat_id = chat();
|
|
622
|
+
body.latitude = need("latitude", config.latitude);
|
|
623
|
+
body.longitude = need("longitude", config.longitude);
|
|
624
|
+
addAdditionalFields(body, config);
|
|
625
|
+
return {
|
|
626
|
+
method: "sendLocation",
|
|
627
|
+
body
|
|
628
|
+
};
|
|
629
|
+
case "sendMessage":
|
|
630
|
+
body.chat_id = chat();
|
|
631
|
+
body.text = need("text", config.text);
|
|
632
|
+
addAdditionalFields(body, config);
|
|
633
|
+
return {
|
|
634
|
+
method: "sendMessage",
|
|
635
|
+
body
|
|
636
|
+
};
|
|
637
|
+
case "sendMediaGroup":
|
|
638
|
+
body.chat_id = chat();
|
|
639
|
+
Object.assign(body, config.additionalFields);
|
|
640
|
+
body.media = need("media", config.media).media.map(({ additionalFields, ...item }) => ({
|
|
641
|
+
...item,
|
|
642
|
+
...additionalFields
|
|
643
|
+
}));
|
|
644
|
+
return {
|
|
645
|
+
method: "sendMediaGroup",
|
|
646
|
+
body
|
|
647
|
+
};
|
|
648
|
+
default: {
|
|
649
|
+
const field = FILE_FIELD[operation];
|
|
650
|
+
if (!field) throw new Error(`"${operation}" is not an operation of "message"`);
|
|
651
|
+
body.chat_id = chat();
|
|
652
|
+
if (!config.binaryData) body[field] = need("file", config.file);
|
|
653
|
+
addAdditionalFields(body, config);
|
|
654
|
+
return {
|
|
655
|
+
method: operation,
|
|
656
|
+
body
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
/** The form of the resume page. Approval needs none: the buttons carry the answer. */
|
|
662
|
+
function waitFormOf(config) {
|
|
663
|
+
const { responseType, formFields, options } = config;
|
|
664
|
+
const base = {
|
|
665
|
+
title: options?.responseFormTitle,
|
|
666
|
+
description: options?.responseFormDescription,
|
|
667
|
+
buttonLabel: options?.responseFormButtonLabel
|
|
668
|
+
};
|
|
669
|
+
if (responseType === "freeText") return {
|
|
670
|
+
...base,
|
|
671
|
+
fields: [{
|
|
672
|
+
fieldLabel: "Response",
|
|
673
|
+
key: "text",
|
|
674
|
+
fieldType: "textarea",
|
|
675
|
+
requiredField: true
|
|
676
|
+
}]
|
|
677
|
+
};
|
|
678
|
+
if (responseType === "customForm") return {
|
|
679
|
+
...base,
|
|
680
|
+
fields: formFields ?? []
|
|
681
|
+
};
|
|
682
|
+
return null;
|
|
683
|
+
}
|
|
684
|
+
/** The Bot API call for `sendAndWait`: the message, with link buttons to the resume page. */
|
|
685
|
+
function buildSendAndWait(config, resumeUrl) {
|
|
686
|
+
if (config.chatId === void 0 || config.chatId === "") throw new Error("Telegram message.sendAndWait needs \"chatId\"");
|
|
687
|
+
if (!config.message) throw new Error("Telegram message.sendAndWait needs \"message\"");
|
|
688
|
+
let buttons;
|
|
689
|
+
if (config.responseType === "approval") {
|
|
690
|
+
const { approvalType = "single", approveLabel = "Approve", disapproveLabel = "Decline" } = config.approvalOptions ?? {};
|
|
691
|
+
buttons = [{
|
|
692
|
+
text: approveLabel,
|
|
693
|
+
url: `${resumeUrl}&approved=true`
|
|
694
|
+
}];
|
|
695
|
+
if (approvalType === "double") buttons.push({
|
|
696
|
+
text: disapproveLabel,
|
|
697
|
+
url: `${resumeUrl}&approved=false`
|
|
698
|
+
});
|
|
699
|
+
} else buttons = [{
|
|
700
|
+
text: config.options?.messageButtonLabel ?? "Respond",
|
|
701
|
+
url: resumeUrl
|
|
702
|
+
}];
|
|
703
|
+
return {
|
|
704
|
+
method: "sendMessage",
|
|
705
|
+
body: {
|
|
706
|
+
chat_id: config.chatId,
|
|
707
|
+
text: config.message,
|
|
708
|
+
disable_web_page_preview: true,
|
|
709
|
+
parse_mode: "Markdown",
|
|
710
|
+
reply_markup: { inline_keyboard: [buttons] }
|
|
711
|
+
}
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
/** When the wait ends without an answer. */
|
|
715
|
+
const waitDeadline = (config) => Date.now() + (config.options?.limitWaitTimeHours ?? 168) * 36e5;
|
|
716
|
+
// src/node.ts
|
|
717
|
+
/** The name of the file field in the Bot API: `sendPhoto` has `photo`. */
|
|
718
|
+
const fileProperty = (operation) => operation.replace("send", "").toLowerCase();
|
|
719
|
+
/** The upload form of a call with binary data. Objects go in as JSON text. */
|
|
720
|
+
function uploadForm(body, property, file) {
|
|
721
|
+
const form = new FormData();
|
|
722
|
+
for (const [key, value] of Object.entries(body)) {
|
|
723
|
+
if (value === void 0 || value === null) continue;
|
|
724
|
+
form.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
|
|
725
|
+
}
|
|
726
|
+
const bytes = Buffer.from(file.data, "base64");
|
|
727
|
+
form.set(property, new Blob([bytes], { type: file.mimeType }), file.fileName);
|
|
728
|
+
return form;
|
|
729
|
+
}
|
|
730
|
+
var node_default = defineNode({
|
|
731
|
+
type: "telegram.bot",
|
|
732
|
+
label: "Telegram",
|
|
733
|
+
description: "Send messages and manage chats with a Telegram bot",
|
|
734
|
+
category: "integration",
|
|
735
|
+
app: "Telegram",
|
|
736
|
+
actions: [
|
|
737
|
+
{
|
|
738
|
+
label: "Send a text message",
|
|
739
|
+
config: {
|
|
740
|
+
resource: "message",
|
|
741
|
+
operation: "sendMessage"
|
|
742
|
+
}
|
|
743
|
+
},
|
|
744
|
+
{
|
|
745
|
+
label: "Edit a text message",
|
|
746
|
+
config: {
|
|
747
|
+
resource: "message",
|
|
748
|
+
operation: "editMessageText"
|
|
749
|
+
}
|
|
750
|
+
},
|
|
751
|
+
{
|
|
752
|
+
label: "Delete a chat message",
|
|
753
|
+
config: {
|
|
754
|
+
resource: "message",
|
|
755
|
+
operation: "deleteMessage"
|
|
756
|
+
}
|
|
757
|
+
},
|
|
758
|
+
{
|
|
759
|
+
label: "Pin a chat message",
|
|
760
|
+
config: {
|
|
761
|
+
resource: "message",
|
|
762
|
+
operation: "pinChatMessage"
|
|
763
|
+
}
|
|
764
|
+
},
|
|
765
|
+
{
|
|
766
|
+
label: "Unpin a chat message",
|
|
767
|
+
config: {
|
|
768
|
+
resource: "message",
|
|
769
|
+
operation: "unpinChatMessage"
|
|
770
|
+
}
|
|
771
|
+
},
|
|
772
|
+
{
|
|
773
|
+
label: "Send a photo",
|
|
774
|
+
config: {
|
|
775
|
+
resource: "message",
|
|
776
|
+
operation: "sendPhoto"
|
|
777
|
+
}
|
|
778
|
+
},
|
|
779
|
+
{
|
|
780
|
+
label: "Send a video",
|
|
781
|
+
config: {
|
|
782
|
+
resource: "message",
|
|
783
|
+
operation: "sendVideo"
|
|
784
|
+
}
|
|
785
|
+
},
|
|
786
|
+
{
|
|
787
|
+
label: "Send an audio file",
|
|
788
|
+
config: {
|
|
789
|
+
resource: "message",
|
|
790
|
+
operation: "sendAudio"
|
|
791
|
+
}
|
|
792
|
+
},
|
|
793
|
+
{
|
|
794
|
+
label: "Send a document",
|
|
795
|
+
config: {
|
|
796
|
+
resource: "message",
|
|
797
|
+
operation: "sendDocument"
|
|
798
|
+
}
|
|
799
|
+
},
|
|
800
|
+
{
|
|
801
|
+
label: "Send an animated file",
|
|
802
|
+
config: {
|
|
803
|
+
resource: "message",
|
|
804
|
+
operation: "sendAnimation"
|
|
805
|
+
}
|
|
806
|
+
},
|
|
807
|
+
{
|
|
808
|
+
label: "Send a sticker",
|
|
809
|
+
config: {
|
|
810
|
+
resource: "message",
|
|
811
|
+
operation: "sendSticker"
|
|
812
|
+
}
|
|
813
|
+
},
|
|
814
|
+
{
|
|
815
|
+
label: "Send a location",
|
|
816
|
+
config: {
|
|
817
|
+
resource: "message",
|
|
818
|
+
operation: "sendLocation"
|
|
819
|
+
}
|
|
820
|
+
},
|
|
821
|
+
{
|
|
822
|
+
label: "Send a media group",
|
|
823
|
+
config: {
|
|
824
|
+
resource: "message",
|
|
825
|
+
operation: "sendMediaGroup"
|
|
826
|
+
}
|
|
827
|
+
},
|
|
828
|
+
{
|
|
829
|
+
label: "Send a chat action",
|
|
830
|
+
config: {
|
|
831
|
+
resource: "message",
|
|
832
|
+
operation: "sendChatAction"
|
|
833
|
+
}
|
|
834
|
+
},
|
|
835
|
+
{
|
|
836
|
+
label: "Send a message and wait for response",
|
|
837
|
+
config: {
|
|
838
|
+
resource: "message",
|
|
839
|
+
operation: "sendAndWait"
|
|
840
|
+
}
|
|
841
|
+
},
|
|
842
|
+
{
|
|
843
|
+
label: "Get information about a chat",
|
|
844
|
+
config: {
|
|
845
|
+
resource: "chat",
|
|
846
|
+
operation: "get"
|
|
847
|
+
}
|
|
848
|
+
},
|
|
849
|
+
{
|
|
850
|
+
label: "Get the administrators of a chat",
|
|
851
|
+
config: {
|
|
852
|
+
resource: "chat",
|
|
853
|
+
operation: "administrators"
|
|
854
|
+
}
|
|
855
|
+
},
|
|
856
|
+
{
|
|
857
|
+
label: "Get a member of a chat",
|
|
858
|
+
config: {
|
|
859
|
+
resource: "chat",
|
|
860
|
+
operation: "member"
|
|
861
|
+
}
|
|
862
|
+
},
|
|
863
|
+
{
|
|
864
|
+
label: "Leave a chat",
|
|
865
|
+
config: {
|
|
866
|
+
resource: "chat",
|
|
867
|
+
operation: "leave"
|
|
868
|
+
}
|
|
869
|
+
},
|
|
870
|
+
{
|
|
871
|
+
label: "Set the title of a chat",
|
|
872
|
+
config: {
|
|
873
|
+
resource: "chat",
|
|
874
|
+
operation: "setTitle"
|
|
875
|
+
}
|
|
876
|
+
},
|
|
877
|
+
{
|
|
878
|
+
label: "Set the description of a chat",
|
|
879
|
+
config: {
|
|
880
|
+
resource: "chat",
|
|
881
|
+
operation: "setDescription"
|
|
882
|
+
}
|
|
883
|
+
},
|
|
884
|
+
{
|
|
885
|
+
label: "Answer a callback query",
|
|
886
|
+
config: {
|
|
887
|
+
resource: "callback",
|
|
888
|
+
operation: "answerQuery"
|
|
889
|
+
}
|
|
890
|
+
},
|
|
891
|
+
{
|
|
892
|
+
label: "Answer an inline query",
|
|
893
|
+
config: {
|
|
894
|
+
resource: "callback",
|
|
895
|
+
operation: "answerInlineQuery"
|
|
896
|
+
}
|
|
897
|
+
},
|
|
898
|
+
{
|
|
899
|
+
label: "Get a file",
|
|
900
|
+
config: {
|
|
901
|
+
resource: "file",
|
|
902
|
+
operation: "get"
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
],
|
|
906
|
+
icon: "Send",
|
|
907
|
+
iconUrl: TELEGRAM_ICON,
|
|
908
|
+
config: telegramConfig,
|
|
909
|
+
defaultConfig: {
|
|
910
|
+
resource: "message",
|
|
911
|
+
operation: "sendMessage",
|
|
912
|
+
chatId: "",
|
|
913
|
+
text: "",
|
|
914
|
+
replyMarkup: "none",
|
|
915
|
+
additionalFields: {},
|
|
916
|
+
timeoutMs: 3e4
|
|
917
|
+
},
|
|
918
|
+
credentialTypes: [TELEGRAM_CREDENTIAL],
|
|
919
|
+
ports: {
|
|
920
|
+
in: ["in"],
|
|
921
|
+
out: ["out"]
|
|
922
|
+
},
|
|
923
|
+
subtitle: (config) => typeof config.operation === "string" ? `${String(config.resource ?? "message")}: ${config.operation}` : void 0,
|
|
924
|
+
waitForm: waitFormOf,
|
|
925
|
+
async run({ config, input, credential, signal, resumeUrl }) {
|
|
926
|
+
const access = telegramAccess(credential);
|
|
927
|
+
const options = {
|
|
928
|
+
signal,
|
|
929
|
+
timeoutMs: config.timeoutMs
|
|
930
|
+
};
|
|
931
|
+
if (config.operation === "sendAndWait") {
|
|
932
|
+
if (!resumeUrl) throw new Error("This worker cannot ask for an answer. Set ZERODOT_BASE_URL on the worker");
|
|
933
|
+
const { method, body } = buildSendAndWait(config, resumeUrl);
|
|
934
|
+
await callTelegram(access, method, body, options);
|
|
935
|
+
return {
|
|
936
|
+
port: "out",
|
|
937
|
+
data: { data: { timedOut: true } },
|
|
938
|
+
waitUntil: waitDeadline(config)
|
|
939
|
+
};
|
|
940
|
+
}
|
|
941
|
+
const { method, body } = buildRequest(config);
|
|
942
|
+
if (config.binaryData && config.resource === "message" && method !== "sendMessage") {
|
|
943
|
+
const file = readBinary(input, config.binaryPropertyName);
|
|
944
|
+
const fileName = config.additionalFields.fileName || file.fileName;
|
|
945
|
+
if (!fileName) throw new Error(`A file name is needed to ${config.operation}. Set "fileName" in additionalFields, or set it in the binary data`);
|
|
946
|
+
const property = fileProperty(config.operation);
|
|
947
|
+
delete body[property];
|
|
948
|
+
return {
|
|
949
|
+
port: "out",
|
|
950
|
+
data: await callTelegram(access, method, uploadForm(body, property, {
|
|
951
|
+
...file,
|
|
952
|
+
fileName
|
|
953
|
+
}), options)
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
const answer = await callTelegram(access, method, body, options);
|
|
957
|
+
if (config.resource === "file" && config.download) {
|
|
958
|
+
const filePath = answer.result?.file_path;
|
|
959
|
+
if (!filePath) throw new Error("Telegram did not give a file path");
|
|
960
|
+
const bytes = await downloadTelegramFile(access, filePath, options);
|
|
961
|
+
const fileName = filePath.split("/").pop() ?? "file";
|
|
962
|
+
const mimeType = config.additionalFields.mimeType || mimeTypeOf(fileName);
|
|
963
|
+
return {
|
|
964
|
+
port: "out",
|
|
965
|
+
data: {
|
|
966
|
+
...answer,
|
|
967
|
+
binary: { data: toBinary(bytes, fileName, mimeType) }
|
|
968
|
+
}
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
return {
|
|
972
|
+
port: "out",
|
|
973
|
+
data: config.operation === "administrators" ? answer.result : answer
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
});
|
|
977
|
+
const triggerConfig = z.object({
|
|
978
|
+
updates: z.array(z.enum([
|
|
979
|
+
"*",
|
|
980
|
+
"message",
|
|
981
|
+
"edited_message",
|
|
982
|
+
"channel_post",
|
|
983
|
+
"edited_channel_post",
|
|
984
|
+
"callback_query",
|
|
985
|
+
"inline_query",
|
|
986
|
+
"poll",
|
|
987
|
+
"pre_checkout_query",
|
|
988
|
+
"shipping_query"
|
|
989
|
+
])).default(["message"]).meta({
|
|
990
|
+
title: "Trigger On",
|
|
991
|
+
labels: {
|
|
992
|
+
"*": "*",
|
|
993
|
+
message: "Message",
|
|
994
|
+
edited_message: "Edited Message",
|
|
995
|
+
channel_post: "Channel Post",
|
|
996
|
+
edited_channel_post: "Edited Channel Post",
|
|
997
|
+
callback_query: "Callback Query",
|
|
998
|
+
inline_query: "Inline Query",
|
|
999
|
+
poll: "Poll",
|
|
1000
|
+
pre_checkout_query: "Pre-Checkout Query",
|
|
1001
|
+
shipping_query: "Shipping Query"
|
|
1002
|
+
},
|
|
1003
|
+
hints: {
|
|
1004
|
+
"*": "All updates",
|
|
1005
|
+
message: "Trigger on new incoming message of any kind — text, photo, sticker, etc",
|
|
1006
|
+
edited_message: "Trigger on new version of a message that is known to the bot and was edited",
|
|
1007
|
+
channel_post: "Trigger on new incoming channel post of any kind — text, photo, sticker, etc",
|
|
1008
|
+
edited_channel_post: "Trigger on new version of a channel post that is known to the bot and was edited",
|
|
1009
|
+
callback_query: "Trigger on new incoming callback query",
|
|
1010
|
+
inline_query: "Trigger on new incoming inline query",
|
|
1011
|
+
poll: "Trigger on new state of a poll. Bots receive only updates about stopped polls and polls that the bot sent",
|
|
1012
|
+
pre_checkout_query: "Trigger on new incoming pre-checkout query. Contains full information about checkout",
|
|
1013
|
+
shipping_query: "Trigger on new incoming shipping query. Only for invoices with a flexible price"
|
|
1014
|
+
}
|
|
1015
|
+
}),
|
|
1016
|
+
additionalFields: z.object({
|
|
1017
|
+
chatIds: z.string().meta({ description: "Only these chats, as ids with commas between" }),
|
|
1018
|
+
userIds: z.string().meta({ description: "Only these users, as ids with commas between" }),
|
|
1019
|
+
download: z.boolean().meta({ description: "Download the image or file of the message as binary data" }),
|
|
1020
|
+
imageSize: z.enum([
|
|
1021
|
+
"small",
|
|
1022
|
+
"medium",
|
|
1023
|
+
"large",
|
|
1024
|
+
"extraLarge"
|
|
1025
|
+
]).meta({ description: "Telegram sends an image in several sizes. Default: large" })
|
|
1026
|
+
}).partial().default({})
|
|
1027
|
+
});
|
|
1028
|
+
/**
|
|
1029
|
+
* The secret that Telegram sends back in `x-telegram-bot-api-secret-token`.
|
|
1030
|
+
* Only characters A-Z, a-z, 0-9, _ and - are allowed, and it is at most 256 long.
|
|
1031
|
+
*/
|
|
1032
|
+
function telegramSecret(token) {
|
|
1033
|
+
return createHmac("sha256", token).update("zerodot-telegram-trigger").digest("base64url");
|
|
1034
|
+
}
|
|
1035
|
+
/** The last part of the webhook address is the token of the trigger. */
|
|
1036
|
+
const tokenOf = (url) => new URL(url).pathname.split("/").filter(Boolean).pop() ?? "";
|
|
1037
|
+
const ids = (list) => list ? list.split(",").map((id) => id.trim()) : void 0;
|
|
1038
|
+
/** Checks one request from Telegram before the run starts. */
|
|
1039
|
+
function checkTelegramUpdate(config, request) {
|
|
1040
|
+
const given = Buffer.from(request.headers["x-telegram-bot-api-secret-token"] ?? "");
|
|
1041
|
+
const wanted = Buffer.from(telegramSecret(request.token));
|
|
1042
|
+
if (given.byteLength !== wanted.byteLength || !timingSafeEqual(given, wanted)) return "forbidden";
|
|
1043
|
+
const parsed = triggerConfig.safeParse(config);
|
|
1044
|
+
const { chatIds, userIds } = parsed.success ? parsed.data.additionalFields : {};
|
|
1045
|
+
const body = request.body ?? {};
|
|
1046
|
+
const chats = ids(chatIds);
|
|
1047
|
+
if (chats && !chats.includes(String(body.message?.chat?.id))) return "ignore";
|
|
1048
|
+
const users = ids(userIds);
|
|
1049
|
+
if (users && !users.includes(String(body.message?.from?.id))) return "ignore";
|
|
1050
|
+
return "accept";
|
|
1051
|
+
}
|
|
1052
|
+
const IMAGE_SIZE = {
|
|
1053
|
+
small: 0,
|
|
1054
|
+
medium: 1,
|
|
1055
|
+
large: 2,
|
|
1056
|
+
extraLarge: 3
|
|
1057
|
+
};
|
|
1058
|
+
const FILE_KINDS = [
|
|
1059
|
+
"document",
|
|
1060
|
+
"video",
|
|
1061
|
+
"audio",
|
|
1062
|
+
"voice",
|
|
1063
|
+
"video_note",
|
|
1064
|
+
"sticker",
|
|
1065
|
+
"animation"
|
|
1066
|
+
];
|
|
1067
|
+
/** The file of a message: the photo in the wanted size, or the one other attachment. */
|
|
1068
|
+
function attachmentOf(update, size) {
|
|
1069
|
+
const message = Object.values(update ?? {}).find((value) => typeof value === "object" && value !== null && ("photo" in value || FILE_KINDS.some((k) => k in value)));
|
|
1070
|
+
if (!message) return null;
|
|
1071
|
+
const photos = message.photo;
|
|
1072
|
+
if (photos?.length) {
|
|
1073
|
+
const photo = photos[IMAGE_SIZE[size]] ?? photos[photos.length - 1];
|
|
1074
|
+
return photo ? {
|
|
1075
|
+
fileId: photo.file_id,
|
|
1076
|
+
mimeType: "image/jpeg"
|
|
1077
|
+
} : null;
|
|
1078
|
+
}
|
|
1079
|
+
for (const kind of FILE_KINDS) {
|
|
1080
|
+
const file = message[kind];
|
|
1081
|
+
if (file?.file_id) return {
|
|
1082
|
+
fileId: file.file_id,
|
|
1083
|
+
fileName: file.file_name,
|
|
1084
|
+
mimeType: file.mime_type
|
|
1085
|
+
};
|
|
1086
|
+
}
|
|
1087
|
+
return null;
|
|
1088
|
+
}
|
|
1089
|
+
/** Tells Telegram to send the updates to `url`. Telegram allows one webhook for each bot. */
|
|
1090
|
+
async function registerTelegramWebhook(access, input, options) {
|
|
1091
|
+
await callTelegram(access, "setWebhook", {
|
|
1092
|
+
url: input.url,
|
|
1093
|
+
allowed_updates: input.updates.includes("*") ? [] : input.updates,
|
|
1094
|
+
secret_token: telegramSecret(input.token),
|
|
1095
|
+
drop_pending_updates: true
|
|
1096
|
+
}, {
|
|
1097
|
+
signal: options.signal,
|
|
1098
|
+
timeoutMs: options.timeoutMs ?? 3e4
|
|
1099
|
+
});
|
|
1100
|
+
}
|
|
1101
|
+
async function removeTelegramWebhook(access, options) {
|
|
1102
|
+
await callTelegram(access, "deleteWebhook", {}, {
|
|
1103
|
+
signal: options.signal,
|
|
1104
|
+
timeoutMs: options.timeoutMs ?? 3e4
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
// src/index.ts
|
|
1108
|
+
const nodes = [defineNode({
|
|
1109
|
+
type: "trigger.telegram",
|
|
1110
|
+
label: "Telegram Trigger",
|
|
1111
|
+
description: "Start the workflow on a Telegram bot update",
|
|
1112
|
+
category: "trigger",
|
|
1113
|
+
app: "Telegram",
|
|
1114
|
+
icon: "Send",
|
|
1115
|
+
iconUrl: TELEGRAM_ICON,
|
|
1116
|
+
config: triggerConfig,
|
|
1117
|
+
defaultConfig: {
|
|
1118
|
+
updates: ["message"],
|
|
1119
|
+
additionalFields: {}
|
|
1120
|
+
},
|
|
1121
|
+
credentialTypes: [TELEGRAM_CREDENTIAL],
|
|
1122
|
+
ports: {
|
|
1123
|
+
in: [],
|
|
1124
|
+
out: ["out"]
|
|
1125
|
+
},
|
|
1126
|
+
subtitle: (config) => Array.isArray(config.updates) ? `Updates: ${config.updates.join(", ")}` : void 0,
|
|
1127
|
+
webhook: {
|
|
1128
|
+
async receive({ config, url, request }) {
|
|
1129
|
+
const verdict = checkTelegramUpdate(config, {
|
|
1130
|
+
token: tokenOf(url),
|
|
1131
|
+
headers: request.headers,
|
|
1132
|
+
body: request.body
|
|
1133
|
+
});
|
|
1134
|
+
if (verdict === "forbidden") return { verdict: "forbidden" };
|
|
1135
|
+
if (verdict === "ignore") return {
|
|
1136
|
+
verdict: "ignore",
|
|
1137
|
+
response: {
|
|
1138
|
+
status: 200,
|
|
1139
|
+
body: { ignored: true }
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
const { method, headers, query, body } = request;
|
|
1143
|
+
return {
|
|
1144
|
+
verdict: "accept",
|
|
1145
|
+
input: {
|
|
1146
|
+
method,
|
|
1147
|
+
headers,
|
|
1148
|
+
query,
|
|
1149
|
+
body
|
|
1150
|
+
}
|
|
1151
|
+
};
|
|
1152
|
+
},
|
|
1153
|
+
async activate({ config, credential, url, signal }) {
|
|
1154
|
+
await registerTelegramWebhook(telegramAccess(credential), {
|
|
1155
|
+
url,
|
|
1156
|
+
token: tokenOf(url),
|
|
1157
|
+
updates: Array.isArray(config.updates) ? config.updates.map(String) : ["message"]
|
|
1158
|
+
}, { signal });
|
|
1159
|
+
},
|
|
1160
|
+
async deactivate({ credential, signal }) {
|
|
1161
|
+
await removeTelegramWebhook(telegramAccess(credential), { signal });
|
|
1162
|
+
}
|
|
1163
|
+
},
|
|
1164
|
+
webhookTest: { hint: "Send a message to your bot" },
|
|
1165
|
+
async run({ config, input, credential, signal }) {
|
|
1166
|
+
const update = input && typeof input === "object" && "body" in input ? input.body : {};
|
|
1167
|
+
if (!config.additionalFields.download) return {
|
|
1168
|
+
port: "out",
|
|
1169
|
+
data: update
|
|
1170
|
+
};
|
|
1171
|
+
const file = attachmentOf(update, config.additionalFields.imageSize ?? "large");
|
|
1172
|
+
if (!file) return {
|
|
1173
|
+
port: "out",
|
|
1174
|
+
data: update
|
|
1175
|
+
};
|
|
1176
|
+
const access = telegramAccess(credential);
|
|
1177
|
+
const options = {
|
|
1178
|
+
signal,
|
|
1179
|
+
timeoutMs: 3e4
|
|
1180
|
+
};
|
|
1181
|
+
const filePath = (await callTelegram(access, "getFile", { file_id: file.fileId }, options)).result?.file_path;
|
|
1182
|
+
if (!filePath) throw new Error("Telegram did not give a file path");
|
|
1183
|
+
const bytes = await downloadTelegramFile(access, filePath, options);
|
|
1184
|
+
const fileName = file.fileName ?? filePath.split("/").pop() ?? "file";
|
|
1185
|
+
return {
|
|
1186
|
+
port: "out",
|
|
1187
|
+
data: {
|
|
1188
|
+
...update,
|
|
1189
|
+
binary: { data: toBinary(bytes, fileName, file.mimeType) }
|
|
1190
|
+
}
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
}), node_default];
|
|
1194
|
+
const credentialTypes = [telegramCredential];
|
|
1195
|
+
export { credentialTypes, nodes };
|