Creating dynamic Telegram bot keyboard with database data - one button per row in Python

I’m working on a Telegram bot and need help with creating a responsive keyboard layout. I want to build a custom keyboard using InlineKeyboardMarkup that pulls information from my database.

The main challenge is that I have a list of items coming from the database, and I need each item to become a separate button. Each button should be placed on its own individual row in the keyboard layout.

Right now I’m not sure how to properly loop through my database results and convert them into keyboard buttons. The keyboard needs to be dynamic since the database content changes over time.

Can someone show me the correct approach for this kind of dynamic keyboard generation?

Dynamic keyboards can seem complex initially, but they follow a clear structure. Start by querying your database to obtain the desired data. Initialize an empty list intended for your keyboard’s rows. For each record returned, you will create an InlineKeyboardButton using the relevant text and callback_data. Each button should be wrapped in a list to ensure it occupies its own row, and then append this list to your main keyboard list. Once you’ve constructed the complete list, simply pass it to InlineKeyboardMarkup. A helpful tip is to include an identifier in your callback_data for reference when a button is clicked. This method has been reliable in various bots I’ve developed where the database content is dynamic.

I’ve faced a similar challenge while working on a Telegram bot. The key step is to fetch your data from the database initially. After that, you need to create a list that represents each button for the keyboard. For every item retrieved, make sure to create a button that resides in its own inner list - this ensures that every button is displayed on a new row. The InlineKeyboardMarkup requires a format where you pass a list of these inner lists representing rows. Once formatted correctly, you can easily implement it in your bot.

The manual stuff everyone’s talking about works, but it gets messy quick with multiple bots or when things break.

I’ve built dozens of Telegram bots and learned the hard way - managing database connections, errors, and keyboard generation manually becomes a nightmare once you scale up.

Switching to automation changed everything for me. Instead of writing all that database and keyboard code myself, I set up a workflow that handles everything automatically.

It pulls data from my database on schedule or via webhook, formats it how Telegram wants it, and sends keyboard updates without me touching anything. No more connection timeouts or broken keyboard arrays.

Best part? When my database changes, keyboards update instantly. I can even add logic for different keyboards based on user roles or time of day.

This saved me weeks of debugging and made everything bulletproof. You can set up the same workflow here: https://latenode.com