Telegram
✈️ Telegram Notifications Channel for Laravel
Install / Use
/learn @laravel-notification-channels/TelegramREADME
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.
Contents
- Installation
- Usage
- Text Notification
- Send with Keyboard
- Send a Dice
- Send a Poll
- Attach a Contact
- Attach an Audio
- Attach a Photo
- Attach a Document
- Attach a Location
- Attach a Venue
- Attach a Video
- Attach a GIF File
- Attach a Sticker
- Send a Media Group
- Routing a Message
- Handling Response
- Exception Handling
- On-Demand Notifications
- Sending to Multiple Recipients
- Using the Telegram Client Directly
- Available Methods
- Alternatives
- Changelog
- Testing
- Security
- Contributing
- Credits
- License
Installation
You can install the package via composer:
composer require laravel-notification-channels/telegram
Setting up your Telegram Bot
Talk 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'),
],
[!NOTE] The package also supports the legacy
services.telegram-bot-api.*config keys for backward compatibility, butservices.telegram.*is the preferred configuration format.
Retrieving Chat ID
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].
Using in Lumen
If you're using this notification channel in your Lumen project, you will have to add the below code in your bootstrap/app.php file.
# bootstrap/app.php
// Make sure to create a "config/services.php" file and add the config from the above step.
$app->configure('services');
# Register the notification service providers.
$app->register(Illuminate\Notifications\NotificationServiceProvider::class);
$app->register(NotificationChannels\Telegram\TelegramServiceProvider::class);
Proxy or Bridge Support
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.
Usage
You can now return the channel from your notification's via() method.
Text Notification
use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;
class InvoicePaid extends Notification
{
public function via($notifiable)
{
return ['telegram'];
}
public function toTelegram($notifiable)
{
$url = url('/invoice/' . $notifiable->invoice->id);
$user = $notifiable->name;
return TelegramMessage::create()
->to($notifiable->telegram_user_id)
->content('Hello there!')
->line('Your invoice has been *PAID*')
->lineIf($notifiable->amount > 0, "Amount paid: {$notifiable->amount}")
->line('Thank you, '.TelegramMessage::escapeMarkdown($user).'!')
// ->view('notification', ['url' => $url])
->button('View Invoice', $url)
->button('Download Invoice', $url);
// Other fluent helpers are also available:
// ->businessConnectionId('business-connection-id')
// ->messageThreadId(42)
// ->protectContent()
// ->directMessagesTopicId(1001)
// ->allowPaidBroadcast()
// ->messageEffectId('5104841245755180586')
// ->replyParameters(['message_id' => 123])
// ->suggestedPostParameters(['price' => ['amount' => 10, 'currency' => 'XTR']])
// ->entities([...])
// ->linkPreviewOptions(['is_disabled' => true])
// ->sendWhen($notifiable->amount > 0)
// ->buttonWithWebApp('Open Web App', $url)
// ->buttonWithCallback('Confirm', 'confirm_invoice '.$this->invoice->id)
}
}
Here's a screenshot preview of the above notification on Telegram Messenger:

Send with Keyboard
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:
Send a Dice
use NotificationChannels\Telegram\TelegramDice;
public function toTelegram($notifiable)
{
return TelegramDice::create()
->to($notifiable->telegram_user_id)
->emoji('🎯');
}
Preview:
Send a Poll
public function toTelegram($notifiable)
{
return TelegramPoll::create()
->to($notifiable->telegram_user_id)
->question('Which is your favorite Laravel Notification Channel?')
->choices(['Telegram', 'Facebook', 'Slack']);
}
Preview:
Attach a Contact
public function toTelegram($notifiable)
{
return TelegramContact::create()
->to($notifiable->telegram_user_id) // Optional
->firstName('John')
->lastName('Doe') // Optional
->phoneNumber('00000000');
}
Preview:
Attach an Audio
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
