Developer

PHP | [PHP] 텔레그램 api로 push 받기(Webhook)

페이지 정보

작성일2019-10-01 12:44 조회4,342회

본문

1. https://telegram.me/botfather 접속

2. [시작] 버튼 클릭

 

 

 

3. /newbot 입력

4. 봇 이름 입력

5. 봇 이름_bot 또는 봇 이름Bot 입력

 

 

 

6. <apikey>값 저장 

7. /start 입력

8. https://api.telegram.org/bot<apikey>/getUpdates 입력

 

 

 

9. <chat_id>값 저장

위에서 발급받은 <apikey>값, <chat_id>값이 쓰입니다.    

-------------------------------------- 

아래 텔레그램 Push PHP 소스

 [FUNCTION]

<?php
$output = telegram_send("안녕하세요");

function telegram_send($msg) {
    $apikey = '914976991:AAhhoyjk2zhm34vepp14blnFyq4DAgq';
    $chat_id = '85162432';
    $params = 'chat_id='.$chat_id.'&text='.urlencode($msg);
    $webhook = 'https://api.telegram.org/bot'.$apikey.'/sendMessage';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $webhook); // Webhook URL
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    $return = curl_exec($ch);
    curl_close($ch);
    return $return;
}
?>

[CLASS]
<?php
class Telegram {

    /*
     * @var string bot_token
     */
    private $bot_token;

    /*
     * @var string $url
     */
    private $url = 'https://api.telegram.org/bot';

    /*
     * @var string $chat_id
     */
    private $chat_id;

    /**
     * @var string $method API method
     */
    private $method;

    /**
     * @var string $headers
     */
    private $headers = [];

    /**
     * @var string $data
     */
    private $data = [];

    /**
     * @var string $http_code
     */
    private $http_code;

    /**
     * @var string $response
     */
    protected $response = '';

    public function __construct($token, $chat_id) {
        $this->headers = array(
            'Accept: application/json',
            'Content-Type: application/json'
        );
        $this->bot_token = $token;
        $this->chat_id = $chat_id;
    }
    public function get_http_code() {
        return $this->http_code;
    }
    public function get_url() {
        return $this->url . $this->bot_token .'/';
    }
    public function get_request() {
        return $this->request;
    }
    public function set_request(string $request) {
        $this->request = $request;
    }
    public function get_data() {
        return $this->data;
    }
    public function set_data($value, $key = '') {
        if (is_array($value) === true && count($value) > 0) {
            $this->data = array_merge($this->data, $value);
        } else {
            if ($key != '') {
                $this->data[$key] = $value;
            } else {
                $this->data[] = $value;
            }
        }
    }
    public function reset_data() {
        $this->data = [];
    }

    /**
     * Curl 통신
     */
    private function api_request() {
        $ch = curl_init();
        $params = '';
        if(count($this->get_data()) > 0 and strtolower($this->request) == 'get') {
            $params = $this->get_data();
            foreach ($params as $key => &$val) {
                // encoding to JSON array parameters, for example reply_markup
                if (!is_numeric($val) && !is_string($val)) {
                    $val = json_encode($val);
                }
            }
            $params = '?'.http_build_query($params);
        }
        $curl = $this->get_url().$this->method.$params;
        curl_setopt_array($ch, array(
            CURLOPT_URL => $curl,
            CURLOPT_HTTPHEADER => $this->headers,
            CURLOPT_CUSTOMREQUEST => $this->request,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_SSL_VERIFYPEER => 0,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT => 5,
        ));
        if (count($this->get_data()) > 0 and strtolower($this->request) == 'post') {
            crl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array('params' => $this->get_data())));
        }
        $this->response = curl_exec($ch);
        $this->http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
    }

    /**
     * Curl 결과
     */
    public function api_response() {
        try {
            $response = $this->response;
            $output = [];
            $output['code'] = 1;
            $output['data'] = $response;
            return $output;
        } catch (Exception $e) {
            $output = [];
            $output['code'] = $e->getCode();
            $output['msg'] = $e->getMessage();
            return $output;
        }
    }

    /**
     * Send Message
     */
    public function send($msg) {
        $this->method = 'sendMessage';
        $this->request = 'GET';
        $this->reset_data();
        $this->set_data($this->chat_id, 'chat_id');
        $this->set_data($msg, 'text');
        $this->api_request();
        return $this->api_response();
    }
}


/**
 * Class 호출
 */
$tg = new Telegram('914976991:AAhhoyjk2zhm34vepp14blnFyq4DAgq', '85162432');
$output = $tg->send('안녕하세요.');

?>

#php #텔레그램 #telegram #API #PUSH #알림 #Webhook



  • 카카오스토리로 보내기
  • 페이스북으로 보내기
  • 트위터로 보내기
  • 구글플러스로 보내기
  • 더보기
  • Naver Blog로 보내기
  • TUMBLR로 보내기
  • LinkedIN으로 보내기
  • REDDIT으로 보내기
  • delicio으로 보내기
  • pinterest으로 보내기
  • 블로거로 보내기
php jquery cloud HTML 무설치 클라우드 script 팀박스 TEAMBOX 포터블 ssh css 기어s3 시그널 스마트워치 공유캐시삭제 facebook 삼성 페이스북 소스 코메디 IT CNET VR가상현실 싸이이비즈 ColorScripter GoingHome LGU+ 기업용클우드 sgnl 스마트시곗줄 extension 3DBChip 아스키코드 드라이버 나무클라우드 미국정보교표준부호 ASCII 아스키 selectbox chrome google 손가락통화 MiBand2 미밴드2 샤오미 Xiaomi 색상표 구글 크롬 확장프로램 제어 Comedy 팝업창 openssl encrypt decrypt 암호화 PHPParser 문서파싱 mRemote 서버관리프로그램 RemoteDesktop PHP암호화 array 레이어 오늘하루닫기 줄바꿈 word-break white-spac CURL/a> ajax 말줄임표 배열 컬러코드 ColorCode ssh2 원태연 시집 넌가끔가다 마술 수여니 재밋다 magic 수호천사 재미 ZOAPROJECT RADAZoa sftp jqueryui datepicker 하늘 하트 구름 김윤아 뮤직비디오 RADA Gamarjobat