Bad Request: BUTTON_DATA_INVALID — Telegram bot error and how to fix it
Bad Request: BUTTON_DATA_INVALID means Telegram refused the callback_data of an inline keyboard button, almost always because it is longer than 64 bytes. The limit is in bytes, not characters: a Cyrillic letter takes 2 bytes and an emoji 3 or 4, so 40 characters can be too long. Put a short id in the button and keep the rest on your server, or use aiogram's CallbackData or python-telegram-bot's arbitrary_callback_data.
By Livops team, the people who build and run LivopsUpdated
The error, as the Telegram Bot API returns it when a button’s data is refused:
{"ok":false,"error_code":400,"description":"Bad Request: BUTTON_DATA_INVALID"}
Each library wraps it in its own words:
| Library | What you see |
|---|---|
| aiogram 3 | TelegramBadRequest: Telegram server says - Bad Request: BUTTON_DATA_INVALID[7][8] |
| python-telegram-bot | telegram.error.BadRequest: Button_data_invalid[9][10] |
| grammY | GrammyError: Call to 'sendMessage' failed! (400: Bad Request: BUTTON_DATA_INVALID)[17] |
| Telegraf | TelegramError: 400: Bad Request: BUTTON_DATA_INVALID[18] |
python-telegram-bot’s spelling looks odd because the library removes Bad Request: and capitalizes the rest, which lowercases every letter after the first[9].
This page explains the 64-byte limit on callback_data and why it is bytes, not characters, shows the close relative can't parse InlineKeyboardButton, lists where long button data comes from, and shows the fixes: a short id with the data kept on your server, aiogram’s CallbackData factory and python-telegram-bot’s arbitrary_callback_data. It ends with where to keep button data on Livops so buttons keep working after a deploy.
What does the error mean?
An inline keyboard button with callback_data sends that data back to your bot when the user presses it. The Bot API allows 1-64 bytes of it[1].
Telegram’s servers refuse a button whose data they do not accept with BUTTON_DATA_INVALID: “The data of one or more of the buttons you provided is invalid”[3]. The Bot API server passes upper-case error names like this one through as they are, after Bad Request: [2]. The whole request fails: the message is not sent, or the keyboard is not changed, even if only one button out of twenty is too long.
Any method that takes reply_markup can hit it: sendMessage, sendPhoto, editMessageText, editMessageReplyMarkup and the rest. Match the error by its description, not by its code alone: the contents of error_code are subject to change[1].
Bytes, not characters
All Bot API requests are made in UTF-8[1], and the 64 is counted in bytes[1]. A character can take more than one:
| What | Example | Characters | Bytes |
|---|---|---|---|
| Latin letters and digits | buy:42 |
6 | 6 |
| Cyrillic | Тошкент |
7 | 14 |
Uzbek Latin with ʻ |
oʻzbek |
6 | 7 |
| Emoji | 🚀 |
1 | 4 |
| A Cyrillic address | city:Тошкент шаҳри, Юнусобод тумани, 4-мавзе |
44 | 75 |
The last one looks short and fails. Measure the encoded length, never the number of characters:
len(data.encode("utf-8")) # must be 1..64
new TextEncoder().encode(data).length; // must be 1..64
The close relative: can’t parse InlineKeyboardButton
Some broken buttons never reach Telegram. The Bot API server reads the keyboard first, and when a button makes no sense it answers with its own error[2]:
{"ok":false,"error_code":400,"description":"Bad Request: can't parse InlineKeyboardButton: Text buttons are not allowed in the inline keyboard"}
An inline button needs exactly one action besides its text — url, callback_data, web_app and so on[1]. The server treats an empty callback_data as no callback_data at all, so a button with callback_data: "" and nothing else has no action and fails this way[2]. That is the other end of the 1-64 rule[1]: data built from a variable that came back empty. Too long gives BUTTON_DATA_INVALID; empty gives this one.
Where long button data comes from, most common first
1. JSON in the button
callback_data=json.dumps({"action": "buy", "product_id": 123456, "variant": "large", "qty": 2})
# 69 bytes
Field names, quotes, spaces and braces use up most of the 64 bytes before any real data is in. It works with small numbers in testing and fails once ids grow.
2. Names and text in the button
A product name, a city, a search query or a user’s own words put into the data. In Russian or Uzbek Cyrillic each letter is 2 bytes, so a name that looks short is not.
3. Several ids in one string
order:{order_id}:item:{item_id}:user:{user_id} with long numbers, or two UUIDs. A UUID alone is 36 characters as text.
4. Things that were never meant for a button
A full URL, a file_id, a token or a date with time zone. They are long by nature; keep them on the server.
How to fix it
Put a short id in the button, keep the rest on your server
If the thing has an id in your database, the button needs nothing else: buy:123456 is 10 bytes. Load the product, the order or the user by the id when the button is pressed.
When the data has no id of its own — a search query, a filter, a multi-step choice — store it and put a short random key in the button:
import json
import os
import secrets
import sqlite3
db = sqlite3.connect(os.path.join(os.environ.get("DATA_DIR", "."), "buttons.db"))
db.execute("CREATE TABLE IF NOT EXISTS buttons (key TEXT PRIMARY KEY, payload TEXT)")
def to_button(payload: dict) -> str:
key = secrets.token_urlsafe(8) # 11 ASCII characters
db.execute("INSERT INTO buttons VALUES (?, ?)", (key, json.dumps(payload)))
db.commit()
return f"p:{key}" # 13 bytes
def from_button(data: str) -> dict | None:
row = db.execute("SELECT payload FROM buttons WHERE key = ?", (data[2:],)).fetchone()
return json.loads(row[0]) if row else None
Handle a key you no longer have — answer the press with “This button has expired” — and check what the payload asks for. Telegram warns that the message a callback query came from may not contain a button with that data at all[1], and python-telegram-bot’s documentation explains why: callback queries are sent by the user’s client, so they can be manipulated[13]. A random key that points to data on your server is safe in a way that delete:123 is not.
Whatever you do with the press, answer the callback query first; a slow handler meets query is too old.
aiogram 3: the CallbackData factory
aiogram builds short, typed data for you. Subclass CallbackData with a prefix and the fields you need; pack() joins them with :[5]:
from aiogram import F, Router
from aiogram.filters.callback_data import CallbackData
from aiogram.types import CallbackQuery
from aiogram.utils.keyboard import InlineKeyboardBuilder
router = Router()
class Buy(CallbackData, prefix="buy"):
product_id: int
qty: int
builder = InlineKeyboardBuilder()
builder.button(text="Buy 2", callback_data=Buy(product_id=123456, qty=2)) # "buy:123456:2"
@router.callback_query(Buy.filter(F.qty > 0))
async def on_buy(query: CallbackQuery, callback_data: Buy):
await query.answer()
product = await get_product(callback_data.product_id)
The keyboard builder packs a CallbackData it is given[6], and pack() checks the result: when the data is over 64 bytes in UTF-8, it raises in your code, before any request is made[4]:
ValueError: Resulted callback data is too long! len('buy:...'.encode()) > 64
So with the factory you get a clear error and a line number instead of BUTTON_DATA_INVALID. Fields may be strings, numbers, booleans, UUIDs or enums[5]; keep them to ids and numbers, not names. A field’s value may not contain the separator either[4].
python-telegram-bot: arbitrary_callback_data
python-telegram-bot can store any object for a button and send Telegram only a random id for it. Install the extra and switch it on in the builder[12]:
pip install "python-telegram-bot[callback-data]"
import os
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram.ext import (
ApplicationBuilder,
CallbackQueryHandler,
InvalidCallbackData,
PersistenceInput,
PicklePersistence,
)
persistence = PicklePersistence(
filepath=os.path.join(os.environ.get("DATA_DIR", "."), "callback_data.pickle"),
store_data=PersistenceInput(bot_data=False, chat_data=False, user_data=False),
)
app = (
ApplicationBuilder()
.token(os.environ["BOT_TOKEN"])
.arbitrary_callback_data(True)
.persistence(persistence)
.build()
)
keyboard = InlineKeyboardMarkup([[
InlineKeyboardButton("Buy", callback_data={"action": "buy", "product_id": 123456, "variant": "large"}),
]])
async def on_expired(update, context):
await update.callback_query.answer("This button has expired.", show_alert=True)
async def on_buy(update, context):
data = update.callback_query.data # the dict you passed
await update.callback_query.answer()
app.add_handler(CallbackQueryHandler(on_expired, pattern=InvalidCallbackData))
app.add_handler(CallbackQueryHandler(on_buy, pattern=dict))
How it behaves, from the library’s own documentation:
- The cache is in memory and holds 1024 keyboards by default; pass a number instead of
Trueto change it[12]. When it is full, the least recently used keyboard’s data is dropped[13]. - Without persistence, buttons stop working after a restart: the press arrives with an
InvalidCallbackDatainstead of your object[13]. The persistence above keeps only the callback data —PersistenceInputhas a switch for each kind of data, andcallback_datais on by default[15] — in a pickle file atfilepath[16]. - Tampering is harmless: an id that was changed cannot be resolved and arrives as
InvalidCallbackDatatoo[13], whose text reads “The object belonging to this callback_data was deleted or the callback_data was manipulated.”[14] - The limits are also constants:
InlineKeyboardButtonLimit.MIN_CALLBACK_DATAis 1 andMAX_CALLBACK_DATAis 64[11].
grammY and Telegraf
Use the short-id pattern above, and check new TextEncoder().encode(data).length before you build a keyboard from user data. API errors carry Telegram’s description, so the error can be told apart from others by it[17][18].
On Livops
Livops does not change what Telegram accepts in a button; the fix is in your code. What matters on Livops is where the data behind your buttons lives.
- Every deploy restarts the bot. A bot’s old version is stopped before the new one starts — see The app did not start. Button data kept only in memory, python-telegram-bot’s cache included, is gone after each
git push, and old buttons stop working. - Keep it on the disk or in a database.
/app/datais kept across deploys and restarts, and its path is in theDATA_DIRvariable, which the code above reads;/tmpis wiped on every restart and deploy. See Files and data. For more than a small bot, add PostgreSQL or Redis to the project: its address is written into every service as a variable,DATABASE_URLorREDIS_URL— see Databases. Pick Redis Persistent, not Cache, for button data: the Cache type keeps nothing on disk and drops the least recently used keys when memory is full. - Logs. The error line is on the project’s Logs page;
livops logs <service> -ffollows it from the terminal, see CLI. Log the data’s byte length where you build the keyboard, and the long button is easy to find.
A bot costs 19 credits a month (19,000 so’m); see Pricing.
Questions
How long can callback_data be in a Telegram bot?
1 to 64 bytes. The limit is in bytes of UTF-8, not in characters: 64 Latin letters or digits fit, but only 32 Cyrillic letters, and only about 16 emoji. Longer data makes Telegram refuse the whole message with BUTTON_DATA_INVALID.
My callback_data is only 40 characters. Why is it invalid?
Because it is more than 64 bytes. Cyrillic letters, the Uzbek ʻ in oʻ and gʻ, and other symbols outside basic Latin take 2 bytes each in UTF-8, and an emoji takes 3 or 4. Measure the encoded length, len(data.encode()) in Python, not the number of characters.
Can I put JSON in callback_data?
Only very small JSON, and it is rarely worth it: field names and quotes use up the 64 bytes fast. Put a short id in the button, such as buy:123456, and keep the rest in your database or in a cache keyed by that id.
What does can't parse InlineKeyboardButton mean?
The button itself is malformed, which the Bot API server finds before Telegram sees it. The common case is an empty callback_data: an empty string counts as no callback_data at all, and a button with no action gets Text buttons are not allowed in the inline keyboard.
Does aiogram check the 64-byte limit for me?
Yes, if you build the data with its CallbackData factory. pack() raises ValueError Resulted callback data is too long when the encoded data is over 64 bytes, so you find out in your code, before any request reaches Telegram.
Why do my old buttons stop working after a restart?
If the data behind a button lived only in memory, a restart forgets it. python-telegram-bot's arbitrary_callback_data keeps its cache in memory unless you add persistence, and then old buttons arrive as InvalidCallbackData. Keep the data in a database or a file that survives restarts.
Can a user change the callback_data a button sends?
Treat it as possible. Callback queries come from the user's client, not from Telegram, so check that the user may do what the data asks, especially for data like delete:123. A random key that points to data on your server cannot be guessed.
Sources
- Telegram Bot API — Making requests, InlineKeyboardButton, CallbackQuery (core.telegram.org). Checked .
- Telegram Bot API server source — telegram-bot-api/Client.cpp (raw.githubusercontent.com). Checked .
- Telegram API — messages.sendMessage, possible errors (core.telegram.org). Checked .
- aiogram source — aiogram/filters/callback_data.py (raw.githubusercontent.com). Checked .
- aiogram docs source — Callback Data Factory & Filter (raw.githubusercontent.com). Checked .
- aiogram source — aiogram/utils/keyboard.py (raw.githubusercontent.com). Checked .
- aiogram source — aiogram/exceptions.py (raw.githubusercontent.com). Checked .
- aiogram source — aiogram/client/session/base.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/error.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/request/_baserequest.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/constants.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/ext/_applicationbuilder.py (raw.githubusercontent.com). Checked .
- python-telegram-bot wiki — Arbitrary callback_data (github.com). Checked .
- python-telegram-bot source — telegram/ext/_callbackdatacache.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/ext/_basepersistence.py (raw.githubusercontent.com). Checked .
- python-telegram-bot source — telegram/ext/_picklepersistence.py (raw.githubusercontent.com). Checked .
- grammY source — src/core/error.ts (raw.githubusercontent.com). Checked .
- Telegraf source — src/core/network/error.ts (raw.githubusercontent.com). Checked .
Put your project online today
Connect GitHub or drop a folder. No card is asked for.
Deploy your botRelated
- Bad Request: query is too old and response timeout expired or query ID is invalid — how to fix itBad Request: query is too old and response timeout expired or query ID is invalid means answerCallbackQuery came too late for a button press, or got the wrong ID. The handler did slow work before answering, or the bot was down and is now working through presses that queued up. Answer the callback query first, do the slow work after, and ignore this error for stale presses.
- Bad Request: message is too long — Telegram bot error and how to fix itBad Request: message is too long means your bot tried to send more than 4096 characters in one text message, counted after HTML or Markdown is parsed out. A caption has a lower limit, 1024 characters, and fails as message caption is too long. Split the text at paragraph or line breaks before you format it and send each part as its own message, or send the whole text as a .txt document.
- Bad Request: message is not modified — Telegram bot error and how to fix itBad Request: message is not modified means your bot asked Telegram to edit a message into exactly what it already shows: the same text, caption and inline keyboard. It usually comes from a user pressing the same button twice or a refresh button with nothing new. Skip the edit when nothing changed, or catch this exact error and ignore it.
- Bad Request: can't parse entities — Telegram bot error and how to fix itBad Request: can't parse entities means Telegram could not read the formatting in your message: with parse_mode set to HTML, Markdown or MarkdownV2, some text — usually a user's name, a username with an underscore, a price with a dot, or an unclosed tag — breaks the markup. Escape that text for the parse mode you use, send entities instead of parse_mode, or send it without parse_mode.
- Bad Request: message text is empty — Telegram bot error and how to fix itBad Request: message text is empty means your bot called sendMessage or editMessageText with no text: an empty string, a variable that came back empty, or no text parameter at all. Text made only of spaces and line breaks fails too, as text must be non-empty. Check the text before you send, and send a fallback line instead.
- Telegram bot hosting in 2026: the options comparedA Telegram bot needs a process that never stops, or a public HTTPS address for a webhook. On Livops it runs from a GitHub push for 19 credits a month (19,000 so'm). Here is how a VPS, Railway, Render, Fly.io and Vercel compare.
- aiogram bot hosting: how to deploy an aiogram 3 botAn aiogram 3 bot needs one process that never stops, the token in an environment variable, state kept outside memory and a clean exit on SIGTERM. On Livops you push a repository with bot.py and requirements.txt, and it runs for 19 credits a month (19,000 so'm), polling or webhook.
- python-telegram-bot hosting: deploying a v22 botA python-telegram-bot bot runs as one Application: run_polling() for polling, run_webhook() with the webhooks extra for a webhook. Both stop cleanly on SIGTERM. On Livops it runs from a push with bot.py and requirements.txt for 19 credits a month (19,000 so'm).
- grammY bot deploy: polling, webhooks and hostingDeploy a grammY bot as one always-on Node.js process: bot.start() for polling, or webhookCallback() behind an HTTP server, with bot.stop() on SIGTERM. On Livops a repository with grammy in package.json runs as a bot from every push, for 19 credits a month (19,000 so'm).
- Telegraf bot hosting: deploying a Telegraf 4 bot on Node.jsA Telegraf bot is one Node.js process: bot.launch() for polling, or bot.webhookCallback() behind an HTTP server for a webhook, with bot.stop() on SIGTERM. On Livops a repository with telegraf in package.json is run as a bot from every push, for 19 credits a month (19,000 so'm).