Samuel Lipoff
Samuel Lipoff

Reputation: 1

InlineKeyboardButton And CallbackData

I want to ask about InlineKeyboardMarkup is how to catch the event when the user clicks the InlineKeyboardButton button with callback_data and how can I call it and process it?

And below is part of my code.

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

API        = "1234567890:API_Example"
Bot        = Updater(API, use_context = True)
Dispatcher = Bot.dispatcher

def start_command(update, context):
  RM       = InlineKeyboardMarkup(
    [[InlineKeyboardButton(
      text = "example button text",
      callback_data = "example data")
    ]])
  message  = "example message"
  context.bot.send_message(update.effective_chat.id, message,reply_markup = RM)

Dispatcher.add_handler(CommandHandler("start", start_command))
Bot.start_polling()

Upvotes: 0

Views: 858

Answers (1)

wowkin2
wowkin2

Reputation: 6355

You need to add CallbackQueryHandler to Dispatcher like:

CallbackQueryHandler(handler_yes_no, pattern=r'^(yes|no)$'),

Full example:

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

API = "1234567890:API_Example"
Bot = Updater(API, use_context = True)
Dispatcher = Bot.dispatcher


def start_command(update, context):
    RM = InlineKeyboardMarkup([
        [InlineKeyboardButton(text="Yes", callback_data="yes")],
        [InlineKeyboardButton(text="No", callback_data="no")],
    ])
    message = "Are you sure?"
    context.bot.send_message(update.effective_chat.id, message, reply_markup=RM)


def handler_yes_no(update, context):
    callback_data = update.callback_query.data
    update.callback_query.answer() 
    print(callback_data)


Dispatcher.add_handler(CommandHandler("start", start_command))
Dispatcher.add_handler(CallbackQueryHandler(handler_yes_no, pattern=r'^(yes|no)$'),)
Bot.start_polling()

P.S. don't forget about PEP8 code style guidelines :)

Upvotes: 1

Related Questions