【问题标题】:When I click on the button, the button id should be returned to me. JSON file当我点击按钮时,按钮 id 应该返回给我。 JSON文件
【发布时间】:2020-04-20 20:25:41
【问题描述】:

我有一本字典,其中有一个问题及其 ID。我遍历所有问题并将它们显示为按钮,然后当我单击按钮时,我应该返回此问题的 id,如何执行此操作??

def start(message):
    r = requests.get("http://x.x.x.x/api/tests/list/getusertestlist", headers=headers)# I get JSON file
    markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
    for i in dp.values(r.json(), "/tests/*/value"):# value it's questions.
        itembtn = types.KeyboardButton(i)
        markup.add(itembtn)
    bot.send_message(message.chat.id,"Get test",reply_markup=markup)

Structure JSON file.
{'tests': [{'description': 'Choose your preferred answer from the suggested ones.', 'id': 85, 'value': 'test 1'}, {'description': 'Choose your preferred answer from the suggested ones.', 'id': 88, 'value': 'test 1'}]}

最后我应该得到一个带有 2 个按钮测试 1 和测试 2 的键盘,当我点击测试 1 时,我应该得到它的 ID

【问题讨论】:

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


    【解决方案1】:

    我和你的 sn-p 迷路了。没有声明像“dp”或“types”这样的变量。另外,我手头没有互联网上的 json 测试文件,所以我在同一个文件中声明了它(使用您提供的示例)。

    from telegram import InlineKeyboardButton, InlineKeyboardMarkup
    from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
    import json
    
    jsonfile='{"tests": [{"description": "Choose your preferred answer from the suggested ones.", "id": 85, "value": "test 1"}, {"description": "Choose your preferred answer from the suggested ones.", "id": 88, "value": "test 1"}]}'
    
    def start(update, context):
        keybrd = []
        jsondic=json.loads(jsonfile)
        for item in jsondic['tests']:
            keybrd.append([InlineKeyboardButton(item['value'], callback_data=item['id'])])
        markup = InlineKeyboardMarkup(keybrd)
        context.bot.send_message(chat_id=update.effective_chat.id,text="Get test",reply_markup=markup)
    
    def button(update, context):
        query = update.callback_query
        query.answer()
        query.edit_message_text(text="Selected option: {}".format(query.data))
    
    def main():
        updater = Updater(tgtoken, use_context=True)
        updater.dispatcher.add_handler(CommandHandler("start", start))
        updater.dispatcher.add_handler(CallbackQueryHandler(button))
    

    就是这样,您可能需要重新排列按钮。您还需要使用 start_polling() 完成主函数并声明记录器,但所有这些详细信息都可以在此包装器的 github 上的 inlinekeyboard 示例中找到。

    【讨论】:

      猜你喜欢
      • 2019-01-13
      • 1970-01-01
      • 2021-11-28
      • 2023-03-18
      • 2021-01-15
      • 2012-06-13
      • 1970-01-01
      • 2019-12-18
      • 1970-01-01
      相关资源
      最近更新 更多