Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

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

2017-11-06 by 편리

이전 포스트에서 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, 채널명을 지정해줘야 한다.

Post navigation

Previous Post:

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

Next Post:

[PHP] onesignal을 이용한 그누보드5 글등록 webpush ssl 적용

Leave a Reply Cancel 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.

Recent Posts

  • SK 세븐모바일 유심 셀프교체
  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes