synsa
1/21/2017 - 2:40 AM

A simple class for sending a message to SlackHQ https://slack.com. Config settings in this example are coming from Laravel's Config facade.

A simple class for sending a message to SlackHQ https://slack.com. Config settings in this example are coming from Laravel's Config facade. Requires Guzzle 4.x http://guzzlephp.org.

<?php

use GuzzleHttp\Client;
use Config; //using Laravel's Config facade

/*
|--------------------------------------------------------------------------
| Usage:
|
| $slack = new Slack;
| $slack->send('This is a test message');
|
| Added $ignore_env to ignore the 'slack.enabled' setting when running 
| an artisan command (like pushing files to a remote) that you wont to include a notification with.
|
|--------------------------------------------------------------------------
*/

class Slack {

    public function __construct()
    {
        $this->client = new Client([
            'base_url' => Config::get('slack.base_url'),
            'defaults' => [
                'query'      => ['token' => Config::get('slack.api_token')],
                'exceptions' => false
            ]
        ]);
    }

    public function send($message, $ignore_env = null, $channel = null, $username = null, $icon_emoji = null)
    {
        if (Config::get('slack.enabled') || $ignore_env == true)
        {
            if ($channel == null)
                $channel = Config::get('slack.channel');

            if ($username == null)
                $username = Config::get('slack.username');

            if ($icon_emoji == null)
                $icon_emoji = Config::get('slack.icon_emoji');

            $payload = json_encode(
                        [
                        'channel'    => $channel,
                        'text'       => $message,
                        'username'   => $username,
                        'icon_emoji' => $icon_emoji
                        ]);

             $response = $this->client->post('/services/hooks/incoming-webhook',['body' => $payload]);

             return $response;
        }
    }

}