Hardik Kalathiya
Hardik Kalathiya

Reputation: 2253

Facebook messenger bot - receives single and very first message

Facebook messenger bot - receives single and very first message continuously at every 2 minutes.

I have created bot in PHP and set webhook. But I am receiving webhook trigger at every two minutes no matter I have added/received new message or not.

One more thing is that we are receiving only very first messages. There are so many new messages after that message but we are receiving single message only.

Where am I incorrect? I have followed this article : http://blog.adnansiddiqi.me/develop-your-first-facebook-messenger-bot-in-php/

Upvotes: 0

Views: 469

Answers (1)

Hardik Kalathiya
Hardik Kalathiya

Reputation: 2253

We got the solution:

$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = isset($input['entry'][0]['messaging'][0]['message']['text']) ? $input['entry'][0]['messaging'][0]['message']['text'] : '';
if (!empty($input['entry'][0]['messaging'])) {

    foreach ($input['entry'][0]['messaging'] as $message) {

        $command = "";

        // When bot receive message from user
        if (!empty($message['message'])) {
            $command = $message['message']['text'];
        }
        // When bot receive button click from user
        else if (!empty($message['postback'])) {
            $command = $message['postback']['payload'];
        }
    }
}



$pagetoken = "PAGE TOKEN"; // Facebook TOKEN
if ($command) {

    if ($command == "hii") {
        $message_to_reply = "test_response";
    } else if ($command == "need more info") {
        $message_to_reply = "Please fill form at link ";
    } else if ($command == "\ud83d\ude00") {
        $message_to_reply = "smiley";
    }

    if ($message_to_reply != "") {
        $url = "https://graph.facebook.com/v2.6/me/messages?access_token=$pagetoken";
//Initiate cURL.
        $ch = curl_init($url);
//The JSON data.
        $jsonData = '{
        "recipient":{
        "id":"' . $sender . '"
        }, 
         "message":{
            "text":"' . $message_to_reply . '"
         }
       }';
        $jsonDataEncoded = $jsonData;
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        if (!empty($input['entry'][0]['messaging'][0]['message'])) {
            $result = curl_exec($ch);
        }
        curl_close($ch);
    }
}

header('HTTP/1.1 200 OK');  //  This line needs to be added

die;

Upvotes: 0

Related Questions