Facebook чат бота (PHP webhook) отправка несколько ответов

голоса
2

Мой Facebook чат бот работает, но он посылает обратно несколько сообщений после моего первого сообщения к нему. Это мой webhook сценарий (я ценю это очень грубый рабочий пример):

$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);
Задан 13/04/2016 в 21:04
источник пользователем
На других языках...                            


3 ответов

голоса
8

FB поражает Ваш webhook URL с оригинальным входящим сообщением, и вы его обработать. Вы затем отправить ответ обратно пользователю и сценарий завершается. Затем, когда сообщение доставляется пользователю, FB отправляет подтверждение доставки в webhook URL. Так как ваш скрипт всегда установлен отправить «Эй Ли!» в любое время, что называется, доставка обратного вызова фактически вызвав еще одно сообщение будет отправлено, а затем еще одно подтверждение доставки приходит, а затем этот процесс повторяется это сам. Чтобы это исправить, если положить заявление вокруг кода, чтобы отправить сообщение. Вот пример.

$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);

Надеюсь, это поможет.

Ответил 14/04/2016 в 00:58
источник пользователем

голоса
8

Я думаю, это потому, что вы не проверить, если сообщения, отправленные пустые:

попробуйте вместо этого:

$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);
}
Ответил 14/04/2016 в 07:18
источник пользователем

голоса
0

Пробовал то же самое, первый запрос содержит фактическое сообщение пользователя, другие запросы нет. Я просто отправить ответ , если
$message = $input['entry'][0]['messaging'][0]['message']['text'];не равно нулю:

if ($message){
//send your message here
}
Ответил 18/11/2016 в 18:12
источник пользователем

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