Approve AI agent actions from Telegram
Three ways to approve an AI agent's action from Telegram: n8n's Send and Wait for Response, your own bot with inline buttons, or a hosted approval service. What a bot must get right, from the webhook secret to who tapped, with a TypeScript handler.
· 9 min read
An agent that asks before it refunds a customer, sends an email or deploys needs someone to answer, and that person is often away from a desk. Telegram is already on their phone. This compares the ways to put the question there, explains what a bot must get right before a tap can count as an approval, and shows a short handler that does it.
There are three ways to approve an AI agent’s action from Telegram: n8n’s Telegram node with Send and Wait for Response, your own bot with inline buttons and callback queries, or a hosted approval service such as VariantGate that sends each waiting request to the approver’s chat. Whichever you choose, tie each tap to a person you authenticated, never to a chat; make approving take two taps; and let the agent act only on an explicit approval it reads from your own record.
Three ways to approve from Telegram
- n8n
- The Telegram node's Send and Wait for Response operation sends a message and pauses the workflow until someone answers. It suits an agent that already runs as an n8n workflow.
- Your own bot
- A bot you make with BotFather, a webhook that receives button taps, and a store that records decisions. It suits a custom agent, a LangGraph graph or a personal assistant you run yourself, if you are willing to own the security of the approval.
- A hosted approval service
- Agents ask an approval API; the service sends each waiting request to the right person's Telegram, records who decided, and gives the agent its answer. It suits several agents, or several people, that should share one set of rules and one record.
n8n’s Approval response shows one button or two, labelled ✅ Approve and ❌ Decline unless you change them, and Limit Wait Time resumes the workflow after an interval or at a set time. By default the buttons are links that open in a browser. With Approve Within Chat, found under Advanced Interactivity, a single tap in the chat answers, the output names the Telegram account that answered, and Restrict Who Can Approve limits answers to a list of Telegram user ids. That needs your n8n instance reachable over public HTTPS on port 443, 80, 88 or 8443, and it uses the bot’s one webhook, so the bot cannot also serve something outside n8n. The approval lives inside that one workflow: another agent, or the same agent outside n8n, needs its own.
Building your own approval bot
A bot of your own is a small web service. Telegram sends it each message and button tap as an update, and it calls Telegram’s Bot API to send and edit messages. The happy path takes an afternoon. What follows are the parts that decide whether an approval from it means anything, each checked against Telegram’s documentation.
Prove that an update came from Telegram
Your webhook is a public HTTPS address, and anyone who finds it can post an update to it that looks like a tap on Approve. When you register the address with setWebhook, pass a secret_token: 1 to 256 characters from A-Z, a-z, 0-9, _ and -. Telegram then sends it in the X-Telegram-Bot-Api-Secret-Token header of every update. Refuse any request without it, and compare in constant time so the time a refusal takes says nothing about how close a guess was.
# 64 random hex characters, inside what Telegram allows. Keep it with the
# handler's other secrets: the handler compares every update against it.
TELEGRAM_WEBHOOK_SECRET=$(openssl rand -hex 32)
curl -s "https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/setWebhook" \
--data-urlencode "url=https://example.com/telegram" \
--data-urlencode "secret_token=$TELEGRAM_WEBHOOK_SECRET" \
--data-urlencode 'allowed_updates=["message","callback_query"]'Telegram’s FAQ still suggests a secret path in the URL instead. The header is the better choice: paths end up in access logs, proxies and error reports, and a header usually does not. Asking only for message and callback_query updates keeps everything else away from the handler. Webhooks can only use ports 443, 80, 88 and 8443.
Tie each tap to a person you signed in
A tap arrives as a callback_query. Its from field is the Telegram account that pressed the button. That account is the only thing in the update that says who decided, and it means nothing until you have tied it to someone in your own system. The chat the message sits in tells you nothing about who is allowed to answer: in a group, everyone in it can press the buttons. n8n’s documentation says the same of its own node: leave its approver list empty and anyone who can see the message can respond.
So make each person link their account while signed in to you:
- Make a one-time code for the signed-in person, keep only its hash, and give it a short life, such as ten minutes.
- Hand it over as a deep link,
https://t.me/your_bot?start=CODE. The parameter can be up to 64 characters fromA-Z,a-z,0-9,_and-, so 64 hex characters fit exactly. Pressing Start sends the bot/start CODE. - When it arrives in a private chat, delete the code and store the sender’s
from.idand chat id against that person. Every later tap is looked up byfrom.id, and an account nobody linked decides nothing. - Check the person’s role at the moment of the tap, not at the moment of linking, and end the link when they leave.
The link also solves a Telegram rule you would hit anyway: a bot cannot start a conversation. Until a person has messaged the bot or added it to a group, it has nowhere to send them a request. Pressing Start in the deep link is that first message.
Put an id in the button, not the decision
Each inline button carries callback_data of 1 to 64 bytes, which Telegram hands back on a tap. A letter, a colon and a UUID, such as a:0196f1a0-55d2-7a11-b3e4-9f8e7d6c5b4a, takes 38. Treat it as untrusted input. Telegram’s own reference warns that the message a tap came from may contain no button with the data you received. Never put an amount, a recipient or a verdict in it that you would act on. Use it to find the request, then check in your own store that the request is still open and that this person may decide it.
Answer every tap
After a tap, Telegram’s apps show a progress indicator on the button until the bot calls answerCallbackQuery, so call it every time, even when nothing happened. Its text, up to 200 characters, appears as a short notice at the top of the chat. That is the place to say what happened: recorded, already decided, expired, or not yours to decide.
Make approving take two taps
Buttons sit under a message on a phone, and phones get tapped by accident. Approve should replace the buttons with Yes, approve and Back, using editMessageReplyMarkup, and record nothing until the second tap. Deny can act on the first: a wrong denial costs a retry, a wrong approval may cost a refund that cannot be taken back. To change an amount or add a note, send the person to a page behind a proper sign-in; a chat button is the wrong place for that. Inline buttons can open a URL as well as send data, so an “Open” button costs nothing.
The webhooks article covers the same ground for the agent’s side: why an event that says approved must never be the permission.
Expect the same tap twice, and two people at once
Telegram sends an update again when your webhook answers with anything but a 2xx, and gives up after what it calls a reasonable number of attempts. Updates wait on its side for at most 24 hours. So a slow database, a deploy or a crash can deliver one tap twice. Separately, two people can press Approve on the same request within the same second.
Both are handled in one place: record a decision with a single conditional write that changes the request only while it is still pending and has not expired. The first tap changes one row; any repeat, and the second person, change none and are told it was already decided. Each update also carries an update_id, which Telegram says you can use to ignore repeats, but the conditional write is what keeps a request from being decided twice. Check expiry in that same write. A message can sit unread in a chat for days, and its buttons work until the bot removes them.
Answer Telegram with a 2xx for every update that carried the right secret, including taps that came to nothing. Otherwise it keeps resending an update you have already dealt with.
Send the agent’s words as plain text
The summary in the message was written by the agent, and the agent may have read a web page or an email that told it what to write. With parse_mode set to Markdown or HTML, that text can format itself: bold a reassuring phrase, or put an innocent word over a link to somewhere else. Telegram’s apps ask before opening such a link, but by then the person has already read the message the agent wanted them to read. Leave parse_mode out and the text arrives exactly as written, with its asterisks, brackets and tags showing. Messages hold up to 4,096 characters, so cut long summaries and link to the full request rather than letting the send fail.
Start the message with a line you wrote, such as which agent asks and for what action, so the person knows where your text ends and the agent’s begins.
Keep the decision in your store, not in the chat
The chat is a way to press a button, never the record. The agent should learn the answer by reading the request from your own store, through an API that only lets it read its own requests, and act only when that answer is an explicit approval. It must not read the chat, wait for a message saying approved, or take the bot’s reply as permission. Messages can be edited, forwarded and deleted, and the chat has no idea that someone paused every agent five minutes after the tap.
Pending, denied and expired all mean the agent does not act. If your approval can time out, a time-out is a no, never a quiet yes. That matters with n8n too: Limit Wait Time resumes the workflow when the time is up, so the step after it has to check that the answer really was an approval rather than assume someone pressed the button.
Keep the bot token out of every log
Every call to the Bot API goes to https://api.telegram.org/bot<token>/METHOD_NAME, so the token sits in the URL of every request your service makes. Anyone who has it controls the bot: they can message everyone who linked, in the bot’s name, and move its webhook to their own server to receive the taps. HTTP clients put URLs into their error messages, and tracing tools often record outgoing URLs. Log the method and the status, never the URL, and strip the URL from errors before they reach a log or an error tracker. If the token leaks, send /token to BotFather: it is the step Telegram gives for a compromised token, and it makes a new one.
A webhook handler in TypeScript
This is the handler for a bot of your own, written as a POST(request) function that takes a web-standard Request, as Next.js route handlers do, using Node’s crypto. It checks the secret header, links accounts from the deep link, sends a request with Approve and Deny, turns Approve into a second step, and records the decision for the linked person only. It is one file, shown in three parts. We type-checked it and ran it against a fake Telegram and a fake store; it has not been run against Telegram’s servers.
import { createHash, timingSafeEqual } from "node:crypto";
import { db, links } from "./store"; // your own database
const API = `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_TOKEN}`;
const SECRET = process.env.TELEGRAM_WEBHOOK_SECRET ?? ""; // the secret_token given to setWebhook
interface Tap {
data?: string;
from: { id: number };
id: string;
message?: { chat: { id: number }; message_id: number };
}
interface StartMessage {
chat: { id: number; type: string };
from?: { id: number };
text?: string;
}
const digest = (text: string) => createHash("sha256").update(text).digest();
/** Both sides are hashed to 32 bytes, so the comparison takes the same time for any guess. */
function fromTelegram(request: Request): boolean {
const given = request.headers.get("x-telegram-bot-api-secret-token") ?? "";
return SECRET !== "" && timingSafeEqual(digest(given), digest(SECRET));
}
async function bot(method: string, body: object): Promise<void> {
const response = await fetch(`${API}/${method}`, {
body: JSON.stringify(body),
headers: { "content-type": "application/json" },
method: "POST",
});
if (!response.ok) {
console.warn("Telegram call failed", method, response.status); // never the URL: it holds the token
}
}
const buttons = (...pairs: [string, string][]) => ({
inline_keyboard: [pairs.map(([text, callback_data]) => ({ callback_data, text }))],
});Both sides of the comparison are hashed first. timingSafeEqual throws when its two inputs differ in length, and hashing gives it 32 bytes on each side whatever was sent. bot() logs the method and the status, never the URL.
/** `/start <code>` from the deep link: ties this Telegram account to whoever made the code. */
async function onStart(message: StartMessage): Promise<void> {
const code = message.text?.match(/^\/start ([\w-]{1,64})$/)?.[1];
if (!(code && message.from && message.chat.type === "private")) {
return;
}
// claim() deletes the code, so it works once, and refuses one older than ten minutes.
const linked = await links.claim(code, message.from.id, message.chat.id);
const text = linked ? "Linked. Requests will arrive here." : "That link has expired or was used.";
await bot("sendMessage", { chat_id: message.chat.id, text });
}
/** A waiting request, sent to the private chat saved when the person linked. */
export async function notify(chatId: number, request: { agent: string; id: string; summary: string }) {
await bot("sendMessage", {
chat_id: chatId,
reply_markup: buttons(["Approve", `a:${request.id}`], ["Deny", `d:${request.id}`]),
text: `${request.agent} asks: ${request.summary}`.slice(0, 4096), // no parse_mode: shown as written
});
}links.claim stands for your own store: it finds the code by its hash, refuses it when it is older than ten minutes, deletes it, and saves the Telegram account and chat against the person who made it. The request goes out without parse_mode.
/** Only a pending, unexpired request in one of this person's workspaces changes, so the first tap wins. */
async function decide(requestId: string, status: "approved" | "denied", userId: string) {
const result = await db.query(
`UPDATE requests SET status = $1, decided_by = $2, decided_at = now()
WHERE id = $3 AND status = 'pending' AND expires_at > now()
AND workspace_id IN (SELECT workspace_id FROM members WHERE user_id = $2)`,
[status, userId, requestId]
);
return result.rowCount === 1 ? `Recorded: ${status}.` : "Already decided, expired or not yours.";
}
async function onTap(tap: Tap): Promise<string> {
const [kind, requestId] = (tap.data ?? "").split(":");
const person = await links.byTelegramId(tap.from.id); // who pressed, not which chat
if (!person) {
return "This Telegram account is not linked.";
}
if (!requestId) {
return "";
}
const message = tap.message && { chat_id: tap.message.chat.id, message_id: tap.message.message_id };
if (kind === "a" && message) {
const confirm = buttons(["Yes, approve", `y:${requestId}`], ["Back", `b:${requestId}`]);
await bot("editMessageReplyMarkup", { ...message, reply_markup: confirm });
return "Tap Yes, approve to approve.";
}
if (kind === "b" && message) {
const choose = buttons(["Approve", `a:${requestId}`], ["Deny", `d:${requestId}`]);
await bot("editMessageReplyMarkup", { ...message, reply_markup: choose });
return "Nothing was decided.";
}
if (kind === "y") {
return decide(requestId, "approved", person.userId);
}
return kind === "d" ? decide(requestId, "denied", person.userId) : "";
}
export async function POST(request: Request): Promise<Response> {
if (!fromTelegram(request)) {
return new Response(null, { status: 401 });
}
const update = await request.json();
const tap: Tap | undefined = update.callback_query;
if (tap) {
const text = await onTap(tap).catch(() => "Something went wrong. Nothing was decided.");
await bot("answerCallbackQuery", { callback_query_id: tap.id, text }); // stops the spinner
} else if (update.message) {
await onStart(update.message);
}
return new Response(null, { status: 200 }); // a 2xx, or Telegram sends the update again
}The UPDATE is where repeats, races and expiry are handled: it changes the request only while it is pending and unexpired, and only in a workspace the person belongs to, so a second tap changes nothing. A real rule set adds more to that check, such as the person’s role or a second approver. Whatever goes wrong inside a tap, the person is told and Telegram gets a 200, so it does not send the tap again.
How VariantGate does it
VariantGate is an approval inbox for AI agents: an agent asks before a risky action, a person approves or denies, and only an explicit approval lets the agent act. Telegram is one more place to answer, next to the inbox, email and push. It follows the list above:
acme_approvals_bot
A request is waiting for a decision.
support-agent (key: support-bot) wants to: Refund €30.00 for order A-1001, the parcel arrived damaged.
refund.create · 30.00 EUR
- Your bot, not ours. A workspace owner makes a bot with BotFather and pastes its token under Settings. The token is stored to call Telegram, never shown again and never logged, and errors from Telegram calls have their URL cut off before they go anywhere.
- A secret per bot. Connecting the bot calls
setWebhookwith a fresh random secret, of which only a hash is kept, and asks only for messages and button taps. An update without the secret is refused. - Linking per person. Each member links their own Telegram with a deep link made while signed in. Its code works once, for ten minutes, and only its hash is stored. Links are only made in a private chat, and they end when the person leaves the workspace.
- Who decides. The member whose link matches the tapping account’s
from.id, with their role as it is now. The decision goes through the same code as the inbox, so rules that send a request to certain people, two-person approval and a paused workspace all hold. - Two taps to approve. Approve shows Yes, approve and Back. Deny records at once. To change the amount or add a note, Open in VariantGate goes to the inbox.
- Plain text. Messages go out without
parse_mode, and they open with a line naming nothing the agent wrote. - The agent reads its answer. It reads
GET /v1/requests/{id}with its own key and acts only onallowed: true. A tap in Telegram never reaches the agent any other way, and while the workspace is paused,allowedstays false whatever was approved.
It works on every plan, Free included. Setting it up takes a few minutes and is on the Telegram page, and the other channels are in Notifications. To see a request go from asked to decided before connecting anything, try the playground, which needs no account.
When not to use Telegram for approvals
A Telegram message is not private between you and your bot. Whatever it says, the agent’s name, the action, the summary and the amount, passes through Telegram’s servers, as a Slack or Discord message would pass through theirs. That rules it out for some work:
- Requests that carry patient, payroll, customer or other regulated data, where your obligations say where that data may go. Decide those in the inbox, behind sign-in. VariantGate’s push notifications name only the agent and the action, so the details never leave it.
- Workplaces that have not approved Telegram as a tool. A personal messenger on a work phone is a question for whoever owns your security policy before it is an engineering one.
- Actions too large for one tap. A Telegram account is only as safe as the phone it is on and the account’s own sign-in. For those, require two different people, which holds whichever channel each of them uses.
Checklist
- Telegram’s calls carry a secret token, compared in constant time.
- Each Telegram account is linked by a one-time, short-lived code made for a signed-in person.
- A tap is decided by its
from.idand that person’s current role, never by the chat. - Button data holds an id; the rest is looked up.
- Every tap gets an answer.
- Approve takes two taps; Deny takes one.
- One conditional write records a decision, so repeats and races decide nothing twice, and expired requests stay expired.
- Agent text goes out without parse_mode.
- The agent acts only on an approval it reads from your store.
- The bot token never reaches a log.
Sources
- n8n docs, Telegram node: Send and Wait for Response pauses the workflow until the user answers; Approval, Free Text or Custom Form; one or two buttons, ✅ Approve and ❌ Decline by default; Limit Wait Time resumes after an interval or at a set time.
- n8n docs, Telegram node, Approve Within Chat: needs n8n reachable over public HTTPS on 443, 80, 88 or 8443; output includes who answered; Restrict Who Can Approve, and without it anyone who can see the message can respond; one webhook per bot; link buttons otherwise.
- Telegram Bot API, setWebhook: an HTTPS POST per update, repeated after any answer that is not 2XY; secret_token of 1 to 256 characters from A-Z, a-z, 0-9, _ and -, sent in X-Telegram-Bot-Api-Secret-Token; allowed_updates; ports 443, 80, 88 and 8443.
- Telegram Bot API, Getting updates: getUpdates and webhooks are mutually exclusive; updates are kept no longer than 24 hours.
- Telegram Bot API, Update: update_id lets a webhook ignore repeated updates or restore their order.
- Telegram Bot API, Making requests: every call goes to https://api.telegram.org/bot<token>/METHOD_NAME.
- Telegram Bot API, InlineKeyboardButton: callback_data is 1 to 64 bytes.
- Telegram Bot API, CallbackQuery: from is the sender; the originating message may contain no button with the data received; clients show a progress bar until answerCallbackQuery is called, so it must always be called.
- Telegram Bot API, answerCallbackQuery: a notification or alert of 0 to 200 characters.
- Telegram Bot API, sendMessage: text of 1 to 4096 characters after entity parsing; parse_mode is optional.
- Telegram Bot API, Formatting options: Markdown and HTML styles, inline links, and the alert clients show before opening an inline link.
- Telegram, Bots: bots can't start conversations with users; a user must add them to a group or message them first.
- Telegram, Bot features, Deep linking: t.me/<bot>?start=<parameter>, up to 64 characters from A-Z, a-z, 0-9, _ and -; the bot receives /start <parameter>.
- Telegram, Bot features, BotFather: the token can be used by anyone to control the bot; /token makes a new one if it is compromised.
- Telegram, Bots FAQ: the older advice of a secret path in the webhook URL.
Give your agents somewhere to ask.
Free for 100 requests a month. Sign in with your email and have a first request waiting a few minutes from now.
Start free