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.
## 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).
Configuration
Add Slack API token to .env:
SLACK_TOKEN=xoxb-your-bot-token
SLACK_TEAM_ID=your-team-id
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);
});
Key Files
vendor/displayce/slack/src/Slack.php (Main class)vendor/displayce/slack/src/Endpoints/ (API endpoints)Instantiation & Initialization
$slack = new \Displayce\Slack\Slack($token, $teamId);
// Or via Laravel/Symfony service provider (recommended for DI)
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!'
]);
Pagination Handling Loop through paginated responses:
$cursor = null;
do {
$response = $slack->users()->listUsers(['cursor' => $cursor]);
$cursor = $response->getCursor();
// Process $response->getMembers()
} while ($cursor);
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
Rate Limiting Respect Slack’s rate limits:
try {
$response = $slack->chat()->postMessage($data);
} catch (\Displayce\Slack\Exceptions\RateLimitExceededException $e) {
sleep($e->getRetryAfter());
retry();
}
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)%'
$slack->setLogger(app(\Illuminate\Log\Logger::class)); // Laravel
$slack->setLogger($this->container->get('logger')); // Symfony
// 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);
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);
}
// 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);
Deprecated Endpoints The package is outdated (last major update 2020). Some Slack API endpoints may have changed. Verify against Slack’s current API docs.
slack/slack-api-php-client for newer features.Token Scopes
Ensure your bot token has the required scopes (e.g., chat:write for posting messages). Missing scopes cause 403 errors.
error field in the response for scope-related messages.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
}
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.
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);
}
}
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)
]);
Symfony 5 Compatibility (v0.23.0)
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
]));
Inspect Raw Responses Access the underlying Guzzle response:
$response = $slack->chat()->postMessage($data);
$rawBody = $response->getBody()->getContents();
Validate API Calls Use Slack’s API Tester to verify endpoints before implementing.
Common HTTP Errors
Retry-After header).Slack class:
class CustomSlack extends \Displayce\Slack\Slack {
public function customEndpoint($params = [
How can I help you explore Laravel packages today?