Philip Mutua
Philip Mutua

Reputation: 6871

How to handle callbacks for InlineKeyboardButtons for telegram bots

How do I handle callbacks for inline keyboards? I tried to check documentation regarding this topic here but I didn't find anything that would assist me resolve this.

Here is what I would like to achieve, if a user presses any button the bot knows which button was pressed and do something with it. Here is my code snippet so far.

from django_tgbot.decorators import processor
from django_tgbot.state_manager import message_types, update_types, state_types
from django_tgbot.types.update import Update
from ..bot import state_manager
from ..models import TelegramState
from ..bot import TelegramBot


from django_tgbot.types.inlinekeyboardbutton import InlineKeyboardButton
from django_tgbot.types.inlinekeyboardmarkup import InlineKeyboardMarkup
from django_tgbot.types.keyboardbutton import KeyboardButton
from django_tgbot.types.replykeyboardremove import ReplyKeyboardRemove

from django_tgbot.types.replykeyboardmarkup import ReplyKeyboardMarkup



@processor(state_manager,success='asked_to_select_main_menu_options')
def main_manu_options(bot: TelegramBot, update: Update, state: TelegramState):
    chat_id = update.get_chat().get_id()

    bot.sendMessage(
        chat_id,
        text='What would you like to do?',
        reply_markup=InlineKeyboardMarkup.a(
            inline_keyboard=[
                [
                    InlineKeyboardButton.a('Parking',callback_data='PK'),
                ],
                [
                    InlineKeyboardButton.a('SBP', callback_data='SBP')
                ],
                [
                    InlineKeyboardButton.a('Land Rates',callback_data='LR')
                ],
                [
                    InlineKeyboardButton.a('Rent',callback_data='R')
                ],
                [
                    InlineKeyboardButton.a('Bill Payment',callback_data='B')
                ]
            ]
        )
    )

Upvotes: 2

Views: 905

Answers (1)

wowkin2
wowkin2

Reputation: 6355

Processor that should handle Update with with result of InlineKeyboardButton is calling CallbackQuery and you should add it in update_type as argument, see example:

@processor(state_manager, from_states=state_types.All, update_types=[update_types.CallbackQuery])
def handle_callback_query(bot: TelegramBot, update, state):
    callback_data = update.get_callback_query().get_data()
    bot.answerCallbackQuery(update.get_callback_query().get_id(), text='Callback data received: {}'.format(callback_data))

Here you can find an example of bot that works with InlineKeyboardButton and utilize django-tgbot library.

Upvotes: 2

Related Questions