Sending notifications to Slack and other channels with Craft CMS

Recently I've released craft-notifications. This plugin allows you to create notifications and send them to different channels based on how Laravel manages notifications.

Configuration and event based notifications

The plugin allows you to configure when the notifications are sent by adding a few lines to the supplied configuration file.

The following code will trigger the BlogPostAdded notification when a new entry is saved:

<?php 
 
return [
    'notifications' => [
        [
            'class' => \craft\elements\Entry::class,
            'event' => \craft\elements\Entry::EVENT_AFTER_SAVE,
            'notification' => \app\notifications\BlogPostAdded::class,
        ],
    ],
];

Making sure only notifications you want are sent

Of course sending a notification each time an entry is saved would become bothersome very quickly, luckily it's easy to define when you want to send your notification through your notification class' via() method:

public function via()
{
	$entry = $this->event->sender;

	if ($entry->section->handle === 'blog' && $this->event->isNew) {
      return [
        'database' => Craft::$app->getUsers()->getUserByUsernameOrEmail('hello@rias.be'),
        'mail' => 'hello@rias.be',
        'slack' => '<YOUR_WEBHOOK_URL>',
      ];
	}

	return [];
}

Defining the Slack notification

If you want to send notifications to slack, your notification class should define a toSlack() method.

The most basic version can look like this:

public function toSlack()
{
    return (new SlackMessage)
          ->content('A new blogpost was added!');
}

There's a lot more functionality available in the plugin like saving to the database, retrieving in your templates, marking as read and custom channels, so make sure you check out the Github repo.

MENU