V
V
violpeople2021-07-03 20:24:24
Python
violpeople, 2021-07-03 20:24:24

How do I add an item to the cart with a floating item?

Bot on Aiogram. There is a product carousel with 3 buttons - "Next" , "Previous" , "Add to Cart".
I plan to do it this way - when you click the "Add to Cart" button on a certain product, the product is sent to the database to the user (each product has its own ID from 1 to 15). But the catch is that I can't move this to a separate function, because in a separate function, the id will not match the product that the user has stopped at.
Please tell me how to do it properly.

@dp.callback_query_handler(lambda c: c.data.startswith('next_'))
async def send_next_item(call: types.CallbackQuery):
    next_item = int(call.data.split('_')[-1])

    kb = InlineKeyboardMarkup(row_width=2)
    next = InlineKeyboardButton(text = 'Следующий',  callback_data = f'next_{next_item+1}')
    previous = InlineKeyboardButton(text= 'Предыдущий',callback_data= 'previous_1')
    add = InlineKeyboardButton(text= 'Добавить в корзину',callback_data= f'add_{next_item+1}')
    
    kb.add(previous,next,add)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2021-07-07
@violpeople

After that:
next_item = int(call.data.split('_')[-1])
next_item value will be equal to item number. You can also do this:
operation = call.data.split('_')[0]
Then we see that operation == 'add' and add an item with the next_item number (although, of course, the word "next" in the variable name confuses confusing, I would rename).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question