Skip to content
Advertisement

Python Telegram Bot: button data invalid

I am trying to make a super simple telegram bot using PTB. The bot has a button, when I click the button bot should make an http request to the web (without opening browser). And show the response data. Here is the piece of code I am using:

def get_data():
    response = requests.get('https://jsonplaceholder.typicode.com/posts/1').json()
    return response['body']

def start(update, context) -> None:
    inline_button = [
        [
            InlineKeyboardButton('test callback', callback_data=get_data())
        ]
    ]

    reply_markup = InlineKeyboardMarkup(inline_button)
    update.message.reply_text("Please choose:", reply_markup=reply_markup)

def button(update, context) -> None:
    query = update.callback_query
    query.answer()
    
    TEXT = f"<h3>{query.data}</h3>"
    query.edit_message_text(text=TEXT, parse_mode=ParseMode.HTML) 
    # context.bot.send_message(chat_id=update.effective_chat.id, text=f'{query.data}')

it works for hard coded values and under 50 characters text however when a text size is over 80 character or so I am getting following error:

telegram.error.BadRequest: Button_data_invalid

I believe its due to telegram limitation of 64 byte texts? but in that case how some bots show thousands of characters data in a single message? What exactly am I doing wrong here?

Advertisement

Answer

You’re trying to pass the json-data that you fetch from the website as the callback_data to the button. But what you actually want (from your description) is to fetch the json data only when the button is pressed. You can simply set callback_data to some string that tells you which button that is (e.g. callback_data='fetch_json') and when you receive the CallbackQuery (i.e. in the button function) call get_data and use the result to edit the message text.

If you indeed want to make the request before sending the button, you’ll have to store the long text somewhere and retrieve it upon receiving the CallbackQuery. python-telegram-bot has a built-in feature for storing data, see this wiki page.


Disclaimer: I’m currently the maintainer of python-telegram-bot.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement