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

cleentfaar/slack

PHP Slack API client that maps Slack Web API methods to dedicated payload and response objects. Uses JMS Serializer for spec-aligned data models, supports OAuth/tokens, and provides examples plus event hooks around the ApiClient.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cleentfaar/slack
    

    Ensure ext-curl is enabled in your PHP environment.

  2. Configure API Token Generate a Slack API token (or OAuth token) from Slack API Dashboard. Store it securely (e.g., Laravel .env):

    SLACK_TOKEN=your_bot_or_user_token_here
    
  3. Initialize Client

    use CL\Slack\ApiClient;
    
    $apiClient = new ApiClient(config('slack.token'));
    
  4. First Use Case: Send a Message

    $chat = $apiClient->chatPostMessage([
        'channel' => '#general',
        'text'    => 'Hello from Laravel!'
    ]);
    

Where to Look First


Implementation Patterns

Core Workflows

1. CRUD Operations

Use dedicated payload classes for each API method (e.g., ChatPostMessagePayload, UsersListPayload).

// Create
$response = $apiClient->chatPostMessage($payload);

// Read
$users = $apiClient->usersList()->getUsers();

// Update (e.g., update user profile)
$response = $apiClient->usersProfileSet($payload);

// Delete (e.g., delete a message)
$response = $apiClient->chatDelete($payload);

2. Handling Responses

Responses are serialized as PHP objects (e.g., ChatPostMessageResponse).

$response = $apiClient->chatPostMessage($payload);
if ($response->isOk()) {
    $ts = $response->getTs(); // Timestamp of the message
}

3. Event Listeners

Attach listeners to the ApiClient for pre/post-request logic:

$apiClient->addListener('beforeRequest', function ($event) {
    $event->setData(['custom_field' => 'value']);
});

4. Rate Limiting

Check isRateLimited() and handle 429 responses:

try {
    $response = $apiClient->chatPostMessage($payload);
} catch (\CL\Slack\Exception\RateLimitExceededException $e) {
    sleep($e->getRetryAfter());
    retry();
}

Integration Tips

Laravel-Specific Patterns

  1. Service Provider Binding Bind the client in AppServiceProvider for dependency injection:

    public function register()
    {
        $this->app->singleton('slack', function ($app) {
            return new ApiClient(config('slack.token'));
        });
    }
    
  2. Config File Define Slack config in config/slack.php:

    return [
        'token' => env('SLACK_TOKEN'),
        'default_channel' => '#general',
    ];
    
  3. Artisan Commands Use the package’s CLI tools (via cleentfaar/slack-cli) or build custom commands:

    use CL\Slack\ApiClient;
    use Illuminate\Console\Command;
    
    class SendSlackMessage extends Command
    {
        protected $apiClient;
    
        public function __construct(ApiClient $apiClient)
        {
            parent::__construct();
            $this->apiClient = $apiClient;
        }
    
        public function handle()
        {
            $this->apiClient->chatPostMessage([
                'channel' => $this->argument('channel'),
                'text'    => $this->argument('message'),
            ]);
        }
    }
    
  4. Queue Jobs Offload Slack API calls to queues (e.g., send notifications asynchronously):

    use CL\Slack\ApiClient;
    use Illuminate\Bus\Queueable;
    use Illuminate\Contracts\Queue\ShouldQueue;
    use Illuminate\Foundation\Bus\Dispatchable;
    
    class SendSlackNotification implements ShouldQueue
    {
        use Dispatchable, Queueable;
    
        public function __construct(private ApiClient $apiClient, private string $message)
        {
        }
    
        public function handle()
        {
            $this->apiClient->chatPostMessage([
                'channel' => '#notifications',
                'text'    => $this->message,
            ]);
        }
    }
    

Advanced Patterns

  1. Custom Payloads Extend Payload classes for domain-specific logic:

    use CL\Slack\Payload\PayloadInterface;
    
    class CustomSlackPayload implements PayloadInterface
    {
        public function getMethod()
        {
            return 'custom.method';
        }
    
        public function getData()
        {
            return ['key' => 'value'];
        }
    }
    
  2. Webhook Integration Use the package to parse incoming Slack events (via Events\EventsPayload):

    $event = new EventsPayload($request->all());
    $apiClient->eventsHandle($event);
    
  3. Testing Mock the ApiClient in tests:

    $mockApiClient = Mockery::mock(ApiClient::class);
    $mockApiClient->shouldReceive('chatPostMessage')
        ->once()
        ->andReturn(new ChatPostMessageResponse(['ok' => true]));
    
    $this->app->instance('slack', $mockApiClient);
    

Gotchas and Tips

Pitfalls

  1. Deprecated Methods The package is archived (last release: 2016). Some Slack API methods (e.g., files.delete, reactions.*) are missing. Check the missing methods list before use.

  2. SSL/CURL Errors

    • Error: CURLE_SSL_CACERT (e.g., on Windows/OS X).
    • Fix: Update CA certificates or disable verification (temporarily for testing):
      $client = new \GuzzleHttp\Client(['verify' => false]);
      $apiClient = new ApiClient($token, $client);
      
      Note: Disabling verification is unsafe for production.
  3. Token Permissions Ensure your Slack token has the required scopes (e.g., chat:write for posting messages). Test with a bot token first.

  4. Rate Limiting Slack enforces rate limits. Handle 429 responses gracefully:

    try {
        $response = $apiClient->chatPostMessage($payload);
    } catch (\CL\Slack\Exception\RateLimitExceededException $e) {
        sleep($e->getRetryAfter());
        // Retry or notify admin
    }
    
  5. JMS Serializer Dependency The package uses JMS Serializer for (de)serialization. If you encounter issues, ensure:

    • No conflicting JMS configurations in your project.
    • The jms/serializer package is installed (composer require jms/serializer).

Debugging Tips

  1. Enable Guzzle Debugging Attach a middleware to log requests/responses:

    $client = new \GuzzleHttp\Client([
        'middleware' => [
            new \GuzzleHttp\Middleware::tap(function ($request) {
                \Log::debug('Slack Request:', $request->getBody());
            }),
            new \GuzzleHttp\Middleware::tap(function ($response) {
                \Log::debug('Slack Response:', $response->getBody());
            }),
        ],
    ]);
    $apiClient = new ApiClient($token, $client);
    
  2. Validate Payloads Use PayloadValidator to check payloads before sending:

    use CL\Slack\Payload\PayloadValidator;
    
    $validator = new PayloadValidator();
    $errors = $validator->validate($payload);
    if (!empty($errors)) {
        throw new \InvalidArgumentException('Payload validation failed');
    }
    
  3. Handle Exceptions Catch specific exceptions for better error handling:

    try {
        $response = $apiClient->chatPostMessage($payload);
    } catch (\CL\Slack\Exception\SlackException $e) {
        \Log::error('Slack API Error:', ['error' => $e->getMessage()]);
    }
    

Extension Points

  1. Custom Serialization Override
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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata