繁体   English   中英

Telegram bot API编辑InlineKeyboard与python-telegram-bot无法正常工作

[英]Telegram bot API edit InlineKeyboard with python-telegram-bot not working

我正在尝试创建一个用户可以在其上导航的菜单。 这是我的代码:

MENU, HELP = range(2)

def start(bot, update):
    keyboard = [
                 [InlineKeyboardButton('Help', callback_data='help')]
               ]

    # Create initial message:
    message = 'Welcome.'

    update.message.reply_text(message, reply_markup=InlineKeyboardMarkup(keyboard))

def help(bot, update):

    keyboard = [
                 [InlineKeyboardButton('Leave', callback_data='cancel')]
               ]


    update.callback_query.edit_message_reply_markup('Help ... help..', reply_markup=InlineKeyboardMarkup(keyboard))

def cancel(bot, update):

    update.message.reply_text('Bye.', reply_markup=ReplyKeyboardRemove())

    return ConversationHandler.END     


# Create the EventHandler and pass it your bot's token.
updater = Updater(token=config.TELEGRAM_API_TOKEN)

# Get the dispatcher to register handlers:
dispatcher = updater.dispatcher

dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_handler(CallbackQueryHandler(help, pattern='help'))
dispatcher.add_handler(CallbackQueryHandler(cancel, pattern='cancel'))

updater.start_polling()

updater.idle()

正如预期的那样,在/ start处,用户可以获得“帮助”菜单。 当用户点击它时,函数help()也会按预期触发。

根据我对python-telegram-bot文档的理解,应该填充update.callback_query.inline_message_id ,但其值为None

我需要update.callback_query.inline_message_id来更新我的InlineKeyboard菜单,对吗? 为什么inline_message_id为空(无)?

Python 3.6.7
python-telegram-bot==11.1.0

最好的祝福。 Kleyson Rios。

我相信您的代码中存在两个问题。

首先 在您的help功能中,您尝试更改邮件的文本及其标记 edit_message_reply_markup方法仅更改标记 而不是

update.callback_query.edit_message_reply_markup(
    'Help ... help..',
    reply_markup=InlineKeyboardMarkup(keyboard)
)

做这个:

bot.edit_message_text(
    text='Help ... help..',
    chat_id=update.callback_query.message.chat_id,
    message_id=update.callback_query.message.message_id,
    reply_markup=InlineKeyboardMarkup(keyboard)
)
bot.answer_callback_query(update.callback_query.id, text='')

注意这些变化:

  • 我用bot替换了update.callback_query
  • 重要提示 :我用edit_message_reply_markup替换了edit_message_text ; 因为第一个只更改标记 ,但第二个可以同时执行这两个操作。
  • 我添加了chat_idmessage_id参数; 因为这就是它在文件中所说的内容
  • 重要提示 :我添加了一个新方法( bot.answer_callback_query ); 因为每次处理回调查询时都需要回答它(使用此方法)。 但是,您可以将text参数留空 ,以便它不显示任何内容。

第二 如果我错了,请纠正我,但我相信当用户按下cancel按钮时,您希望将消息文本更改为“再见”。 删除键盘 如果是这样的话,你在做什么错的是你发送一个新的消息( reply_text )在试图取下键盘( reply_markup=ReplyKeyboardRemove() 你可以这样做:

bot.edit_message_text(
    text='Bye',
    chat_id=update.callback_query.message.chat_id,
    message_id=update.callback_query.message.message_id,
)
bot.answer_callback_query(update.callback_query.id, text='')

这里的想法是,当您编辑消息的文本而不使用标记键盘时, 先前的键盘会自动删除 ,因此您不需要使用ReplyKeyboardRemove()

这是一个GIF(有一个硬G),它的工作原理!

在此输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM