0

I am writing my first telegram bot and have encountered a strange problem. I cannot somehow pass kwargs from keyboard button to callback query, which should be executed after this button is clicked.

Here is the code:

async def handler(message: types.Message):
    user_id = message.from_user.id
    keyboard = InlineKeyboardMarkup()
    try:
        parser = Parser(message=message)
        for i in parser.parse():
            keyboard.add(InlineKeyboardButton(text=i[0],
                                              callback_data="answer",
                                              kwargs={"text": i[1][0],
                                                      "link": hlink(i[0], i[1][1])}))
        await message.answer("Here are the results:", reply_markup=keyboard)
    except (PageNotAccessible, TermNotFound, TooManyResults) as e:
        await bot.send_message(chat_id=user_id, text=str(e))


@dp.callback_query_handler(text=["answer"])
async def answer(call, text, link):
    await call.message.answer(f"{text}\n<i>{link}</i>")

But after clicking the button, it throws me this error:

TypeError: answer() missing 2 required positional arguments: 'text' and 'link'

So my question is how to pass kwargs to callback query in aiogram or how to do it any other way, without callbacks maybe?

Thanks in advance!

1 Answers1

2

The only way to pass data is by using the callback_data param.

So to provide multiple values, the easiest way is to convert your data to JSON string, pass that, and on button click, decode the JSON


Something like this (untested)

Pass an object with your data

keyboard.add(
    InlineKeyboardButton(text=i[0],
        callback_data=json.dumps({
            "type": "answer", 
            "text": i[1][0],
            "link": hlink(i[0], i[1][1])})
    )
)

On the callback, decode the JSON

@dp.callback_query_handler(text=["answer"])
async def answer(call, callback_data):
    decoded = json.loads(callback_data)
    # do something with the data from the json object
0stone0
  • 34,288
  • 4
  • 39
  • 64
  • Now it throws me another error: ```aiogram.utils.exceptions.ButtonDataInvalid: Button_data_invalid``` As I understood, the reason for this is that callback_data shouldn`t be bigger than 64 bytes and my callback exceeds it. Thanks for your advice anyway! – Алексей Василенко Feb 21 '23 at 18:38
  • 2
    Ow yea, forgot to mention that. There is indeed a small limit. The best way is to create and save an uid in a db, then receive that on button press to check what kind of button it was. – 0stone0 Feb 21 '23 at 20:10