Skip to main content

Slack Notifiable in MoonGuard Filament Plugin

· 2 min read
Alexis Fraudita

In previous versions of the MoonGuard Filament Plugin, the team used Slack notifications to monitor different internal applications and test features of the MoonGuard package. However, these notifications were configured to be sent repeatedly to the same channel for each registered user, which presented a problem.

In the ExceptionLogGroupCreatedListener class, the all() method of the UserRepository was being used to send messages to all users.

<?php

use Illuminate\Support\Facades\Notification;
use Taecontrol\MoonGuard\Repositories\UserRepository;
use Taecontrol\MoonGuard\Events\ExceptionLogGroupCreatedEvent;
use Taecontrol\MoonGuard\Notifications\ExceptionLogGroupNotification;

class ExceptionLogGroupCreatedListener
{
public function handle(ExceptionLogGroupCreatedEvent $event): void
{
Notification::send(
UserRepository::all(),
new ExceptionLogGroupNotification($event->exceptionLogGroup)
);
}
}

This works when you want to send email notifications, but in the particular case of Slack, in MoonGuard we set up a general channel to receive all notifications.

To solve this problem, we created a class called SlackNotifiable, inspired by the post from ralphjsmit, which allows us to send MoonGuard notifications to Slack only once. In this class, we pass the webhook URL of the Slack application as shown below.

<?php

namespace Taecontrol\MoonGuard\Notifications;

use Illuminate\Notifications\Notifiable;

class SlackNotifiable
{
use Notifiable;

public function routeNotificationForSlack(): string
{
return config('moonguard.notifications.slack.webhook_url');
}
}

We updated the listeners that are responsible for listening to MoonGuard events and sending notifications according to the type of channel used, whether it's email or slack, taking into account that the Slack channel will use the SlackNotifiable object and the email will be sent to all users. For example:

<?php

namespace Taecontrol\MoonGuard\Listeners;

use Illuminate\Support\Facades\Notification;
use Taecontrol\MoonGuard\Repositories\UserRepository;
use Taecontrol\MoonGuard\Notifications\SlackNotifiable;
use Taecontrol\MoonGuard\Events\ExceptionLogGroupCreatedEvent;
use Taecontrol\MoonGuard\Notifications\ExceptionLogGroupNotification;

class ExceptionLogGroupCreatedListener
{
public function handle(ExceptionLogGroupCreatedEvent $event): void
{
$channels = config('moonguard.notifications.channels');

foreach ($channels as $channel) {
$notifiables = ($channel === 'slack') ? new SlackNotifiable() : UserRepository::all();

Notification::send(
$notifiables,
new ExceptionLogGroupNotification($event->exceptionLogGroup, $channel)
);
}
}
}

If you want to know more in detail about our update, please check our latest release 1.0.9.

I hope this post has been useful for you. Remember to follow us on Twitter/X @moonguard_dev and join our Discord community for more information.