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

Slack Bundle Laravel Package

displayce/slack-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require displayce/slack-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Displayce\SlackBundle\SlackBundle::class => ['all' => true],
    ];
    
  2. Configuration: Publish the default config:

    php bin/console config:dump-reference DisplayceSlackBundle
    

    Update config/packages/displayce_slack.yaml:

    displayce_slack:
        token: '%env(SLACK_API_TOKEN)%'  # Your Slack API token
        default_channel: '#general'      # Optional default channel
    
  3. First Use Case: Inject the API client in a controller/service:

    use Displayce\SlackBundle\Client\ApiClientInterface;
    
    public function __construct(private ApiClientInterface $slackClient) {}
    
    public function sendNotification()
    {
        $payload = new \Displayce\SlackBundle\Payload\ChatPostMessagePayload();
        $payload->setChannel('#general')
                ->setText('Hello from Laravel!')
                ->setUsername('LaravelBot');
    
        $response = $this->slackClient->send($payload);
        return $response->getTs(); // Timestamp of the message
    }
    

Implementation Patterns

Common Workflows

1. Sending Messages

  • Basic Text:
    $payload = new ChatPostMessagePayload();
    $payload->setChannel('#channel')
            ->setText('Hello, world!');
    $this->slackClient->send($payload);
    
  • Formatted Messages (Slack Markdown):
    $payload->setText('*Bold text* and _italic text_ with `code`');
    
  • Attachments (Legacy):
    $attachment = new Attachment();
    $attachment->setText('Attachment content')
               ->setColor('#36a64f');
    $payload->addAttachment($attachment);
    

2. Handling Responses

  • Async Processing: Use sendAsync() for non-blocking calls (if supported by the underlying library).
    $this->slackClient->sendAsync($payload)->then(function ($response) {
        // Handle response
    });
    
  • Error Handling:
    try {
        $response = $this->slackClient->send($payload);
    } catch (\Displayce\SlackBundle\Exception\SlackException $e) {
        Log::error('Slack API error: ' . $e->getMessage());
    }
    

3. Channel Management

  • Dynamic Channel Selection:
    $channel = $this->getChannelFromUserInput($userInput);
    $payload->setChannel($channel);
    
  • Default Channel Fallback: Configure default_channel in config/packages/displayce_slack.yaml to avoid hardcoding.

4. Integration with Laravel Services

  • Event Listeners: Trigger Slack notifications on Laravel events (e.g., Illuminate\Auth\Events\Registered):
    public function handle(Registered $event)
    {
        $payload = new ChatPostMessagePayload();
        $payload->setText("New user registered: {$event->user->email}");
        $this->slackClient->send($payload);
    }
    
  • Queue Jobs: Dispatch Slack notifications to a queue for async processing:
    SendSlackNotification::dispatch($payload)->onQueue('slack');
    

5. Configuration Overrides

  • Per-Environment Tokens: Use .env variables:
    # config/packages/displayce_slack.yaml
    displayce_slack:
        token: '%env(SLACK_TOKEN_PROD)%'  # Override per environment
    
  • Dynamic Payloads: Extend payload classes for reusable logic:
    class AlertPayload extends ChatPostMessagePayload
    {
        public function __construct(string $message, string $color = '#ff0000')
        {
            $this->setText($message)
                 ->setAttachments([new Attachment(['color' => $color])]);
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Token Security:

    • Never hardcode tokens in config files. Always use .env:
      SLACK_API_TOKEN=xoxb-your-token-here
      
    • Restrict token scopes in Slack API to only necessary permissions (e.g., chat:write).
  2. Channel Format:

    • Channels must start with # (e.g., #general). Omitting this will fail silently or return an error.
    • DMs require @username format, not #.
  3. Rate Limiting:

    • Slack enforces rate limits. Handle 429 Too Many Requests errors gracefully:
      catch (\Displayce\SlackBundle\Exception\RateLimitException $e) {
          sleep($e->getRetryAfter());
          retry();
      }
      
  4. Deprecated Methods:

    • The underlying displayce/slack library is unmaintained (last release: 2020). Some methods (e.g., sendAsync) may not work as expected. Test thoroughly.
  5. Payload Validation:

    • Slack API rejects malformed payloads. Validate required fields (e.g., channel or text) before sending:
      if (empty($payload->getChannel()) && empty($payload->getUser())) {
          throw new \InvalidArgumentException('Channel or user must be specified.');
      }
      

Debugging

  1. Enable Verbose Logging: Add to config/packages/monolog.yaml:

    handlers:
        slack:
            type: stream
            path: "%kernel.logs_dir%/slack.log"
            level: debug
    

    Then enable debug mode in config/packages/displayce_slack.yaml:

    displayce_slack:
        debug: true
    
  2. Inspect Raw Responses: Dump the raw response object to debug API issues:

    $response = $this->slackClient->send($payload);
    \Log::debug('Slack Response:', ['raw' => $response->getData()]);
    
  3. Test with Slack CLI: Use slack-cli to manually test API calls before integrating:

    slack chat.postMessage --token=xoxb-your-token --channel=#general --text="Test message"
    

Tips

  1. Reusable Payload Builders: Create static methods for common payloads:

    class SlackNotifier
    {
        public static function alert(string $message, string $channel = '#alerts'): ChatPostMessagePayload
        {
            $payload = new ChatPostMessagePayload();
            $payload->setChannel($channel)
                    ->setText($message)
                    ->setUsername('AlertBot')
                    ->setIconEmoji(':bell:');
            return $payload;
        }
    }
    
  2. Environment-Specific Channels: Use Laravel's config caching to switch channels per environment:

    # config/packages/displayce_slack.yaml
    displayce_slack:
        channels:
            dev: '#dev-channel'
            prod: '#prod-channel'
    

    Then dynamically set:

    $payload->setChannel(config('displayce_slack.channels.' . app()->environment()));
    
  3. Webhook Fallback: If the API client fails, fall back to Slack Incoming Webhooks:

    $webhookUrl = config('services.slack.webhook_url');
    $ch = curl_init($webhookUrl);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
        'text' => 'Fallback message',
        'username' => 'FallbackBot'
    ]));
    curl_exec($ch);
    
  4. Extend Payload Classes: Override payload classes to add custom logic:

    class CustomPayload extends ChatPostMessagePayload
    {
        public function setAsAdmin(): self
        {
            $this->setUsername('AdminBot')
                 ->setIconEmoji(':shield:');
            return $this;
        }
    }
    
  5. Monitor API Usage: Use Slack's API Dashboard to track usage and set up alerts for anomalies.

  6. Fallback for Missing Bundle: If the bundle fails to load, manually instantiate the client:

    use Displayce\Slack\Client;
    $client = new Client(config('displayce_slack.token'));
    
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
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
spatie/mailcoach-vapor