Tgcloud Widgets
ASecurityBuild HTML widgets (Bot API 10.4) for a Telegram Serverless (tgcloud) bot — small interactive blocks drawn inside a message (a counter, a poll, a ticker, a game, a promo code) — with sendWidget / sendSharedWidget, the widget_query and shared_widget_query handlers, answerWidgetQuery, the chat state and shared state (editMessageWidgetData / editSharedWidgetData), the TelegramWidget JavaScript object and its sandbox rules, size limits, TON wallet payments, and offline tests. Use whenever the use...
- 2 stars
- 0 votes
- 0 copies
- 0 views
- Added November 11, 2026
Works with
Security analysis
100/100Pro scans all 8 files and shows the line behind each finding
npx -y skills add IsAmirMmd/nim-byte-telegram-serverless --skill tgcloud-widgets --agent claude-codeAre you the author of Tgcloud Widgets?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/isamirmmd-tgcloud-widgets-nim-byte-telegram-serverless)---
name: tgcloud-widgets
description: Build HTML widgets (Bot API 10.4) for a Telegram Serverless (tgcloud) bot — small interactive blocks drawn inside a message (a counter, a poll, a ticker, a game, a promo code) — with sendWidget / sendSharedWidget, the widget_query and shared_widget_query handlers, answerWidgetQuery, the chat state and shared state (editMessageWidgetData / editSharedWidgetData), the TelegramWidget JavaScript object and its sandbox rules, size limits, TON wallet payments, and offline tests. Use whenever the user wants a widget, an interactive or live message, an in-chat poll / counter / game / ticker, or asks about sendWidget, widget_query or TelegramWidget.
---
# tgcloud widgets
A **widget** is one small HTML document (inline CSS and JS) that the bot sends
in a message. Telegram apps run it inside the message bubble, in a sandbox
with **no network**, styled like the chat. It is **fixed code plus changeable
state**:
- The code (the HTML) is set at sending and never changes. For a new layout,
send a new widget.
- The state is two strings of up to 1024 bytes each, usually JSON, and **only
the bot writes it**:
- `chat_data` (chat state): this message in its chat. In a group, all members share it.
- `public_data` (shared state): the same wherever the widget is shown, forwards included.
- The widget reads its state, redraws when it changes, and asks the bot with
`TelegramWidget.request(data)` (1-64 bytes, like callback_data). The bot gets
a `widget_query` update and answers with `answerWidgetQuery`.
**In production, widgets work only in private chats with the bot**, and they
can't be forwarded (they're sent with protected content). Groups, inline mode
and forwards work only on the test server for now. Design for the private
chat first.
Sources (Markdown, fetch them when something here isn't enough):
- the guide and the TelegramWidget reference: https://core.telegram.org/bots/widgets.md
- the Bot API methods and types: https://core.telegram.org/bots/api.md (sendWidget, WidgetQuery, …)
Sibling skills: **tgcloud-bot** (the project, `references/bot-api.md` for
the rest of Bot API 10.4), **tgcloud-mini-app** (full apps).
## Widget or Mini App?
| Choose | When |
|---|---|
| **Widget** | It lives in the chat and should stay visible as it scrolls: a counter, a poll, an order status, a price, a small game, a code to copy. Taps only, no keyboard, at most 600 px tall, 4 KB compressed. |
| **Mini App** | Forms with text input, lists that scroll, many screens, network calls, files. Link to it from a widget with `openTelegramLink('https://t.me/<bot>/<app>')`. |
## Where things go in a tgcloud project
```
widgets/<name>.html the widget's source (not deployed; edit this)
tgcloud/lib/widgets/<name>.html.js generated by `npm run widgets`: export default "<html>"
tgcloud/lib/widgets/<name>.js send<Name>(), handle<Name>Query(query), its DB queries
tgcloud/handlers/widget_query.js thin router by the prefix of data, like callback_query.js
tgcloud/handlers/shared_widget_query.js only for shared widgets that forwards may ask (test server)
test/widgets.test.mjs requests, edits, limits
scripts/widgets.mjs builds and checks the widgets (from this skill)
```
tgcloud has no filesystem at runtime, so the HTML must be a string inside a
module. `scripts/widgets.mjs` turns `widgets/<name>.html` into
`tgcloud/lib/widgets/<name>.html.js`. It also checks the limits: 32768 bytes,
no NUL, and 4096 bytes after zlib level 9 (exact with python3).
The handler file is what turns widget queries on: the platform keeps the
webhook's update types in sync with `tgcloud/handlers/`, so without
`handlers/widget_query.js` every request ends in `TIMEOUT`.
## Step 1: Add the example (the full loop), then adapt it
[assets/example/](assets/example/) is a working counter: `/counter` sends it,
the buttons − ↺ + ask the bot, and the bot keeps the count in the DB, edits the
chat state and answers. Copy it into a project scaffolded with tgcloud-bot:
```
cp -r "${CLAUDE_SKILL_DIR}/assets/example/." .
mkdir -p scripts && cp "${CLAUDE_SKILL_DIR}/scripts/widgets.mjs" scripts/
npm pkg set scripts.widgets="node scripts/widgets.mjs"
```
The generated `tgcloud/lib/widgets/*.html.js` files are committed and
deployed like any other module. The widgets test fails when one is older than
its `.html`, so CI never deploys a stale widget. Run `npm run widgets` after
every change to a `.html` file.
Then wire it up:
1. `tgcloud/schema.js`:
```js
// State of each counter widget, keyed by its message (lib/widgets/counter.js).
export const widget_counters = table('widget_counters', {
chat_id: integer('chat_id').notNull(),
message_id: integer('message_id').notNull(),
count: integer('count').default(0),
rev: integer('rev').default(0), // raised on every edit; the widget ignores older states
}, (t) => ({
msg: uniqueIndex('uidx_widget_counters_msg').on(t.chat_id, t.message_id),
}));
```
2. `tgcloud/handlers/message.js`, public section:
`if (text === '/counter') return sendCounter(message);`
with `import { sendCounter } from '../lib/widgets/counter.js';`.
3. `npm run widgets && npm test`. Then `npm run deploy` and
`npx tgcloud migrate`, and send `/counter` to the bot.
`test/helpers.mjs` has `widgetQuery(from, data, messageId)`. A project
scaffolded before this skill existed may not have it: copy it from the
tgcloud-bot skill's `assets/template/test/helpers.mjs`, together with the
`sendWidget` default in `test/sdk/sdk.mjs`.
For a new widget, copy the three counter files under a new name and a new
`data` prefix (`<feature>:<action>`), add a line to `handlers/widget_query.js`,
and remove the counter if the user doesn't want it.
## Step 2: The bot side
**Send**: `api.sendWidget(params)` returns the Message, whose `.widget` holds
the HTML, the size, the state and, for a shared widget, its `id`.
| Parameter | |
|---|---|
| `chat_id`, `html` | required. `html` comes from the generated module |
| `caption` | **always send one**: it's the text in the chat list, notifications and search, and what apps without widget support show |
| `chat_data`, `public_data` | the initial state (≤1024 bytes each) |
| `allow_queries: true` | the widget may call the bot. Without it every request is `NOT_ALLOWED` |
| `is_shared: true` | a shared widget (one object, one shared state for every message showing it). Send it again with `sendSharedWidget({ chat_id, widget_id, chat_data, caption })` |
| `width`, `height` | size hints in px, for the placeholder. Omit both for full width and automatic height (50-600 px) |
| also | `parse_mode`, `caption_entities`, `show_caption_above_media`, `reply_markup`, `reply_parameters`, `message_thread_id`, `disable_notification`, `protect_content`, `message_effect_id` |
**Answer** every `widget_query` / `shared_widget_query` within **15 seconds**,
also when the request was invalid or something failed:
`api.answerWidgetQuery({ widget_query_id: query.id, data })`. `data` (≤1024
bytes) is the widget's promise result, for the widget that asked only. The
answer doesn't change the state.
**Change the state**: only these methods do it, and the edits are silent:
- `editMessageWidgetData({ chat_id, message_id, chat_data?, public_data? })`
(or `inline_message_id`). An omitted field is kept, and `''` clears it. Each
call counts as one sent message against the bot's rate limits.
- `editSharedWidgetData({ widget_id, public_data, cache_time? })`: a shared
widget's shared state, at most once a second. `cache_time` (5-3600 s, 30 by
default) is how often open widgets that call `watchPublicData()` poll it.
- "message is not modified" means nothing changed: treat it as done.
- Edit the caption with `editMessageCaption`, as for any media.
**The query** (`widget_query`): `id`, `from` (the user who tapped, verified by
Telegram), `chat` + `message_id` (or `inline_message_id` + `chat_type`),
`chat_instance`, `type`, `data`, and `widget_id` for a shared widget.
`shared_widget_query` (from a forward) has only `id`, `from`, `type`, `data`
and `widget_id`. `type.type` is `'data'`, `'sign_data'` or `'sent_transaction'`
(wallet, below).
Rules, the same as for callback_query:
- `data` comes from the client. Check it against the state kept in the DB,
keyed by `(chat_id, message_id)`, or by `widget_id` for shared widgets.
The query never carries the widget's state.
- For one vote per user or a paid action, key on `(widget_id, from.id)`.
- Update the DB **after** the edit went through, so a failed edit doesn't
change it.
- Put a revision `r` in the state, raised on every edit and returned in the
answer. The widget then ignores anything older.
- When many users act at once (votes on a shared widget), keep the state in
the DB and write it to the widget at most once a second.
- Never put secrets in a widget's code or state: forwards carry them.
- Like every message, a widget has a way back: send it with
`reply_markup: { inline_keyboard: [[homeButton(lang)]] }` (or `withBack(lang, [], '<screen>')`)
from `lib/menu.js`. Pressing it sends the menu as a new message, because a
widget can't be edited into text.
- `copyMessage` / `copyMessages` refuse widget messages. In groups, the bot
needs `can_send_other_messages`.
**Inline mode** (test server only): an `InlineQueryResultArticle` whose
`input_message_content` is `InputWidgetMessageContent` (the sendWidget fields)
or `InputSharedWidgetMessageContent` (`{ widget_id, chat_data?, caption? }`).
Requests from those messages carry `inline_message_id`.
## Step 3: The widget side
Write the HTML with [references/widget-runtime.md](references/widget-runtime.md):
the `TelegramWidget` object, what the sandbox keeps and removes, gestures, the
limits, and a checklist. The essentials:
- `window.TelegramWidget` exists before the first script runs (it's
`undefined` in a plain browser). Draw the first state **synchronously** from
`TelegramWidget.chatData` / `.publicData` (strings or `null`: `JSON.parse` in
`try`). Redraw on `onEvent('chatDataChanged' | 'publicDataChanged', fn)`.
- Call `request(data)` **synchronously inside a click handler**: one request
per tap, one in flight. Show "sending…" and every error `code`
(`NOT_ALLOWED`, `BUSY`, `RATE_LIMITED`, `TIMEOUT`, `FAILED`,
`INVALID_ANSWER`). In the private chat a widget may also ask in the
background: once when it appears, then every 5 s at most.
- Use the theme variables (`--tg-theme-*`) and system fonts. An unstyled
`<button>` looks like the app's own. No inputs, no keyboard, no network, no
scrolling, no vertical drags.
- Persian UI: add `dir="rtl"` where needed, and use `Intl.NumberFormat(navigator.language)` for numbers.
## Step 4: Test
- `npm test`: the example's tests show the shape. They press the widget with
`widgetQuery(user, data, messageId)`, check `take()` (sendWidget,
editMessageWidgetData, answerWidgetQuery), fail an edit with `failNext`, and
check the size of every built widget.
- In the cloud, without a deploy:
`npx tgcloud run handlers/widget_query '{ id: "1", from: { id: <ADMIN_ID> }, chat: { id: <ADMIN_ID>, type: "private" }, message_id: 1, chat_instance: "1", type: { type: "data" }, data: "count:inc" }'`.
`answerWidgetQuery` then fails with an invalid query id, which is expected.
- The look: open `widgets/<name>.html` in a browser 320-430 px wide, with the
stub `TelegramWidget` from the guide's "A first look in a browser" section.
Then try it in Telegram: light and dark themes, a narrow phone, the
desktop app.
## Payments with the wallet
A widget can ask the user to pay or sign with Telegram's built-in TON wallet
(TON Connect formats, no manifest or bridge):
1. On a tap, the widget calls `request('pay:42', { wallet: true })`. The query's
`type` is `{ type: 'data', wallet_card }` (TonWalletCard: the address and balance).
2. The bot answers with a fresh transaction as JSON: `{ valid_until,
messages: [{ address, amount /* nanotons, string */, payload?, stateInit? }] }`.
Leave `from` out.
3. In the answer's handler, the widget calls
`TelegramWidget.wallet.sendTransaction(tx, 'paid:42')`. No second tap is
needed within 10 s.
4. The bot gets `type: { type: 'sent_transaction', wallet, msg_hash }` with
data `'paid:42'`. It checks the transaction **on the chain** (sender,
recipients, amounts, outcome), not just the hash, then answers.
`wallet.signData(payload, data)` works the same way: `type: 'sign_data'`,
signed for the domain `bot<bot_id>`. `TelegramWidget.wallet` is `null` where
there's no wallet: draw a pay button only when it's there. After `TIMEOUT`,
ask the bot about the order. Never pay again blindly.
Files in this skill
- SKILL.md
- assets/example/test/widgets.test.mjs
- assets/example/tgcloud/handlers/widget_query.js
- assets/example/tgcloud/lib/widgets/counter.html.js
- assets/example/tgcloud/lib/widgets/counter.js
- assets/example/widgets/counter.html
- references/widget-runtime.md
- scripts/widgets.mjs
Attribution
Related skills
View all in ai-agents →Comments
Loading comments…
Newsletter
Get the weekly list of safe new skills, and the ones we pulled.