Facebook Chat Bot (PHP webhook) отправляет несколько ответов
Мой чат-бот в 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);
3 ответа
Я думаю, это потому, что вы не проверяете, являются ли отправленные сообщения пустыми:
попробуйте это вместо:
$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);
}
FB отправляет на ваш URL-адрес веб-крючка исходное входящее сообщение, и вы его обрабатываете. Затем вы отправляете ответ обратно пользователю, и сценарий завершается. Затем, как только сообщение доставлено пользователю, FB отправляет подтверждение доставки на URL веб-крючка. Поскольку ваш сценарий всегда настроен на отправку "Привет, Ли!" в любое время, когда он вызывается, обратный вызов доставки фактически инициирует отправку другого сообщения, и затем приходит другое подтверждение доставки, а затем этот процесс сам повторяется. Чтобы это исправить, поместите оператор if вокруг своего кода, чтобы отправить сообщение. Вот пример.
$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);
Надеюсь, это поможет.
Пробовал то же самое, первый запрос содержит фактическое сообщение пользователя, другие запросы нет. Я просто отправляю ответ, если$message = $input['entry'][0]['messaging'][0]['message']['text'];
не является нулевым:
if ($message){
//send your message here
}