我正在尝试创建一个用户可以在其上导航的菜单。这是我的代码:
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='')
注意这些变化:
update.callback_query
取代了bot
。edit_message_reply_markup
取代了edit_message_text
;因为第一个只更改标记,但第二个可以同时执行这两个操作。chat_id
和message_id
论点;因为that's what it says in the documents。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),它的工作原理!