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

Rocket Chat Notifier Laravel Package

symfony/rocket-chat-notifier

Symfony Notifier bridge for Rocket.Chat. Configure a rocketchat:// DSN with incoming webhook token and default channel, then send ChatMessages. Supports custom payload (alias/avatar/channel overrides) and multiple attachments for rich messages.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package Add to composer.json:

    composer require symfony/rocket-chat-notifier
    

    For Laravel, ensure compatibility with Symfony’s HTTP client (Laravel 10+ works natively).

  2. Configure DSN Add to .env:

    ROCKETCHAT_DSN=rocketchat://ACCESS_TOKEN@your-rocketchat-host?channel=general
    
    • Replace ACCESS_TOKEN with your RocketChat webhook token (URL-encoded if needed).
    • Replace your-rocketchat-host with your RocketChat instance domain (e.g., rocketchat.example.com).
    • channel is optional but recommended for default routing.
  3. First Notification Use Symfony’s Notifier in a Laravel controller or command:

    use Symfony\Component\Notifier\NotifierInterface;
    use Symfony\Component\Notifier\Message\ChatMessage;
    
    public function sendAlert(NotifierInterface $notifier)
    {
        $message = new ChatMessage('Deployment failed! Check logs.');
        $notifier->send($message);
    }
    

    Register the notifier in Laravel’s service container (see Implementation Patterns).


Implementation Patterns

Core Workflows

1. Basic Notifications

  • Use Case: Send simple alerts or status updates.
  • Pattern:
    $notifier = app(NotifierInterface::class);
    $message = new ChatMessage('System maintenance in 10 mins.');
    $notifier->send($message);
    
  • Laravel Integration: Bind the notifier in AppServiceProvider:
    public function register()
    {
        $this->app->bind(NotifierInterface::class, function ($app) {
            $dsn = getenv('ROCKETCHAT_DSN');
            $transport = new RocketChatTransport($dsn);
            return new Notifier([$transport]);
        });
    }
    

2. Rich Messages with Attachments

  • Use Case: Format messages with structured data (e.g., error logs, metrics).
  • Pattern:
    use Symfony\Component\Notifier\Bridge\RocketChat\RocketChatOptions;
    
    $payload = [
        'alias' => 'Laravel Monitor',
        'emoji' => ':robot_face:',
        'channel' => '#alerts', // Overrides DSN channel
    ];
    
    $attachment = [
        'title' => 'Database Error',
        'text' => 'Query timeout at 2023-10-05T12:34:56Z',
        'color' => '#ff0000',
    ];
    
    $options = new RocketChatOptions($attachment, $payload);
    $message = new ChatMessage('Critical DB Issue!', $options);
    $notifier->send($message);
    

3. Event-Driven Notifications

  • Use Case: Trigger RocketChat messages from Laravel events (e.g., OrderShipped, UserRegistered).
  • Pattern:
    // Listen to an event in EventServiceProvider
    public function boot()
    {
        OrderShipped::listen(function ($order) {
            $notifier = app(NotifierInterface::class);
            $message = new ChatMessage(
                "Order #{$order->id} shipped to {$order->customer_email}",
                new RocketChatOptions(null, [
                    'channel' => '#orders',
                    'alias' => 'Order Bot',
                ])
            );
            $notifier->send($message);
        });
    }
    

4. Dynamic Channel Routing

  • Use Case: Route messages to different channels based on context (e.g., user role, event type).
  • Pattern:
    $channel = auth()->user()->role === 'admin' ? '#admin-alerts' : '#team-alerts';
    $payload = ['channel' => $channel];
    $message = new ChatMessage('New login detected.', new RocketChatOptions(null, $payload));
    $notifier->send($message);
    

5. Queueing Notifications

  • Use Case: Avoid blocking HTTP requests during peak loads.
  • Pattern:
    // Dispatch a job
    SendRocketChatNotification::dispatch(
        'Server restarting now',
        '#ops',
        ['alias' => 'Server Bot']
    );
    
    // Job class
    class SendRocketChatNotification implements ShouldQueue
    {
        use Dispatchable, InteractsWithQueue, Queueable;
    
        public function handle(NotifierInterface $notifier)
        {
            $message = new ChatMessage($this->message, new RocketChatOptions(null, $this->payload));
            $notifier->send($message);
        }
    }
    

Integration Tips

Laravel-Specific Adjustments

  1. DSN Configuration Use Laravel’s config() to centralize DSN settings:

    // config/rocket_chat.php
    return [
        'dsn' => env('ROCKETCHAT_DSN'),
        'default_channel' => env('ROCKETCHAT_CHANNEL', 'general'),
    ];
    

    Then reference in your notifier binding:

    $dsn = config('rocket_chat.dsn');
    
  2. HTTP Client Customization If you need to customize the HTTP client (e.g., add headers, timeouts), extend the transport:

    use Symfony\Component\Notifier\Transport\Dsn;
    use Symfony\Component\Notifier\Bridge\RocketChat\RocketChatTransport;
    
    $dsn = Dsn::fromEnvironment('ROCKETCHAT_DSN');
    $client = new Client([
        'headers' => ['X-Custom-Header' => 'value'],
        'timeout' => 10,
    ]);
    $transport = new RocketChatTransport($dsn, $client);
    
  3. Testing Mock the notifier in tests:

    $notifier = $this->createMock(NotifierInterface::class);
    $notifier->expects($this->once())
             ->method('send')
             ->with($this->isInstanceOf(ChatMessage::class));
    

Advanced Patterns

  1. Message Templates Create reusable message templates in a service:

    class RocketChatNotifierService
    {
        public function sendDeploymentAlert(string $status, string $commit)
        {
            $payload = [
                'alias' => 'CI/CD Bot',
                'emoji' => $status === 'success' ? ':white_check_mark:' : ':x:',
                'channel' => '#devops',
            ];
    
            $attachment = [
                'title' => 'Deployment Alert',
                'text' => "Status: {$status}\nCommit: {$commit}",
                'color' => $status === 'success' ? '#00ff00' : '#ff0000',
            ];
    
            $message = new ChatMessage('', new RocketChatOptions($attachment, $payload));
            app(NotifierInterface::class)->send($message);
        }
    }
    
  2. Webhook Scripts For complex payloads, deploy a RocketChat Incoming Webhook Script to process raw data:

    // RocketChat script (deploy via Admin Panel)
    class Script {
        process_incoming_request({ request }) {
            const { content, attachments } = request;
            return {
                text: `Custom Processed: ${content}`,
                attachments: attachments.map(attach => ({
                    ...attach,
                    footer: 'Processed by RocketChat Script',
                })),
            };
        }
    }
    

    Then send raw JSON payloads from Laravel:

    $payload = [
        'content' => 'Raw data: {"key": "value"}',
        'attachments' => [/* ... */],
    ];
    $message = new ChatMessage('', new RocketChatOptions(null, $payload));
    

Gotchas and Tips

Common Pitfalls

  1. DSN Format Errors

    • Issue: Incorrect DSN format (e.g., missing @ or ?channel).
    • Fix: Use the exact format:
      rocketchat://TOKEN@HOST?channel=CHANNEL
      
      For webhook URLs (e.g., https://host/hooks/...), encode slashes:
      rocketchat://TOKEN%2FHOOK_ID@host?channel=CHANNEL
      
    • Debug: Check Symfony’s Dsn class for validation errors.
  2. Channel Permissions

    • Issue: Messages fail silently if the bot lacks permissions for the channel.
    • Fix: Verify the bot user’s role in RocketChat (e.g., bot role with post permissions).
  3. Payload Overrides

    • Issue: text and attachments in the payload are overridden by ChatMessage content and RocketChatOptions attachments.
    • Fix: Use the payload for metadata (e.g., alias, emoji) and pass data via `ChatMessage
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky