python 如何在我的电报机器人上循环键盘按钮

How to loop keyboard button on my telegram bot in python

我是 python 和电报机器人的新手。我想循环 MySQL 数据库中的数据并将其打印为按钮。 “餐厅”、“酒店”、“航班”正在从 MySQL 数据库中获取。现在,我想将这三个数据打印为 KeyboardButtons 以替换“Button 1”、“Button 2”、“Button 3”。是否可以从 MySQL 数据库获取数据并将其作为 KeyboardButtons 循环?提前致谢!

mydb = mysql.connector.connect(
    host='localhost',
    user='root',
    passwd='',
    database='my_telegram_bot')

sql = mydb.cursor()

def startCommand(update: Update, context: CallbackContext):

    sql.execute("select name from types")
    sql_result = sql.fetchall() 

    for x in sql_result:
      context.bot.send_message(chat_id=update.effective_chat.id, text=x)
      
    buttons = [[KeyboardButton(button1)], [KeyboardButton(button2)], [KeyboardButton(button3)]]
    context.bot.send_message(chat_id=update.effective_chat.id, text="What kind of places are you looking for?", reply_markup=ReplyKeyboardMarkup(buttons))

我的结果

我的预期结果

您可以使用 markup.add() 函数:

markup = types.ReplyKeyboardMarkup()

for x in sql_result:
  markup.add(types.ReplyKeyboardButton(x[0]))

context.bot.send_message(chat_id=update.effective_chat.id, text="What kind of places are you looking for?", reply_markup=markup)