Laravel Slack Notification Channel

repository·3.x·Indexed 21 days ago

https://github.com/laravel/slack-notification-channel

Official integration for sending notifications from Laravel applications to Slack via webhooks. It provides the SlackWebhookChannel for routing notifications, SlackMessage and SlackAttachment for legacy messaging, and a comprehensive set of Block Kit components including ActionsBlock, ContextBlock, ImageBlock, and SectionBlock for creating rich, interactive Slack messages.

Tokens
6.8K
Snippets
28
Records
34
Agent score
75%

What's inside laravel-slack-notification-channel

  1. Upgrade to Slack Notifications Channel 3.0

    3.x
    Version 3.0 introduces a new way to write Slack notifications using the Slack BlockKit API. While previous notification formats remain supported for backward compatibility, upgrading to 3.0 allows you to leverage the more advanced BlockKit API for richer message layouts. To transition to the new format, you should rewrite your existing notifications following the patterns defined in the official Laravel documentation.
  2. Route Slack notifications to a webhook URL

    3.x

    For the SlackWebhookChannel to function, the object receiving the notification must define where the webhook should be sent. Implement the routeNotificationForSlack method (or routeNotificationFor with the 'slack' argument) on your notifiable model to return the webhook URL.

    public function routeNotificationForSlack($notification)
    {
        return 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX';
    }
  3. Configure a SlackMessage

    3.x

    The SlackMessage class is used to construct the payload for Slack notifications. You can configure the destination channel, fallback text, username, and visual identity (icon/image). It also supports threading via threadTimestamp and controlling link/media unfurling.

    use Illuminate\Notifications\Slack\SlackMessage;
    
    SlackMessage::to('general')
        ->text('This is the fallback text')
        ->username('My Bot')
        ->emoji(':robot_face:')
        ->unfurlLinks()
        ->unfurlMedia();
  4. Create an ActionsBlock for Slack Block Kit

    3.x

    The ActionsBlock class is used to define an interactive section in a Slack message using Block Kit. It acts as a container for interactive elements like buttons and select menus.

    Key constraints:

    • You must add at least one element to the block.
    • There is a maximum of 25 elements allowed per ActionsBlock.
    • The block_id (set via the id() method) must not exceed 255 characters.

    Use the id() method to provide a unique identifier. This is useful when handling interaction payloads from Slack to identify which block triggered an action.

    use Illuminate\Notifications\Slack\BlockKit\Blocks\ActionsBlock;
    
    $block = (new ActionsBlock())
        ->id('my_unique_block_id')
        ->button('Click Me')
        ->staticSelect('Choose an option');
  5. Build a legacy Slack message with SlackMessage

    3.x

    The SlackMessage class is used to construct messages using Slack's legacy attachment-based messaging format. It provides a fluent interface to set the message content, destination channel, sender identity, and visual styling based on the notification level.

    Available Levels and Colors

    The visual color of the message attachment is automatically determined by the level set via these methods:

    • success(): Sets level to success (color: good)
    • error(): Sets level to error (color: danger)
    • warning(): Sets level to warning (color: warning)
    • info(): Sets level to info (no specific color mapping)
    use Illuminate\Notifications\Messages\SlackMessage;
    
    SlackMessage::create()\n    ->content('Hello World!')\n    ->success()\n    ->to('#general');
  6. Create an ImageBlock for Slack Block Kit

    3.x

    Use the ImageBlock class to include images in your Slack notifications via Block Kit. An ImageBlock requires a URL for the image and an alternative text description (altText).

    Properties and Constraints

    • URL: The image URL (max 3000 characters).
    • Alt Text: A plain-text summary of the image (max 2000 characters). Note: This is required when converting the block to an array.
    • Block ID: An optional unique identifier used to identify the source of an action when receiving interaction payloads (max 255 characters).
    • Title: An optional PlainTextOnlyTextObject that serves as a title for the image.

    Methods

    • __construct(string $url, ?string $altText = null): Initializes the block.
    • id(string $id): Sets a unique block_id.
    • alt(string $altText): Sets or updates the alternative text.
    • title(string $title): Sets an optional title using a PlainTextOnlyTextObject.
    use Illuminate\Notifications\Slack\BlockKit\Blocks\ImageBlock;
    
    $imageBlock = ImageBlock::id('user-profile-image')
        ->title('Profile Picture')
        ->alt('A photo of the user')
        ->url('https://example.com/image.png');
  7. Send Slack notifications via SlackWebhookChannel

    3.x

    The SlackWebhookChannel is used to send notifications to Slack using incoming webhooks.

    To use this channel, your notifiable entity (e.g., a User or Team model) must implement a routeNotificationFor method that returns the Slack webhook URL when requested for the 'slack' channel.

    When a notification is sent, the channel calls the toSlack method on your notification class. This method should return either a Illuminate\Notifications\Slack\SlackMessage or a legacy Illuminate\Notifications\Messages\SlackMessage object.

    public function toSlack($notifiable)
    {
        return (new SlackMessage)
            ->content('Hello, Slack!');
    }
  8. Configure the visual style of a ConfirmObject

    3.x

    You can control the color scheme of the confirmation button using the style property.

    • Use the danger() method to set the style to danger. This displays the button with a red background on desktop or red text on mobile.
    • If no style is specified, it defaults to primary, which displays a green background on desktop or blue text on mobile.
    $confirmObject = (new ConfirmObject())->danger();
  9. Configure attachment fields using SlackAttachment::field()

    3.x

    The field() method allows you to add structured data to an attachment. It supports two ways of defining fields:

    1. Simple Key-Value Pair: Pass a string title and a string content. The title acts as the key. $attachment->field('Key', 'Value');

    2. Closure for Complex Fields: Pass a Closure as the first argument. The closure receives a SlackAttachmentField instance, allowing for more granular control (e.g., setting markdown content). $attachment->field(function (SlackAttachmentField $field) { $field->title('Key')->content('Value'); });

    // Simple key-value
    $attachment->field('Status', 'Completed');
    
    // Using a closure for advanced configuration
    $attachment->field(function ($field) {
        $field->title('Details');
        $field->content('This is a complex field');
    });
  10. Add a confirmation dialog to a ButtonElement

    3.x

    You can attach an optional confirmation dialog to a button using the confirm method. This prevents accidental clicks by prompting the user before the action is executed.

    When calling confirm, you must provide the confirmation text. You can optionally provide a callback to configure the ConfirmObject.

    $button = new ButtonElement('Delete Record');
    
    $button->confirm('Are you sure you want to delete this?', function ($confirm) {
        // Configure the confirm object if needed
    });
  11. Configure Slack message link unfurling and name linking

    3.x

    Use these methods to control how Slack handles links and mentions within your message:

    • linkNames(): Enables automatic linking of channel names and usernames.
    • unfurlLinks($unfurlLinks): A boolean flag to determine if Slack should provide a preview of links in the message.
    • unfurlMedia($unfurlMedia): A boolean flag to determine if Slack should provide a preview of media links.
    SlackMessage::create()
        ->content('Check out #general and https://example.com')
        ->linkNames()
        ->unfurlLinks(true)
        ->unfurlMedia(true);