Last active
September 1, 2015 17:28
-
-
Save niklasb/769fa73eba716b516048 to your computer and use it in GitHub Desktop.
Monolog handler for Slack's (new?) incoming webooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MonologSlackHandler extends \Monolog\Handler\MailHandler { | |
protected $hook_url; | |
protected $channel; | |
protected $username; | |
protected $icon; | |
/** | |
* @param string $hook_url The URL of your incoming web hook (e.g. | |
* https://hooks.slack.com/services/$token) | |
* @param string $channel Slack channel to post in (with leading # sign) | |
* @param string $username Username you'd like to display message as | |
* @param string $icon URL to custom icon | |
*/ | |
public function __construct( | |
$hook_url, $channel, $username, $icon, | |
$level = \Monolog\Logger::ERROR, $bubble = true) | |
{ | |
parent::__construct($level, $bubble); | |
$this->hook_url = $hook_url; | |
$this->channel = $channel; | |
$this->username = $username; | |
$this->icon = $icon; | |
} | |
/** | |
* Post the message to Slack using CURL | |
*/ | |
protected function send($content, array $records) { | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $this->hook_url); | |
curl_setopt($ch, CURLOPT_HEADER, 0); | |
$payload = json_encode( | |
array( | |
"channel" => $this->channel, | |
"username" => $this->username, | |
"text" => $content, | |
"icon_emoji" => $this->icon | |
) | |
); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload); | |
// supress output | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_VERBOSE, 0); | |
curl_exec($ch); | |
curl_close($ch); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment