mirror of
https://github.com/aiogram/aiogram.git
synced 2025-12-08 17:13:56 +00:00
62 lines
1.9 KiB
Python
62 lines
1.9 KiB
Python
"""
|
|
This bot is created for the demonstration of a usage of inline keyboards.
|
|
"""
|
|
|
|
import logging
|
|
|
|
from aiogram import Bot, Dispatcher, executor, types
|
|
|
|
|
|
API_TOKEN = 'BOT_TOKEN_HERE'
|
|
|
|
# Configure logging
|
|
logging.basicConfig(level=logging.INFO)
|
|
|
|
# Initialize bot and dispatcher
|
|
bot = Bot(token=API_TOKEN)
|
|
dp = Dispatcher(bot)
|
|
|
|
|
|
@dp.message_handler(commands='start')
|
|
async def start_cmd_handler(message: types.Message):
|
|
keyboard_markup = types.InlineKeyboardMarkup(row_width=3)
|
|
# default row_width is 3, so here we can omit it actually
|
|
# kept for clearness
|
|
|
|
text_and_data = (
|
|
('Yes!', 'yes'),
|
|
('No!', 'no'),
|
|
)
|
|
# in real life for the callback_data the callback data factory should be used
|
|
# here the raw string is used for the simplicity
|
|
row_btns = (types.InlineKeyboardButton(text, callback_data=data) for text, data in text_and_data)
|
|
|
|
keyboard_markup.row(*row_btns)
|
|
keyboard_markup.add(
|
|
# url buttons have no callback data
|
|
types.InlineKeyboardButton('aiogram source', url='https://github.com/aiogram/aiogram'),
|
|
)
|
|
|
|
await message.reply("Hi!\nDo you love aiogram?", reply_markup=keyboard_markup)
|
|
|
|
|
|
# Use multiple registrators. Handler will execute when one of the filters is OK
|
|
@dp.callback_query_handler(text='no') # if cb.data == 'no'
|
|
@dp.callback_query_handler(text='yes') # if cb.data == 'yes'
|
|
async def inline_kb_answer_callback_handler(query: types.CallbackQuery):
|
|
answer_data = query.data
|
|
# always answer callback queries, even if you have nothing to say
|
|
await query.answer(f'You answered with {answer_data!r}')
|
|
|
|
if answer_data == 'yes':
|
|
text = 'Great, me too!'
|
|
elif answer_data == 'no':
|
|
text = 'Oh no...Why so?'
|
|
else:
|
|
text = f'Unexpected callback data {answer_data!r}!'
|
|
|
|
await bot.send_message(query.from_user.id, text)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
executor.start_polling(dp, skip_updates=True)
|