2

I am trying to return a command with python-telegram-bot when I press a button with InlineKeyboardButton. I am trying the following but with no luck:

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

1 Answer 1

9

First define your button by callback data:

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
    )

Show help button to user in start command or another way:

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

Define help command handler:

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

Handle callback data:

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

At last add handlers to your bot and start polling

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()
Sign up to request clarification or add additional context in comments.

2 Comments

the code works perfectly fine when I try to send a normal text when I press the button, but I cannot seem to make the following work: /mon name. It doesn't seem to recognize commands which are send by the bot itself. Do you know how to address this issue?
reply_markup needs to be a list of lists. So it should be telegram.InlineKeyboardMarkup([[help_button]]).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.