Advertisement
Guest User

Untitled

a guest
Jan 19th, 2023
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.53 KB | Source Code | 0 0
  1. from aiogram import Router, types, filters
  2. from contextlib import suppress
  3. from aiogram.exceptions import TelegramBadRequest
  4.  
  5. echo_router = Router()
  6.  
  7.  
  8. def get_keyboard():
  9.     buttons = [
  10.         [
  11.             # callback_data будет передана в callback.data при нажатии
  12.             types.InlineKeyboardButton(text="-1", callback_data="num_decr"),
  13.             types.InlineKeyboardButton(text="+1", callback_data="num_incr")
  14.         ],
  15.     ]
  16.     keyboard = types.InlineKeyboardMarkup(inline_keyboard=buttons)
  17.     return keyboard
  18.  
  19. # Сработает при нажатии на любую Inline кнопку
  20. @echo_router.callback_query(filters.Text(startswith='num_'))
  21. async def update_num_text(callback: types.CallbackQuery):
  22.     new_value = int(callback.message.text)
  23.  
  24.     # Удаляет num_ с начала
  25.     command = callback.data.removeprefix('num_')
  26.     if command == 'incr':
  27.         new_value += 1
  28.     elif command == 'decr':
  29.         new_value -= 1
  30.  
  31.     # Если сообщение не изменилось, то выдаст TelegramBadRequest
  32.     # С помощью suppress мы подавляем ошибку
  33.     with suppress(TelegramBadRequest):
  34.         await callback.message.edit_text(
  35.             f"{new_value}",
  36.             reply_markup=get_keyboard()
  37.         )
  38.  
  39. # Сработает при получении /numbers
  40. @echo_router.message(filters.Command(commands=['numbers']))
  41. async def echo(message: types.Message):
  42.     await message.answer('0', reply_markup=get_keyboard())
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement