Refactor examples/regular_keyboard_example.py

This commit is contained in:
Suren Khorenyan 2019-08-11 21:52:58 +03:00
parent 747c87631e
commit 8538e6af57

View file

@ -6,6 +6,7 @@ import logging
from aiogram import Bot, Dispatcher, executor, types
API_TOKEN = 'BOT_TOKEN_HERE'
# Configure logging
@ -18,24 +19,27 @@ bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)
@dp.message_handler(commands=['start'])
@dp.message_handler(commands='start')
async def start_cmd_handler(message: types.Message):
keyboard_markup = types.ReplyKeyboardMarkup(row_width=3)
# default row_width is 3, so here we can omit it actually
# kept for clearness
keyboard_markup.row(types.KeyboardButton("Yes!"),
types.KeyboardButton("No!"))
btns_text = ('Yes!', 'No!')
keyboard_markup.row(*(types.KeyboardButton(text) for text in btns_text))
# adds buttons as a new row to the existing keyboard
# the behaviour doesn't depend on row_width attribute
keyboard_markup.add(types.KeyboardButton("I don't know"),
types.KeyboardButton("Who am i?"),
types.KeyboardButton("Where am i?"),
types.KeyboardButton("Who is there?"))
# adds buttons. New rows is formed according to row_width parameter
more_btns_text = (
"I don't know",
"Who am i?",
"Where am i?",
"Who is there?",
)
keyboard_markup.add(*(types.KeyboardButton(text) for text in more_btns_text))
# adds buttons. New rows are formed according to row_width parameter
await message.reply("Hi!\nDo you love aiogram?", reply_markup=keyboard_markup)
await message.reply("Hi!\nDo you like aiogram?", reply_markup=keyboard_markup)
@dp.message_handler()
@ -45,15 +49,17 @@ async def all_msg_handler(message: types.Message):
# in real bot, it's better to define message_handler(text="...") for each button
# but here for the simplicity only one handler is defined
text_of_button = message.text
logger.debug(text_of_button) # print the text we got
button_text = message.text
logger.debug('The answer is %r', button_text) # print the text we've got
if text_of_button == 'Yes!':
await message.reply("That's great", reply_markup=types.ReplyKeyboardRemove())
elif text_of_button == 'No!':
await message.reply("Oh no! Why?", reply_markup=types.ReplyKeyboardRemove())
if button_text == 'Yes!':
reply_text = "That's great"
elif button_text == 'No!':
reply_text = "Oh no! Why?"
else:
await message.reply("Keep calm...Everything is fine", reply_markup=types.ReplyKeyboardRemove())
reply_text = "Keep calm...Everything is fine"
await message.reply(reply_text, reply_markup=types.ReplyKeyboardRemove())
# with message, we send types.ReplyKeyboardRemove() to hide the keyboard