Anton Evseev2022-04-22 01:01:34
Anton Evseev, 2022-04-22 01:01:34

How to pull data from the database in InlineKeyboardButton?


def generate_kb(current_amount):
    current_amount = int(current_amount)
    keyboard_markup = types.InlineKeyboardMarkup(row_width=3)
        types.InlineKeyboardButton('-', callback_data='counter_{}'.format(current_amount - 1)),
        types.InlineKeyboardButton('{} шт'.format(current_amount), callback_data='empty?'),
        types.InlineKeyboardButton('+', callback_data='counter_{}'.format(current_amount + 1)),
        types.InlineKeyboardButton('Добавить в корзину',
    return keyboard_markup

@dp.message_handler(text=" Menu")
async def store_menu(message: types.Message):
    read_db = await sql_admin.sql_read_store_menu()
    kb = generate_kb(0)
    for ret in read_db:
        await bot.send_photo(message.from_user.id, ret[4],
                             f'{ret[1]}\n{ret[2]}\nЦена: {ret[3]}₽', reply_markup=kb)

async def update_counter(callback: types.CallbackQuery):
    current_amount = callback.data.split('_')[-1]
    await bot.edit_message_reply_markup(callback.message.chat.id, callback.message.message_id,

Good afternoon.
There is a keyboard in the screenshot. It has a product counter and an "add" button.
The picture and description text are pulled up in the store_menu function from the database. Also in the database under the index ret[0] is the
product id.
I want the callback to collect data from the database and after clicking "add" I could catch the product id, product quantity and user id, so that through the function I would transfer it back to the "basket" database, where the selected but unpaid products will be stored.
I think I’ll figure out how to transfer data to the database, but I can’t figure out how to put them in the callback.
I admit that you need to use Callback_data, but I did not understand how to write it correctly in my case.
Thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Mikhail Krostelev, 2022-04-22

As an option - put json with data there.
Collect a dictionary with the necessary data, and with the help of either json, convert
When reading callback_data, convert back to a dictionary.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question