【问题标题】:How to return a command when pressing on a button with Telegram Bot使用 Telegram Bot 按下按钮时如何返回命令
【发布时间】:2019-01-12 22:58:28
【问题描述】:

当我按下带有InlineKeyboardButton 的按钮时,我正在尝试使用python-telegram-bot 返回一个命令。我正在尝试以下但没有运气:

 bot.send_message(chat_id=chat_id, 
        text='/help', 
        parse_mode=telegram.ParseMode.HTML)

【问题讨论】:

    标签: python button bots telegram python-telegram-bot


    【解决方案1】:

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

    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
        )
    

    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]),
            )
    

    定义帮助命令处理程序:

    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 ...',
            )
    

    处理回调数据:

    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
    

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

    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()
    

    【讨论】:

    • 当我按下按钮尝试发送普通文本时,代码工作得非常好,但我似乎无法完成以下工作:/mon name。它似乎无法识别机器人本身发送的命令。你知道如何解决这个问题吗?
    • reply_markup 需要是列表的列表。所以应该是telegram.InlineKeyboardMarkup([[help_button]])
    猜你喜欢
    • 2018-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-17
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多