'How can I change the number of buttons on the telegram bot keyboard to match the number of values in the database?
I'm writing a telegram bot for a haircut appointment. In my database, barber adds the available time for haircuts. I want to create a keyboard from the available values in the database. But the number of these values is constantly changing, respectively, and the number of buttons also changes. How can I make the number of buttons in the telegram bot keyboard automatically change to match the number of available entries in the database?
Function that shows the time available for recording
def get_date(message):
global date
date = message.text
db = sqlite3.connect('database.db')
c = db.cursor()
c.execute("SELECT time FROM datetime")
lst = c.fetchall()
print(lst)
print(lst) outputs the following data - [('10:00',), ('17:00',), ('14:00',), ('11:00',)]
I need to create a keyboard in the telegram bot from this list, but the problem is that the number of values in this list changes periodically
button1 = lst[0][0]
button2 = lst[0][1]
button3 = lst[0][2]
button4 = lst[0][3]
...
markup.add(button1,button2,button3,button4...)
How to make sure that the required number of "button" variables is automatically created (the corresponding number of values in the "lst" list) and all these variables are added to the markup.add keyboard?
Solution 1:[1]
You can't use a simple for cycle to dynamically add your list's element in the markup?
for element in lst[0]:
markup.add(element)
EDIT: This is how i personally manage the Inline Keyword Buttons
keyboard = [
[
InlineKeyboardButton(TEXT, callback_data/url)
],
[
InlineKeyboardButton(TEXT, callback_data/url)
]
]
reply_markup = InlineKeyboardMarkup(keyboard)
If i want to dynamically add buttons i do the same thing appending the new one to the markup list
keyboard = [
[
InlineKeyboardButton(TEXT, callback_data/url)
],
[
InlineKeyboardButton(TEXT, callback_data/url)
]
]
for txt in texts:
keyboard.append([InlineKeyboardButton(txt, callback_data/url)])
reply_markup = InlineKeyboardMarkup(keyboard)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
