Last active
September 23, 2017 20:58
-
-
Save topperblues/3fea59de33ef36dbb259ffb6b4390ac1 to your computer and use it in GitHub Desktop.
Send simple slack message to an incoming webhook (https://api.slack.com/incoming-webhooks)
This file contains hidden or 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
| <?php | |
| class Slack | |
| { | |
| //Options | |
| private static $url = 'https://hooks.slack.com/services/.../.../...'; | |
| private static $channel = '#application_logs'; | |
| private static $bot_name = 'application-logs'; | |
| private static $authorName = "Application Logs"; | |
| private static $authorIcon = "https://application/icon.png"; | |
| public function sendMessage($message, $fallback = null, $color = null, $fields = []) | |
| { | |
| /* | |
| FIELDS ARRAY ITEM: | |
| 'title' => 'Title', | |
| 'value' => 'Lorem ipsum', | |
| 'short' => true | |
| */ | |
| $icon = ":8ball:"; | |
| switch ($color) { | |
| case 'good': | |
| $icon = ":+1:"; | |
| break; | |
| case 'warning': | |
| $icon = ":warning:"; | |
| break; | |
| case 'danger': | |
| $icon = ":sos:"; | |
| break; | |
| } | |
| $attachments = array(); | |
| if ($fallback!=null) { | |
| $attachments['fallback'] = $fallback; | |
| } | |
| if ($color!=null) { | |
| $attachments['color'] = $color; | |
| } | |
| if (count($fields)>0) { | |
| $attachments['fields'] = $fields; | |
| } | |
| $data = array( | |
| 'channel' => self::$channel, | |
| 'username' => self::$bot_name, | |
| 'text' => $message, | |
| 'icon_emoji' => $icon | |
| ); | |
| if (count($attachments)>0) { | |
| $attachments['pretext'] = $message; | |
| $attachments['author_name'] = self::$authorName; | |
| $attachments['author_icon'] = self::$authorIcon; | |
| $data['text'] = ""; | |
| $data['attachments'] = [$attachments]; | |
| } | |
| $data_string = json_encode($data); | |
| echo "DATA:"; | |
| echo $data_string; | |
| $ch = curl_init(self::$url); | |
| curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST"); | |
| curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string); | |
| curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
| curl_setopt($ch, CURLOPT_HTTPHEADER, array( | |
| 'Content-Type: application/json', | |
| 'Content-Length: ' . strlen($data_string)) | |
| ); | |
| //Execute CURL | |
| return curl_exec($ch); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment