使用 Telegram Bot 按下按钮时如何返回命令

Yuk*_*uya 0 python bots button telegram python-telegram-bot

当我按下带有InlineKeyboardButton. 我正在尝试以下但没有运气:

 bot.send_message(chat_id=chat_id, 
        text='/help', 
        parse_mode=telegram.ParseMode.HTML)
Run Code Online (Sandbox Code Playgroud)

小智 7

首先通过回调数据定义您的按钮:

import telegram
HELP_BUTTON_CALLBACK_DATA = 'A unique text for help button callback data'
help_button = telegram.InlineKeyboardButton(
    text='Help me', # text that show to user
    callback_data=HELP_BUTTON_CALLBACK_DATA # text that send to bot when user tap button
    )
Run Code Online (Sandbox Code Playgroud)

start命令或其他方式向用户显示帮助按钮:

def command_handler_start(bot, update):
    chat_id = update.message.from_user.id
    bot.send_message(
        chat_id=chat_id,
        text='Hello ...',
        reply_markup=telegram.InlineKeyboardMarkup([help_button]),
        )
Run Code Online (Sandbox Code Playgroud)

定义帮助命令处理程序:

def command_handler_help(bot, update):
    chat_id = update.message.from_user.id
    bot.send_message(
        chat_id=chat_id,
        text='Help text for user ...',
        )
Run Code Online (Sandbox Code Playgroud)

处理回调数据:

def callback_query_handler(bot, update):
    cqd = update.callback_query.data
    #message_id = update.callback_query.message.message_id
    #update_id = update.update_id
    if cqd == HELP_BUTTON_CALLBACK_DATA:
        command_handler_help(bot, update)
    # elif cqd == ... ### for other buttons
Run Code Online (Sandbox Code Playgroud)

最后将处理程序添加到您的机器人并开始轮询

update = telegram.ext.Updater('BOT_TOKEN')
bot = update.bot
dp = update.dispatcher
print('Your bot is --->', bot.username)
dp.add_handler(telegram.ext.CommandHandler('start', command_handler_start))
dp.add_handler(telegram.ext.CommandHandler('help', command_handler_help))
dp.add_handler(telegram.ext.CallbackQueryHandler(callback_query_handler))
update.start_polling()
Run Code Online (Sandbox Code Playgroud)