Skip to content
Advertisement

Getting callback query from telegram inline buttons

I am new to telegram inline bot. I have no clue how I can retrieve the callback function of telegram’s inlinekeyboardbuttons. Would be forever greatful if someone can explain this to me how I could retrieve user response.

def options(update, context):
button_list = []
for each in ["yes", "no"]:
    button_list.append(InlineKeyboardButton(each, callback_data=each))
reply_markup = InlineKeyboardMarkup(build_menu(button_list))
context.bot.send_message(chat_id=update.message.chat_id,
                         text="Option Selected:",
                         reply_markup=reply_markup)

def build_menu(buttons, n_cols=1, header_buttons=None, footer_buttons=None):
"""
Returns a list of inline buttons used to generate inlinekeyboard responses

:param buttons: `List` of InlineKeyboardButton
:param n_cols: Number of columns (number of list of buttons)
:param header_buttons: First button value
:param footer_buttons: Last button value
:return: `List` of inline buttons
"""
menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
if header_buttons:
    menu.insert(0, header_buttons)
if footer_buttons:
    menu.append(footer_buttons)
return menu

Advertisement

Answer

You have to use CallbackQueryHandler to assing function to data

If you use pattern .* then it will get all data in one function

def handle_callback_query(update, context):
    print(update.callback_query.data)
    context.bot.send_message(chat_id=update.effective_chat.id, 
                             text='[handle_callback_query] callback data: ' + update.callback_query.data)

dispatcher.add_handler(CallbackQueryHandler(handle_callback_query, pattern='.*'))

You can also use pattern to assing different functions

def query_yes(update, context):
    print(update.callback_query.data)
    context.bot.send_message(chat_id=update.effective_chat.id, 
                             text='[query_yes] callback data: ' + update.callback_query.data)

def query_no(update, context):
    print(update.callback_query.data)
    context.bot.send_message(chat_id=update.effective_chat.id, 
                             text='[query_no] callback data: ' + update.callback_query.data)

dispatcher.add_handler(CallbackQueryHandler(query_yes, pattern='^yes$'))
dispatcher.add_handler(CallbackQueryHandler(query_no,  pattern='^no$'))

Minimal working example.

import os
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
from telegram import InlineKeyboardButton, InlineKeyboardMarkup

# --- init ---

TOKEN = os.getenv('TELEGRAM_TOKEN')

updater = Updater(token=TOKEN, use_context=True)
dispatcher = updater.dispatcher

# --- commands ---

def options(update, context):
    button_list = []
    for each in ["yes", "no"]:
        button_list.append(InlineKeyboardButton(each, callback_data=each))
    reply_markup = InlineKeyboardMarkup(build_menu(button_list))
    context.bot.send_message(chat_id=update.message.chat_id,
                             text="Option Selected:",
                             reply_markup=reply_markup)
    
def build_menu(buttons, n_cols=1, header_buttons=None, footer_buttons=None):
    """
    Returns a list of inline buttons used to generate inlinekeyboard responses
    
    :param buttons: `List` of InlineKeyboardButton
    :param n_cols: Number of columns (number of list of buttons)
    :param header_buttons: First button value
    :param footer_buttons: Last button value
    :return: `List` of inline buttons
    """
    menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)]
    if header_buttons:
        menu.insert(0, header_buttons)
    if footer_buttons:
        menu.append(footer_buttons)
    return menu
dispatcher.add_handler(CommandHandler('options', options))

# --- one function for all data ---

def handle_callback_query(update, context):
    print(update.callback_query.data)
    context.bot.send_message(chat_id=update.effective_chat.id, 
                             text='[handle_callback_query] callback data: ' + update.callback_query.data)

#dispatcher.add_handler(CallbackQueryHandler(handle_callback_query, pattern='.*'))

# --- different functions for different data ---

def query_yes(update, context):
    print(update.callback_query.data)
    context.bot.send_message(chat_id=update.effective_chat.id, 
                             text='[query_yes] callback data: ' + update.callback_query.data)

def query_no(update, context):
    print(update.callback_query.data)
    context.bot.send_message(chat_id=update.effective_chat.id, 
                             text='[query_no] callback data: ' + update.callback_query.data)

dispatcher.add_handler(CallbackQueryHandler(query_yes, pattern='^yes$'))
dispatcher.add_handler(CallbackQueryHandler(query_no,  pattern='^no$'))

# --- start ---

print('Starting ...')    
updater.start_polling()
updater.idle()
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement