Telegram Bot API

Telegram Bot Keyboards: Inline Keyboard, Callback Buttons and Reply Keyboard

· 9 min read

A Telegram inline keyboard is a set of buttons attached to a bot message: you pass an InlineKeyboardMarkup object in the reply_markup parameter of sendMessage, and a press on a callback button sends your bot a callback_query update that you must answer with answerCallbackQuery. A reply keyboard (ReplyKeyboardMarkup) instead replaces the user's letter keyboard with predefined answers. This guide covers both kinds of Telegram bot buttons, every button type, editing the message after a press and a complete working example in Python and JavaScript.

Inline keyboard vs reply keyboard

Inline keyboardReply keyboard
ObjectInlineKeyboardMarkupReplyKeyboardMarkup
Where it appearsUnder a specific messageIn place of the user's keyboard
What a press doesCallback query, opens a URL, Mini App, inline mode, copies text…Sends the button text as a message, or shares a contact, location, users, chat
Can be edited laterYes, with editMessageReplyMarkupNo, send a new keyboard or remove it
ChannelsSupportedNot supported

Both go into the same reply_markup parameter, together with ReplyKeyboardRemove and ForceReply. A message carries only one of these four objects.

Send a Telegram inline keyboard

inline_keyboard is an array of rows, each row an array of buttons:

curl -X POST "https://api.telegram.org/bot123456789:AAEexampleTokenReplaceWithYours/sendMessage" \
  -H "Content-Type: application/json" \
  -d '{
    "chat_id": 123456789,
    "text": "Choose an option:",
    "reply_markup": {
      "inline_keyboard": [
        [{"text": "Like", "callback_data": "like"}, {"text": "Help", "callback_data": "help"}],
        [{"text": "Bot API docs", "url": "https://core.telegram.org/bots/api"}]
      ]
    }
  }'

Besides text, each button must have exactly one field that defines its type:

FieldWhat the button does
callback_dataSends a callback query with this string to the bot, 1–64 bytes
urlOpens an HTTP or tg:// link
web_appLaunches a Mini App; only in private chats between the user and the bot
login_urlOpens an HTTPS URL and authorizes the user on your site
switch_inline_query, switch_inline_query_current_chat, switch_inline_query_chosen_chatPuts the bot's username and a query into the input field of another chat, the current chat or a chat of a chosen type
copy_textCopies {"text": "…"} (1–256 characters) to the clipboard
payPay button; only in invoice messages, must be the first button in the first row
callback_gameLaunches a game; must be the first button in the first row
disabledA DisabledButton that does nothing (Bot API 10.3)

Two optional fields change the look of a button (Bot API 9.4, also available on reply keyboard buttons): style with "danger" (red), "success" (green) or "primary" (blue), and icon_custom_emoji_id for a custom emoji before the text. Custom emoji work only if the bot can use them: it has purchased additional usernames on Fragment, or its owner has Telegram Premium and the message is sent directly to a private chat, group or supergroup.

Designing callback_data

The 64-byte limit counts bytes, not characters, so keep values short and machine-readable, for example like, page:3 or del:8812, and keep the real data in your database. The API also warns that the message may contain no button with the data you receive, so treat it as untrusted user input: parse it, validate it and check that the user is allowed to perform the action. Too long a value is rejected when you send the keyboard, typically with Bad Request: BUTTON_DATA_INVALID.

Answer every press with answerCallbackQuery

A press on a callback button produces an update with a callback_query field: id, from (the user), data and, for messages sent by the bot, message with the original message. After the press, Telegram clients show a progress indicator until the bot calls answerCallbackQuery, so call it every time, even with no parameters besides the id.

ParameterMeaning
callback_query_idRequired, the id of the callback query
textNotification text, 0–200 characters; nothing is shown if omitted
show_alerttrue shows an alert instead of a notification at the top of the chat
urlA game URL (for callback_game buttons) or a link like t.me/your_bot?start=XXXX
cache_timeSeconds the result may be cached on the client, default 0

Answer quickly: an old query fails with Bad Request: query is too old and response timeout expired or query ID is invalid. See the answerCallbackQuery reference for details.

Edit the message after a press

Updating the existing message is faster and cleaner than sending a new one, and Telegram recommends it for settings and pagination. Take chat.id and message_id from callback_query.message and call:

If the new text and keyboard are identical to the current ones, the API returns Bad Request: message is not modified, so compare before editing or ignore that specific error.

Full example: inline menu with callback buttons

This bot answers /start with a menu, counts likes per message, shows an alert for Help and edits the message on every change. It uses getUpdates long polling, so it runs on localhost without a webhook. Set BOT_TOKEN in the environment first.

import os
import requests

TOKEN = os.environ["BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}"
likes = {}  # (chat_id, message_id) -> count


def call(method, **params):
    data = requests.post(f"{API}/{method}", json=params, timeout=40).json()
    if not data["ok"]:
        raise RuntimeError(f"{method}: {data['error_code']} {data['description']}")
    return data["result"]


def menu(count):
    return {"inline_keyboard": [
        [{"text": f"Like ({count})", "callback_data": "like", "style": "success"},
         {"text": "Reset", "callback_data": "reset", "style": "danger"}],
        [{"text": "Help", "callback_data": "help"},
         {"text": "Bot API docs", "url": "https://core.telegram.org/bots/api"}],
    ]}


def on_callback(cq):
    msg, data = cq.get("message"), cq.get("data")
    if not msg or data not in ("like", "reset", "help"):
        call("answerCallbackQuery", callback_query_id=cq["id"], text="Unknown button")
        return
    if data == "help":
        call("answerCallbackQuery", callback_query_id=cq["id"], show_alert=True,
             text="Like adds one, Reset starts over.")
        return
    key = (msg["chat"]["id"], msg["message_id"])
    old = likes.get(key, 0)
    new = old + 1 if data == "like" else 0
    call("answerCallbackQuery", callback_query_id=cq["id"],
         text="Thanks!" if data == "like" else "Counter reset")
    if new != old:  # avoid "message is not modified"
        likes[key] = new
        call("editMessageText", chat_id=key[0], message_id=key[1],
             text=f"Likes: {new}", reply_markup=menu(new))


offset = 0
while True:
    updates = call("getUpdates", offset=offset, timeout=30,
                   allowed_updates=["message", "callback_query"])
    for update in updates:
        offset = update["update_id"] + 1
        if "callback_query" in update:
            on_callback(update["callback_query"])
        elif update.get("message", {}).get("text") == "/start":
            chat_id = update["message"]["chat"]["id"]
            call("sendMessage", chat_id=chat_id, text="Likes: 0", reply_markup=menu(0))
const TOKEN = process.env.BOT_TOKEN;
const API = `https://api.telegram.org/bot${TOKEN}`;
const likes = new Map(); // "chatId:messageId" -> count

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 data = await res.json();
  if (!data.ok) throw new Error(`${method}: ${data.error_code} ${data.description}`);
  return data.result;
}

function menu(count) {
  return { inline_keyboard: [
    [{ text: `Like (${count})`, callback_data: "like", style: "success" },
     { text: "Reset", callback_data: "reset", style: "danger" }],
    [{ text: "Help", callback_data: "help" },
     { text: "Bot API docs", url: "https://core.telegram.org/bots/api" }],
  ] };
}

async function onCallback(cq) {
  const msg = cq.message;
  const data = cq.data;
  if (!msg || !["like", "reset", "help"].includes(data)) {
    await call("answerCallbackQuery", { callback_query_id: cq.id, text: "Unknown button" });
    return;
  }
  if (data === "help") {
    await call("answerCallbackQuery", { callback_query_id: cq.id, show_alert: true,
      text: "Like adds one, Reset starts over." });
    return;
  }
  const key = `${msg.chat.id}:${msg.message_id}`;
  const old = likes.get(key) ?? 0;
  const next = data === "like" ? old + 1 : 0;
  await call("answerCallbackQuery", { callback_query_id: cq.id,
    text: data === "like" ? "Thanks!" : "Counter reset" });
  if (next !== old) { // avoid "message is not modified"
    likes.set(key, next);
    await call("editMessageText", { chat_id: msg.chat.id, message_id: msg.message_id,
      text: `Likes: ${next}`, reply_markup: menu(next) });
  }
}

let offset = 0;
while (true) {
  const updates = await call("getUpdates", { offset, timeout: 30,
    allowed_updates: ["message", "callback_query"] });
  for (const update of updates) {
    offset = update.update_id + 1;
    if (update.callback_query) {
      await onCallback(update.callback_query);
    } else if (update.message?.text === "/start") {
      await call("sendMessage", { chat_id: update.message.chat.id, text: "Likes: 0",
        reply_markup: menu(0) });
    }
  }
}

Save the JavaScript version as bot.mjs (it uses top-level await) and run it with Node.js 18+. The counter lives in memory; a real bot stores it in a database. Drop the style fields if you want the default button colors.

Reply keyboard in Telegram

A reply keyboard offers predefined answers. A plain text button, which can also be written as just a string, sends its text to the chat as if the user typed it, so your bot handles it like any other message:

{
  "keyboard": [
    ["Catalog", "Cart"],
    [{"text": "Share my phone", "request_contact": true},
     {"text": "Send location", "request_location": true}]
  ],
  "resize_keyboard": true,
  "one_time_keyboard": true,
  "input_field_placeholder": "Choose a section"
}
FieldEffect
resize_keyboardFits the height to the number of rows; by default the keyboard is as tall as the standard one
one_time_keyboardHides the keyboard after a press; the user can open it again with the keyboard icon
is_persistentAlways shows the keyboard when the regular keyboard is hidden
input_field_placeholderPlaceholder in the input field, 1–64 characters
selectiveShows the keyboard only to @mentioned users or the sender of the replied-to message

Special buttons work in private chats only: request_contact sends the user's phone number as a contact, request_location their current location, request_poll asks them to create a poll, and web_app launches a Mini App. request_users (KeyboardButtonRequestUsers) and request_chat (KeyboardButtonRequestChat) open a picker and return the result in the users_shared and chat_shared service messages; both need a request_id, a signed 32-bit number unique within the message:

{"keyboard": [[
  {"text": "Pick a user", "request_users": {"request_id": 1, "user_is_bot": false, "max_quantity": 3}},
  {"text": "Pick my group", "request_chat": {"request_id": 2, "chat_is_channel": false, "chat_is_created": true}}
]], "resize_keyboard": true}

ReplyKeyboardRemove and ForceReply

A reply keyboard stays visible until the bot sends another one. To remove it, send a message with {"remove_keyboard": true}. ForceReply, {"force_reply": true, "input_field_placeholder": "Your city"}, opens the reply interface to the bot's message, as if the user tapped Reply. It is handy for step-by-step input in groups, because the answer reaches the bot even with privacy mode on. Like reply keyboards, neither object works in channels.

Try it in the Bot API Tester

  1. Open sendMessage in the Bot API Tester and enter your token and chat id.
  2. Paste one of the JSON keyboards above into reply_markup and execute.
  3. Press a callback button in Telegram, then run getUpdates in the tester to see the callback_query update, and answer it with answerCallbackQuery.

Troubleshooting Telegram bot buttons

SymptomCause and fix
Loading indicator after a pressNo answerCallbackQuery call. Answer every callback query.
No callback_query updatesallowed_updates doesn't include callback_query, or another process consumes the updates (a webhook or a second polling instance).
BUTTON_DATA_INVALIDcallback_data is empty or longer than 64 bytes.
message is not modifiedThe edit doesn't change the text or the keyboard.
query is too old…The answer came too late, for example after a restart processed old updates.
Contact or location button does nothing in a groupThese buttons are available in private chats only.

For the full list of error messages, see Telegram Bot API errors. Formatting and other sendMessage options are covered in how to send messages via the Bot API, and switch-to-inline buttons pair with inline mode.

Frequently asked questions

What is the difference between an inline keyboard and a reply keyboard in Telegram?

An inline keyboard (InlineKeyboardMarkup) is attached to a specific message; pressing its buttons sends nothing to the chat. A reply keyboard (ReplyKeyboardMarkup) replaces the user's letter keyboard; a simple text button sends its text as a regular message.

How long can callback_data be?

1–64 bytes. Bytes, not characters: non-Latin letters take 2 or more bytes in UTF-8. Store short keys like item:42 and keep the real data on your server.

Why does a button keep showing a loading indicator after I press it?

The bot didn't call answerCallbackQuery. Telegram clients show a progress bar until you answer, so call it for every callback query, even without text.

How do I change the buttons after a user presses one?

Call editMessageReplyMarkup with the chat_id and message_id from callback_query.message to replace only the keyboard, or editMessageText to change the text and the keyboard together.

How do I remove a reply keyboard?

Send a message with reply_markup set to {"remove_keyboard": true} (ReplyKeyboardRemove). To only hide it after one press while keeping it available, use one_time_keyboard instead.

Can I add buttons to messages in a channel?

Inline keyboards, yes. Reply keyboards, ReplyKeyboardRemove and ForceReply are not supported in channels.

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.

How to Deploy a Telegram Bot: VPS, Docker and Serverless Hosting

How to deploy a Telegram bot: polling vs webhook, a systemd service on a VPS, Docker, Cloudflare Workers with secret_token, plus a launch checklist.

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 Errors: What Each Error Means and How to Fix It

Telegram Bot API errors explained: 400 chat not found, 403 bot was blocked by the user, 409 Conflict, 429 retry_after. Causes, fixes and handling code.

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.

Telegram Bot Commands: setMyCommands, Command Scopes and /start Deep Links

Set up Telegram bot commands: @BotFather /setcommands, setMyCommands with scopes and languages, /start deep link parameters and /cmd@bot in groups.

n8n Telegram Integration: Connect a Telegram Bot, Trigger Workflows and Send Messages

Connect n8n to Telegram: bot token as Access Token, Telegram Trigger webhook over public HTTPS, sending messages by chat id, and fixes for common errors.

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 Inline Bot: How to Enable Inline Mode and Answer Inline Queries

Build a Telegram inline bot: enable inline mode with @BotFather or setMySettings, handle inline_query updates and reply with answerInlineQuery.

Telegram Stars Payments for Bots: Invoices, Pre-Checkout, Refunds and Subscriptions

Accept Telegram Stars payments in your bot: sendInvoice with XTR, pre_checkout_query, successful_payment, refunds, subscriptions, Python/JS code.

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 Widget Examples: Complete HTML and Python Bot Code

Working Telegram widget examples with full code: a static order card, a counter with widget_query requests, a shared live poll and a local preview stub.

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.