python - 如何使用 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()
解决方案
这里的关键部分是文档中的“订单和优先级计数”行Dispatcher.add_handler
:您的第一个CallbackQueryHandler
将只处理任何传入CallbackQuery
,第二个将永远不会被解雇。
作为问题的解决方案,我建议:
- 使用or的
pattern
论点CallbackQueryHandler
- 使用 a
ConversationHandler
在多步骤设置中获取用户输入。
请看一下这个inlinekeyboard2.py
例子,它展示了两者。
免责声明:我目前是python-telegram-bot
.
推荐阅读
- github - GitHub 提交守门人
- java - 在目标之前在 Java Eclipse Maven 中执行 jar
- typescript - 如何使用 ng-2 智能表在创建和编辑时自动完成
- laravel - Laravel Auth 重置密码功能视图不起作用
- php - MySQL查询无结果
- abap - 有没有办法检查 RFC 是否存在于 SAP 系统中
- ios - 在 swift (iOS) 中的文本字段内添加前缀
- javascript - 将字符串转换为日期而不考虑时区
- kubernetes - OpenEBS 是否支持 Jiva Volumes 的 ReadOnlyMany 选项?
- php - 使用 PHP 使用包含电子邮件地址的查询字符串验证 url