使用InlineKeyboardButton python电报bot发送命令

时间:2020-06-16 08:29:56

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

在python电报bot中,InlineKeyboardButton是否可以在按下时发送类似/cancel的命令?

例如,当用户按下“取消”按钮时,他们将自动发送一个/ cancel命令,然后由机器人进行处理。

从此处的示例中:

https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinekeyboard2.py

conv_handler = ConversationHandler(
    entry_points=[CommandHandler('start', start)],
    states={
        FIRST: [CallbackQueryHandler(one, pattern='^' + str(ONE) + '$'),
                CallbackQueryHandler(two, pattern='^' + str(TWO) + '$'),
                CallbackQueryHandler(three, pattern='^' + str(THREE) + '$'),
                CallbackQueryHandler(four, pattern='^' + str(FOUR) + '$')],
        SECOND: [CallbackQueryHandler(start_over, pattern='^' + str(ONE) + '$'),
                 CallbackQueryHandler(end, pattern='^' + str(TWO) + '$')]
    },
    fallbacks=[CommandHandler('start', start)]
)

我希望能够做到这一点,以便我可以更改进入点并在按下按钮时使用其他对话处理程序。

然后按下按钮将生成一个/ cancel命令,它将使漫游器进入另一个对话处理程序。

这可能吗?

1 个答案:

答案 0 :(得分:0)

要处理InlineKeyboardButton的输入,您定义一个CallbackQueryHandler,它将处理用户按下的按钮的callback_data。 即使您指定了一条命令,CallbackQueryHandler也会处理输入

 #'/help' sent to CallbackQueryHandler
 options.append(InlineKeyboardButton("a", callback_data="/help"))

如果我正确理解了您想要实现的目标,则可以定义一个CallbackQueryHandler方法,该方法然后控制工作流程,甚至可以调用命令(如果需要这样做)

def callback_query_handler(update, context):
   # process input
   input = update.callback_query.data
   # invoke handler
   if input == '/help':
       help_command_handler(update, context)