Install the Package
composer require laravel-notification-channels/telegram
Publish the config file:
php artisan vendor:publish --provider="NotificationChannels\Telegram\TelegramServiceProvider"
Configure .env
Add your bot token and default chat ID:
TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_DEFAULT_CHAT_ID=your_chat_id_here
First Use Case: Send a Text Notification
Create a notification class (e.g., App\Notifications\TelegramAlert):
use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;
class TelegramAlert extends Notification
{
public function via($notifiable)
{
return ['telegram'];
}
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->text('Hello from Laravel!');
}
}
Trigger it in your code:
$user->notify(new TelegramAlert());
config/services/telegram.php (adjust timeouts, proxies, or default settings).Define Notifications
Extend Notification and implement toTelegram() for custom payloads:
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->text('Order #'.$notifiable->order_id.' is ready!')
->parseMode('HTML')
->replyKeyboard(['Cancel', 'Confirm']);
}
Dynamic Recipients
Use notifiable data to route messages:
public function via($notifiable)
{
return ['telegram', 'email']; // Multi-channel support
}
public function toTelegram($notifiable)
{
return TelegramMessage::create()
->chatId($notifiable->telegram_chat_id) // Override default
->text("Hi {$notifiable->name}, your balance is {$notifiable->balance}");
}
Media Attachments Streamline file uploads with helper methods:
use NotificationChannels\Telegram\TelegramMedia;
public function toTelegram($notifiable)
{
return TelegramMedia::create()
->photo('path/to/image.jpg')
->caption('Monthly Report');
}
Queue Notifications Use Laravel’s queue system for async delivery:
$user->notify(new TelegramAlert())->onQueue('telegram');
Configure queue in config/queue.php for dedicated workers.
Webhook Responses Handle Telegram updates via a route:
Route::post('/telegram/webhook', [TelegramController::class, 'handle']);
Use the NotificationChannels\Telegram\Telegram facade to process updates:
public function handle(Request $request)
{
$update = $request->json()->all();
$telegram = app(\NotificationChannels\Telegram\Telegram::class);
$telegram->handleUpdate($update);
}
Proxy Support
Configure proxies in .env for restricted networks:
TELEGRAM_PROXY_HOST=proxy.example.com
TELEGRAM_PROXY_PORT=8080
Chat ID Mismatch
chat_id is invalid or expired.NotificationFailed event:
Event::listen(NotificationFailed::class, function ($event) {
logger()->error('Telegram failed', ['error' => $event->exception]);
});
/getUpdates in BotFather to verify active chats.Rate Limits
'telegram' => [
'driver' => 'database',
'retry_after' => 60, // Retry after 60 seconds on failure
],
Media File Size
https URLs (not local paths).$url = Storage::disk('s3')->url('large-file.pdf');
return TelegramMedia::create()->document($url);
Enable Debug Mode
Set TELEGRAM_DEBUG=true in .env to log raw API responses.
Test Locally
Use tgbot CLI tool to simulate updates:
tgbot getMe
Custom Payloads
Extend TelegramMessage for unsupported features:
class CustomTelegramMessage extends TelegramMessage
{
public function inlineKeyboard($buttons)
{
$this->data['reply_markup'] = json_encode($buttons);
return $this;
}
}
Middleware Add logic before sending (e.g., sanitize text):
NotificationChannels\Telegram\Telegram::extend(function ($channel) {
$channel->extend('sanitize', function ($message) {
$message->text = strip_tags($message->text);
return $message;
});
});
Webhook Security Validate updates with a token:
$telegram = app(\NotificationChannels\Telegram\Telegram::class);
$telegram->setWebhookToken('your_secret_token');
Batch Processing
Use TelegramMediaGroup for carousel-style messages:
$group = TelegramMediaGroup::create();
$group->addPhoto('image1.jpg', 'Caption 1');
$group->addPhoto('image2.jpg', 'Caption 2');
return $group;
Environment-Specific Config Override settings per environment (e.g., dev/staging/prod):
config(['services.telegram.timeout' => env('TELEGRAM_TIMEOUT', 30)]);
Monitor Deliveries Track failed notifications in a database table:
Event::listen(NotificationFailed::class, function ($event) {
if ($event->channel === 'telegram') {
DB::table('telegram_failures')->insert([
'notifiable_id' => $event->notifiable->id,
'error' => $event->exception->getMessage(),
'created_at' => now(),
]);
}
});
How can I help you explore Laravel packages today?