Search code examples
pythontelegrampython-telegram-bot

How do I programmatically create a vertical custom keyboard layout with python using the telegram bot api?


I'm trying to create a card-based game bot using the telepot api wrapper for telegram, but I can't figure out how to make it use a vertical layout instead of a horizontal layout

sample code:

keyboard = []
for card in data['current_games'][userGame]['players'][messageLocationID]['cards']:
    button = [KeyboardButton(text=card)]
    keyboard += button

Then I use the sendMessage() method with the ReplyKeyboardMarkup() method, but it creates a row of buttons that are tall and thin, which affects the display of the text.

Is there a step I'm missing? I was able to create a square of keys using:

keyboard = [[KeyboardButton(text='0'), KeyboardButton(text='1'), KeyboardButton(text='2'), KeyboardButton(text='3')],
            [KeyboardButton(text='4'), KeyboardButton(text='5'), KeyboardButton(text='6'), KeyboardButton(text='7')],
            [KeyboardButton(text='8'), KeyboardButton(text='9'), KeyboardButton(text='10'), KeyboardButton(text='11')],
            [KeyboardButton(text='12'), KeyboardButton(text='13'), KeyboardButton(text='14'), KeyboardButton(text='15')]]

I only created a keyboard using the second method because I was able to create it manually instead of programmatically, but I don't have a way to process the card list without accessing each card in sequence since it's a dynamic list that changes with each turn.

I looked in the api notes but I couldn't find anything that I was able to use

I assumed based on the results of the second keyboard that I would be able to create vertical rows by making each card be an array so it would be nested inside the original array, but that proved to not be the case in my experience

Am I missing a step?


Solution

  • Since keyboard in telegram is an array of array of strings, at first you should create a "row of buttons" (first array) and only after that add it to keyboard (second array) as one element. Something like this:

    keyboard = []
    row1 = ["card1", "card2", "card3"]
    keyboard.append(row1)
    row2 = ["card4", "card5", "card6"]
    keyboard.append(row2)
    print (keyboard)
    
    >>>
    [['card1', 'card2', 'card3'], ['card4', 'card5', 'card6']]
    

    You may put it into a cycle, so it would be created dynamicly as you wish.