BlogSimple Slack Messages for Laravel 4.2

25th September 2015

I've implemented this quick solution (if I have time in future I'll implement a more Object Oriented solution) to post Slack messages to the a slack channel. It is literally just an event listener which excepts a couple of params (the message, an optional title and optional emoji – for added fun) then fires them off to the Slack API.

N.B. I use Sentry for Authentication so you may want to either strip that out or customise that bit to whatever you use.

1) Add a slackbot integration to the channel in Slack. Make a note of the URL given (to be used in the config later).

2) Add slack.php to the config directory.

3) Add the following to the slack config…

'slackChannel' => "channel_name",
'slackUsername' => "slackbot",
'slackURL' => "https://hooks.slack.com/services/xxxxx/xxxxxx/xxxxxx",

4) Add the following listener to app/start/global.php…

Event::listen('slack.message', function($message, $title = '', $emoji = ''){
    if(!empty($message)){
        
        $currentUser = \Sentry::getUser();

        $channel = \Config::get('slackChannel');
        $username = \Config::get('slackUsername');
        $url = \Config::get('slackURL');
        
        $env = \App::environment();
        $clock_icon = ':clock'.date('g').(date('i') > 30 ? '30' : '').':';
        $user_time = "\n{$clock_icon} ".date('H:i:s').($currentUser ? ", :bust_in_silhouette: {$currentUser->first_name} {$currentUser->last_name}" : '');
        $message = (!empty($emoji) ? $emoji : '').(!empty($title) ? "*{$title}* ({$env}): " : '').$message.$user_time;

        $data = "payload=" . json_encode([
                "channel"       => "#{$channel}",
                "username"      => $username,
                "text"          => $message,
                "mrkdwn"        => true,
            ]);

        // curl out a request to the slack API
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($ch);
        curl_close($ch);

        Log::info("Sent to Slack: " . $message, array('context' => 'Notifications'));
    }
});

Then all you need to do is fire the event.

This is the event that I've implemented in one of my projects in app/start/global.php/App::error and sends exceptions to Slack...

Event::fire('slack.message', [$exception->getMessage(), 'Exception thrown', ':heavy_exclamation_mark:']);

Enjoy!

Let's Talk