ChatBot PHP - Facebook Messenger

1

Hello, how are you? I am creating a chatbot but I am having problems with HTTP (POST) request.

When I call a function to send the POST to Facebook Messenger it seems to loop and start sending all the posts. Generating this as a result:

Lookatthemaincode(index.php)thatcallsthefunction:

include'Banco.php';include'Envio.php';$banco=newBanco();$envio=newEnvio();switch($banco->getSecao($sender_id)){case0://APRESENTACAOEPEDECPF$envio->apresentacao($sender_id);break;case1://BOASVINDASEPEDECPF$banco->setSecao($sender_id,2);$envio->boasvindas($sender_id);break;case2://EXIBERASTREIO$banco->setSecao($sender_id,3);$envio->pedidos($sender_id);break;case3://PEDECODIGODERASTREIO$banco->setSecao($sender_id,4);$envio->tracking($sender_id);break;case4://AGRADECEOUSOPEDECPFECOLOCAASECAOEM2$banco->setSecao($sender_id,2);$envio->agradecimento($sender_id);break;}

BotshouldsendthePOSTonlyfromthe"section" that is returned from the registry. But he goes into all of them. I've tried leaving just one case. he keeps sending this case several times. Here is an example of class Shipping:

private function send($dados){            
        $url = $this->apiUrl . '?access_token=' . $this->access_token;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        $params = http_build_query($dados);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
        $server_output = curl_exec ($ch);
        curl_close ($ch);
        return $server_output;
    }

    public function apresentacao($idClient){
        $responseJSON = array(
            "recipient" => array(
                "id" => $idClient
            ),
            "message" => array(
                "text" => "Olá, eu sou o Onex, tudo bem?\nQue legal te ver por aqui! Posso te ajudar a rastrear algum pedido?"
            )
        );
        $response = $this->send($responseJSON);

        $responseJSON = array(
            "recipient" => array(
                "id" => $idClient
            ),
            "message" => array(
                "text" => "Pra começar, vou precisar de seu CPF ou CNPJ:"
            )
        );
        $response = $this->send($responseJSON);
    }
    
asked by anonymous 06.11.2017 / 12:37

1 answer

2

I came to share the solution.

I started to write in txt of every post that was sent, and I noticed that the facebook itself generates the loop, but since it is not my bot that is sending the message field in the JSON is blank, then I made a validation in this field :

$message = isset($input['entry'][0]['messaging'][0]['message']['text']) ? $input['entry'][0]['messaging'][0]['message']['text']: 'vazio' ;

And before activating the switch I validate:

if($message != 'vazio'){

And so it worked correctly and broke the loops.

Thank you very much and hugs!

    
06.11.2017 / 13:30