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

cleentfaar/slack-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require cleentfaar/slack-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Cleentfaar\SlackBundle\CLSlackBundle::class => ['all' => true],
    ];
    
  2. Configuration: Add Slack credentials to config/packages/cleentfaar_slack.yaml:

    cleentfaar_slack:
        token: '%env(SLACK_TOKEN)%'
        default_channel: '#general'
    
  3. First Use Case: Inject the SlackClient service in a controller or command:

    use Cleentfaar\SlackBundle\Service\SlackClient;
    
    class MyController extends AbstractController
    {
        public function sendMessage(SlackClient $slack)
        {
            $response = $slack->chatPostMessage([
                'channel' => '#general',
                'text' => 'Hello from Laravel!',
            ]);
            return new Response('Message sent!');
        }
    }
    

Implementation Patterns

Core Workflows

  1. Sending Messages: Use chatPostMessage for basic messages or chatPostEphemeral for private replies:

    $slack->chatPostMessage([
        'channel' => '#channel',
        'text' => 'Alert: Database backup failed!',
        'username' => 'Laravel Bot',
        'icon_emoji' => ':robot_face:',
    ]);
    
  2. Interactive Components: Attach buttons or modals via chatPostMessage with attachments or blocks:

    $slack->chatPostMessage([
        'channel' => '#channel',
        'text' => 'Approve this action?',
        'attachments' => [
            [
                'fallback' => 'Approve action',
                'callback_id' => 'approve_action',
                'actions' => [
                    ['name' => 'approve', 'text' => 'Approve', 'type' => 'button', 'value' => 'yes'],
                    ['name' => 'reject', 'text' => 'Reject', 'type' => 'button', 'value' => 'no'],
                ],
            ],
        ],
    ]);
    
  3. Handling Interactions: Use events to listen for Slack interactions (e.g., button clicks):

    # config/packages/cleentfaar_slack.yaml
    cleentfaar_slack:
        events:
            slack.interaction: ['App\EventListener\SlackInteractionListener']
    
    // src/EventListener/SlackInteractionListener.php
    public function onSlackInteraction(SlackInteractionEvent $event)
    {
        $payload = $event->getPayload();
        if ($payload['actions'][0]['value'] === 'yes') {
            $event->getSlack()->chatPostMessage([
                'channel' => $payload['channel']['id'],
                'text' => 'Action approved!',
            ]);
        }
    }
    
  4. File Uploads: Stream files directly to Slack:

    $filePath = storage_path('logs/laravel.log');
    $response = $slack->filesUpload([
        'channels' => '#logs',
        'filename' => 'laravel.log',
        'filetype' => 'log',
        'content' => file_get_contents($filePath),
    ]);
    

Integration Tips

  • Laravel Events: Trigger Slack notifications from Laravel events (e.g., registered, failed):

    // In an event subscriber
    public function onUserRegistered(UserRegisteredEvent $event)
    {
        $slack = $this->container->get('cleentfaar_slack.client');
        $slack->chatPostMessage([
            'channel' => '#notifications',
            'text' => sprintf('New user registered: %s', $event->user->email),
        ]);
    }
    
  • Queue Jobs: Offload Slack messages to a queue for async processing:

    // Dispatch a job
    SendSlackMessage::dispatch('Channel', 'Message text');
    
    // Job class
    public function handle()
    {
        $slack = app(SlackClient::class);
        $slack->chatPostMessage([
            'channel' => $this->channel,
            'text' => $this->message,
        ]);
    }
    
  • Environment-Specific Channels: Override the default channel per environment:

    # config/packages/dev/cleentfaar_slack.yaml
    cleentfaar_slack:
        default_channel: '#dev-alerts'
    

Gotchas and Tips

Pitfalls

  1. Deprecated Package:

    • The bundle is archived (last release in 2016) and may not support newer Slack API versions.
    • Mitigation: Use the underlying cleentfaar/slack library directly or fork the bundle for updates.
  2. Token Security:

    • Hardcoding tokens in config/ is unsafe. Always use environment variables (%env(SLACK_TOKEN)%).
    • Tip: Restrict the Slack token to minimal required scopes (e.g., chat:write instead of all).
  3. Rate Limits:

    • Slack enforces rate limits. Handle SlackException gracefully:
    try {
        $slack->chatPostMessage([...]);
    } catch (SlackException $e) {
        if ($e->getCode() === 429) {
            // Retry logic or log the error
        }
    }
    
  4. Event Listener Quirks:

    • The slack.interaction event may not trigger if the Slack app isn’t properly configured for interactive components.
    • Fix: Verify the Request URL in Slack app settings matches your endpoint (e.g., /slack/interaction).
  5. Blocks vs. Attachments:

    • The bundle primarily supports attachments (legacy). For modern Slack features (e.g., modals, home tabs), use the Slack Bolt framework instead.

Debugging

  • Enable Debug Mode:

    cleentfaar_slack:
        debug: true
    

    Logs API requests/responses to var/log/dev.log.

  • Validate Payloads: Use SlackClient::validatePayload() to check incoming webhook payloads:

    if (!$slack->validatePayload($request->getContent())) {
        throw new \RuntimeException('Invalid Slack payload');
    }
    

Extension Points

  1. Custom Services: Extend the SlackClient to add domain-specific methods:

    // src/Service/CustomSlackService.php
    class CustomSlackService extends SlackClient
    {
        public function sendAlert(string $message, string $channel = null)
        {
            $this->chatPostMessage([
                'channel' => $channel ?: $this->getDefaultChannel(),
                'text' => "[ALERT] $message",
                'username' => 'Laravel Alerts',
                'icon_emoji' => ':bell:',
            ]);
        }
    }
    

    Register it as a service in services.yaml:

    services:
        App\Service\CustomSlackService: '@cleentfaar_slack.client'
    
  2. Middleware for Webhooks: Secure Slack webhook endpoints with middleware:

    // src/Middleware/SlackSignatureMiddleware.php
    public function handle($request, Closure $next)
    {
        $slack = $this->container->get('cleentfaar_slack.client');
        if (!$slack->validateSignature($request->headers->get('X-Slack-Signature'), $request->getContent())) {
            abort(403, 'Invalid Slack request');
        }
        return $next($request);
    }
    
  3. Fallback for Missing Features: Use the underlying Slack\Client for unsupported API methods:

    $client = $slack->getClient(); // Access the raw Slack\Client
    $response = $client->conversationsList();
    

Performance Tips

  • Batch Messages: Use chatScheduleMessage to send messages at a later time:

    $slack->chatScheduleMessage([
        'channel' => '#channel',
        'text' => 'Scheduled message',
        'post_at' => strtotime('+1 hour'),
    ]);
    
  • Caching: Cache frequent Slack API responses (e.g., channel lists) with Laravel’s cache:

    $cacheKey = 'slack_channels_' . $this->getDefaultChannel();
    $channels = Cache::remember($cacheKey, now()->addHours(1), function () use ($slack) {
        return $slack->conversationsList();
    });
    
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