Build Your First Telegram Widget: A Bot API 10.4 Tutorial
Telegram’s Bot API 10.4 lets bots send interactive widgets inside chat messages. Learn how they work and build a working rating card in Node.js.
Published
Updated

On 9 November, Telegram released Bot API 10.4, and the headline feature is widgets: small interactive blocks drawn right inside a chat message. A bot can now send an FAQ whose answers expand when tapped, an order card with a status button, or a rating row, all without sending the user to a web page. In this tutorial, we will look at how widgets work and build a small rating card with Node.js.
Note: I wrote the code below from Telegram’s documentation and have not run it against a live bot, so test it before you rely on it.
What a widget is
- One HTML document. Inline CSS and JavaScript, at most 32 KB of HTML and 4 KB after compression. Images must be inline
data:URLs or SVG. - Sandboxed and offline. Widgets run in a small JavaScript engine called QuickJS, not a WebView. They have no network access, so
fetchand similar APIs throw errors. - Fixed code, changeable state. The HTML never changes after sending. What changes is the state, which only the bot writes (
chat_datafor one message,public_datafor shared state). The widget reads it and redraws. - Talks to the bot through Telegram. A tap in the widget calls
TelegramWidget.request()with up to 64 bytes of data. That arrives at your bot as awidget_queryupdate, and you answer withanswerWidgetQuerywithin 15 seconds. - Not a Mini App. A Mini App is a web page you host. A widget is part of the message and has no network.
Limits to know before you start
- In production, widgets can currently be sent only to private chats, and they are protected from forwarding. Groups, inline mode and forwards work only on Telegram’s test server for now.
- The only form control is
<button>. There is no keyboard input, and vertical drags scroll the chat rather than the widget. - State and answers are limited to 1024 bytes of text each, and a user and bot can make 5 requests per 5 seconds.
- Treat the HTML and the state as public. Never put secrets in them.
The plan
We will build a rating card. The bot sends a row of five stars, the user taps one, the bot saves it, and the card redraws.
- Create a bot with @BotFather and copy its token.
- Save the code below as
bot.js. - Run it with Node 18 or newer:
BOT_TOKEN=your-token node bot.js. - Send
/startto your bot in a private chat.
The code
// bot.js — Node 18+ (built-in fetch)
const API = `https://api.telegram.org/bot${process.env.BOT_TOKEN}`;
async function call(method, body) {
const res = await fetch(`${API}/${method}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const json = await res.json();
if (!json.ok) throw new Error(`${method}: ${json.description}`);
return json.result;
}
const WIDGET_HTML = `
<h3>How was this article?</h3>
<div id='row'></div>
<p id='msg' style='color:var(--tg-theme-hint-color)'></p>
<script>
const W = window.TelegramWidget;
const row = document.getElementById('row');
const msg = document.getElementById('msg');
function rating() {
try { return (JSON.parse(W.chatData) || {}).r || 0; } catch (e) { return 0; }
}
function draw() {
const r = rating();
row.replaceChildren(...[1, 2, 3, 4, 5].map((n) => {
const b = document.createElement('button');
b.textContent = n <= r ? '★' : '☆';
b.onclick = () => rate(n);
return b;
}));
}
function rate(n) {
msg.textContent = 'Saving...';
W.request('rate:' + n).then(
(a) => { msg.textContent = a.result || ''; },
(e) => { msg.textContent = 'Not saved (' + e.code + ')'; }
);
}
W.onEvent('chatDataChanged', draw);
draw();
</script>`;
async function sendCard(chatId) {
await call('sendWidget', {
chat_id: chatId,
html: WIDGET_HTML,
caption: 'Rate this article (1-5)',
allow_queries: true,
chat_data: JSON.stringify({ r: 0 }),
});
}
async function onWidgetQuery(q) {
const match = /^rate:([1-5])$/.exec(q.data || '');
// Answer every query within 15 seconds.
await call('answerWidgetQuery', {
widget_query_id: q.id,
data: match ? 'Thanks!' : 'Unknown request',
});
if (!match || !q.chat) return;
try {
await call('editMessageWidgetData', {
chat_id: q.chat.id,
message_id: q.message_id,
chat_data: JSON.stringify({ r: Number(match[1]) }),
});
} catch (err) {
if (!String(err.message).includes('not modified')) throw err;
}
}
async function main() {
let offset = 0;
for (;;) {
const updates = await call('getUpdates', {
offset,
timeout: 30,
allowed_updates: ['message', 'widget_query'],
});
for (const u of updates) {
offset = u.update_id + 1;
if (u.message && u.message.text === '/start') await sendCard(u.message.chat.id);
if (u.widget_query) await onWidgetQuery(u.widget_query);
}
}
}
main();
How it works
- Sending.
sendWidgettakes the chat, the HTML and a caption. We passallow_queries: true, because without it every request from the widget is refused. We also pass an initialchat_data, so the widget has state to draw from the first moment. - Drawing. The widget reads
TelegramWidget.chatData, parses it, and draws filled or empty stars. It draws synchronously, because there is nothing to load. - Asking. Tapping a star calls
TelegramWidget.request('rate:4'). The call must happen inside the tap handler. - Answering. Your bot receives a
widget_queryupdate with the user and the data. It must callanswerWidgetQueryfor every query within 15 seconds. The answer goes only to the widget that asked and does not change its state. - Updating state. The bot then calls
editMessageWidgetDatato write the newchat_data. The widget receives achatDataChangedevent and redraws.
Tips and pitfalls
- Include
widget_queryinallowed_updatesif you set that list, or your bot will never see the taps. - Check your library. A developer write-up warns that older Bot API libraries may silently drop update types they do not know, so
widget_querycan vanish. Handle it before the dispatcher or call the API directly as above. The Go library go-telegram/bot added widget support in version 1.28.0, according to Techenclave. - Always send a caption. It appears in the chat list and notifications and is what apps without widget support display.
- Validate every request. Treat
q.dataas untrusted input, like callback data, and keep the real state on your server. - Handle “message is not modified”. Editing to the same state returns that error. Treat it as success.
- Use theme variables such as
--tg-theme-text-colorinstead of hard-coded colours, so the widget looks right in light and dark chats. - Test groups, inline mode and forwards on Telegram’s test server, where every bot has the full feature set.
Where to go next
Widgets can show a live price by combining a shared widget with watchPublicData(), track an order, run a two-player game in a group on the test server, or collect payments through the wallet integration that came with the same release. Start with something small and useful, and remember that the widget’s code is fixed once sent, so design the layout carefully.
Was this article helpful?
Comments
Comments are reviewed before they appear. Links are displayed as plain text and are not clickable.




