Installation:
composer require cleentfaar/slack-bundle
Register the bundle in config/bundles.php:
return [
// ...
Cleentfaar\SlackBundle\CLSlackBundle::class => ['all' => true],
];
Configuration:
Add Slack credentials to config/packages/cleentfaar_slack.yaml:
cleentfaar_slack:
token: '%env(SLACK_TOKEN)%'
default_channel: '#general'
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!');
}
}
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:',
]);
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'],
],
],
],
]);
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!',
]);
}
}
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),
]);
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'
Deprecated Package:
cleentfaar/slack library directly or fork the bundle for updates.Token Security:
config/ is unsafe. Always use environment variables (%env(SLACK_TOKEN)%).chat:write instead of all).Rate Limits:
SlackException gracefully:try {
$slack->chatPostMessage([...]);
} catch (SlackException $e) {
if ($e->getCode() === 429) {
// Retry logic or log the error
}
}
Event Listener Quirks:
slack.interaction event may not trigger if the Slack app isn’t properly configured for interactive components.Request URL in Slack app settings matches your endpoint (e.g., /slack/interaction).Blocks vs. Attachments:
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');
}
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'
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);
}
Fallback for Missing Features:
Use the underlying Slack\Client for unsupported API methods:
$client = $slack->getClient(); // Access the raw Slack\Client
$response = $client->conversationsList();
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();
});
How can I help you explore Laravel packages today?