diff --git a/examples/callback_data_factory_simple.py b/examples/callback_data_factory_simple.py index 2c6a8358..5fc9c548 100644 --- a/examples/callback_data_factory_simple.py +++ b/examples/callback_data_factory_simple.py @@ -27,42 +27,40 @@ likes = {} # user_id: amount_of_likes def get_keyboard(): return types.InlineKeyboardMarkup().row( types.InlineKeyboardButton('👍', callback_data=vote_cb.new(action='up')), - types.InlineKeyboardButton('👎', callback_data=vote_cb.new(action='down'))) + types.InlineKeyboardButton('👎', callback_data=vote_cb.new(action='down')), + ) @dp.message_handler(commands=['start']) async def cmd_start(message: types.Message): amount_of_likes = likes.get(message.from_user.id, 0) # get value if key exists else set to 0 - await message.reply(f'Vote! Now you have {amount_of_likes} votes.', reply_markup=get_keyboard()) + await message.reply(f'Vote! You have {amount_of_likes} votes now.', reply_markup=get_keyboard()) -@dp.callback_query_handler(vote_cb.filter(action='up')) -async def vote_up_cb_handler(query: types.CallbackQuery, callback_data: dict): - logging.info(callback_data) # callback_data contains all info from callback data - likes[query.from_user.id] = likes.get(query.from_user.id, 0) + 1 # update amount of likes in storage - amount_of_likes = likes[query.from_user.id] +@dp.callback_query_handler(vote_cb.filter(action=['up', 'down'])) +async def callback_vote_action(query: types.CallbackQuery, callback_data: dict): + logging.info('Got this callback data: %r', callback_data) # callback_data contains all info from callback data + await query.answer() # don't forget to answer callback query as soon as possible + callback_data_action = callback_data['action'] + likes_count = likes.get(query.from_user.id, 0) - await bot.edit_message_text(f'You voted up! Now you have {amount_of_likes} votes.', - query.from_user.id, - query.message.message_id, - reply_markup=get_keyboard()) + if callback_data_action == 'up': + likes_count += 1 + else: + likes_count -= 1 + likes[query.from_user.id] = likes_count # update amount of likes in storage -@dp.callback_query_handler(vote_cb.filter(action='down')) -async def vote_down_cb_handler(query: types.CallbackQuery, callback_data: dict): - logging.info(callback_data) # callback_data contains all info from callback data - likes[query.from_user.id] = likes.get(query.from_user.id, 0) - 1 # update amount of likes in storage - amount_of_likes = likes[query.from_user.id] - - await bot.edit_message_text(f'You voted down! Now you have {amount_of_likes} votes.', - query.from_user.id, - query.message.message_id, - reply_markup=get_keyboard()) + await bot.edit_message_text( + f'You voted {callback_data_action}! Now you have {likes_count} vote[s].', + query.from_user.id, + query.message.message_id, + reply_markup=get_keyboard(), + ) @dp.errors_handler(exception=MessageNotModified) # handle the cases when this exception raises async def message_not_modified_handler(update, error): - # pass return True