【问题标题】:How to loop keyboard button on my telegram bot in python如何在python中循环我的电报机器人上的键盘按钮
【发布时间】:2022-01-16 19:33:31
【问题描述】:

我是 python 和电报机器人的新手。我想循环来自 MySQL 数据库的数据并将其打印为按钮。 "Restaurant","Hotel","Flight" 是从 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))

我的结果????

我的预期结果????

【问题讨论】:

    标签: python-3.x telegram telegram-bot python-telegram-bot py-telegram-bot-api


    【解决方案1】:

    您可以使用 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)
    

    【讨论】:

    • sql = mydb.cursor() def startCommand(update: Update, context: CallbackContext): sql.execute("select name from types") sql_result = sql.fetchall() markup = types.ReplyKeyboardMarkup () for x in sql_result: markup.add(types.ReplyKeyboardMarkup(x)) context.bot.send_message(chat_id=update.effective_chat.id, text="你在找什么样的地方?", reply_markup=markup)
    • 未注册错误处理程序,记录异常。回溯(最后一次调用):文件“C:\Users\Admin\mambaforge\lib\site-packages\telegram\ext\dispatcher.py”,第 555 行,在 process_update handler.handle_update(update, self, check, context )
    • 文件“C:\Users\Admin\mambaforge\lib\site-packages\telegram\ext\handler.py”,第 198 行,在 handle_update 返回 self.callback(update, context) 文件“ C:\xampp\htdocs\telegram_bot_python.py”,第 179 行,在 startCommand markup.add(types.ReplyKeyboardMarkup(x)) 文件“C:\Users\Admin\mambaforge\lib\site-packages\telebot\types.py ",第 966 行,在添加 button_array.append(button.to_dict()) AttributeError: 'ReplyKeyboardMarkup' 对象没有属性 'to_dict'
    • sql_result是什么类型的数据结构?再看一遍,好像是一个嵌套列表。你可以试试:for x in sql_result: context.bot.send_message(chat_id=update.effective_chat.id, text=x[0])
    • 或者,您可以展平嵌套列表并使用相同的循环。
    猜你喜欢
    • 1970-01-01
    • 2018-12-03
    • 1970-01-01
    • 2018-03-23
    • 2016-03-22
    • 2020-10-10
    • 2017-04-11
    • 2022-10-05
    • 2020-10-08
    相关资源
    最近更新 更多