Webhooks Overview
Telegram bots can interact with chats and users through a webhook system that enables it to be updated about chats changes, new commands and user interactions without continuously polling Telegram APIs for updates.
WarningBy default webhooks can handle incoming requests from "known" chats (the one stored in database as TelegraphChat models) and will reject all others. In order to handle unknown chats see below
Default Handler
A default "do nothing" handler is shipped with Telegraph installation, it can only handle a single chat command:
/chatid
And answers with the ID of the chat the command is issued into. It is useful to get the ChatID in order to register a new chat in Telegraph
Custom Handler
In order to write custom webhook and commands handlers the default handler must be switched with a custom one
// app/Http/Webhooks/MyWebhookHandler.php class MyWebhookHandler extends \DefStudio\Telegraph\Handlers\WebhookHandler { public function myCustomHandler(): void { // ... My awesome code } }
WarningA custom webhook handler must extend
DefStudio\Telegraph\Handlers\WebhookHandler
and has to be registered inconfig('telegraph.webhook.handler')
A detailed description of how WebhookHandlers work can be found in the next sections
Middleware
A custom middleware can be applied to all webhook requests by adding a telegraph.webhook.middleware
config entry:
'webhook' => [ // ... /* * Middleware to be applied to the webhook route */ 'middleware' => [], // ...
Handle requests from unknown chats
By default webhooks can handle incoming requests from "known" chats (the one stored in database as TelegraphChat models) and will reject all others.
Callback queries, commands and messages handling from unknown chats can be enabled from telegraph config in security settings:
'security' => [ /* * if enabled, allows callback queries from unregistered chats */ 'allow_callback_queries_from_unknown_chats' => true, /* * if enabled, allows messages and commands from unregistered chats */ 'allow_messages_from_unknown_chats' => true, /* * if enabled, store unknown chats as new TelegraphChat models */ 'store_unknown_chats_in_db' => true, ],
How to handle failures
By default, the webhook handler will reply with a Sorry, an error occurred
message and will report the exception in logs if something goes wrong (an Exception is thrown) during the webhook call handling. This will avoid the bot to keep sending its call to the server (the default Telegram behaviour in case of 500 errors)
to customize the webhook behavior in case of exceptions, the onFailure()
method can be overridden:
class MyWebhookHandler extends \DefStudio\Telegraph\Handlers\WebhookHandler { protected function onFailure(Throwable $throwable): void { if ($throwable instanceof NotFoundHttpException) { throw $throwable; } report($throwable); $this->reply('sorry man, I failed'); } }