Search code examples
phpfacebookfacebook-messengerfacebook-messenger-bot

Facebook Messenger repeats sending user input


I have Facebook Messenger set up with a chatbot in PHP.
I am breaking up what would normally be a single response into multiple reply messages so that it looks more natural in a chat and easier to read than a single large chat bubble.

Here is how I am doing that:

for ($i=0; $i<count($response_array); $i++){
     $message_fb_format = [
         'recipient' => [
             'id' => $userID,
         ],
         'message' => [
             'text' => $response_array[$i],
        ],
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $replyMessageJSON);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Hub-Signature: xxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type: application/json'));
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_HTTP_VERSION, 'CURLOPT_HTTP_VERSION_NONE');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);

    sleep(2);
}

I found that when I set sleep() to 2 seconds or more, Facebook Messenger repeats sending the original user input. The chat window then appears as if my chatbot repeats its responses many times to a single input, but my logs clearly show that my server is receiving the same message from Facebook many times and the chatbot is responding correctly to each one.

Question is, why?
Why does a 2 second pause between multiple response messages cause Facebook Messenger to repeat the sending of the original message?


Solution

  • Because they expect you to respond to the webhook request with a 200 OK in a timely manner, and otherwise assume something must have gone wrong, that your bot was notable to receive the send data, and so it gets send again.

    https://developers.facebook.com/docs/messenger-platform/webhook#unsubscribe

    You would have to answer the incoming webhook request first with 200 OK and the first reply, and then send your additional messages to the recipient afterwards, independently from that initial request. (Only with Standard Messaging you won’t be able to do that in an unlimited way, because of the “24 + 1” policy.)