본문 바로가기

자료

PHP - 텔레그램 API - push 알림 받기

728x90

메뉴얼 링크는 아래와 같다.

 

https://core.telegram.org/bots/samples 

https://core.telegram.org/bots/samples/hellobot 

 

하지만 우리의 개발자들 중에 영어에 약한 분들이 존재하는 관계로 친절하게 한글로 설명을 하겠다.

 

개발언어는 php 이다.

 

순서는 아래와 같다.

1. push를 발송할 bot(봇)을 생성한다.

2. bot(봇)의 token(토큰)을 발급받는다.

3. bot(봇)과 token(토큰)을 이용하여 클라이언트의 message_id(메세지 id)값을 생성한다.

 

 

자 1번부터 가보자.

1. 데스크탑에 텔레그램을 설치한다.

구글이나 포탈 사이트에 텔레그램 치면 다 나오니깐 설치부터 하자.

설치후에 아래 링크를 클릭한다.

https://telegram.me/botfather

위와같이 나오는데 Telegram.exe 링크 항상 열기

를 클릭한다.

그러면 PC에 설치된 텔레그램이 실행된다.

 

그리고 BotFather 과 대화를 하면서 진행을 해나가면 된다.

 

BotFather 과의 대화를 아래와 같이 진행하자.

1. /newbot

2. 본인이 생성한 봇아이디 입력

3. 본인이 생성한 봇아이디_bot 입력

4. token 발급받은거 메모해두기

 



쉽게설명을 위해 위와같이 이미지를 첨부한다.

 

자 여기서 이제 발급받은 토큰을 기억해두자.

앞으로 개발해야할 소스코드에 적용해야 하기 때문이다.

 

 

그리고 push(푸쉬)를 처리할 소스코드이다.

 

라이브러리

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
    define('BOT_TOKEN', '318662010:AAH2lmrWMlzHhXrKQ2g7DS99xdQn9rxOhIQ');
    define('API_URL', 'https://api.telegram.org/bot'.BOT_TOKEN.'/');
     
    $_TELEGRAM_CHAT_ID    = array("132544306");
     
    function telegramExecCurlRequest($handle) {
        $response = curl_exec($handle);
     
        if ($response === false) {
            $errno = curl_errno($handle);
            $error = curl_error($handle);
            error_log("Curl returned error $errno: $error\n");
            curl_close($handle);
            return false;
        }
     
        $http_code = intval(curl_getinfo($handle, CURLINFO_HTTP_CODE));
        curl_close($handle);
     
        if ($http_code >= 500) {
            // do not wat to DDOS server if something goes wrong
            sleep(10);
            return false;
        } else if ($http_code != 200) {
            $response = json_decode($response, true);
            error_log("Request has failed with error {$response['error_code']}: {$response['description']}\n");
            if ($http_code == 401) {
                throw new Exception('Invalid access token provided');
            }
            return false;
        } else {
            $response = json_decode($response, true);
            if (isset($response['description'])) {
                error_log("Request was successfull: {$response['description']}\n");
            }
            $response = $response['result'];
        }
        return $response;
    }
     
    function telegramApiRequest($method, $parameters) {
        if (!is_string($method)) {
            error_log("Method name must be a string\n");
            return false;
        }
     
        if (!$parameters) {
            $parameters = array();
        } else if (!is_array($parameters)) {
            error_log("Parameters must be an array\n");
            return false;
        }
     
        foreach ($parameters as $key => &$val) {
            // encoding to JSON array parameters, for example reply_markup
            if (!is_numeric($val) && !is_string($val)) {
                $val = json_encode($val);
            }
        }
        $url = API_URL.$method.'?'.http_build_query($parameters);
        $handle = curl_init($url);
        curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($handle, CURLOPT_TIMEOUT, 60);
     
        return telegramExecCurlRequest($handle);
    }
cs


BOT_TOKEN 상수값에 위에서 발급받은 token 값을 넣는다. 

$_TELEGRAM_CHAT_ID 에는 본인의 message_id 값을 입력한다. 

본인의 message_id 값을 알아내는 방법은

텔레그램 검색바에서 "본인이 생성한 봇아이디_bot" 을 검색하여 아까 본인이 생성한 봇이 검색된다.

그리고 메세지 대화창에 아래 URL을 전송한다.

 

https://api.telegram.org/bot발급받은토큰값/getUpdates

 

아래와 같이 하면 된다.


 

그리고 위 URL을 클릭하면 아래와 같이 json 데이터가 브라우저창에 리턴된다.

 

그리고 리턴받은 json 데이터에서 아이디를 찾아내면 된다.

 

그리고 발송 소스이다.

 

1
2
3
4
5
6
7
    foreach($_TELEGRAM_CHAT_ID AS $_TELEGRAM_CHAT_ID_STR) {
        $_TELEGRAM_QUERY_STR    = array(
            'chat_id' => $_TELEGRAM_CHAT_ID_STR,
            'text'    => "{$_POST['name']} 님이 새글을 작성하셨습니다.",
        );
        telegramApiRequest("sendMessage",$_TELEGRAM_QUERY_STR);
    }
cs

 

$_POST["name"] 은 POST 데이터로 전송받은 게시글 작성자 name 값이다.

728x90