Telegram bot¶
This tutorial deploys a Telegram bot that keeps notes and reminders for each chat and sends alerts when the Central Bank of Uzbekistan changes its exchange rates. It is written for developers who want to see how a webhook-driven, stateful service fits a runtime that keeps no state between requests.
Deno
What you build¶
A bot that answers these commands:
| Command | What it does |
|---|---|
/note → text |
Saves a note. /note buy milk saves at once |
/notes, /delnote <id> |
Lists the last 10 notes, deletes one |
/remind → text → time → yes/no |
Sets a reminder. /remind 2h 30m call mom skips the dialog |
/reminders, /unremind <id> |
Lists pending reminders, cancels one |
/rates |
Current rates, fetched from the cbu-rates service |
/subscribe, /unsubscribe |
Turns rate change alerts on or off |
/cancel |
Ends the current dialog (any other command ends it too) |
Times such as 10m, in 2 hours, 18:30, tomorrow 9:00 or 31.12.2026 23:00 are read in one fixed UTC offset,
BOT_TZ_OFFSET_MINUTES (default 300, Tashkent).
Why it fits the runtime. A webhook bot is a stream of short HTTP requests, one per Telegram update, so it needs
no long-running process. By default each request runs in a fresh isolate (a reused one is only a cache), so the
dialog state lives in std:kv and the data in std:sql. Reminders are delayed queue messages to the bot itself, so there is no cron daemon to run. Retries, backoff
and the dead-letter queue come with the queue trigger, and the bot token stays in a write-only secret.
Architecture¶
flowchart LR
TG["Telegram Bot API"] -- "POST /webhook" --> BOT["telegram-bot (Deno, Form B)"]
BOT -- "sendMessage" --> TG
BOT --- KV[("std:kv: dialog state")]
BOT --- SQL[("std:sql: notes, reminders, subscribers")]
BOT -- "enqueue (delayed)" --> Q[["telegram-bot queue"]]
Q -- "queue()" --> BOT
BOT -- "call GET /latest" --> CBU["cbu-rates"]
CBU -- "enqueue cbu.rate_changed" --> Q
- Telegram posts each update to
POST /webhookwith a secret header. The bot checks it in constant time. - The bot claims the
update_idin SQL, so a re-delivered update is answered200without doing anything. - It loads the chat's dialog state from KV, runs a pure state machine, applies the resulting effect (a note, a reminder, a subscription) and replies through the Bot API.
- A reminder is a queue message to the bot itself, delayed until the reminder is due.
cbu-ratesenqueues acbu.rate_changedmessage when a rate moves. The bot fans it out as onesendmessage per subscriber.
Prerequisites¶
- A running node and a tenant key in
RT_KEY(see First run). A key created with the default scopes works; the scripts needservices:read,services:write,deploy,env:write,secrets:write, andqueue:writefor the smoke test. 21ci(see Install), orbash,curlandjqforsample/scripts/*.sh.- A bot token from @BotFather.
- A public
https://URL for the node's invoke listener. Telegram only callshttps://URLs on ports 443, 80, 88 or 8443, so put the public listener (:8080) behind a TLS proxy, or map a custom domain to the service.
The bot reads these settings:
| Name | Kind | Meaning |
|---|---|---|
TELEGRAM_BOT_TOKEN |
secret | Bot API token from BotFather |
TELEGRAM_WEBHOOK_SECRET |
secret | 16-256 characters of A-Za-z0-9_-; Telegram sends it back in X-Telegram-Bot-Api-Secret-Token |
ADMIN_TOKEN |
secret | Bearer token for /setup, /status and /admin/outbox (at least 16 characters; not a tenant key, since the platform removes Authorization: Bearer rtk_…) |
PUBLIC_URL |
env | Public base URL of the service; the webhook is PUBLIC_URL/webhook |
BOT_TZ_OFFSET_MINUTES |
env | Users' UTC offset in minutes (default 300) |
RATES_SERVICE |
env | Slug of the rates service (default cbu-rates) |
TELEGRAM_DRY_RUN |
env | 1 records Bot API calls in an outbox table instead of sending them |
SELF_SLUG |
env | Own slug for self-enqueues, a fallback for older nodes that leave ctx.service.slug empty |
Deploy it¶
1. Push the code and set the secrets¶
The source is the src/ directory. Without an rt.json, the CLI and deploy.sh bundle every source file and pick
main.ts as the entry.
cd sample/apps/telegram-bot
21ci push src --service telegram-bot --create --wait
printf %s "$BOT_TOKEN" | 21ci secret set telegram-bot TELEGRAM_BOT_TOKEN
SECRET=$(openssl rand -hex 24)
printf %s "$SECRET" | 21ci secret set telegram-bot TELEGRAM_WEBHOOK_SECRET
ADMIN=$(openssl rand -hex 24)
printf %s "$ADMIN" | 21ci secret set telegram-bot ADMIN_TOKEN
21ci env set telegram-bot PUBLIC_URL=https://fn.example.com/s/telegram-bot BOT_TZ_OFFSET_MINUTES=300
cd sample/apps/telegram-bot
RT_COMPILE=eager ../../scripts/deploy.sh src telegram-bot # create if missing, upload, activate
SVC=$(../../scripts/svc-id.sh telegram-bot)
put_secret() { # NAME VALUE
jq -nc --arg v "$2" '{value: $v}' | curl -sS -X PUT -H "Authorization: Bearer $RT_KEY" \
-H 'Content-Type: application/json' --data-binary @- "$RT_API/v1/services/$SVC/secrets/$1"
}
SECRET=$(openssl rand -hex 24)
ADMIN=$(openssl rand -hex 24)
put_secret TELEGRAM_BOT_TOKEN "$BOT_TOKEN"
put_secret TELEGRAM_WEBHOOK_SECRET "$SECRET"
put_secret ADMIN_TOKEN "$ADMIN"
# PUT replaces the whole env map
curl -sS -X PUT -H "Authorization: Bearer $RT_KEY" -H 'Content-Type: application/json' \
-d '{"PUBLIC_URL": "https://fn.example.com/s/telegram-bot", "BOT_TZ_OFFSET_MINUTES": "300"}' \
"$RT_API/v1/services/$SVC/env"
Keep $ADMIN and $SECRET: you need them for the admin routes and for testing the webhook by hand, and secrets are
write-only, so you cannot read them back later. Secrets and env changes apply to the next task, so there is no
redeploy.
2. Register the webhook¶
POST /setup calls the Bot API's getMe, setWebhook (with your secret token and allowed_updates: ["message"])
and setMyCommands. GET /status shows Telegram's getWebhookInfo plus counters.
B=https://fn.example.com/s/telegram-bot
curl -sS -X POST -H "Authorization: Bearer $ADMIN" $B/setup
curl -sS -H "Authorization: Bearer $ADMIN" $B/status
/setup takes an optional body {"url": "https://…", "dropPendingUpdates": true} when the webhook URL is not
PUBLIC_URL/webhook. Open the bot in Telegram and send /help.
3. Connect the rates service (optional)¶
Deploy cbu-rates in the same tenant, project and environment, then point it at the bot:
/rates calls the service named by RATES_SERVICE (default cbu-rates). Calls and enqueues between services are
admitted by the target's environment and caller list, see Calls and queues.
Try it without Telegram¶
With TELEGRAM_DRY_RUN=1 the bot records Bot API calls in an outbox table instead of sending them, so you can post
updates yourself and read what the bot would have answered. Turn it on with
21ci env set telegram-bot TELEGRAM_DRY_RUN=1 (with curl, add "TELEGRAM_DRY_RUN": "1" to the env map: PUT
replaces the whole map), then:
B=http://127.0.0.1:8080/s/telegram-bot
curl -sS -X POST $B/webhook -H "X-Telegram-Bot-Api-Secret-Token: $SECRET" -H 'Content-Type: application/json' \
-d '{"update_id": 1001, "message": {"message_id": 1, "date": 0, "chat": {"id": 42, "type": "private"}, "text": "/note buy milk"}}'
curl -sS "$B/admin/outbox?chat_id=42" -H "Authorization: Bearer $ADMIN"
How the code works¶
The service has four source files: main.ts (handlers and I/O), bot.ts (the conversation logic, pure functions),
telegram.ts (update parsing and a small Bot API client) and http.ts (JSON and auth helpers). Only main.ts
imports std:* modules, so the other files run under node --test as they are.
One module, two triggers¶
The default export is an object (Form B). fetch handles HTTP; queue receives batches of queue messages. There is
no scheduled: reminders do not need a schedule.
webhook = { error: e instanceof TelegramError ? e.message : "telegram unreachable" };
}
return json({ dryRun: cfg.dryRun, counts, webhook });
}
async function handleOutbox(url: URL): Promise<Response> {
await ensureSchema();
// … the other routes …
});
}
const admin = ["/setup", "/status", "/admin/outbox"].includes(path);
if (!admin) return error(404, "not_found", "no such route");
const denied = await requireAdmin(req, cfg.adminToken);
if (denied) return denied;
if (path === "/setup" && req.method === "POST") return await handleSetup(req, cfg);
if (path === "/status" && req.method === "GET") return await handleStatus(cfg);
if (path === "/admin/outbox" && req.method === "GET") return await handleOutbox(url);
return error(405, "method_not_allowed", `${req.method} is not allowed here`);
} catch (e) {
console.error(errorText(e));
return error(500, "internal", "internal error");
}
},
async queue(batch: { messages: QueueMessage[] }, ctx: Ctx): Promise<void> {
const cfg = config();
if (!cfg.botToken && !cfg.dryRun) {
// Not configured yet: keep the messages (they reach the DLQ after queue.max_attempts).
console.warn("TELEGRAM_BOT_TOKEN is not set; delaying queue messages");
for (const m of batch.messages) m.retry({ delaySeconds: 300 });
return;
}
await ensureSchema();
const outbox: OutboxEntry[] = [];
const bot = botFor(cfg, outbox);
A message the handler does not retry() is acknowledged when the handler returns. m.retry() without options uses
the runtime backoff and moves the message to the dead-letter queue after queue.max_attempts. A Telegram 429
carries retry_after, which becomes retry({delaySeconds}).
The webhook: authenticate, then claim the update¶
const now = Date.now();
await sql.batch([
...outbox.map((o) => ({ sql: "INSERT INTO outbox (at, method, params) VALUES (?, ?, ?)", args: [now, o.method, JSON.stringify(o.params)] })),
"DELETE FROM outbox WHERE id <= (SELECT MAX(id) - 200 FROM outbox)",
], "write");
}
// ---------------------------------------------------------------------------------- webhook
async function handleWebhook(req: Request, cfg: Config, ctx: Ctx): Promise<Response> {
if (!isValidSecretToken(cfg.webhookSecret) || (!cfg.botToken && !cfg.dryRun)) {
return error(503, "not_configured", "the bot is not configured");
}
const given = req.headers.get("x-telegram-bot-api-secret-token") ?? "";
if (!(await safeEqual(given, cfg.webhookSecret))) return error(401, "unauthorized", "bad secret token");
const body = await readJson(req, MAX_UPDATE_BYTES);
if (!body.ok) return body.response;
const update = parseUpdate(body.value);
if (!update) return error(400, "invalid_update", "not a Telegram update");
await ensureSchema();
const now = Date.now();
// Telegram re-delivers an update until it gets a 2xx. Claim the id atomically; a second
// delivery finds it and is answered 200 without doing anything.
const claim = await sql.execute(
"INSERT OR IGNORE INTO updates (update_id, received_at) VALUES (?, ?)",
[update.updateId, now],
) as SqlResult;
if (claim.rowsAffected === 0) return json({ ok: true, duplicate: true });
const outbox: OutboxEntry[] = [];
try {
if (update.message?.text != null) await converse(update.message, update.updateId, botFor(cfg, outbox), cfg, ctx, now);
if (update.updateId % 100 === 0) await sql.execute("DELETE FROM updates WHERE received_at < ?", [now - 3 * DAY_MS]);
} catch (e) {
// Release the claim and answer 5xx, so Telegram's retry processes the update again. Effects
safeEqualhashes both strings with SHA-256 and compares every byte, so the comparison time depends on neither the content nor the length of the secret.- Telegram re-delivers an update until it gets a
2xx.INSERT OR IGNOREon theupdate_idprimary key is an atomic claim: a second delivery seesrowsAffected === 0and is answered200 {duplicate: true}. - If anything fails, the handler deletes the claim and answers
500, so Telegram's retry processes the update again. Notes and reminders are keyed by(chat_id, source_update), which makes the retry safe.
Dialog state in KV¶
Each chat has at most one dialog in progress, stored under fsm/<chat id> with a one-hour TTL, so an abandoned
dialog expires on its own:
// A structured record: `21ci logs` shows the fields, `--json` prints them as they are.
log.with({ updateId: update.updateId }).error("update failed", { error: errorText(e) });
await sql.execute("DELETE FROM updates WHERE update_id = ?", [update.updateId]).catch(() => {});
return error(500, "temporary_failure", "try again later");
} finally {
await saveOutbox(outbox).catch((e) => console.warn("outbox:", errorText(e)));
}
return json({ ok: true });
}
// One dialog step per chat at a time: a message that arrives while the chat's previous step runs
// waits for it (std:lock), so both steps read and save the state in order. A wait past 5 s is a 5xx,
// and Telegram retries the update.
async function converse(msg: IncomingMessage, updateId: number, bot: BotApi, cfg: Config, ctx: Ctx, now: number) {
await lock(`fsm/${msg.chatId}`, () => advance(msg, updateId, bot, cfg, ctx, now), { waitMs: 5000, leaseMs: 30000 });
}
async function advance(msg: IncomingMessage, updateId: number, bot: BotApi, cfg: Config, ctx: Ctx, now: number) {
const fsmKey = `fsm/${msg.chatId}`;
kv.getMany reads the state and the bot's username in one call. The new state is written only after the reply was
sent: when sendMessage fails, the update is retried and replays the same transition.
A pure state machine¶
transition takes the current state, the message text and the environment (time, offset, chat type) and returns
the next state plus either a reply or an effect. It does no I/O, so every dialog path is a unit test:
// Idle is "no state" (null). Every other state is one step of a dialog.
export type State =
| { step: "note_text" }
| { step: "remind_text" }
| { step: "remind_when"; text: string }
| { step: "remind_confirm"; text: string; dueAt: number };
export type Effect =
| { kind: "save_note"; text: string }
| { kind: "list_notes" }
| { kind: "delete_note"; id: number }
| { kind: "create_reminder"; text: string; dueAt: number }
| { kind: "list_reminders" }
| { kind: "cancel_reminder"; id: number }
| { kind: "subscribe" }
| { kind: "unsubscribe" }
| { kind: "rates" };
export interface Step {
state: State | null; // the next state; null = idle
reply?: string; // plain text to send (no parse_mode, so nothing needs escaping)
effect?: Effect; // run by the handler; its result becomes the reply
}
export function transition(state: State | null, rawText: string, env: Env): Step {
const text = rawText.trim();
const cmd = parseCommand(text, env.botUsername);
if (cmd === "foreign") return { state }; // not for us: keep the dialog as it is, say nothing
if (cmd) return onCommand(state, cmd, env);
if (state === null) return env.privateChat ? { state: null, reply: HINT } : { state: null };
switch (state.step) {
case "note_text":
return saveNote(text, state);
case "remind_text": {
if (!text) return { state, reply: "What should I remind you about?" };
if (text.length > MAX_REMINDER_CHARS) {
return { state, reply: `That is too long (max ${MAX_REMINDER_CHARS} characters). Try a shorter text.` };
}
return { state: { step: "remind_when", text }, reply: whenPrompt(env.tzOffsetMin) };
}
case "remind_when": {
const when = parseWhen(text, env.now, env.tzOffsetMin);
if (!when.ok) return { state, reply: `${when.error} ${whenPrompt(env.tzOffsetMin)}` };
const range = checkRange(when.at, env.now);
if (range) return { state, reply: range };
return {
state: { step: "remind_confirm", text: state.text, dueAt: when.at },
reply: `Remind you on ${formatLocal(when.at, env.tzOffsetMin)} (${formatIn(when.at - env.now)}):\n` +
`"${state.text}"\nReply yes or no.`,
};
}
case "remind_confirm": {
const answer = text.toLowerCase();
if (YES.has(answer)) {
// The time may have passed while the user was thinking.
if (state.dueAt - env.now < MIN_REMIND_AHEAD_MS / 2) {
return { state: { step: "remind_when", text: state.text }, reply: `That time has passed. ${whenPrompt(env.tzOffsetMin)}` };
}
return { state: null, effect: { kind: "create_reminder", text: state.text, dueAt: state.dueAt } };
}
if (NO.has(answer)) return { state: null, reply: "OK, not saved." };
return { state, reply: "Please answer yes or no (or /cancel)." };
}
}
}
isState validates whatever comes back from KV before it is used, because a stored state may come from an older
version of the bot.
Reminders are delayed messages to yourself¶
Creating a reminder stores a row and enqueues a message to the bot's own queue, delayed until the reminder is due:
}
case "list_notes": {
const r = await sql.execute(
"SELECT id, text, created_at FROM notes WHERE chat_id = ? ORDER BY id DESC LIMIT 10",
[chatId],
) as SqlResult;
const notes = objects(r);
if (notes.length === 0) return "No notes yet. Send /note to add one.";
return ["Your latest notes:", ...notes.map((n) => `#${n.id} ${short(Number(n.created_at), tz)} ${preview(String(n.text))}`)].join("\n");
}
case "delete_note": {
const r = await sql.execute("DELETE FROM notes WHERE id = ? AND chat_id = ?", [effect.id, chatId]) as SqlResult;
return r.rowsAffected ? `Deleted note #${effect.id}.` : `There is no note #${effect.id}.`;
}
case "create_reminder": {
let row = await one("SELECT id, due_at FROM reminders WHERE chat_id = ? AND source_update = ?", [chatId, updateId]);
if (!row) {
delaySecondscan be at most 7 days, which is why the bot refuses reminders further ahead.dedupId: "rem:<id>"makes a retried update enqueue the message once: the samededupIdwithin 24 hours is delivered once.selfSlug(ctx)isctx.service.slug, withSELF_SLUGandtelegram-botas fallbacks for older nodes that left the slug empty.
When the message arrives, the queue handler sends the reminder unless it was cancelled meanwhile:
| { type: "send"; chatId: number; text: string }
| { type: "rates"; msg: RatesMessage; after: number };
function parseJob(body: unknown): Job | null {
if (!isObject(body)) return null;
if (body.type === "reminder" && Number.isSafeInteger(body.id)) return { type: "reminder", id: body.id as number };
if (body.type === "send" && Number.isSafeInteger(body.chatId) && typeof body.text === "string" && body.text.length <= 4096) {
return { type: "send", chatId: body.chatId as number, text: body.text };
}
const msg = parseRatesMessage(body);
if (msg) {
const after = Number.isSafeInteger(body.after) ? body.after as number : Number.MIN_SAFE_INTEGER;
return { type: "rates", msg, after };
}
return null;
}
async function handleJob(m: QueueMessage, job: Job, bot: BotApi, ctx: Ctx) {
switch (job.type) {
case "reminder": {
const r = await one("SELECT id, chat_id, text, due_at, status FROM reminders WHERE id = ?", [job.id]);
if (!r || r.status !== "pending") return m.ack(); // cancelled, already sent or unknown
A message that arrives early (for example after a dead-letter redrive) is pushed back with retry({delaySeconds}).
Delivery is at least once: a crash between sendMessage and the status update can send a reminder twice.
Rate alerts: fan-out through the queue¶
cbu-rates enqueues one cbu.rate_changed message per change. The bot turns it into one send message per
subscriber, so every chat is retried on its own and one slow chat does not hold up the rest:
if (wait > 5000) return m.retry({ delaySeconds: Math.min(Math.ceil(wait / 1000), 7 * 86400) }); // early (e.g. a DLQ redrive)
const sent = await sendOrSkip(bot, Number(r.chat_id), `Reminder: ${r.text}`);
await sql.execute(
"UPDATE reminders SET status = ?, sent_at = ? WHERE id = ? AND status = 'pending'",
[sent ? "sent" : "failed", Date.now(), job.id],
);
return m.ack();
}
case "send": {
// Unreachable subscribers are dropped, so the next broadcast skips them.
if (!(await sendOrSkip(bot, job.chatId, job.text))) {
await sql.execute("DELETE FROM subscribers WHERE chat_id = ?", [job.chatId]);
}
return m.ack();
}
case "rates": {
// Fan-out: one "send" message per subscriber, so each chat is retried on its own (Telegram
// 429s, network errors) and a big subscriber list does not hit one task's fetch limit.
const text = formatRateChanges(job.msg);
const self = selfSlug(ctx);
let after = job.after;
for (;;) {
const r = await sql.execute(
Subscribers are read in pages of 500. When less than 20 seconds of the task's wall time are left
(ctx.deadline), the handler enqueues a continuation message that starts after the last chat id, and acknowledges
the current one. The dedupIds keep both the per-chat sends and the continuation idempotent.
Calling another service¶
/rates asks cbu-rates in-process with std:services. Only the path and query of the Request are used, so the
host part of the URL does not matter:
return r.rowsAffected ? `Reminder #${effect.id} cancelled.` : `There is no pending reminder #${effect.id}.`;
}
case "subscribe":
await sql.execute("INSERT OR IGNORE INTO subscribers (chat_id, created_at) VALUES (?, ?)", [chatId, now]);
return "Subscribed. I will message you when the CBU changes USD, EUR or RUB rates. /unsubscribe to stop.";
case "unsubscribe": {
const r = await sql.execute("DELETE FROM subscribers WHERE chat_id = ?", [chatId]) as SqlResult;
return r.rowsAffected ? "Unsubscribed." : "You were not subscribed.";
}
case "rates":
return await currentRates(cfg);
}
}
call throws for a missing service or a refused call (not_found, call_not_allowed, …); a failing child returns a
5xx response instead. The bot handles both and answers politely.
Read-first schema creation¶
Every task may be the first one on a fresh database, so the handler checks for the schema before using it. It
reads first and writes the CREATE batch only when the last index is missing, so ordinary requests never take the
write lock for DDL:
function objects(r: SqlResult): Record<string, unknown>[] {
return r.rows.map((row) => Object.fromEntries(r.columns.map((c, i) => [c, row[i]])));
}
async function one(text: string, args: unknown[] = []): Promise<Record<string, unknown> | null> {
return objects(await sql.execute(text, args) as SqlResult)[0] ?? null;
}
// Read first; only a database without the schema pays for the write batch (the sql-todo pattern).
// The index created last proves the whole batch committed.
let schemaReady = false;
async function ensureSchema() {
if (schemaReady) return;
const found = await sql.execute("SELECT 1 FROM sqlite_master WHERE type = 'index' AND name = 'notes_chat'") as SqlResult;
if (found.rows.length === 0) {
await sql.batch([
`CREATE TABLE IF NOT EXISTS updates (update_id INTEGER PRIMARY KEY, received_at INTEGER NOT NULL)`,
`CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT, chat_id INTEGER NOT NULL, text TEXT NOT NULL,
source_update INTEGER NOT NULL, created_at INTEGER NOT NULL, UNIQUE (chat_id, source_update))`,
`CREATE TABLE IF NOT EXISTS reminders (
id INTEGER PRIMARY KEY AUTOINCREMENT, chat_id INTEGER NOT NULL, text TEXT NOT NULL,
due_at INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
source_update INTEGER NOT NULL, created_at INTEGER NOT NULL, sent_at INTEGER,
UNIQUE (chat_id, source_update))`,
The Bot API client and dry-run mode¶
async call<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
if (this.#dryRun) {
this.#outbox.push({ method, params });
return dryRunResult(method) as T;
}
const ac = new AbortController();
const timer = setTimeout(() => ac.abort(), this.#timeoutMs);
let res: Response;
try {
// The token is part of the URL: never log the URL or the request.
res = await this.#fetch(`${this.#base}/bot${this.#token}/${method}`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(params),
signal: ac.signal,
});
} finally {
clearTimeout(timer);
}
let data: Record<string, unknown> | null = null;
try {
const parsed = await res.json();
data = isObj(parsed) ? parsed : null;
} catch {
// not JSON (proxy error page, …)
}
if (res.ok && data?.ok === true) return data.result as T;
const p = isObj(data?.parameters) ? data!.parameters as Record<string, unknown> : {};
throw new TelegramError(
res.status,
typeof data?.error_code === "number" ? data.error_code : res.status,
typeof data?.description === "string" ? data.description : `HTTP ${res.status}`,
typeof p.retry_after === "number" ? p.retry_after : null,
);
}
The token is part of the Bot API URL, so the code never logs URLs or requests. A 10 s AbortController timeout
keeps a slow Bot API from eating the task's wall time. In dry-run mode the client records the call and returns a
canned result.
Test it¶
Unit tests. test/bot.test.ts covers command parsing, time parsing in the user's offset, both dialogs, quick
forms, range checks, /cancel, group-chat silence, KV state validation and the rate message format.
test/telegram.test.ts covers update parsing, secret token rules, the dry-run client, retry_after and the
"permanent" error flag, constant-time comparison and the body size limit.
cd sample/apps/telegram-bot
node --test test/*.test.ts # Node >= 22.18 (type stripping); or: deno test
Smoke test. smoke.sh deploys the bot as telegram-bot-smoke in dry-run mode, so it needs no bot token, and
walks through setup, webhook authentication, update_id dedupe, both dialogs, subscriptions and the queue fan-out
(it enqueues a cbu.rate_changed message through the control API and waits for the alert in the outbox):
RT_API=http://127.0.0.1:8081 RT_INVOKE=http://127.0.0.1:8080 RT_KEY=rtk_… ./smoke.sh
SMOKE_SLOW=1 ./smoke.sh # also waits about 70 s for a reminder to fire
SMOKE_CLEANUP=1 ./smoke.sh # deletes the service at the end
See Running the smoke tests for the shared helpers.
Notes and limits¶
- Reminders are limited to 7 days ahead (the queue's maximum delay) and to 50 pending per chat; notes to 1,000 per chat.
- Message text is plain (no
parse_mode), so user input never needs escaping. Replies are clipped to Telegram's 4,096 characters. - Chats that blocked the bot are unsubscribed on the next alert. Errors that retrying cannot fix (
403, chat not found) are not retried. - The
updatesdedupe table drops entries older than 3 days whenever an update id is a multiple of 100.
Ideas to extend it¶
- Add a
scheduledhandler and a daily schedule that sends each subscriber a morning summary. - Store per-chat time zones in SQL instead of one
BOT_TZ_OFFSET_MINUTES. - Accept photos and keep them in
std:blobnext to the notes. - Add inline keyboards for the yes/no step;
transitionstays the same, only the reply format changes.
Where the code lives¶
sample/apps/telegram-bot/ in the runtime repository: src/ (the service), test/ (unit tests), smoke.sh and a
README.
See also¶
- Calls and queues:
enqueue, delays, dedupe, DLQ and service calls - Deno services: handler forms,
ctx, env and secrets - Guest API reference:
std:kv,std:sql,std:queue,std:services 21ci secret,21ci queue