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 Notifier Laravel Package

symfony/telegram-notifier

Symfony Telegram Notifier provides a Telegram integration for the Symfony Notifier component, letting you send notifications and messages to Telegram chats via bots. Easy to configure in Symfony apps and compatible with the broader notifier channel system.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:

    composer require symfony/telegram-notifier
    
  2. Configure the DSN in .env:

    TELEGRAM_DSN=telegram://TOKEN@default?channel=CHAT_ID
    
    • Replace TOKEN with your Telegram Bot Token.
    • Replace CHAT_ID with your target chat ID (e.g., @username or a numeric group ID).
  3. Register the transport in config/packages/notifier.yaml:

    notifier:
        chat:
            telegram: '%env(TELEGRAM_DSN)%'
    
  4. First use case: Send a simple message in a controller or command:

    use Symfony\Component\Notifier\NotifierInterface;
    use Symfony\Component\Notifier\Message\ChatMessage;
    
    public function sendNotification(NotifierInterface $notifier): void
    {
        $message = new ChatMessage('Hello from Laravel!');
        $notifier->send($message);
    }
    

Key Entry Points

  • DSN Configuration: Centralize credentials in .env for security.
  • Notifier Service: Inject NotifierInterface (autowired by Symfony) to send messages.
  • ChatMessage: The base class for all Telegram messages.

Implementation Patterns

1. Basic Notifications

Use Case: Alerts, logs, or status updates.

$message = new ChatMessage('Deployment failed on staging!');
$message->options((new TelegramOptions())->parseMode('MarkdownV2'));
$notifier->send($message);

2. Rich Messages with Media

Use Case: Attachments, images, or documents.

$options = (new TelegramOptions())
    ->photo('https://example.com/image.jpg')
    ->caption('Monthly Report')
    ->parseMode('HTML');

$message = new ChatMessage('Check the report below:');
$message->options($options);
$notifier->send($message);

3. Interactive Buttons

Use Case: Polls, surveys, or workflows.

$markup = (new InlineKeyboardMarkup())
    ->inlineKeyboard([
        (new InlineKeyboardButton('Approve'))->callbackData('approve'),
        (new InlineKeyboardButton('Reject'))->callbackData('reject'),
    ]);

$options = (new TelegramOptions())->replyMarkup($markup);
$message = new ChatMessage('Review this PR?');
$message->options($options);
$notifier->send($message);

4. Threaded Conversations

Use Case: Organize messages in threads (Symfony 7.3+).

$options = (new TelegramOptions())->messageThreadId(-100123456789); // Thread ID
$message = new ChatMessage('Threaded reply');
$message->options($options);
$notifier->send($message);

5. File Uploads

Use Case: Local files (e.g., logs, reports).

$options = (new TelegramOptions())
    ->uploadDocument(storage_path('logs/laravel.log'))
    ->caption('Server Logs');

$message = new ChatMessage('Check the logs:');
$message->options($options);
$notifier->send($message);

6. Dynamic Recipients

Use Case: Route messages to multiple chats.

$chats = ['@admin', '-100123456789']; // Group/channel IDs
foreach ($chats as $chatId) {
    $message = new ChatMessage('Urgent: Server down!');
    $message->options((new TelegramOptions())->chatId($chatId));
    $notifier->send($message);
}

7. Error Handling

Use Case: Retry failed sends or log errors.

try {
    $notifier->send($message);
} catch (TransportException $e) {
    Log::error('Telegram send failed: ' . $e->getMessage());
    // Retry logic or fallback (e.g., email)
}

Integration Tips

  1. Symfony Messenger: Integrate with Symfony’s Messenger component for async processing:

    # config/packages/messenger.yaml
    framework:
        messenger:
            transports:
                telegram: '%env(TELEGRAM_DSN)%'
            routing:
                'App\Message\TelegramAlert': telegram
    
    $bus->dispatch(new TelegramAlert('Alert message'));
    
  2. Laravel Events: Trigger notifications on events (e.g., job.failed):

    Event::listen(JobFailed::class, function (JobFailed $event) {
        $message = new ChatMessage("Job failed: {$event->job}");
        $notifier->send($message);
    });
    
  3. Scheduled Tasks: Use Laravel’s scheduler to send periodic updates:

    $schedule->call(function () {
        $notifier->send(new ChatMessage('Daily digest'));
    })->daily();
    
  4. Local Development: Use sslmode=disable for local testing (see README).


Gotchas and Tips

Pitfalls

  1. DSN Format:

    • Error: telegram://TOKEN@default?chat=CHAT_ID (incorrect parameter name).
    • Fix: Use channel or chat (both work, but channel is explicit for groups).
    • Example: telegram://TOKEN@default?channel=-100123456789.
  2. File Size Limits:

    • Telegram’s file size limits apply (e.g., 50MB for documents).
    • Workaround: Compress large files or split into multiple messages.
  3. Markdown Escaping:

    • Special characters (*, _, [) in messages may break formatting.
    • Fix: Use parseMode('HTML') or escape characters manually.
  4. Rate Limits:

    • Telegram enforces rate limits.
    • Fix: Implement retries with exponential backoff (e.g., using symfony/messenger).
  5. Callback Queries:

    • Error: Forgetting to answerCallbackQuery can leave buttons unresponsive.
    • Fix: Always handle callbacks in your bot’s update handler.
  6. Local Testing:

    • Disabling SSL (sslmode=disable) exposes traffic to MITM attacks.
    • Fix: Use a local proxy (e.g., Nginx with TLS) or stick to HTTPS.

Debugging Tips

  1. Enable Debug Mode: Configure the DSN to log requests:

    TELEGRAM_DSN=telegram://TOKEN@default?channel=CHAT_ID&debug=1
    

    Check logs for raw API responses.

  2. Inspect Raw API Calls: Use a Telegram API proxy to debug locally.

  3. Validate Chat IDs:

  4. Handle Exceptions: Catch Symfony\Component\Notifier\Exception\TransportException for failed sends:

    try {
        $notifier->send($message);
    } catch (TransportException $e) {
        // Log or notify admins
    }
    

Extension Points

  1. Custom Transport: Extend TelegramTransport to add features (e.g., custom API endpoints):

    class CustomTelegramTransport extends TelegramTransport
    {
        protected function getUri(): UriInterface
        {
            return new Uri('https://custom-api.example.com/bot' . $this->token);
        }
    }
    
  2. Message Factories: Create reusable message builders:

    class TelegramAlertFactory
    {
        public static function create(string $title, string $message): ChatMessage
        {
            $options = (new TelegramOptions())
                ->parseMode('MarkdownV2')
                ->disableWebPagePreview(true);
    
            $chatMessage = new ChatMessage($message);
            $chatMessage->options($options);
    
            return $chatMessage->subject($title);
        }
    }
    
  3. Middleware: Use Symfony Messenger middleware to modify messages:

    $bus->addMiddleware(new class implements MiddlewareInterface {
        public function handle(Envelope $envelope, HandleMiddleware $next): Envelope
        {
            $message = $envelope->getMessage();
            if ($message instanceof ChatMessage) {
                $message->options((new TelegramOptions())->addReplyMarkup(...));
            }
            return $next->handle($envelope);
    
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.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle