# Telegram inline keyboards and callback queries

> Build Telegram inline keyboards, read callback_query updates, stop the spinner with answerCallbackQuery and edit the message in place.

Published 2026-11-02. Z-API Omni team.

Attach an `InlineKeyboardMarkup` to a message through `reply_markup`, give each button a `callback_data` string of 1 to 64 bytes, and read the press as a `callback_query` update. Then call `answerCallbackQuery` with the query's `id`. Until you do, Telegram clients show a progress bar on the button. Change the result in place with `editMessageText` or `editMessageReplyMarkup`. Quotes are from the Bot API reference, version 10.3 of 2026-08-24, unless marked as the features page ([Telegram Bot API, accessed 2026-11-02](https://core.telegram.org/bots/api)).

## How an inline keyboard is built

Telegram defines the inline keyboard as one "that appears right next to the message it belongs to." Its single required field, `inline_keyboard`, is an "Array of button rows, each represented by an Array of InlineKeyboardButton objects". So the outer array holds rows, and each inner array holds the buttons on one row. Telegram doesn't state a maximum number of rows or buttons in the reference.

Pressing an inline button "doesn't send messages to the chat", per Telegram's features page ([Bot features, accessed 2026-11-02](https://core.telegram.org/bots/features#inline-keyboards)). The press goes to your bot as an update, and the chat history stays as it was.

Version 10.3 added an optional `force_reply` field to the markup: "Pass True if the reply interface must be shown to the user." You can't change it later by editing the keyboard.

## Button types

Each button has a `text` label plus exactly one field that sets its type. In Telegram's words, "Exactly one of the fields other than text, icon_custom_emoji_id, and style must be used to specify the type of the button."

| Field | What the press does |
| --- | --- |
| `callback_data` | Sends a callback query to your bot with this data, 1-64 bytes |
| `url` | Opens an HTTP or `tg://` URL, including `tg://user?id=<user_id>` |
| `web_app` | Launches a Web App from an HTTPS URL; private chats only |
| `login_url` | Opens a URL with Telegram Login authorization |
| `switch_inline_query`, `switch_inline_query_current_chat`, `switch_inline_query_chosen_chat` | Starts inline mode with a query |
| `copy_text` | Copies text to the clipboard |
| `callback_game` | Launches a game; must be the first button in the first row |
| `pay` | Pay button for invoice messages; first button in the first row |
| `disabled` | A `DisabledButton`, which "does nothing" |

Two more fields change how a button looks without changing what it does. `style` takes `danger`, `success` or `primary`, and `icon_custom_emoji_id` puts a custom emoji on it.

The 64-byte limit is in bytes. Telegram doesn't say which encoding it counts, but JSON strings travel as UTF-8, so a `callback_data` value in Cyrillic or with emoji uses more than one byte per character. Measure with `Buffer.byteLength` in Node or `len(s.encode())` in Python. Store real state in your database and put a short key in `callback_data`, such as `order:8812:cancel`.

## Sending a keyboard

`sendMessage` takes the keyboard in `reply_markup`, which Telegram describes as "A JSON-serialized object for an inline keyboard". A message with two rows:

```bash
curl -s "https://api.telegram.org/bot$BOT_TOKEN/sendMessage" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": '"$CHAT_ID"',
    "text": "Order 8812 is ready to ship.",
    "reply_markup": {
      "inline_keyboard": [
        [
          {"text": "Ship now", "callback_data": "order:8812:ship", "style": "success"},
          {"text": "Cancel", "callback_data": "order:8812:cancel", "style": "danger"}
        ],
        [
          {"text": "Track on the website", "url": "https://example.com/orders/8812"}
        ]
      ]
    }
  }'
```

## What a callback query contains

Telegram publishes no full JSON sample of a callback update. The one below is built from the `Update` and `CallbackQuery` field tables, with placeholder values.

```json
{
  "update_id": 100000001,
  "callback_query": {
    "id": "CALLBACK_QUERY_ID",
    "from": {"id": 111111111, "is_bot": false, "first_name": "Ana"},
    "message": {"message_id": 42, "chat": {"id": 111111111, "type": "private"}, "date": 1762041600, "text": "Order 8812 is ready to ship."},
    "chat_instance": "CHAT_INSTANCE",
    "data": "order:8812:ship"
  }
}
```

`id` is what you pass back to `answerCallbackQuery`. `data` is your `callback_data`. `chat_instance` is a "Global identifier, uniquely corresponding to the chat to which the message with the callback button was sent."

The `message` field is optional. Telegram says it is present "If the button that originated the query was attached to a message sent by the bot." Its type is `MaybeInaccessibleMessage`, so check it before reading `text` or `chat`. A keyboard on a message sent in inline mode gives you `inline_message_id` instead. A game button fills `game_short_name` instead of `data`.

## Answer every callback query

The spinner keeps turning until you answer. Telegram's note reads: "After the user presses a callback button, Telegram clients will display a progress bar until you call answerCallbackQuery." Call it even when you have nothing to show.

| Parameter | Behavior |
| --- | --- |
| `callback_query_id` | Required. "Unique identifier for the query to be answered" |
| `text` | Notification text, 0-200 characters. "If not specified, nothing will be shown to the user" |
| `show_alert` | If true, the client shows an alert "instead of a notification at the top of the chat screen" |
| `url` | Only for `callback_game` buttons |
| `cache_time` | Seconds the client may cache the answer. "Defaults to 0" |

Answer first and do slow work after. If your handler waits on a database or an external API before answering, the user watches the spinner for the whole call.

## Edit the message instead of sending a new one

Telegram's features page recommends editing the keyboard "when the user toggles a setting button or navigates to a new page". It calls this "both faster and smoother than sending a whole new message and deleting the previous one."

`editMessageText` changes the text, 1-4096 characters after entity parsing, and can take a new `reply_markup` in the same call. `editMessageReplyMarkup` changes only the buttons. It takes `chat_id` plus `message_id`, or `inline_message_id` for inline messages. It returns the edited `Message`, or `true` for an inline message. Editing is "currently only possible" for messages without `reply_markup` or with inline keyboards. Business messages not sent by the bot and without an inline keyboard can only be edited within 48 hours.

A webhook handler in Node.js 18 or later that answers the press, then replaces the text and removes the buttons:

```js
// callbacks.mjs. Run: BOT_TOKEN=... PORT=8080 node callbacks.mjs  (webhook already set to this server)
import http from 'node:http';

const api = (method, body) =>
  fetch(`https://api.telegram.org/bot${process.env.BOT_TOKEN}/${method}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
  }).then((r) => r.json());

http.createServer((req, res) => {
  const chunks = [];
  req.on('data', (c) => chunks.push(c));
  req.on('end', async () => {
    res.writeHead(200).end();
    let update;
    try { update = JSON.parse(Buffer.concat(chunks).toString('utf8')); } catch { return; }
    const q = update.callback_query;
    if (!q) return;

    const [, orderId, action] = (q.data ?? '').split(':');
    await api('answerCallbackQuery', { callback_query_id: q.id, text: `Order ${orderId}: ${action}` });
    if (!['ship', 'cancel'].includes(action)) return;

    const text = action === 'ship' ? `Order ${orderId} shipped.` : `Order ${orderId} cancelled.`;
    const target = q.inline_message_id
      ? { inline_message_id: q.inline_message_id }
      : { chat_id: q.message?.chat?.id, message_id: q.message?.message_id };
    if (target.inline_message_id || target.chat_id) {
      await api('editMessageText', { ...target, text, reply_markup: { inline_keyboard: [] } });
    }
  });
}).listen(process.env.PORT || 8080);
```

Sending an empty `inline_keyboard` array removes the buttons once the first press is handled. Two fast taps can still arrive before the edit, so make the order action idempotent on your side. This server skips the secret token check to stay short. Add the `X-Telegram-Bot-Api-Secret-Token` comparison from [Telegram webhook setup with a secret token](/academy/articles/telegram-bot-api-webhook-setup-secret-token/) before you expose it.

Every answer and every edit is a Bot API call. Telegram doesn't document whether edits and callback answers count toward its sending limits, which are covered in [Telegram Bot API limits and retry_after](/academy/articles/telegram-bot-api-rate-limits-flood-429/). WhatsApp has its own version of tappable options, with fixed button counts and title lengths, in [WhatsApp interactive buttons and lists](/academy/articles/whatsapp-interactive-buttons-list-messages-limits/).

*Z-API Omni team*
