Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Telegram Laravel Package

laravel-notification-channels/telegram

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require laravel-notification-channels/telegram
    

    Publish the config file:

    php artisan vendor:publish --provider="NotificationChannels\Telegram\TelegramServiceProvider"
    
  2. 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
    
  3. 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());
    

Where to Look First

  • Config File: config/services/telegram.php (adjust timeouts, proxies, or default settings).
  • Documentation: Focus on the Usage section in the README for quick examples.
  • Telegram Bot API Docs: Core Telegram Bot API for advanced payloads.

Implementation Patterns

Core Workflow: Sending Notifications

  1. 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']);
    }
    
  2. 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}");
    }
    
  3. 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');
    }
    

Integration Tips

  • 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
    

Gotchas and Tips

Pitfalls

  1. Chat ID Mismatch

    • Issue: Messages fail silently if the chat_id is invalid or expired.
    • Fix: Log failed notifications via NotificationFailed event:
      Event::listen(NotificationFailed::class, function ($event) {
          logger()->error('Telegram failed', ['error' => $event->exception]);
      });
      
    • Tip: Use /getUpdates in BotFather to verify active chats.
  2. Rate Limits

    • Issue: Telegram throttles bots at 30 requests/second.
    • Fix: Implement exponential backoff in custom channels or use Laravel’s queue with retries:
      'telegram' => [
          'driver' => 'database',
          'retry_after' => 60, // Retry after 60 seconds on failure
      ],
      
  3. Media File Size

    • Issue: Files > 50MB require https URLs (not local paths).
    • Fix: Upload to cloud storage (S3) first, then attach:
      $url = Storage::disk('s3')->url('large-file.pdf');
      return TelegramMedia::create()->document($url);
      

Debugging

  • 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
    

Extension Points

  1. Custom Payloads Extend TelegramMessage for unsupported features:

    class CustomTelegramMessage extends TelegramMessage
    {
        public function inlineKeyboard($buttons)
        {
            $this->data['reply_markup'] = json_encode($buttons);
            return $this;
        }
    }
    
  2. 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;
        });
    });
    
  3. Webhook Security Validate updates with a token:

    $telegram = app(\NotificationChannels\Telegram\Telegram::class);
    $telegram->setWebhookToken('your_secret_token');
    

Pro Tips

  • 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(),
            ]);
        }
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware