Transport for the Telegram Bot API: JSON and multipart requests, the response envelope, and file downloads.
Per-call credentials. Every API-calling function in this package
takes an optional trailing opts Map, resolved by resolve: opts
first, then the telegram.bot.token context variable. Nothing from
opts is written to ctx, so one run can act as many bots and parallel
flows don't share credentials. A bot-token from opts is masked in
call records, and marked before the URL is built because it goes in the
URL path. A bot-token present but blank or null is an error, never a
fallback to telegram.bot.token.
bot-token: the bot token for this call
Context Vars
telegram.bot.token
Values
MEDIA_FILE_KEYS
MEDIA_FILE_KEYS: Vec [
"media",
"thumbnail",
"cover"
]
Functions
clean-body
fn (body: Map): Map
untype a request body and drop its top-level nulls, so unset or
explicitly-null optional parameters are never sent. Exposed for testing.
Example
::telegram::api/clean-body({chat_id: 123, text: null}) // {chat_id: 123}
download
fn (file-path: Str): Bytes
fn (file-path: Str, bot-token: Str): Bytes
fn (file-path: Str, opts: Map): Bytes
Download a file by its file_path (from ::telegram::files/get-file)
and return its Bytes. Bots can download files up to 20 MB. Prefer
::telegram::files/download-file, which takes a file_id.
Example
::api ::telegram::api
file ::telegram::files/get-file("AgACAgIAAxkBAAIB")
content ::api/download(file.file_path)
length(content)
// As another bot
other ::api/download(file.file_path, {bot-token: ::hot::ctx/get("tenant_b.telegram.token")})
telegram.bot.token
field-text
fn (value: Any): Str
A multipart field's text: Str as-is, Map/Vec as JSON (the Bot API's "JSON-serialized" parameters), anything else interpolated. Exposed for testing.
Example
::telegram::api/field-text("hello") // "hello"
::telegram::api/field-text([1, 2]) // "[1,2]"
::telegram::api/field-text(true) // "true"
file-url
fn (file-path: Str, bot-token: Str): Str
https://api.telegram.org/file/bot<token>/<file_path> for a file_path
from getFile. Contains the token: never log or share it. Exposed for
testing.
Example
::telegram::api/file-url("photos/file 12.jpg", "test-token") // "https://api.telegram.org/file/bottest-token/photos/file%2012.jpg"
input-file
fn (content: Bytes, filename: Str): InputFile
fn (content: Bytes, filename: Str, mime-type: Str): InputFile
Wrap bytes as an InputFile for upload.
Example
::api ::telegram::api
::messages ::telegram::messages
report ::api/input-file(::hot::file/read-file-bytes("report.pdf"), "report.pdf", "application/pdf")
::messages/send-document(::messages/SendDocumentRequest({chat_id: 123456789, document: report}))
is-input-file
fn (value: Any): Bool
True for an InputFile (or its untyped Map form: a Map whose content
is Bytes). Exposed for testing.
Example
::telegram::api/is-input-file(::telegram::api/input-file(Bytes("hi"), "hi.txt")) // true
::telegram::api/is-input-file("AgACAgIAAxkBAAIB") // false
method-url
fn (method: Str, bot-token: Str): Str
https://api.telegram.org/bot<token>/<method>. The token is a secret:
never log this URL. Exposed for testing.
Example
::telegram::api/method-url("getMe", "test-token") // "https://api.telegram.org/bottest-token/getMe"
multipart-body
fn (upload: Map, boundary: Str): Bytes
Encode a prepared upload (prepare-upload) as a multipart/form-data
body. Built as Bytes with concat, so binary file content is never
passed through a string. Exposed for testing.
Example
::api ::telegram::api
upload ::api/prepare-upload({chat_id: 123})
body ::api/multipart-body(upload, "BOUNDARY")
starts-with(::hot::bytes/to-str(body), "--BOUNDARY") // true
parse-response
fn (response: Result): Any
Unwrap a Bot API response envelope: result when ok is true;
err(TelegramError) when Telegram answered ok: false (whatever the
HTTP status, typically 400/403/429); err(HttpError) for anything
else (a non-JSON proxy error, a 5xx without an envelope). Exposed for
testing.
Example
::api ::telegram::api
::api/parse-response(::hot::http/HttpResponse({status: 200, headers: {}, body: {ok: true, result: {id: 1}}})) // {id: 1}
limited ::api/parse-response(::hot::http/HttpResponse({status: 429, headers: {}, body: {
ok: false,
error_code: 429,
description: "Too Many Requests",
parameters: {retry_after: 5}
}}))
if-err(limited, (e) { e.retry_after }) // 5
prepare-upload
fn (body: Map): Map
Split a request body into JSON-able fields and the files to upload.
Top-level InputFile values become file parts named after their field;
InputFile values inside InputMedia objects (media: [...] in
sendMediaGroup, media: {...} in editMessageMedia) become parts named
<field><index>_<key> and are referenced as attach://<name>, per the
Bot API. Exposed for testing.
Example
::api ::telegram::api
upload ::api/prepare-upload({chat_id: 123, document: ::api/input-file(Bytes("hi"), "hi.txt")})
upload.fields // {chat_id: 123}
first(upload.files).name // "document"
request
fn (method: Str): Any
fn (method: Str, body: Map): Any
fn (method: Str, body: Map, bot-token: Str): Any
fn (method: Str, body: Map, opts: Map): Any
Call a Telegram Bot API method. The bot token comes from per-call opts (see resolve), the telegram.bot.token context variable, or a token passed as the 3rd argument, and is placed in the URL path per Telegram's convention.
Bodies are sent as JSON, or as multipart/form-data when they carry an InputFile (see input-file). Unset and null top-level fields are omitted; a call with no parameters is a GET.
Returns the result field of the response envelope ({ok: true, result: ...}). An ok: false answer returns err(TelegramError) with error_code, description, and retry_after; other failures return err(HttpError).
Example
::api ::telegram::api
// GET method (no body)
me ::api/request("getMe")
// POST method with JSON body
sent ::api/request("sendMessage", {chat_id: 123456, text: "Hello"})
// As another bot
other ::api/request("getMe", {}, {bot-token: "123456:tenant-b-token"})
telegram.bot.token
resolve
fn (opts: Map): Map
The bot token for one call (see resolve-from). A bot-token from
opts is masked in call records with ::hot::ctx/mark-secret, before
any URL holds it, and opts values are never written to ctx.
Example
::telegram::api/resolve({bot-token: "123456:tenant-b-token"}).bot-token
telegram.bot.token
resolve-from
fn (opts: Map, ctx-values: Map): Map
The one resolver, pure: {bot-token} for a call from opts first, then
ctx-values (a Map of context variables). An Err when no token is set,
or when bot-token is in opts but blank or null (that never falls
back to context). Exposed for testing; resolve feeds it the context.
Example
::telegram::api/resolve-from({}, {"telegram.bot.token": "test-token"}) // {bot-token: "test-token"}
is-err(::telegram::api/resolve-from({bot-token: ""}, {"telegram.bot.token": "test-token"})) // true
Types
HttpError
HttpError type {
status: Int,
headers: Map,
body: Any
}
InputFile
InputFile type {
content: Bytes,
filename: Str,
mime-type: Str?
}
A file to upload with multipart/form-data. Pass one anywhere the Bot API
accepts InputFile (photo, document, audio, video, voice,
thumbnail, an InputMedia's media); a Str there is still sent as a
file_id or URL. Build one with input-file.
TelegramError
TelegramError type {
ok: Bool,
status: Int?,
error_code: Int?,
description: Str?,
retry_after: Int?,
migrate_to_chat_id: Int?,
parameters: Map?
}
A Bot API error: the {ok: false, error_code, description, parameters}
envelope Telegram answers with (usually alongside HTTP 4xx). status
is the HTTP status. retry_after (seconds to wait, on 429 flood
control) and migrate_to_chat_id (a group upgraded to a supergroup)
are lifted out of parameters.
Example
sent ::telegram::messages/send-message(::telegram::messages/SendMessageRequest({chat_id: 123, text: "hi"}))
if-err(sent, (e) {
cond {
is-some(e.retry_after) => { println(`flood control: retry in ${e.retry_after}s`) }
=> { println(`telegram error ${e.error_code}: ${e.description}`) }
}
})