Facebook PHP Messenger Bot - receive two messages
Asked Answered
I

1

1

I would like to write messenger bot based on this script:

<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];

// Set this Verify Token Value on your Facebook App 
if ($verify_token === 'testtoken') {
  echo $challenge;
}

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

// Get the Senders Graph ID
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];

// Get the returned message
$message = $input['entry'][0]['messaging'][0]['message']['text'];

//API Url and Access Token, generate this token value on your Facebook App Page
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<ACCESS-TOKEN-VALUE>';

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

//The JSON data.
$jsonData = '{
    "recipient":{
        "id":"' . $sender . '"
    }, 
    "message":{
        "text":"The message you want to return"
    }
}';

//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, $jsonData);

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

//Execute the request but first check if the message is not empty.
if(!empty($input['entry'][0]['messaging'][0]['message'])){
  $result = curl_exec($ch);
}
?>

All works correctly but i receive two responses to variable $message, for example:

  1. Send "Hello";
  2. $message = "Hello";
  3. Receive message: "Hi";
  4. $message = "Hi";

I would like to skip 3 and 4 points and receive only "Hello" message because i have to check if $message is my question or answer. Is it possible? Greetings

Immortelle answered 21/8, 2016 at 13:3 Comment(0)
S
1

You should skip any read and delivery messages, like this:

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

        // Skipping delivery messages
        if (!empty($message['delivery'])) {
            continue;
        }

        // Skipping read messages
        if (!empty($message['read'])) {
            continue;
        }
    }
}

Or, you can deselect message_reads & message_deliveries checkboxes in Page Subscription section of your Facebook Page Settings/Webhooks.

Stoke answered 6/9, 2016 at 14:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.