首页 > 解决方案 > 如何使用 InlinKeyBoardMarkup 使用多种方法 - 电报机器人

问题描述

我正在尝试使用 2 种快速回复的方法。这两种方法是 cmd_language 和 cmd_crypto。问题是第一种方法(cmd_language)效果很好,但第二种方法不行。

我希望程序像这样工作:我输入 /start,输入“欢迎”,然后自动执行 cmd_language,显示“选择语言”和选项(现在有效)。然后我输入/crypto,显示选项,但是当我选择一个选项时出现错误。

from telegram.ext import *
from telegram import InlineKeyboardButton, InlineKeyboardMarkup

#-------------------- START ------------------------
def cmd_start(update, context:CallbackContext):
    update.message.reply_text("Welcome")
    cmd_language(update, context)
    
        
#-------------------LANGUAGE---------------------------
def cmd_language(update, context:CallbackContext):
        
    languages= [[InlineKeyboardButton("Español", callback_data="ES")],
                [InlineKeyboardButton("English", callback_data="EN")]]
    
    menuLanguages = InlineKeyboardMarkup(languages)
    
    update.message.reply_text("Select the language", reply_markup=menuLanguages)
        
def selectionLanguage(update, context):
    
    query = update.callback_query
    
    language = query.data
    query.edit_message_text(text=f"You have selected {language}")
    
#-----------------------CRYTO-------------------
def cmd_crypto(update, context:CallbackContext):
        
    cryptos= [[InlineKeyboardButton("ADA - Cardano", callback_data="ADA")],
                [InlineKeyboardButton("BTC - Bitcoin", callback_data="BTC")]]
    
    menuCryptos= InlineKeyboardMarkup(cryptos)
    
    update.message.reply_text("Select the cryptocurrency:", reply_markup=menuCryptos)
        

def selectionCrypto(update, context):
    
    query = update.callback_query
    
    crypto= query.data
        
    query.edit_message_text(text=f"You have selected {crypto}"))

#----------------ERROR-------------------------
def error(update, context):
    print(f"Update {update} caused error {context.error}")

#--------------MAIN-------------------------------
def main():
    updater = Updater("TOKEN", use_context=True)
    dp = updater.dispatcher
    
    dp.add_handler(CommandHandler("start", cmd_start))
    
    dp.add_handler(CommandHandler("language", cmd_language))
    dp.add_handler(CallbackQueryHandler(selectionLanguage))
    
    dp.add_handler(CommandHandler("crypto", cmd_crypto))
    dp.add_handler(CallbackQueryHandler(selectionCrypto))    
    
    dp.add_error_handler(error)
    
    updater.start_polling()
    updater.idle()
    

if __name__ == "__main__":
    main()
    

标签: pythonpython-3.xtelegrampython-telegram-bot

解决方案


这里的关键部分是文档中的“订单和优先级计数”行Dispatcher.add_handler:您的第一个CallbackQueryHandler将只处理任何传入CallbackQuery,第二个将永远不会被解雇。

作为问题的解决方案,我建议:

请看一下这个inlinekeyboard2.py例子,它展示了两者。


免责声明:我目前是python-telegram-bot.


推荐阅读