The DevBlog.

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

Build Your First Telegram Widget: A Bot API 10.4 Tutorial

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 fetch and 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_data for one message, public_data for 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 a widget_query update, and you answer with answerWidgetQuery within 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.

  1. Create a bot with @BotFather and copy its token.
  2. Save the code below as bot.js.
  3. Run it with Node 18 or newer: BOT_TOKEN=your-token node bot.js.
  4. Send /start to 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

  1. Sending. sendWidget takes the chat, the HTML and a caption. We pass allow_queries: true, because without it every request from the widget is refused. We also pass an initial chat_data, so the widget has state to draw from the first moment.
  2. Drawing. The widget reads TelegramWidget.chatData, parses it, and draws filled or empty stars. It draws synchronously, because there is nothing to load.
  3. Asking. Tapping a star calls TelegramWidget.request('rate:4'). The call must happen inside the tap handler.
  4. Answering. Your bot receives a widget_query update with the user and the data. It must call answerWidgetQuery for every query within 15 seconds. The answer goes only to the widget that asked and does not change its state.
  5. Updating state. The bot then calls editMessageWidgetData to write the new chat_data. The widget receives a chatDataChanged event and redraws.

Tips and pitfalls

  • Include widget_query in allowed_updates if 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_query can 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.data as 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-color instead 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.

Written by Methembe Nyoni

I'm Methembe, a developer and IT student who builds full-stack web and mobile apps with React, Node.js, Python, and Android. I like making tech that solves real problems in Zimbabwe and across Africa. I run The DevBlog, my own tech news site.