DEV Community

Cover image for Managing CallbackQuery and message types in Telegram bots
Benyamin Khalife
Benyamin Khalife

Posted on • Edited on

Managing CallbackQuery and message types in Telegram bots

Continuing from the previous article, this time I will describe the changes I made to the library.

The user in the Telegram bot can send different types of messages, such as text messages, photos, videos, etc. In some cases, we need to know what type of message the client has sent so that we can respond to it accordingly, or perhaps we need to limit the type of message for the client

So, a method had to be created to detect the type of message sent by the client, and as a result, the message type could be received using the following method:

$type =  Bot::message()->type();
Enter fullscreen mode Exit fullscreen mode

I think this is a clean and simple syntax, don't you?

The values ​​it returns are one of these:
'text', 'photo', 'video', 'audio', 'document', 'sticker', 'animation', 'location', 'contact', 'poll'

I also put the consts of these types in the message method, which are:

const TYPE_TEXT = 'text';
const TYPE_PHOTO = 'photo';
const TYPE_VIDEO = 'video';
const TYPE_AUDIO = 'audio';
const TYPE_DOCUMENT = 'document';
const TYPE_STICKER = 'sticker';
const TYPE_ANIMATION = 'animation';
const TYPE_LOCATION = 'location';
const TYPE_CONTACT = 'contact';
const TYPE_POLL = 'poll';
const TYPE_MESSAGE = 'message';

Enter fullscreen mode Exit fullscreen mode

These constants are accessible from the Message class, so creating a condition to check the type of user message could look something like this:

if(Bot::message()->type() == Message::TYPE_TEXT){
    // Do something.
}
else{
    Bot::new()->text('Please send your message as text.')->send();
}
Enter fullscreen mode Exit fullscreen mode

What is your opinion about this structure? I would be happy if you share it with me.

Detecting a query callback in a Telegram bot

Image description

There is another type of message. When the client clicks on an inline button In this case, Telegram sends us a Callback that also contains the data object of that message.

I created the isCallbackQuery method for this purpose, which can be used as follows:

if ( Bot::isCallbackQuery() ) {

    $data = Bot::callback()->data();

    Bot::new()->text("πŸ›œ Get Callback Query:\nData : $data")->send();
}
Enter fullscreen mode Exit fullscreen mode

So if the value of Bot::isCallbackQuery() is true, we know that the client has clicked a button. In this case, we have access to the callback method and we can get the data of the button that the client clicked using Bot::callback()->data()

View on GitHub: BotFire

This library is under development and is not yet ready for use.

Top comments (0)