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

displayce/slack

PHP Slack API client with object-based payload and response classes mirroring Slack’s docs. Supports all Slack API methods, serializes data via JMS Serializer, and includes docs for installation, OAuth/tokens, usage, methods, and events.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Setup
1. **Installation**
   ```bash
   composer require displayce/slack

Ensure your project has PHP 7.2+, Laravel 5.8+ (or Lumen), or Symfony 5+ (new in v0.23.0).

  1. Configuration Add Slack API token to .env:

    SLACK_TOKEN=xoxb-your-bot-token
    SLACK_TEAM_ID=your-team-id
    
  2. First Use Case Fetch a list of channels in routes/web.php:

    use Displayce\Slack\Slack;
    
    Route::get('/channels', function () {
        $slack = new Slack(config('slack.token'), config('slack.team_id'));
        $channels = $slack->channels()->listChannels();
        return response()->json($channels);
    });
    
  3. Key Files

    • vendor/displayce/slack/src/Slack.php (Main class)
    • vendor/displayce/slack/src/Endpoints/ (API endpoints)

Implementation Patterns

Core Workflows

  1. Instantiation & Initialization

    $slack = new \Displayce\Slack\Slack($token, $teamId);
    // Or via Laravel/Symfony service provider (recommended for DI)
    
  2. Endpoint Chaining Use fluent methods to interact with Slack APIs:

    $slack->users()->listUsers(); // Get all users
    $slack->conversations()->listConversations(); // List channels/DMs
    $slack->chat()->postMessage([
        'channel' => '#general',
        'text' => 'Hello from Laravel/Symfony!'
    ]);
    
  3. Pagination Handling Loop through paginated responses:

    $cursor = null;
    do {
        $response = $slack->users()->listUsers(['cursor' => $cursor]);
        $cursor = $response->getCursor();
        // Process $response->getMembers()
    } while ($cursor);
    
  4. Webhook Integration Validate and process Slack events in a Laravel/Symfony route:

    // Laravel
    Route::post('/slack/webhook', function (Request $request) {
        $slack = new \Displayce\Slack\Slack(config('slack.token'));
        $event = $slack->rtm()->parseEvent($request->all());
        // Handle $event
    });
    
    // Symfony
    $request->request->all(); // Access payload similarly
    
  5. Rate Limiting Respect Slack’s rate limits:

    try {
        $response = $slack->chat()->postMessage($data);
    } catch (\Displayce\Slack\Exceptions\RateLimitExceededException $e) {
        sleep($e->getRetryAfter());
        retry();
    }
    
  6. Laravel/Symfony Service Provider Laravel:

    // app/Providers/SlackServiceProvider.php
    public function register() {
        $this->app->singleton(\Displayce\Slack\Slack::class, function ($app) {
            return new \Displayce\Slack\Slack(
                config('slack.token'),
                config('slack.team_id')
            );
        });
    }
    

    Symfony:

    # config/services.yaml
    services:
        Displayce\Slack\Slack:
            arguments:
                $token: '%env(SLACK_TOKEN)%'
                $teamId: '%env(SLACK_TEAM_ID)%'
    

Integration Tips

  • Logging: Use Laravel/Symfony’s logging to track API calls:
    $slack->setLogger(app(\Illuminate\Log\Logger::class)); // Laravel
    $slack->setLogger($this->container->get('logger'));    // Symfony
    
  • Caching: Cache frequent API responses:
    // Laravel
    $channels = Cache::remember('slack_channels', now()->addHours(1), function () {
        return $slack->channels()->listChannels();
    });
    
    // Symfony
    $channels = $this->cache->get('slack_channels', function () use ($slack) {
        return $slack->channels()->listChannels();
    }, null, 3600);
    
  • Error Handling: Centralize exception handling:
    try {
        $response = $slack->someEndpoint()->call();
    } catch (\Displayce\Slack\Exceptions\SlackException $e) {
        Log::error("Slack API Error: {$e->getMessage()}");
        return response()->json(['error' => 'Slack API failed'], 500);
    }
    
  • Testing: Mock the Slack client in tests:
    // Laravel/PHPUnit
    $mock = Mockery::mock(\Displayce\Slack\Slack::class);
    $mock->shouldReceive('chat->postMessage')->andReturn(['ok' => true]);
    $this->app->instance(\Displayce\Slack\Slack::class, $mock);
    
    // Symfony/PHPUnit
    $this->container->set(\Displayce\Slack\Slack::class, $mock);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Endpoints The package is outdated (last major update 2020). Some Slack API endpoints may have changed. Verify against Slack’s current API docs.

  2. Token Scopes Ensure your bot token has the required scopes (e.g., chat:write for posting messages). Missing scopes cause 403 errors.

    • Debug: Check error field in the response for scope-related messages.
  3. Rate Limits The package doesn’t auto-retry on rate limits. Implement manual retries with Retry-After header:

    if ($e instanceof \Displayce\Slack\Exceptions\RateLimitExceededException) {
        sleep($e->getRetryAfter() + 1); // Add buffer
    }
    
  4. Team ID vs. Workspace ID Confusion between team_id (legacy) and workspace_id (new) can break requests. Use team_id unless migrating to Slack’s new IDs.

  5. RTM Connection Drops Real-time API (rtm.start) may disconnect. Implement reconnection logic:

    $rtm = $slack->rtm();
    while (true) {
        try {
            $rtm->start();
            break;
        } catch (\Displayce\Slack\Exceptions\ConnectionException $e) {
            sleep(5);
        }
    }
    
  6. File Uploads The package lacks direct file upload support. Use Slack’s files.upload endpoint via chat->uploadFile() (if available) or raw HTTP:

    $response = $slack->callApi('files.upload', [
        'channels' => '#general',
        'file' => new \CURLFile($filePath)
    ]);
    
  7. Symfony 5 Compatibility (v0.23.0)

    • Breaking Changes: None reported, but test thoroughly if using Symfony’s dependency injection.
    • New Use Case: Symfony developers can now leverage the package’s DI integration seamlessly.

Debugging Tips

  1. Enable Verbose Logging Set the logger to output raw API responses:

    $slack->setLogger(new \Monolog\Logger('slack', [
        new \Monolog\Handler\StreamHandler(storage_path('logs/slack.log')) // Laravel
        // OR
        new \Monolog\Handler\StreamHandler('%kernel.logs_dir%/slack.log') // Symfony
    ]));
    
  2. Inspect Raw Responses Access the underlying Guzzle response:

    $response = $slack->chat()->postMessage($data);
    $rawBody = $response->getBody()->getContents();
    
  3. Validate API Calls Use Slack’s API Tester to verify endpoints before implementing.

  4. Common HTTP Errors

    • 401: Invalid token or missing scope.
    • 403: Bot not in channel or missing permissions.
    • 429: Rate limit exceeded (check Retry-After header).

Extension Points

  1. Custom Endpoints Add unsupported endpoints by extending the Slack class:
    class CustomSlack extends \Displayce\Slack\Slack {
        public function customEndpoint($params = [
    
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.
ippanelcom/laravel-sdk
adachsoft/changelog-linter
adachsoft/collection
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus