Facebook Chat bot (PHP web hook) el envío de múltiples respuestas

votos
2

Mi chat de Facebook robot está funcionando pero está devolviendo varios mensajes después de mi mensaje inicial a la misma. Esta es mi script web hook (i aprecio es un ejemplo de trabajo muy duro):

$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];

if ($verify_token === 'MY_VERIFICATION_TOKEN') {
  echo $challenge;
}

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

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


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

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

//The JSON data.
$jsonData = '{
    recipient:{
        id:'.$sender.'
    }, 
    message:{
        text:Hey Lee!
    }
}';

//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'));

//Execute the request
$result = curl_exec($ch);
Publicado el 13/04/2016 a las 18:04
fuente por usuario
En otros idiomas...                            


3 respuestas

votos
8

FB golpea su url web hook con el mensaje entrante original y lo procesa. Luego se le envía una respuesta de vuelta al usuario y finaliza la secuencia de comandos. Entonces, una vez que el mensaje se entrega al usuario, FB envía una confirmación de entrega a la url web hook. Dado que la secuencia de comandos siempre está configurado para enviar "Hey Lee!" cualquier momento que se llama, la devolución de llamada de entrega es en realidad desencadenando otro mensaje que se enviará, y luego otra confirmación de entrega entra, y luego ese proceso se repite lo mismo. Para solucionar este problema, se puso una sentencia if alrededor de su código para enviar un mensaje. He aquí un ejemplo.

$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];

if ($verify_token === 'MY_VERIFICATION_TOKEN') {
  echo $challenge;
}

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

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


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

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

if($message=="hello")
{
        //The JSON data.
        $jsonData = '{
        "recipient":{
                "id":"'.$sender.'"
        },
        "message":{
                "text":"Hey Lee!"
        }
        }';
}

//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'));

//Execute the request
$result = curl_exec($ch);

Espero que ayude.

Respondida el 13/04/2016 a las 21:58
fuente por usuario

votos
8

Creo que es porque no verifica si los mensajes enviados están vacías:

probar este lugar:

$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];

if ($verify_token === 'MY_VERIFICATION_TOKEN') {
  echo $challenge;
}

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

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


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

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

//The JSON data.
$jsonData = '{
    "recipient":{
        "id":"'.$sender.'"
    }, 
    "message":{
        "text":"Hey Lee!"
    }
}';

//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'));

//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
Respondida el 14/04/2016 a las 04:18
fuente por usuario

votos
0

Probamos la misma, la primera petición sostiene el mensaje real del usuario, las otras peticiones no. Acabo de mandar una respuesta si el
$message = $input['entry'][0]['messaging'][0]['message']['text'];no es nulo:

if ($message){
//send your message here
}
Respondida el 18/11/2016 a las 15:12
fuente por usuario

Cookies help us deliver our services. By using our services, you agree to our use of cookies. Learn more