DEF STUDIO srl

Webhook Request Types

Telegraph can handle four incoming webhook request types: Chat Messages, Message Reactions, Chat Commands, Callback Queries and Inline Queries:

Chat Messages

Plain chat messages (messages that are not commands or queries) can be handled by overriding DefStudio\Telegraph\Handlers\WebhookHandler::handleChatMessage() method:

class CustomWebhookHandler extends WebhookHandler
{
    protected function handleChatMessage(Stringable $text): void
    {
        // in this example, a received message is sent back to the chat
        $this->chat->html("Received: $text")->send();
    }
}
Warning

A bot can read non-command/queries messages only if its privacy mode is disabled. To change a bot privacy settings see this guide

You can also handle any content of Telegram, like: Contact, Photo, Voice and etc...

class CustomWebhookHandler extends WebhookHandler
{
    protected function handleChatMessage(Stringable $text): void
    {
        // checks that the contact matches the sender ID

        $contactUserId = $this->message->contact()->userId();
        $senderId = $this->message->from()->id();

        if($contactUserId == $senderId){
            $this->reply('this is your contact');
        }else{
            $this->reply('this is NOT your contact');  
        }
    }
}

Message Reactions

Chat messages containing adding and/or deleting user reactions (emojis) to messages.

It can be handled by overriding DefStudio\Telegraph\Handlers\WebhookHandler::handleChatReaction() method:

class CustomWebhookHandler extends WebhookHandler
{
    protected function handleChatReaction(array $newReactions, array $oldReactions): void
    {
        // in this example, a received emoji message is sent back to the chat
        $this->chat->html("Received: " . $newReactions[0]['emoji'])->send();
    }
}
Warning

By default, Telegram does not report events related to reactions to messages. To interact with reactions, specify in the settings all types of messages for which you want to catch events.

Chat Commands

Telegraph bots can receive commands from chats where they are registered. A command is a telegram message has a slash (/) char followed by a descriptive word:

/hi Fabio

what the command will trigger is up to the developer, but a webhook will react to it if it has a public method named as the command:

class CustomWebhookHandler extends WebhookHandler
{
    public function hi()
    {
        $this->chat->markdown("*Hi* happy to be here!")->send();
    }
}

optionally, the handler method can receive the command parameters:

class CustomWebhookHandler extends WebhookHandler
{
    public function hi(string $userName)
    {
        $this->chat->markdown("*Hi* $userName, happy to be here!")->send();
    }
}

The full chat message data can be retrieved through the DefStudio\Telegraph\DTO\Message DTO:

class CustomWebhookHandler extends WebhookHandler
{
    public function hi()
    {
        $text = $this->message->text(); // /hi Fabio
    }
}

Unknown commands

The default Telegraph's behaviour for unknown commands is to report an exception in application log (this can be disabled in telegraph config) and answer the user that the command is unknown

A custom handler can be defined by overriding the WebhookHandler::handleUnknownCommand method:

class MyWebhookHandler extends WebhookHandler
{
    // ... 

    protected function handleUnknownCommand(Stringable $text): void
    {
        if (!self::$handleUnknownCommands) {
            parent::handleUnknownCommand($text);
        }

        $this->chat->html("I can't understand your command: $text")->send();
    }
}

Callback Queries

Bots messages may ship with keyboard of buttons that trigger actions when pressed:

<img src=/img/screenshots/keyboard-example.png" />

when pressed, a new call will be forwarded to the webhook with the following payload

action:dismiss;notification-id:42

and the dismiss action will be handled by a corresponding public method in the custom webhook handler:

class CustomWebhookHandler extends WebhookHandler
{
    public function dismiss()
    {
        $notificationId = $this->data->get('notification-id'); //42

        Notification::find($notificationId)->dismiss();

        $this->reply("notification dismissed");
    }
}

The full callback query data can be retrieved through the DefStudio\Telegraph\DTO\CallbackQuery DTO

class CustomWebhookHandler extends WebhookHandler
{
    public function dismiss()
    {
        $notificationId = $this->callbackQuery->data()->get('notification-id'); //42

        Notification::find($notificationId)->dismiss();

        $this->reply("notification dismissed");
    }
}

Inline queries

Users can interact with a bot through inline queries calling it by typing its name followed by the query. The query is sent to the webhook (or can be manually polled) wrapped in a DefStudio\Telegraph\DTO\InlineQuery. For more information see inline bot page and the official api documentation

Inline queries should be enabled inside bot configuration (see here for more info)

Inside a WebhookHandler, incoming inline queries are handled by overriding the handleInlineQuery method:

use DefStudio\Telegraph\DTO\InlineQuery;
use DefStudio\Telegraph\DTO\InlineQueryResultPhoto;

class CustomWebhookHandler extends WebhookHandler
{
    public function handleInlineQuery(InlineQuery $inlineQuery): void
    {
        $query = $inlineQuery->query(); // "pest logo"

        $logo = LogoFinder::search($query); // the code to handle the query. just an example here

        $this->bot->answerInlineQuery($inlineQuery->id(), [
            InlineQueryResultPhoto::make($logo->id."-light", "https://logofinder.dev/$logo->id/light.jpg", "https://logofinder.dev/$logo->id/light/thumb.jpg")
                ->caption('Light Logo'),
            InlineQueryResultPhoto::make($logo->id."-dark", "https://logofinder.dev/$logo->id/dark.jpg", "https://logofinder.dev/$logo->id/dark/thumb.jpg")
                ->caption('Light Logo'),
        ])->send();
    }
}

Different kind of result can be sent through the handler:

Member activities

Telegraph bots can listen for members join/leave activity in chats where they are registered and handle them by overriding handleChatMemberJoined and handleChatMemberLeaved methods:

Member joined

class CustomWebhookHandler extends WebhookHandler
{
    protected function handleChatMemberJoined(User $member): void
    {
        $this->chat->html("Welcome {$member->firstName()}")->send();
    }
}

Member left

class CustomWebhookHandler extends WebhookHandler
{
    protected function handleChatMemberLeft(User $member): void
    {
        $this->chat->html("{$member->firstName()} just left")->send();
    }
}
Suggest a change
Last updated 03 October 2024