File logs

เนื่องจากว่าการดีบักโค้ดบอทเราไม่สามารถใช้คำสั่ง var_dump หรือคำสั่งอื่นๆที่เกี่ยวข้องกับการดีบักได้ เพราะมันไม่ใช่หน้าเว็บ เราจึงเลือกใช้วิธีเขียนสิ่งที่ต้องการรู้ลงไฟล์แล้ว เปิดดูเอาผ่านหน้าเว็บ วิธีการให้ทำดังนี้

1.ไปยัง GitHub repository คลิกไฟล์ index.php

2.คลิกปุ่มแก้ไขเพื่อแก้ไฟล์ index.php

3.เขียนโค้ดนี้ลงไป อย่าลืมแก้ไข $access_token ให้เป็นของท่านนะครับ ซึ่งการเอา access token จากเฟชบุกมาท่านสามารถดูจากบท Create Facebook App

 <?php

$access_token = '1234iZA8ywOtEUZB52ZBLYziFtXjZCZAUZBmqlUtuemBnbbkN3M25NBKutMZCDzngjD0Uxz530fFmIiJHnFDHZBen9KRGvWZBjnti5awKG6a1g4XfaO8ZCKVfG2Cer5nu3W0uvubzk4wYfpsZCc9QfLGe2tiVZA5JGY6QZDZD';

/* validate verify token needed for setting up web hook */ 

if (isset($_GET['hub_verify_token'])) { 
    if ($_GET['hub_verify_token'] === $access_token) {
        echo $_GET['hub_challenge'];
        return;
    } else {
        echo 'Invalid Verify Token';
        return;
    }
}


/* Debug data */
$file = fopen("logs.txt","w"); 
fwrite($file, file_get_contents('php://input')); 
fclose($file); 


/* receive and send messages */
$input = json_decode(file_get_contents('php://input'), true);
if (isset($input['entry'][0]['messaging'][0]['sender']['id'])) {

    $sender = $input['entry'][0]['messaging'][0]['sender']['id']; //sender facebook id
    $message = $input['entry'][0]['messaging'][0]['message']['text']; //text that user sent

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

    /*initialize curl*/
    $ch = curl_init($url);

    /*prepare response*/
    $jsonData = '{
    "recipient":{
        "id":"' . $sender . '"
        },
        "message":{
            "text": "OK"
        }
    }';

    /* curl setting to send a json post data */
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    if (!empty($message)) {
        $result = curl_exec($ch); // user will get the message
    }
}

คำสั่งที่ใช้สำหรับดีบักคือ

/* Debug data */
$file = fopen("logs.txt","w"); 
fwrite($file, file_get_contents('php://input')); 
fclose($file);

fopen เป็นคำสั่งเปิดไฟล์ในโหมด w คือ write เขียน และถ้าหากไม่มีไฟล์ให้สร้างขึ้นมาใหม่

fwrite เขียนข้อความลงไฟล์ โดยให้เอาค่าที่ Facebook ส่งมาเขียนลงไป

fclose ปิดไฟล์

เปิด/เขียน/ปิด แค่นี้

4.กดปุ่ม Commit changes

5.ทักบอทไปสักคำคำว่า Hi ก็ได้ ซึ่งบอทจะต้องตอบกลับมาว่า OK

6.เปิดหน้าเบราเซอร์เข้าไปยัง https://select2web-facebookbot.herokuapp.com/logs.txt (URL ของท่านก็ให้เป็นของท่านนะครับ เพียงแค่ให้ตามด้วย /logs.txt ) ซึ่งมันจะต้องแสดงข้อความ json ขึ้นมา ข้อความนี้เป็นข้อความที่ Facebook ส่งมาให้บอท

*** ในกรณีที่ท่านลืม URL ของท่าน ให้ทำดังนี้

1.เข้าไปยัง Heroku apps https://dashboard.heroku.com/apps คลิกที่แอพบอท

2.คลิกปุ่ม Open app หน้าต่างใหม่จะแสดงขึ้นมาพร้อม URL ของท่าน

results matching ""

    No results matching ""