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!
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