Psoriaz
Psoriaz

Reputation: 35

InlineKeyboardMarkup Telegram bot (pyTelegramBotAPI)

I am making a bot on pyTelegramBotAPI, I need to generate a list of buttons and write it into the keyboard (So that there are 5 buttons in a row). How should I do it? I have a code:

def start(message):
    markup = types.InlineKeyboardMarkup()
    buttons = []
    for i in range(-12, 15):
        if i < 0:
            button = types.InlineKeyboardButton(f'{i}', callback_data=f'{i}')
        elif i == 0:
            button = types.InlineKeyboardButton(f'±{i}', callback_data=f'{i}')
        else:
            button = types.InlineKeyboardButton(f'+{i}', callback_data=f'{i}')
        buttons.append(button)
        if len(buttons) == 5:
            # here i want to add buttons in a row
 
    bot.send_message(message.chat.id, f'Здравствуйте, <b>{message.from_user.first_name}</b>. Для начала необходимо настроить часовой пояс. Выберите разницу во времени относительно UTC (Москва: "+3", Владивосток: "+10", Исландия: "+1")', parse_mode='html', reply_markup=markup)```

Upvotes: 1

Views: 1926

Answers (2)

MXNS
MXNS

Reputation: 81

I can advise you to create a separate module responsible for keyboards.
example of modules
This way you can separate the logic of handlers from the logic of keyboards.
As torrua wrote earlier, you can use the keyboa (how to use keyboa) library. or write the functions yourself to create keyboards and buttons in it.
What you need to know for this:

telebot.types.InlineKeyboardMarkup() # creates an empty keyboard.
telebot.type.InlineKeyboardButton()  # creates a button for the keyboard created earlier.

.row() # determines the position of the buttons in the keyboard.

example of function to get keyboards

Upvotes: 1

torrua
torrua

Reputation: 41

You can do it easy with keyboa:

from keyboa import Keyboa

def start():
    
    buttons = []

    for i in range(-12, 15):

        if i < 0:
            button = (f'{i}', i)
        elif i == 0:
            button = (f'±{i}', i)
        else:
            button = (f'+{i}', i)

        buttons.append(button)

    keyboard = Keyboa(items=buttons, items_in_row=5).keyboard

    bot.send_message(message.chat.id, f'Здравствуйте, <b>{message.from_user.first_name}</b>. Для начала необходимо настроить часовой пояс. Выберите разницу во времени относительно UTC (Москва: "+3", Владивосток: "+10", Исландия: "+1")', parse_mode='html', reply_markup=keyboard)```

Upvotes: 0

Related Questions