# Telegram

A Telegram bot, from the back end, over the Bot API: messages with inline
and reply keyboards, pictures, documents and other files sent by their id,
by an address or as bytes, messages edited and deleted, buttons answered,
files fetched; and what Telegram has for the bot, by a webhook checked by
its secret token or by long polling in a job, each update done once. An
[extension](../extensions/README.md): ordinary Mote in
`extensions/telegram/`. Back to the [map](README.md).

```mote
use "pkg:telegram/updates.mote"

// /start: a welcome, with two buttons.
fn telegramCommand(command: string, args: string, m: TelegramMessage): bool
  if command != "start" return false
  telegramSend(m.chat.id, `Welcome, ${telegramEscape(m.from.name)}.`, {parse: "HTML", keyboard: telegramInline([[telegramButton("Lamps", "show:lamps"), telegramButton("Chairs", "show:chairs")]])}, "")?
  return true

// A button pressed: the list, and a notice at the top of the chat.
fn telegramPressed(c: TelegramCallback): string
  if c.data == "show:lamps" && c.message != none
    telegramEdit(c.message?.chat.id ?? 0, c.message?.id ?? 0, "Lamps: the Arc, the Dome.", {}, "")?
  return "Shown"

// Anything else said to the bot.
fn telegramMessage(m: TelegramMessage): bool
  telegramSend(m.chat.id, "Say /start to begin.", {reply: m.id}, "")?
  return true
```

```toml
[packages]
telegram = "../mote/extensions/telegram"
```

```sh
TELEGRAM_TOKEN=123456:AA… TELEGRAM_WEBHOOK_SECRET=… bun dist/server/main.js   # a webhook
TELEGRAM_TOKEN=123456:AA… TELEGRAM_POLL=on bun dist/server/main.js           # long polling
```

**Not met Telegram.** Written from the Bot API's documentation (Bot API 9,
as of 2026: `reply_parameters` and `link_preview_options` in place of the
older `reply_to_message_id` and `disable_web_page_preview`), and run
against a stand-in that answers as it does, holds a long poll until an
update comes, and reads files sent as parts (`tests/svc_standin.mjs code`).
The steps with a real bot are [below](#checking-it-against-telegram).

## The settings

| | |
|---|---|
| `TELEGRAM_TOKEN` | The bot's token from @BotFather, a secret, read by the default `fn telegramToken()`. It is a part of every address of the Bot API, so no address is logged. Every call takes a `token` last: `""` for this one, or another bot's. |
| `TELEGRAM_WEBHOOK_SECRET` | With the webhook: what Telegram sends as `X-Telegram-Bot-Api-Secret-Token` (1 to 256 of `A-Z a-z 0-9 _ -`). Give the same to `telegramSetWebhook`. |
| `TELEGRAM_POLL` | `on`: long polling, for a bot with no public address (one back end only, and no webhook set). |
| `TELEGRAM_API` | Another address: a local Bot API server, or a stand-in. |
| `TELEGRAM_WAIT` | The longest wait a 429 may ask for, in seconds (30 unsaid). |

## The calls

| | |
|---|---|
| `telegramSend(chat, text, o, token)` | A message (cut at 4096): `TelegramMessage {id, chat, from, date, text, thread, replyTo, files, raw}`. |
| `telegramSendFile(chat, kind, f, caption, o, token)` | `kind` `"photo"`, `"document"`, `"audio"`, `"video"`, `"voice"`, `"animation"`, `"sticker"`; `f` is `{id}` (a file Telegram has: `m.files[0].id`), `{address}`, or `{data, name, type}` (sent as parts). `telegramPhoto(chat, f, caption, token)` and `telegramDocument` for the two most used. |
| `telegramEdit(chat, message, text, o, token)` · `telegramEditKeyboard(chat, message, keyboard, token)` · `telegramDelete(chat, message, token)` | |
| `telegramAnswer(callback, text, alert, token)` | A press answered (the updates do it for you after `telegramPressed`). |
| `telegramDoing(chat, action, token)` | "typing…" and the like. |
| `telegramFile(id, token)` · `telegramDownload(id, token)` | Where a file is kept (20 MB at most through the Bot API); its bytes. |
| `telegramMe(token)` · `telegramCommands(commands, token)` | The bot; its menu of commands (`[{command, description}]`). |
| `telegramSetWebhook(address, secretToken, allowed, drop, token)` · `telegramDeleteWebhook(drop, token)` · `telegramWebhookInfo(token)` | |
| `telegramCall(method, params, wait, token)` | Any other method: its `result`. |

`o` (`TelegramOut`), each optional: `parse` (`"HTML"` or `"MarkdownV2"`;
`telegramEscape(text)` for words inside HTML), `keyboard`, `reply` (the
message it answers), `thread` (a forum's topic), `silent`, `noPreview`,
`protect`.

Keyboards: `telegramInline([[telegramButton("Yes", "pick:yes"),
telegramLinkButton("Site", "https://…")]])` under the message;
`telegramKeyboard([["Lamps", "Chairs"]], once)` in place of the person's
own; `telegramNoKeyboard()`; `telegramForceReply(placeholder)`. A button's
`data` is 64 bytes at most.

| Kind | |
|---|---|
| `"auth"` (401), `"refused"` (403: blocked, put out), `"missing"` (400 "… not found"), `"invalid"` (400: `data.migrateTo` when a group became a supergroup), `"conflict"` (409: a webhook and getUpdates, or two pollers), `"limited"` (`data.retryAfter`), `"telegram"` (5xx), `"offline"` | The sentence is Telegram's description (`Telegram: Bad Request: chat not found`). |

**Limits.** A 429 says `parameters.retry_after`: waited out and asked once
more when it is within `TELEGRAM_WAIT`, else a failure. Telegram's own
limits (about 30 messages a second in all, one a second in a chat, twenty a
minute in a group) are not paced ahead: a bot that sends to many chats at
once sends from a job, a few at a time.

## Updates

`use "pkg:telegram/updates.mote"`: by `POST /telegram/webhook` (the secret
token compared in constant time, first: [`webhook.check`](back-end.md#webhooks)'s `"telegram"`) or by long polling (`job fn
telegramPoll`: `getUpdates` with a 25-second wait, the next update id kept
in `TelegramOffset` so a restart goes on from there, asked again at once).
Each update is kept once by its `update_id` (`TelegramUpdateSeen`, a week)
and handed to `job fn telegramDeliver`, which calls, each optional:

| | |
|---|---|
| `fn telegramCommand(command, args, m): bool` | A message that begins with `/command` (its `@botname` left off): true when it was the program's; false (unsaid) and `telegramMessage` is told. |
| `fn telegramMessage(m: TelegramMessage): bool` | A message, an edited one, a channel's post. Its files are in `m.files` (the largest size of a photo). |
| `fn telegramPressed(c: TelegramCallback): string` | An inline button pressed (`c.data`, `c.message`): the notice to show, `""` for none. The press is answered after. |
| `fn telegramUpdate(u: json): bool` | Every update as Telegram sent it, after the above. |

## Left out

Inline mode (`inline_query`), payments and Stars, games, Web Apps' data
check (`initData`'s HMAC), business connections, stories, polls, media
groups (`sendMediaGroup`: `telegramCall` does it), the local Bot API
server's files over 20 MB, MTProto (a user account, not a bot).

## Checking it against Telegram

1. A bot from @BotFather: `TELEGRAM_TOKEN`. `telegramMe` gives its name.
2. Long polling: `TELEGRAM_POLL=on` with no webhook set; send the bot
   `/start` and a message and a photo; each hook is told once, a restart
   in between tells nothing twice.
3. The webhook: `telegramSetWebhook("https://<site>/telegram/webhook",
   <the secret>, [], true, "")`, `TELEGRAM_WEBHOOK_SECRET` the same, polling
   off; the same three. `telegramWebhookInfo` shows no last error.
4. A photo as bytes, then sent again by `m.files[0].id`; a document
   downloaded with `telegramDownload`.
5. A button pressed: the spinner stops and the notice shows.

Recorded in `tests/expect/real_svc_code.txt` (`tests/all.sh
real_svc_code`).
