Kle*_*ios 5 python python-telegram-bot telegram-bot
我正在尝试创建一个菜单,用户可以在其中导航。这是我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
正如预期的那样,在 /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
Run Code Online (Sandbox Code Playgroud)
此致。克莱森·里奥斯。
我相信您的代码中有两个问题。
第一的。在您的help函数中,您尝试更改消息的文本及其标记。但该edit_message_reply_markup方法仅更改标记。所以而不是
update.callback_query.edit_message_reply_markup(
'Help ... help..',
reply_markup=InlineKeyboardMarkup(keyboard)
)
Run Code Online (Sandbox Code Playgroud)
做这个:
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='')
Run Code Online (Sandbox Code Playgroud)
注意变化:
update.callback_query为bot.edit_message_reply_markup为edit_message_text; 因为第一个仅更改标记,但第二个可以同时更改标记。chat_id和message_id参数;因为文件上就是这么说的。bot.answer_callback_query); 因为每次处理回调查询时,您都需要回答它(使用此方法)。但是,您可以将text参数留空,这样它就不会显示任何内容。第二。如果我错了,请纠正我,但我相信当用户按下按钮时cancel,您希望将消息文本更改为“再见”。并取下键盘。如果是这种情况,则您的错误在于您在尝试移除键盘 ( ) 时发送了新消息( ) 。你可以简单地这样做:reply_textreply_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='')
Run Code Online (Sandbox Code Playgroud)
这里的想法是,当您编辑消息文本并且不使用标记键盘时,以前的键盘会自动删除,因此您不需要使用ReplyKeyboardRemove().
这是一个 GIF(带有硬 G),它有效!
| 归档时间: |
|
| 查看次数: |
2352 次 |
| 最近记录: |