개발자의 끄적끄적

페이스북 챗봇 예제 (facebook chatbot example) 본문

개발/php

페이스북 챗봇 예제 (facebook chatbot example)

효벨 2019. 9. 18. 10:46
728x90
반응형

예전에 만들어봤던 페이스북 예제 소스임.

참고하시고 도움들 되시길...ㅎㅎ

참고로 payload 와 postback 부분은 꼭 확인하면서 체크!!

   // 페이스북에 등록한 get_url 소스
    $access_token = "페이스북에서 발급받은 토큰";
    $v_token = "fbchat";
    $challenge = $_REQUEST['hub_challenge'];
    $verify_token = $_REQUEST['hub_verify_token'];

    if ($verify_token === $v_token) {
        echo $challenge;
    }

    $input = json_decode(file_get_contents('php://input'), true);

    $sender = $input['entry'][0]['messaging'][0]['sender']['id'];

    // 실제 메세지를 보내기전 입력중이라는 표시
    $action = "typing_on";
    $r = array();
    $r["recipient"]["id"] = $sender;
    $r["sender_action"] = $action;

    $jsonData = json_encode($r);
    //Encode the array into JSON.
    $jsonDataEncoded = $jsonData;
    //API Url
    $url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;

    //Initiate cURL.
    $ing = curl_init($url);

    //Tell cURL that we want to send a POST request.
    curl_setopt($ing, CURLOPT_POST, 1);

    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ing, CURLOPT_POSTFIELDS, $jsonDataEncoded);

    //Set the content type to application/json
    curl_setopt($ing, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    //curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));

    //Execute the request
    if(!empty($input['entry'][0]['messaging'][0]['message'])){
        $result = curl_exec($ing);
    }

    $message = "";
    $postback = $input['entry'][0]['messaging'][0]['postback']['payload'];
    if ( $postback != "" ) {
        $foundPostback = true;
        $message = $postback;
    }else{
        $message = $input['entry'][0]['messaging'][0]['message']['text'];
    }    

    // 전송 메세지 처리 부분
    // 전송 타입을 선택한다. button / text
    $send_type = "text";
    if( $message == "안녕" ) {
        $send_txt = "어 안녕";
    }else{
        if( $message == "이벤트" ) {
            $send_txt = "아래링크중에 골라봐!";
            $send_type = "button";
        }else if( $message == "기타" ){
            $send_txt = "아래 목록을 순서대로 클릭해봐! 누를떄마다 메뉴가 바뀔꺼야!";
            $send_type = "postback";
        }else if( $message == "선택" ) {
            $send_txt = "아래중에 골라봐!";
            $send_type = "quick";
        }else{
            $send_txt = "뭐라고?";
            $send_type = "text";
        }
    }

    //API Url
    $url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;

    //Initiate cURL.
    $ch = curl_init($url);
    $r = array();
    // json data encoding
    if( $send_type == "button" ) {
        $r["recipient"]["id"] = $sender;
        $r["message"]["attachment"]["type"] = "template";
        $r["message"]["attachment"]["payload"]["template_type"] = "button";
        $r["message"]["attachment"]["payload"]["text"] = $send_txt;
        $r["message"]["attachment"]["payload"]["buttons"][0]["type"] = "web_url";
        $r["message"]["attachment"]["payload"]["buttons"][0]["url"] = "https://www.naver.com";
        $r["message"]["attachment"]["payload"]["buttons"][0]["title"] = "네이버";
        $r["message"]["attachment"]["payload"]["buttons"][1]["type"] = "postback";
        $r["message"]["attachment"]["payload"]["buttons"][1]["title"] = "네이버1";
        $r["message"]["attachment"]["payload"]["buttons"][1]["payload"] = "1";
    }else if( $send_type == "postback" ){
        // 버튼 선택형 오류인지 동작불가 - 원인 확인중
        $payload = "aaa";
        $r["recipient"]["id"] = $sender;
        $r["message"]["attachment"]["type"] = "template";
        $r["message"]["attachment"]["payload"]["template_type"] = "button";
        $r["message"]["attachment"]["payload"]["text"] = $send_txt;
        $r["message"]["attachment"]["payload"]["buttons"][0]["type"] = "postback";
        $r["message"]["attachment"]["payload"]["buttons"][0]["title"] = "이벤트";
        $r["message"]["attachment"]["payload"]["buttons"][0]["payload"] = "이벤트";
        $r["message"]["attachment"]["payload"]["buttons"][1]["type"] = "postback";
        $r["message"]["attachment"]["payload"]["buttons"][1]["title"] = "선택";
        $r["message"]["attachment"]["payload"]["buttons"][1]["payload"] = "선택";
        $r["message"]["attachment"]["payload"]["buttons"][2]["type"] = "postback";
        $r["message"]["attachment"]["payload"]["buttons"][2]["title"] = "기타";
        $r["message"]["attachment"]["payload"]["buttons"][2]["payload"] = "기타";

    }else if( $send_type == "quick" ) {
        // 선택형
        $r["recipient"]["id"] = $sender;
        $r["message"]["text"] = $send_txt;
        $r["message"]["quick_replies"][0]["content_type"] = "text";
        $r["message"]["quick_replies"][0]["title"] = "이벤트";
        $r["message"]["quick_replies"][0]["payload"] = "이벤트";
        $r["message"]["quick_replies"][1]["content_type"] = "text";
        $r["message"]["quick_replies"][1]["title"] = "기타";
        $r["message"]["quick_replies"][1]["payload"] = "기타";
    }else{
        $r["recipient"]["id"] = $sender;
        $r["message"]["text"] = $send_txt;
    }
    $jsonData = json_encode($r);

    //Encode the array into JSON.
    $jsonDataEncoded = $jsonData;

    //Tell cURL that we want to send a POST request.
    curl_setopt($ch, CURLOPT_POST, 1);

    //Attach our encoded JSON string to the POST fields.
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);

    //Set the content type to application/json
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    //Execute the request
    if(!empty($input['entry'][0]['messaging'][0]['message']) || $foundPostback ){
        $result = curl_exec($ch);
    }
반응형
Comments