✈️ Telegram Notifications Channel for Laravel
[![Join PHP Chat][ico-phpchat]][link-phpchat] [![Chat on Telegram][ico-telegram]][link-telegram] [![Latest Version on Packagist][ico-version]][link-packagist] ![Software License][ico-license] [![Total Downloads][ico-downloads]][link-packagist]
This package makes it easy to send Telegram notifications from Laravel via the Telegram Bot API.
You can install the package via composer:
composer require laravel-notification-channels/telegramTalk to @BotFather and generate a Bot API token.
Then, configure your Telegram Bot API token:
# config/services.php
'telegram' => [
'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE'),
// Optional bridge / self-hosted Bot API server
// 'base_uri' => env('TELEGRAM_API_BASE_URI'),
// Optional Guzzle HTTP client options.
// Defaults: 30s request timeout, 10s connection timeout.
// 'http' => [
// 'timeout' => 30,
// 'connect_timeout' => 10,
// 'proxy' => env('TELEGRAM_HTTP_PROXY'),
// ],
],[!NOTE] The package also supports the legacy
services.telegram-bot-api.*config keys for backward compatibility, butservices.telegram.*is the preferred configuration format.
To send notifications to a Telegram user, channel, or group, you need its chat ID.
You can retrieve it by fetching your bot [updates][link-telegram-docs-update] with the getUpdates method described in the Telegram Bot API [docs][link-telegram-docs-getupdates].
An [update][link-telegram-docs-update] is an object whose shape depends on the event type, such as message, callback_query, or poll. For the full list of fields, see the [Telegram Bot API docs][link-telegram-docs-update].
To make this easier, the package ships with TelegramUpdates, which lets you fetch updates and inspect the chat IDs you need.
Keep in mind that the user must interact with your bot first before you can obtain their chat ID and store it for future notifications.
Here's an example of fetching an update:
use NotificationChannels\Telegram\TelegramUpdates;
// Response is an array of updates.
$updates = TelegramUpdates::create()
// (Optional) Get the latest update.
// NOTE: All previous updates will be forgotten using this method.
// ->latest()
// (Optional) Limit to 2 updates. By default, updates start with the earliest unconfirmed update.
->limit(2)
// (Optional) Add more request parameters.
->options([
'timeout' => 0,
])
->get();
if ($updates['ok']) {
// Chat ID
$chatId = $updates['result'][0]['message']['chat']['id'];
}[!NOTE] This method will not work while an outgoing webhook is configured.
For the full list of supported options(), see the [Telegram Bot API docs][link-telegram-docs-getupdates].
You may not be able to send notifications directly if the Telegram Bot API is blocked in your region.
In that case, you can either configure a proxy by following the Guzzle instructions here or
point the package at a bridge or self-hosted Bot API server by setting the base_uri config shown above.
You can also set HTTPS_PROXY in your .env file, or set the proxy key (or any other Guzzle request option, such as timeout) in the services.telegram.http config array shown above.
You can now return the channel from your notification's via() method.
…Here's a screenshot preview of the above notification on Telegram Messenger:
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->to($notifiable->telegram_user_id)
->content('Choose an option:')
->keyboard('Button 1')
->keyboard('Button 2');
}Preview:
You can also request structured input from the keyboard:
TelegramMessage::create()
->content('Please share your phone number or location')
->keyboard('Send your number', requestContact: true)
->keyboard('Send your location', requestLocation: true);Preview:
use NotificationChannels\Telegram\TelegramDice;
public function toTelegram($notifiable)
{
return TelegramDice::create()
->to($notifiable->telegram_user_id)
->emoji('');
}Preview:
…Preview:
Rich messages (Bot API 10.1) let you send long-form, formatted posts built from blocks or from a single Markdown / HTML document.
The simplest way is to pass Markdown (or HTML) content, referencing any attached media with tg://photo?id=, tg://video?id= or tg://audio?id= links:
use NotificationChannels\Telegram\TelegramRichMessage;
public function toTelegram($notifiable)
{
return TelegramRichMessage::create()
->to($notifiable->telegram_user_id)
->markdown(media('receipt', ['type' => 'photo', 'media' => 'https://example.com/receipt.jpg'])
->button('View Invoice', url('/invoice/1234'));
// Or render a Blade view as the HTML content instead:
// ->view('invoices.telegram', ['invoice' => $notifiable->invoice])
}For full control over the layout, build the message out of blocks:
…All the common methods (to(), button(), keyboard(), disableNotification(), replyParameters(), ...) work as usual and are sent alongside the encoded rich_message param.
[!NOTE] Block types without a dedicated builder (such as
collageandslideshow) can be added with theblock()escape hatch. Direct file uploads for rich message media are not supported: reference media by URL orfile_id.
Drafts (sendRichMessageDraft) are temporary messages shown to the user while they're still being written. Sending again with the same draftId() animates the replacement of the previous content, which makes TelegramRichMessageDraft a good fit for streaming an AI generated answer as it's produced:
…Every content and block builder of TelegramRichMessage is available on the draft, so you can stream blocks instead of Markdown if you prefer.
[!IMPORTANT] Drafts can only be sent to private chats and the
draft_idmust be a non-zero integer. Batch your updates (roughly onesend()every 0.5-1 seconds) instead of sending one per token, otherwise your bot will quickly hit the API rate limits. A draft that's never finalized simply disappears: onlyfinalize()leaves a permanent message behind. The endpoint acceptschat_id,message_thread_id,draft_id,rich_message,can_stopandkeep_on_stoponly, so buttons and notification flags are applied when the draft is finalized.
public function toTelegram($notifiable)
{
return TelegramContact::create()
->to($notifiable->telegram_user_id) // Optional
->firstName('John')
->lastName('Doe') // Optional
->phoneNumber('00000000');
}Preview:
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id) // Optional
->content('Audio') // Optional caption
->captionEntities([
['offset' => 0, 'length' => 5, 'type' => 'bold'],
])
->audio('/path/to/audio.mp3');
}Preview:
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id) // Optional
->content('Awesome *bold* text and [inline URL](http://www.example.com/)')
->showCaptionAboveMedia()
->file('/storage/archive/6029014.jpg', 'photo'); // local photo
}You can also use a helper method with a remote file or Telegram file ID:
TelegramFile::create()
->photo('https://samples-files.com/samples/images/jpg/1280-720-sample.jpg');If you already know whether you're dealing with a URL or a Telegram file ID, use the explicit methods instead — they validate the input and skip the detection heuristics:
use NotificationChannels\Telegram\Enums\FileType;
TelegramFile::create()
->url('https://samples-files.com/samples/images/jpg/1280-720-sample.jpg', FileType::Photo);
TelegramFile::create()
->fileId('AgACAgQAAxkDAAIBLGV3', FileType::Photo);Preview:
public function toTelegram($notifiable)
{
return TelegramFile::create()
->to($notifiable->telegram_user_id) // Optional
->content('Here is your PDF document')
->document('https://samples-files.com/samples/documents/pdf/sample-1-small-size.pdf');
}Preview:
If you want to control the filename, you need to upload the actual file contents instead of passing the remote URL directly:
$contents = file_get_contents('https://samples-files.com/samples/documents/pdf/sample-1-small-size.pdf');
TelegramFile::create()
->content('Did you know we can set a custom filename too?')
->document($contents, 'sample.pdf');Preview:
Raw file contents are also supported when you provide a filename:
TelegramFile::create()
->document('Hello Text Document Content', 'hello.txt');Preview:
public function toTelegram($notifiable)
{
return TelegramLocation::create()
->to($notifiable->telegram_user_id)
->latitude('40.6892494')
->longitude('-74.0466891');
}Preview:
You can also sen
No open issues yet, or sync has not completed.