问题
I've setup a working facebook chatbot in PHP and built a generic template carousel with one of the postback buttons being:
[
type"=>"postback",
"title"=>"Opening Hours",
"payload"=>"Opening Hours"
],
Pressing the postback button and checking my PHP logs I am getting:
{"object":"page","entry":[{"id":"457107221010xxx","time":1513219207386,
"messaging": [{"recipient":
{"id":"457107221010xxx"},"timestamp":1513219207386,"sender":
{"id":"1510264525690xxx"},"postback":{"payload":"Opening
Hours","title":"Opening Hours"}}]}]}
I'm handling this postback in my code by:
$postback = $input['entry'][0]['messaging'][0]['postback']['payload'];
if ($postback!="") {
$answer = ["text"=> $openingHours];
}
But in messenger window after pressing said postback button, messenger seem to be "typing" with the three dots dialog showing for a few seconds, but then it just stops without any replies. I did enable "message_postback" option in webhooks, and other queries are working (e.g. if I type "Opening Hours" manually I'll get the Opening Hours reply). I process other queries with following code and it works:
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];
if(preg_match('[opening|hours]', strtolower($message))) {
$answer = ["text"=>"
Opening Hours:
10:30 am – 1:00 am (Sun-Thu)"];
} else {
//show menu
}
Any advice much appreciated!
回答1:
As I dont see the code, which triggers the actual sending, the error could be found there. If you've copied the basic tutorial it might look like this one I started with a long time ago:
if(preg_match('[time|current time|now]', strtolower($message))) {
$message_to_reply = date('l jS \of F Y h:i:s A');
} else {
$message_to_reply = 'Huh! what do you mean?';
}
// your code here
$postback = $input['entry'][0]['messaging'][0]['postback']['payload'];
if ($postback!="") {
$message_to_reply = "postback!";
$foundPostback = true;
}
$url = 'https://graph.facebook.com/v2.11/me/messages?access_token='.$access_token;
$ch = curl_init($url);
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{
"text":"'.$message_to_reply.'"
}
}';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(!empty($input['entry'][0]['messaging'][0]['message']) || $foundPostback ){
$result = curl_exec($ch);
}
Notice the $foundPostback
. If your send trigger looks like this from one the tutorials, it will not send messages, as there is no $input['entry'][0]['messaging'][0]['message']
attribute in postback messages. So if you detect a postback, you have to keep that flag.
However, I strongly suggest to build own classes for handling messages, postback, deliveries, echos and so on. More about those you can find here: Facebook Messenger Docs
来源:https://stackoverflow.com/questions/47805187/facebook-chatbot-postback-not-working