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 Client Bundle Laravel Package

chaplean/slack-client-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require chaplean/slack-client-bundle
    

    Add to config/bundles.php (Symfony 4+):

    return [
        // ...
        Chaplean\Bundle\SlackClientBundle\ChapleanSlackClientBundle::class => ['all' => true],
    ];
    
  2. Configuration: Add to config/packages/chaplean_slack_client.yaml:

    chaplean_slack_client:
        access_token: '%env(SLACK_ACCESS_TOKEN)%'
    

    Define the token in .env:

    SLACK_ACCESS_TOKEN=xoxb-your-token
    
  3. First Use Case: Inject the client into a service/controller and send a test message:

    use Chaplean\Bundle\SlackClientBundle\Client\SlackClientInterface;
    
    class MyController
    {
        public function __construct(private SlackClientInterface $slack)
        {
        }
    
        public function sendTestMessage()
        {
            $this->slack->chatPostMessage([
                'channel' => '#general',
                'text' => 'Hello from Laravel!',
            ]);
        }
    }
    

Implementation Patterns

Common Workflows

  1. Sending Messages:

    $this->slack->chatPostMessage([
        'channel' => '#notifications',
        'text' => 'New order #12345 created!',
        'username' => 'OrderBot',
        'icon_emoji' => ':package:',
    ]);
    
  2. Handling API Responses: Use the chatPostMessage response to log or retry:

    try {
        $response = $this->slack->chatPostMessage([...]);
        if ($response->isOk()) {
            // Success
        }
    } catch (SlackApiException $e) {
        // Handle error (e.g., rate limit, invalid token)
    }
    
  3. File Uploads:

    $filePath = storage_path('app/report.pdf');
    $this->slack->filesUpload([
        'channels' => '#reports',
        'file' => new \CURLFile($filePath),
        'title' => 'Monthly Report',
    ]);
    
  4. Reactions:

    $this->slack->reactionsAdd([
        'channel' => 'C12345',
        'timestamp' => '1234567890.123456',
        'name' => 'thumbsup',
    ]);
    

Integration Tips

  • Event-Driven Notifications: Trigger Slack messages from Laravel events (e.g., OrderCreated):

    event(new OrderCreated($order));
    // In listener:
    $this->slack->chatPostMessage([...]);
    
  • Queue Jobs: Offload Slack messages to a queue (e.g., sendSlackNotificationJob) to avoid timeouts:

    dispatch(new SendSlackNotificationJob($message));
    
  • Rate Limiting: Implement exponential backoff for retries:

    $attempts = 0;
    while ($attempts < 3) {
        try {
            $this->slack->chatPostMessage([...]);
            break;
        } catch (SlackApiException $e) {
            if ($e->getCode() === 429) {
                sleep(2 ** $attempts);
                $attempts++;
            } else {
                throw $e;
            }
        }
    }
    

Gotchas and Tips

Pitfalls

  1. Token Security:

    • Never hardcode tokens in config files. Use .env and env() helper.
    • Restrict Slack API token permissions to only what’s needed (e.g., chat:write).
    • Rotate tokens periodically and update them in .env.
  2. Rate Limits:

    • Slack enforces rate limits. Monitor responses for 429 errors.
    • Use X-RateLimit-Limit and X-RateLimit-Remaining headers in responses to track usage.
  3. Channel IDs vs. Names:

    • Slack API uses channel IDs (e.g., C12345) for most endpoints, not names (e.g., #general).
    • Cache channel IDs after first lookup to avoid repeated API calls:
      $channelId = $this->slack->conversationsList(['types' => 'public_channel'])->getData()['channels'][0]['id'];
      
  4. Async Operations:

    • File uploads and some API calls are asynchronous. Use filesInfo to check status:
      $fileId = $response->getData()['file_id'];
      $status = $this->slack->filesInfo(['file' => $fileId])->getData()['file']['status'];
      
  5. Deprecation:

    • The bundle may not support the latest Slack API features. Check Slack’s API docs for updates.

Debugging

  • Enable Debug Mode: Add to config/packages/chaplean_slack_client.yaml:

    debug: true
    

    This logs raw API requests/responses to var/log/dev.log.

  • Common Errors:

    Error Code Cause Solution
    401 Invalid token Regenerate token in Slack app settings.
    404 Channel/user not found Verify channel ID/name.
    429 Rate limit exceeded Implement retries with backoff.
    500 Slack server error Retry or check Slack status page.

Extension Points

  1. Custom Responses: Extend the SlackResponse class to add domain-specific methods:

    class CustomSlackResponse extends SlackResponse
    {
        public function getMessageText(): string
        {
            return $this->getData()['message']['text'];
        }
    }
    

    Bind it in services.yaml:

    Chaplean\Bundle\SlackClientBundle\Client\SlackClientInterface: '@custom_slack_client'
    
  2. Middleware: Add request/response middleware to log or modify payloads:

    $client->getMiddleware()->add(new class implements MiddlewareInterface {
        public function handle(Request $request, callable $next) {
            // Pre-process request
            $response = $next($request);
            // Post-process response
            return $response;
        }
    });
    
  3. Testing: Mock the SlackClientInterface in PHPUnit:

    $mock = $this->createMock(SlackClientInterface::class);
    $mock->method('chatPostMessage')->willReturn(new SlackResponse(['ok' => true]));
    $this->container->set('chaplean_slack_client.client', $mock);
    
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.
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager