Skip to content

CHICPRO

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

[PHP] Slack Webhook Class

2018-07-05 by 편리

Slack Webhook 사용을 위한 PHP Class 코드이다.

<?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 $attachmentsTitle;
    private $attachmentsPreText;
    private $attachmentsColor;
    private $attachmentsAuthor;
    private $attachmentsFields;
    private $attachmentsFooter;

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

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

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

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

    public function setMessage($message) {
        $this->message = $message;
    }

    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 setAttachmentsTitle($title) {
        $this->attachmentsTitle = $title;
    }

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

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

    public function setAttachmentsAuthor($author) {
        $this->attachmentsAuthor = $author;
    }

    public function setAttachmentsFields($title, $value, $short = false)
    {
        $this->attachmentsFields[] = array(
            'title' => $title,
            'value' => $value,
            'short' => $short
        );
    }

    public function setAttachmentsFooter($footer) {
        $this->attachmentsFooter = $footer;
    }

    private function setAttachments() {
        $this->attachments[] = array(
            'pretext'     => $this->attachmentsPreText,
            'title'       => $this->attachmentsTitle,
            'author_name' => $this->attachmentsAuthor,
            'text'        => $this->attachmentsText,
            'color'       => $this->attachmentsColor,
            'fields'      => $this->attachmentsFields,
            'footer'      => $this->attachmentsFooter,
            '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';
        }
    }
}

기존 코드에서 fields 등 몇 가지 메세지 포맷을 추가했다.

Post navigation

Previous Post:

우분투 RSS 리더 프로그램 FeedReader

Next Post:

우분투 18.04 LTS 에서 nimf 입력기 설치

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