Creating a Vertical Custom Keyboard for a Telegram Bot Game in Python

I’m developing a card game bot for Telegram using Python and have most of it working, but I’m having trouble with the keyboard layout. Currently, my buttons appear in a horizontal line, but I need them displayed vertically.

Here’s an example of what I’ve tried:

card_buttons = []
for card in player_cards:
    card_buttons.append([CustomButton(card)])

send_message(chat_id, 'Select a card:', reply_markup=CustomKeyboard(card_buttons))

This setup creates buttons in a single row. I need each card to appear on a new line. For a fixed grid, I can do something like:

grid_buttons = [
    [CustomButton('A'), CustomButton('B')],
    [CustomButton('C'), CustomButton('D')]
]

However, that method doesn’t work with my dynamic list of cards. I’ve checked the documentation and still can’t find a solution. Does anyone know how to force a vertical layout programmatically or suggest an alternative?

hey, i had the same problem. try this:

card_buttons = [[CustomButton(card)] for card in player_cards]

it puts each button in its own list, so telegram shows em vertically. works like a charm for me. good luck with ur game!

I’ve dealt with this exact problem in my Telegram bot projects. The solution is straightforward: nest each button in its own list. Here’s the code that should work for you:

card_buttons = [[CustomButton(card)] for card in player_cards]
send_message(chat_id, ‘Select a card:’, reply_markup=CustomKeyboard(card_buttons))

This creates a vertical layout where each card appears on a separate line. The Telegram API interprets each sublist as a new row.

If you need more control over spacing or want to group certain cards together, you can adjust the list comprehension accordingly. Just remember to handle any layout changes in your callback function.

Let me know if you need any clarification or run into other issues!

I’ve encountered a similar issue when developing a Telegram bot for a different game. The key is to create a separate list for each button, even if it’s just one button per list. Here’s what worked for me:

card_buttons = [[CustomButton(card)] for card in player_cards]
send_message(chat_id, 'Select a card:', reply_markup=CustomKeyboard(card_buttons))

This approach creates a nested list where each inner list contains a single button. Telegram’s API interprets each inner list as a new row, resulting in a vertical layout.

If you want to add some spacing between buttons, you can include empty buttons:

card_buttons = [[CustomButton(card)], [CustomButton(' ')] for card in player_cards]

This adds an empty button row between each card, giving a more spread-out appearance. Just remember to handle these empty buttons in your callback function.

Hope this helps solve your layout issue!