[PHP] Slack WebHooks를 이용한 메세지 전송

이전 포스트에서 Webhook을 이용해 Slack으로 메세지를 전송했는데 메세지 속성중 attachments 를 이용해서 알림 내용을 좀 더 커스터마이징 했다.

<?php
/*
https://api.slack.com/incoming-webhooks
https://www.webpagefx.com/tools/emoji-cheat-sheet/
*/

class SLACK
{
    private $webHookUrl;
    private $channel;
    private $userName;
    private $message;
    private $iconEmoji;
    private $iconUrl;
    private $attachments;
    private $attachmentsText;
    private $attachmentsPreText;
    private $attachmentsColor;

    public function __construct($webHookUrl='', $userName='') {
        $this->webHookUrl  = $webHookUrl;
        $this->userName    = $userName;
        $this->iconEmoji   = '';
        $this->iconUrl     = '';
        $this->message     = '';
        $this->attachments = array();
    }

    public function setWebHookUrl($webHookUrl) {
        $this->webHookUrl = $webHookUrl;
    }

    public function setChannel($channel) {
        $this->channel = $channel;
    }

    public function setUserName($userName) {
        $this->userName = $userName;
    }

    private function subString($str, $len=0, $suffix='…') {
        $_str = trim($str);

        if($len > 0) {
            $arrStr = preg_split("//u", $_str, -1, PREG_SPLIT_NO_EMPTY);
            $strLen = count($arrStr);

            if ($strLen >= $len) {
                $sliceStr = array_slice($arrStr, 0, $len);
                $str = join('', $sliceStr);

                $_str = $str . ($strLen > $len ? $suffix : '');
            } else {
                $_str = join('', $arrStr);
            }
        }

        return $_str;
    }

    public function setAttachmentsText($text, $len=0) {
        $this->attachmentsText = $this->subString($text, $len);
    }

    public function setAttachmentPreText($pretext) {
        $this->attachmentsPreText = $pretext;
    }

    public function setAttachmentsColor($color) {
        $this->attachmentsColor = $color;
    }

    private function setAttachments() {
        $this->attachments[] = array(
            'pretext'   => $this->attachmentsPreText,
            'text'      => $this->attachmentsText,
            'color'     => $this->attachmentsColor,
            'mrkdwn_in' => array('text', 'pretext')
        );
    }

    public function setIconEmoji($iconEmoji) {
        $iconEmoji = strip_tags(trim($iconEmoji));

        if($iconEmoji)
            $this->iconEmoji = $iconEmoji;
    }

    public function setIconUrl($iconUrl) {
        $iconUrl = strip_tags(trim($iconUrl));

        if($iconUrl)
            $this->iconUrl = $iconUrl;
    }

    public function send() {
        if($this->webHookUrl) {
            $this->setAttachments();

            $postData = array(
                'channel'     => $this->channel,
                'username'    => $this->userName,
                'icon_emoji'  => $this->iconEmoji,
                'icon_url'    => $this->iconUrl,
                'text'        => $this->message,
                'attachments' => $this->attachments,
                'mrkdwn'      => true,
                'link_names'  => 1
            );

            $ch = curl_init($this->webHookUrl);
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST,  'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS,     'payload='.json_encode($postData));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            $result = curl_exec($ch);
            curl_close($ch);

            return $result;
        } else {
            return 'WebHook URL Error';
        }
    }
}

slack.class.php 파일의 코드는 위와 같다. 위 class를 이용해 Slack에 메세지를 전송하는 코드는 아래와 같다.

<?php
require_once('./slack.class.php');

// 담당자
// 회원 아이디를 Slack member id 로 치환
$_CHECKSTAFF = array(
    'aaaa'   => 'U124454',
    'bbbb'   => 'U123456'
);

$info = array();

$info[] = '아이디 : ' . strip_tags($wr['mb_id']);
$info[] = '고객명 : ' . strip_tags($wr['wr_name']);

// 담당자
if($wr['wr_10']) {
    $_temp = array_unique(array_map('trim', explode('||', $wr['wr_10'])));

    $_mentions = array();

    foreach($_temp as $val) {
        $_mention = $_CHECKSTAFF[$val];
        if($_mention)
            $_mentions[] = '<@' . $_mention . '>';
    }

    if(!empty($_mentions))
        $info[] = implode(' ', $_mentions);
}

// 게시글 링크
$info[] = '<'.urlencode(G5_HTTP_BBS_URL.'/board.php?bo_table='.$bo_table.'&wr_id='.$wr['wr_parent'].'#c_'.$comment_id).'|게시글 보기>';

// wr_content 가공
// 메일 발송을 사용하는 경우 $wr_content 변경됨
$_temp = explode("댓글\n", preg_replace('#<br\s*/?>#i', "\n", $wr_content));
$_wr_content = array_pop($_temp);

$info[] = strip_tags($_wr_content);

$_text    = implode("\n", $info);
$_pretext = strip_tags($wr['ca_name']) . ' | ' . strip_tags($wr['wr_subject']);

$slack = new SLACK();

$slack->setWebHookUrl('https://hooks.slack.com/services/TTTTTT/XXXX/uidyJNkO');
$slack->setChannel('#general');

$slack->setUserName('[댓글등록알림]');
//$slack->setIconEmoji(':loudspeaker:');
$slack->setIconUrl('https://a.slack-edge.com/41b0a/img/plugins/app/service_36.png');
//$slack->setMessage('Slack 메세지 내용');
$slack->setAttachmentsText($_text);
$slack->setAttachmentPreText($_pretext);
$slack->setAttachmentsColor('#36a64f');

$result = $slack->send();

//print_r($result); exit;

메세지를 발송하는 것은 그누보드5에서 댓글을 작성했을 때 Slack으로 알림 메세지를 발송하는 경우이다. 실제 사용을 위해서는 47, 48라인의 Webhook Url, 채널명을 지정해줘야 한다.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.