Skip to content

Instantly share code, notes, and snippets.

@rufhausen
Last active October 25, 2021 14:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save rufhausen/9835111 to your computer and use it in GitHub Desktop.
Save rufhausen/9835111 to your computer and use it in GitHub Desktop.
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
//This code is licensed under the terms of the MIT license
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;
}
}
}
@ostretsov
Copy link

You could also use Monolog for the same purpose.

@KristianI
Copy link

What's the license for the gist shown?

@rufhausen
Copy link
Author

What's the license for the gist shown?

I added "This code is licensed under the terms of the MIT license" to the top of the file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment