Telegram bot - CallbackQueryHandler上的KeyboardButton(python)

时间:2018-01-11 04:22:14

标签: python bots telegram

我试图在python中的内联按钮按下处理程序(CallbackQueryHandler)上发送自定义键盘(KeyboardButton) - 但没有运气。

如果我将发送自定义键盘的代码放入/ start处理程序,它可以正常工作。

有什么想法吗?

代码:

# -*- coding: utf-8 -*-

import config
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from telegram import KeyboardButton, ReplyKeyboardMarkup, 
ReplyKeyboardRemove
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler

def start(bot, update):
  keyboard = []
  keyboard.append([InlineKeyboardButton(u'11', callback_data='1')])
  keyboard.append([InlineKeyboardButton(u'22', callback_data='2')])
  keyboard.append([InlineKeyboardButton(u'33', callback_data='3')])
  reply_markup = InlineKeyboardMarkup(keyboard)

  update.message.reply_text('Please choose:',  reply_markup=reply_markup)

def button(bot, update):
  query = update.callback_query
  keyboard = [[KeyboardButton('button1'), KeyboardButton('button2')]]
  reply_markup = ReplyKeyboardMarkup(keyboard)
  bot.edit_message_text(text='some text',\
  chat_id=query.message.chat_id,\
  message_id=query.message.message_id,reply_markup=reply_markup)

if __name__ == '__main__':
  updater = Updater(config.token)
  updater.dispatcher.add_handler(CommandHandler('start', start))
  updater.dispatcher.add_handler(CallbackQueryHandler(button))
  updater.start_polling()
  updater.idle()

2 个答案:

答案 0 :(得分:0)

好像我找到了答案 - 使用bot.edit_message_text()函数编辑与内联按钮相关的消息,即当我们通过上面的函数发送消息时,内联键盘消失,新消息取而代之。 相反,我们应该这样使用,     bot.send_message(query.message.chat_id,'some text',reply_markup = reply_markup)

答案 1 :(得分:0)

对我有用的逻辑如下:

def function_I_want_to_call(update, context):
(...)
InlineKeyboardButton('Text on UI', callback_data='function_I_want_to_call')
updater.dispatcher.add_handler(CallbackQueryHandler(function_I_want_to_call))

每次用户点击按钮时,它都会调用你想要的函数。