Telegram Bot API

Telegram Widget Examples: Complete HTML and Python Bot Code

· 12 min read

These Telegram widget examples are complete and ready to run: each one has the widget HTML (well under the 4 KB compressed limit), the Python bot code built on requests and long polling, and a description of what the user sees. Start with a static order card, add requests with a counter, then build a live poll as a shared widget. If widgets are new to you, read what Telegram widgets are first.

Before you start: in the production environment widgets currently work only in the private chat with the bot, and they're sent with protected content, so they can't be forwarded. Groups, inline mode and forwards work only on the test server. All examples below run in a private chat.

What you need: Python 3 with requests (pip install requests), a bot token (how to get it) and your chat id. Save each widget as a file next to the bot script. Before writing code you can paste any widget into the sendWidget form of the Bot API Tester and see it in your chat.

Example 1: a static order card (no requests)

An order summary whose status line the bot updates as the order moves. The widget never asks the bot anything, so it is sent without allow_queries. The status lives in chat_data; the widget draws it at start and again on every chatDataChanged event. The message also has a caption and an inline keyboard under the widget.

order.html (919 bytes, 520 bytes compressed):

<style>
h3{margin:0 0 6px}
.row{display:flex;justify-content:space-between;gap:12px}
.st{margin-top:10px;padding:6px 10px;border-radius:8px;background:var(--tg-theme-secondary-bg-color)}
.hint{color:var(--tg-theme-hint-color);font-size:.87em}
</style>
<h3>Order #1042</h3>
<div class="row"><span>2 × Margherita</span><span>$19.00</span></div>
<div class="row"><span>1 × Lemonade</span><span>$4.50</span></div>
<div class="row"><strong>Total</strong><strong>$23.50</strong></div>
<div class="st"><span id="st">Order received</span> <span class="hint" id="at"></span></div>
<script>
const W = window.TelegramWidget;
function render() {
  let s = null;
  try { s = JSON.parse(W.chatData); } catch (e) {}
  if (!s) return;
  document.getElementById('st').textContent = s.status;
  document.getElementById('at').textContent = s.at ? 'as of ' + s.at : '';
}
if (W) W.onEvent('chatDataChanged', render);
render();
</script>

bot_order.py: send the card, then change its status three times:

import json
import time
import requests

TOKEN = "123456789:AAEexampleTokenReplaceWithYours"
API = f"https://api.telegram.org/bot{TOKEN}"
CHAT_ID = 123456789  # your private chat with the bot
HTML = open("order.html", encoding="utf-8").read()


def call(method, **params):
    r = requests.post(f"{API}/{method}", json=params, timeout=40).json()
    if not r["ok"]:
        if "message is not modified" in r.get("description", ""):
            return True  # the widget already shows this state
        raise RuntimeError(f"{method}: {r['description']}")
    return r["result"]


msg = call(
    "sendWidget",
    chat_id=CHAT_ID,
    html=HTML,
    chat_data=json.dumps({"status": "Order received"}),
    caption="Order #1042: $23.50",
    reply_markup={"inline_keyboard": [[
        {"text": "Track the order", "url": "https://example.com/orders/1042"},
    ]]},
)

for status in ["Cooking", "On the way", "Delivered"]:
    time.sleep(60)  # in a real bot: when your order system reports a change
    call(
        "editMessageWidgetData",
        chat_id=CHAT_ID,
        message_id=msg["message_id"],
        chat_data=json.dumps({"status": status, "at": time.strftime("%H:%M")}),
    )
// bot_order.mjs
import { readFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";

const TOKEN = "123456789:AAEexampleTokenReplaceWithYours";
const API = `https://api.telegram.org/bot${TOKEN}`;
const CHAT_ID = 123456789; // your private chat with the bot
const HTML = await readFile("order.html", "utf-8");

async function call(method, params = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
    signal: AbortSignal.timeout(40_000),
  });
  const r = await res.json();
  if (!r.ok) {
    if ((r.description ?? "").includes("message is not modified")) {
      return true; // the widget already shows this state
    }
    throw new Error(`${method}: ${r.description}`);
  }
  return r.result;
}

function hhmm() {
  return new Date().toTimeString().slice(0, 5); // like time.strftime("%H:%M")
}

const msg = await call("sendWidget", {
  chat_id: CHAT_ID,
  html: HTML,
  chat_data: JSON.stringify({ status: "Order received" }),
  caption: "Order #1042: $23.50",
  reply_markup: { inline_keyboard: [[
    { text: "Track the order", url: "https://example.com/orders/1042" },
  ]] },
});

for (const status of ["Cooking", "On the way", "Delivered"]) {
  await sleep(60_000); // in a real bot: when your order system reports a change
  await call("editMessageWidgetData", {
    chat_id: CHAT_ID,
    message_id: msg.message_id,
    chat_data: JSON.stringify({ status, at: hhmm() }),
  });
}

What the user sees: a card in the chat's colors with the items, the total and "Order received", the caption "Order #1042: $23.50" and a "Track the order" button below. Every minute the status line silently changes to "Cooking" with a grey "as of 19:40", and so on: widget edits produce no "edited" mark and no notification. Note the "as of" time: a status should read as a snapshot, not as a progress bar someone waits on.

Example 2: a counter with widget_query requests

A counter with +1 and Reset buttons. A tap calls TelegramWidget.request(); the bot updates the count, writes it into chat_data with editMessageWidgetData and answers with the same value through answerWidgetQuery, so the widget can show it at once. A revision number r makes the widget ignore an older state that arrives after a newer one.

counter.html (1215 bytes, 670 bytes compressed):

<style>
.n{font-size:2.4em;font-weight:600;text-align:center;font-variant-numeric:tabular-nums}
.row{display:flex;gap:8px}
.row button{flex:1}
#m{min-height:1.35em;margin-top:6px;text-align:center;color:var(--tg-theme-hint-color);font-size:.87em}
</style>
<div class="n" id="n">0</div>
<div class="row"><button id="like">+1</button><button id="reset">Reset</button></div>
<div id="m"></div>
<script>
const W = window.TelegramWidget, $ = (id) => document.getElementById(id);
let rev = -1;
function show(text) {
  let s = null;
  try { s = JSON.parse(text); } catch (e) {}
  if (!s || typeof s.n !== 'number' || s.r < rev) return false;
  rev = s.r;
  $('n').textContent = s.n;
  return true;
}
function ask(data) {
  if (!W) return;
  $('m').textContent = 'Sending…';
  W.request(data).then((a) => {
    $('m').textContent = show(a.result) ? '' : 'Send /start to get a new counter';
  }, (e) => {
    $('m').textContent = e.code === 'TIMEOUT' ? 'The bot did not answer' : 'Not sent: ' + e.code;
  });
}
$('like').addEventListener('click', () => ask('like'));
$('reset').addEventListener('click', () => ask('reset'));
if (W) {
  W.onEvent('chatDataChanged', () => show(W.chatData));
  show(W.chatData);
}
</script>

Key points in the widget code:

bot_counter.py: long polling with allowed_updates that includes widget_query:

import json
import time
import requests

TOKEN = "123456789:AAEexampleTokenReplaceWithYours"
API = f"https://api.telegram.org/bot{TOKEN}"
HTML = open("counter.html", encoding="utf-8").read()
counters = {}  # (chat_id, message_id) -> {"n": count, "r": revision}


def call(method, **params):
    r = requests.post(f"{API}/{method}", json=params, timeout=40).json()
    if r["ok"]:
        return r["result"]
    if "message is not modified" in r.get("description", ""):
        return True  # nothing to change: treat as success
    print(f"{method} failed: {r.get('description')}")
    return None


def dump(state):
    return json.dumps(state, separators=(",", ":"))


def send_counter(chat_id):
    state = {"n": 0, "r": 0}
    msg = call("sendWidget", chat_id=chat_id, html=HTML, chat_data=dump(state),
               caption="Tap +1 to count", allow_queries=True)
    if msg:
        counters[(chat_id, msg["message_id"])] = state


def on_widget_query(q):
    key = (q["chat"]["id"], q["message_id"])
    state = counters.get(key)
    if state is None or q["data"] not in ("like", "reset"):
        # unknown message (e.g. the bot restarted) or unknown data: answer anyway
        call("answerWidgetQuery", widget_query_id=q["id"])
        return
    new = {"n": state["n"] + 1 if q["data"] == "like" else 0, "r": state["r"] + 1}
    if call("editMessageWidgetData", chat_id=key[0], message_id=key[1],
            chat_data=dump(new)):
        counters[key] = new  # commit only after the edit went through
    call("answerWidgetQuery", widget_query_id=q["id"], data=dump(counters[key]))


def main():
    offset = 0
    while True:
        updates = call("getUpdates", offset=offset, timeout=30,
                       allowed_updates=["message", "widget_query"])
        if updates is None:
            time.sleep(3)
            continue
        for u in updates:
            offset = u["update_id"] + 1
            if "widget_query" in u:
                on_widget_query(u["widget_query"])
            elif u.get("message", {}).get("text") == "/start":
                send_counter(u["message"]["chat"]["id"])


main()
// bot_counter.mjs
import { readFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";

const TOKEN = "123456789:AAEexampleTokenReplaceWithYours";
const API = `https://api.telegram.org/bot${TOKEN}`;
const HTML = await readFile("counter.html", "utf-8");
const counters = new Map(); // "chat_id:message_id" -> {n: count, r: revision}

async function call(method, params = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
    signal: AbortSignal.timeout(40_000),
  });
  const r = await res.json();
  if (r.ok) return r.result;
  if ((r.description ?? "").includes("message is not modified")) {
    return true; // nothing to change: treat as success
  }
  console.log(`${method} failed: ${r.description}`);
  return null;
}

function dump(state) {
  return JSON.stringify(state); // already compact, like separators=(",", ":")
}

async function sendCounter(chatId) {
  const state = { n: 0, r: 0 };
  const msg = await call("sendWidget", {
    chat_id: chatId, html: HTML, chat_data: dump(state),
    caption: "Tap +1 to count", allow_queries: true,
  });
  if (msg) counters.set(`${chatId}:${msg.message_id}`, state);
}

async function onWidgetQuery(q) {
  const chatId = q.chat.id, messageId = q.message_id;
  const key = `${chatId}:${messageId}`;
  const state = counters.get(key);
  if (state === undefined || !["like", "reset"].includes(q.data)) {
    // unknown message (e.g. the bot restarted) or unknown data: answer anyway
    await call("answerWidgetQuery", { widget_query_id: q.id });
    return;
  }
  const next = { n: q.data === "like" ? state.n + 1 : 0, r: state.r + 1 };
  if (await call("editMessageWidgetData", {
    chat_id: chatId, message_id: messageId, chat_data: dump(next),
  })) {
    counters.set(key, next); // commit only after the edit went through
  }
  await call("answerWidgetQuery", { widget_query_id: q.id, data: dump(counters.get(key)) });
}

async function main() {
  let offset = 0;
  while (true) {
    const updates = await call("getUpdates", {
      offset, timeout: 30, allowed_updates: ["message", "widget_query"],
    });
    if (updates === null) {
      await sleep(3000);
      continue;
    }
    for (const u of updates) {
      offset = u.update_id + 1;
      if (u.widget_query) {
        await onWidgetQuery(u.widget_query);
      } else if (u.message?.text === "/start") {
        await sendCounter(u.message.chat.id);
      }
    }
  }
}

main();

What the user sees: after /start, a big "0" with two native buttons. A tap on +1 shows "Sending…", then the new number. If the bot is stopped, the widget shows "The bot did not answer" after 15 seconds (TIMEOUT). After a bot restart the in-memory dictionary is empty, so the bot answers without data and the widget asks the user to send /start; a real bot keeps its state in a database, keyed by chat and message.

Example 3: a live poll as a Telegram shared widget

One poll shown in many private chats with one set of results. The first sendWidget with is_shared and allow_queries creates the shared widget; the bot stores widget.id from the returned message and later shows the same poll to every user who sends /start with sendSharedWidget. Votes go to public_data through editSharedWidgetData, so every message showing the poll gets the new totals.

poll.html (1790 bytes, 963 bytes compressed):

<style>
.o{display:block;width:100%;margin:6px 0;text-align:left}
.me{outline:2px solid var(--tg-theme-button-color)}
.bar{height:4px;margin-top:4px;border-radius:2px;background:var(--tg-theme-button-color)}
.h{color:var(--tg-theme-hint-color);font-size:.87em}
</style>
<strong>Which language for the next tutorial?</strong>
<div id="list"></div>
<div class="h" id="msg"></div>
<script>
const W = window.TelegramWidget, $ = (id) => document.getElementById(id);
const OPTS = ['Python', 'JavaScript', 'Go'];
let st = { v: [0, 0, 0], r: -1 }, mine = null;
try { mine = JSON.parse(localStorage.getItem('vote')); } catch (e) {}
function take(text) {
  let s = null;
  try { s = JSON.parse(text); } catch (e) {}
  if (s && Array.isArray(s.v) && s.r >= st.r) { st = s; draw(); }
}
function draw() {
  const total = st.v.reduce((a, b) => a + b, 0);
  $('list').replaceChildren(...OPTS.map((name, i) => {
    const b = document.createElement('button');
    const pct = total ? Math.round(st.v[i] / total * 100) : 0;
    b.className = 'o' + (mine === i ? ' me' : '');
    b.innerHTML = name + ' <span class="h">' + pct + '% (' + st.v[i] + ')</span><div class="bar" style="width:' + pct + '%"></div>';
    b.addEventListener('click', () => vote(i));
    return b;
  }));
}
function vote(i) {
  if (!W) return;
  $('msg').textContent = 'Sending…';
  W.request('vote:' + i).then((a) => {
    mine = i;
    try { localStorage.setItem('vote', String(i)); } catch (e) {}
    $('msg').textContent = 'Vote counted';
    take(a.result);
    draw();
  }, (e) => {
    $('msg').textContent = e.code === 'NOT_ALLOWED' ? 'Open the bot to vote' : 'Not sent: ' + e.code;
  });
}
if (W) {
  W.onEvent('publicDataChanged', () => take(W.publicData));
  W.watchPublicData();
  take(W.publicData);
}
draw();
</script>

The widget calls watchPublicData(): without it a shared widget already on screen would get the new shared state only when the message is loaded again. While the poll is visible, the app polls the shared state at the widget's refresh period, which the bot sets to 10 seconds with cache_time. The user's own choice is kept in localStorage, which belongs to this message on this device.

bot_poll.py: votes keyed by user, edits coalesced to one per second:

import json
import time
import requests

TOKEN = "123456789:AAEexampleTokenReplaceWithYours"
API = f"https://api.telegram.org/bot{TOKEN}"
ADMIN_CHAT_ID = 123456789  # your own private chat with the bot
HTML = open("poll.html", encoding="utf-8").read()
OPTIONS = 3
DB_FILE = "poll.json"

try:
    with open(DB_FILE) as f:
        db = json.load(f)
except FileNotFoundError:
    db = {"widget_id": None, "votes": {}, "r": 0}  # votes: user id -> option
dirty, last_edit = False, 0.0


def save():
    with open(DB_FILE, "w") as f:
        json.dump(db, f)


def call(method, **params):
    r = requests.post(f"{API}/{method}", json=params, timeout=40).json()
    if r["ok"]:
        return r["result"]
    if "message is not modified" in r.get("description", ""):
        return True
    print(f"{method} failed: {r.get('description')}")
    return None


def public_state():
    v = [0] * OPTIONS
    for option in db["votes"].values():
        v[option] += 1
    return json.dumps({"v": v, "r": db["r"]}, separators=(",", ":"))


def flush():
    """Write the shared state at most once per second (the shared widget limit)."""
    global dirty, last_edit
    if dirty and time.monotonic() - last_edit >= 1:
        last_edit = time.monotonic()
        if call("editSharedWidgetData", widget_id=db["widget_id"],
                public_data=public_state(), cache_time=10):
            dirty = False


def on_query(q):
    global dirty
    data = q["data"]
    if q.get("widget_id") == db["widget_id"] and data.startswith("vote:") \
            and data[5:].isdigit() and int(data[5:]) < OPTIONS:
        db["votes"][str(q["from"]["id"])] = int(data[5:])  # one vote per user
        db["r"] += 1
        save()
        dirty = True
    # the voter sees the new counts at once; everyone else gets them via the edit
    call("answerWidgetQuery", widget_query_id=q["id"], data=public_state())


def main():
    if not db["widget_id"]:
        # the first send with is_shared creates the shared widget
        msg = call("sendWidget", chat_id=ADMIN_CHAT_ID, html=HTML,
                   public_data=public_state(), is_shared=True, allow_queries=True,
                   caption="Poll: which language for the next tutorial?")
        db["widget_id"] = msg["widget"]["id"]
        save()
    offset = 0
    while True:
        updates = call("getUpdates", offset=offset, timeout=1 if dirty else 25,
                       allowed_updates=["message", "widget_query", "shared_widget_query"])
        if updates is None:
            time.sleep(3)
            continue
        for u in updates:
            offset = u["update_id"] + 1
            q = u.get("widget_query") or u.get("shared_widget_query")
            if q:
                on_query(q)
            elif u.get("message", {}).get("text") == "/start":
                call("sendSharedWidget", chat_id=u["message"]["chat"]["id"],
                     widget_id=db["widget_id"],
                     caption="Poll: which language for the next tutorial?")
        flush()


main()
// bot_poll.mjs
import { readFile, writeFile } from "node:fs/promises";
import { setTimeout as sleep } from "node:timers/promises";

const TOKEN = "123456789:AAEexampleTokenReplaceWithYours";
const API = `https://api.telegram.org/bot${TOKEN}`;
const ADMIN_CHAT_ID = 123456789; // your own private chat with the bot
const HTML = await readFile("poll.html", "utf-8");
const OPTIONS = 3;
const DB_FILE = "poll.json";

let db;
try {
  db = JSON.parse(await readFile(DB_FILE, "utf-8"));
} catch (e) {
  if (e.code !== "ENOENT") throw e;
  db = { widget_id: null, votes: {}, r: 0 }; // votes: user id -> option
}
let dirty = false, lastEdit = -Infinity;

async function save() {
  await writeFile(DB_FILE, JSON.stringify(db));
}

async function call(method, params = {}) {
  const res = await fetch(`${API}/${method}`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(params),
    signal: AbortSignal.timeout(40_000),
  });
  const r = await res.json();
  if (r.ok) return r.result;
  if ((r.description ?? "").includes("message is not modified")) return true;
  console.log(`${method} failed: ${r.description}`);
  return null;
}

function publicState() {
  const v = new Array(OPTIONS).fill(0);
  for (const option of Object.values(db.votes)) v[option] += 1;
  return JSON.stringify({ v, r: db.r });
}

// Write the shared state at most once per second (the shared widget limit).
async function flush() {
  const now = performance.now() / 1000; // monotonic seconds
  if (dirty && now - lastEdit >= 1) {
    lastEdit = now;
    if (await call("editSharedWidgetData", {
      widget_id: db.widget_id, public_data: publicState(), cache_time: 10,
    })) {
      dirty = false;
    }
  }
}

async function onQuery(q) {
  const data = q.data;
  const digits = data.slice(5);
  if (q.widget_id === db.widget_id && data.startsWith("vote:")
      && /^\d+$/.test(digits) && Number(digits) < OPTIONS) {
    db.votes[String(q.from.id)] = Number(digits); // one vote per user
    db.r += 1;
    await save();
    dirty = true;
  }
  // the voter sees the new counts at once; everyone else gets them via the edit
  await call("answerWidgetQuery", { widget_query_id: q.id, data: publicState() });
}

async function main() {
  if (!db.widget_id) {
    // the first send with is_shared creates the shared widget
    const msg = await call("sendWidget", {
      chat_id: ADMIN_CHAT_ID, html: HTML,
      public_data: publicState(), is_shared: true, allow_queries: true,
      caption: "Poll: which language for the next tutorial?",
    });
    db.widget_id = msg.widget.id;
    await save();
  }
  let offset = 0;
  while (true) {
    const updates = await call("getUpdates", {
      offset, timeout: dirty ? 1 : 25,
      allowed_updates: ["message", "widget_query", "shared_widget_query"],
    });
    if (updates === null) {
      await sleep(3000);
      continue;
    }
    for (const u of updates) {
      offset = u.update_id + 1;
      const q = u.widget_query || u.shared_widget_query;
      if (q) {
        await onQuery(q);
      } else if (u.message?.text === "/start") {
        await call("sendSharedWidget", {
          chat_id: u.message.chat.id,
          widget_id: db.widget_id,
          caption: "Poll: which language for the next tutorial?",
        });
      }
    }
    await flush();
  }
}

main();

What the user sees: three native buttons with percentages and bars. After a tap, "Vote counted", the user's option is outlined and the counts include their vote immediately (from the answer). Other users' votes appear within about 10 seconds, without reopening the chat.

Example 4: browser preview, size check and errors

A widget is HTML, so a desktop browser window 320–430 px wide gives a quick first look. Outside Telegram there is no TelegramWidget, so put a stand-in above the widget code. Keep it in its own file, stub.html, so it never ends up in what you send. This is a shortened version of the stand-in from the official docs, preset for the counter:

<style>:root{--tg-theme-bg-color:#fff;--tg-theme-text-color:#000;--tg-theme-hint-color:#707579;
--tg-theme-link-color:#3390ec;--tg-theme-button-color:#3390ec;--tg-theme-button-text-color:#fff;
--tg-theme-secondary-bg-color:#f1f1f4}body{max-width:360px}</style>
<script>
window.TelegramWidget = window.TelegramWidget || {
  profile: 1, colorScheme: 'light', themeParams: {}, isActive: true, isPreview: false,
  isForward: false, chatType: 'private', viewer: { id: 1, first_name: 'Test' },
  chatData: '{"n":4,"r":1}', publicData: null, wallet: null,
  HapticFeedback: { impactOccurred() { return this; }, notificationOccurred() { return this; }, selectionChanged() { return this; } },
  onEvent() {}, offEvent() {}, ready() {}, watchPublicData() {}, unwatchPublicData() {},
  openLink: (url) => console.log('openLink', url), openTelegramLink: (url) => console.log('openTelegramLink', url),
  copyText: (text) => console.log('copyText', text),
  request: (data) => { console.log('request', data); return Promise.resolve({ result: '{"n":5,"r":2}' }); },
};
</script>

preview.py glues the stub and a widget into preview.html:

import sys

stub = open("stub.html", encoding="utf-8").read()
widget = open(sys.argv[1], encoding="utf-8").read()
with open("preview.html", "w", encoding="utf-8") as f:
    f.write(stub + widget)
print("Open preview.html in a browser window 320-430 px wide")
// preview.mjs
import { readFile, writeFile } from "node:fs/promises";

const stub = await readFile("stub.html", "utf-8");
const widget = await readFile(process.argv[2], "utf-8");
await writeFile("preview.html", stub + widget, "utf-8");
console.log("Open preview.html in a browser window 320-430 px wide");

Run python3 preview.py counter.html, open preview.html and watch the console for request like. Set chatData, publicData, viewer and isForward to the cases you want to see. Remember that a browser draws things Telegram removes (inputs, vh, scrolling) and enforces none of the limits.

check_widget.py counts the size exactly as the server does (Python's zlib at level 9) before you send. The Node.js version is handy in a JavaScript project, but Node's zlib can be a few bytes off, so near 4096 trust the Python number:

import sys
import zlib

raw = open(sys.argv[1], "rb").read()
raw.decode("utf-8")  # raises UnicodeDecodeError on invalid UTF-8
packed = len(zlib.compress(raw, 9))
print(f"{len(raw)} bytes, {packed} bytes after zlib level 9")
if b"\x00" in raw:
    sys.exit("NUL character: the server answers INPUT_MEDIA_WIDGET_HTML_INVALID")
if len(raw) > 32768 or packed > 4096:
    sys.exit("too large: the server answers INPUT_MEDIA_WIDGET_TOO_LARGE")
print("OK")
// check_widget.mjs
import { readFile } from "node:fs/promises";
import { deflateSync } from "node:zlib";

function fail(message) {
  console.error(message);
  process.exit(1);
}

const raw = await readFile(process.argv[2]);
new TextDecoder("utf-8", { fatal: true }).decode(raw); // throws TypeError on invalid UTF-8
// Node's bundled zlib can differ from the server's (Python) by a few bytes:
// keep a small margin below 4096
const packed = deflateSync(raw, { level: 9 }).length;
console.log(`${raw.length} bytes, ${packed} bytes after zlib level 9`);
if (raw.includes(0)) {
  fail("NUL character: the server answers INPUT_MEDIA_WIDGET_HTML_INVALID");
}
if (raw.length > 32768 || packed > 4096) {
  fail("too large: the server answers INPUT_MEDIA_WIDGET_TOO_LARGE");
}
console.log("OK");
$ python3 check_widget.py counter.html
1215 bytes, 670 bytes after zlib level 9
OK

Errors you may get from the Bot API while working with these examples:

ErrorCauseFix
INPUT_MEDIA_WIDGET_TOO_LARGEHTML over 32768 bytes or over 4096 bytes compressedRemove comments and dead code, prefer SVG and CSS to data: images
INPUT_MEDIA_WIDGET_HTML_INVALIDInvalid UTF-8 or a NUL character in the HTMLRead the file as UTF-8 text and send it as a string
INPUT_MEDIA_WIDGET_DATA_TOO_LARGEchat_data or public_data over 1024 bytesShort keys, compact JSON (separators=(",", ":"))
message is not modifiedThe edit sets the state it already hasTreat as success
query is too oldanswerWidgetQuery after 15 secondsAnswer first, do slow work afterwards
invalid cache time specifiedcache_time below 5Use 5–3600 seconds

And in the widget, the code of a rejected request: NOT_ALLOWED (no allow_queries, no tap, a preview or a forward of a static widget), BUSY (one request at a time), RATE_LIMITED (over 5 requests per 5 seconds), TIMEOUT, FAILED and INVALID_ANSWER. Data that is empty or longer than 64 bytes throws a TypeError before anything is sent.

Checklist before sending a widget to users

  1. The compressed size is under 4096 bytes (check_widget.py).
  2. The widget draws something useful from null state and when TelegramWidget is missing.
  3. Colors come from --tg-theme-* variables; checked in light and dark chat themes.
  4. The message has a caption, which is what notifications and older apps show.
  5. The bot answers every widget_query within 15 seconds, and allowed_updates lists widget_query and shared_widget_query.
  6. Edits are rate-limited on your side and "message is not modified" is not treated as an error.

All properties, events and limits used here are listed in the TelegramWidget JavaScript API reference; the official documentation is at core.telegram.org/bots/widgets. For the rest of the 10.4 release, see what's new in Bot API 10.

Frequently asked questions

How do I send HTML to the sendWidget method?

Pass the whole document as the string parameter html. Send the request as JSON, for example requests.post(url, json={"chat_id": 123456789, "html": html}) in Python, so quotes and line breaks in the HTML are encoded correctly.

Why does my widget show TIMEOUT after a tap?

The bot did not call answerWidgetQuery within 15 seconds. Usually the bot is not running, or it passes allowed_updates without widget_query (and shared_widget_query), so it never receives the query.

What should I do with "message is not modified" from editMessageWidgetData?

Treat it as success: the widget already has that state. It happens when the new chat_data or public_data equals the current one. Still answer the widget query that triggered the edit.

How do I make a live poll with a Telegram shared widget?

Send the widget once with is_shared and allow_queries, store widget.id, send it to other chats with sendSharedWidget, count votes per (widget_id, from.id) and write the totals with editSharedWidgetData at most once per second. The widget must call watchPublicData().

How can I preview a widget in a browser?

Outside Telegram window.TelegramWidget is undefined, so put a small stand-in object and the theme variables above the widget's code in a separate preview file. A browser does not enforce the widget profile or limits, so test in Telegram before sending to users.

How to Create a Telegram Bot: Step by Step with BotFather and Python

How to create a Telegram bot step by step: register it with @BotFather, get the token, test it with getMe and send a first message with curl or Python.

Telegram Bot API 10.0–10.5: Bot Settings, Widgets, Rich Messages, Ephemeral Messages, Guest Mode and More

What's new in Telegram Bot API 10.0–10.5: setMySettings and BotFullInfo, HTML widgets, rich and ephemeral messages, guest mode, with JSON examples.

Telegram Bot API Limits: Rate Limits, 429 Errors, File Sizes and Message Length

Telegram Bot API rate limits explained: 30 msg/s, 1 msg/s per chat, 20/min in groups, handling 429 retry_after, plus file size and message length limits.

How to Send a Message with the Telegram Bot API (sendMessage)

Telegram Bot API send message guide: sendMessage with curl, Python and JavaScript, HTML and MarkdownV2 formatting, inline buttons and error fixes.

Telegram Bot Token: How to Get It, Find It Again, Check It and Keep It Safe

Telegram bot token guide: get one from @BotFather, find the token of an existing bot, check it with getMe, revoke a leaked token and store it safely.

How to Set Up a Telegram Bot Webhook: setWebhook, Secret Token and Troubleshooting

Set up a Telegram bot webhook: setWebhook URL requirements, secret_token header check, getWebhookInfo debugging, deleteWebhook and fixes for n8n.

How to Get a Telegram Chat ID for a User, Group, Channel or Topic

How to get a Telegram chat ID for a user, group, supergroup, channel or forum topic with getUpdates, plus fixes for an empty result and 409 Conflict.

Telegram Test Server: How to Test a Bot in the Telegram Test Environment

Use the Telegram test server for bots: log in to the test environment, create a test bot, call the Bot API via /test/ and switch our tester to TEST.

Telegram Widgets for Your Website: Login Widget, Post Embed, Discussion and Share Button

Add Telegram to your website: the new Telegram Login (OIDC), the legacy Login Widget with hash check code, post embeds, comments and a share button.

TelegramWidget JavaScript API: Reference, Events, Error Codes and Limits

TelegramWidget JavaScript API reference: properties, request(), events, error codes, CSS variables, widget_query and answerWidgetQuery, plus every limit.

Telegram Widgets: Interactive HTML Inside Bot Messages

Telegram widgets (Bot API 10.4): what they are, how sendWidget, chat_data and public_data work, where they run today and how they differ from Mini Apps.

How to Test a Telegram Mini App: From Browser Mock to Real Telegram

Test a Telegram Mini App step by step: browser mock mode, localhost via HTTPS tunnel, test environment, DevTools per platform, initData validation.