【问题标题】:Facebook PHP Messenger Bot - receive two messagesFacebook PHP Messenger Bot - 接收两条消息
【发布时间】:2016-08-21 13:03:50
【问题描述】:

我想根据这个脚本编写Messenger bot:

<?php
$challenge = $_REQUEST['hub_challenge'];
$verify_token = $_REQUEST['hub_verify_token'];

// Set this Verify Token Value on your Facebook App 
if ($verify_token === 'testtoken') {
  echo $challenge;
}

$input = json_decode(file_get_contents('php://input'), true);

// Get the Senders Graph ID
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];

// Get the returned message
$message = $input['entry'][0]['messaging'][0]['message']['text'];

//API Url and Access Token, generate this token value on your Facebook App Page
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token=<ACCESS-TOKEN-VALUE>';

//Initiate cURL.
$ch = curl_init($url);

//The JSON data.
$jsonData = '{
    "recipient":{
        "id":"' . $sender . '"
    }, 
    "message":{
        "text":"The message you want to return"
    }
}';

//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, $jsonData);

//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

//Execute the request but first check if the message is not empty.
if(!empty($input['entry'][0]['messaging'][0]['message'])){
  $result = curl_exec($ch);
}
?>

一切正常,但我收到两个对变量 $message 的响应,例如:

  1. 发送“你好”;
  2. $message = "你好";
  3. 接收消息:“嗨”;
  4. $message = "你好";

我想跳过 3 分和 4 分,只收到“Hello”消息,因为我必须检查 $message 是否是我的问题或答案。可能吗? 问候

【问题讨论】:

    标签: php facebook facebook-graph-api facebook-messenger messenger


    【解决方案1】:

    您应该跳过任何 readdelivery 消息,如下所示:

    if (!empty($input['entry'][0]['messaging'])) {
        foreach ($input['entry'][0]['messaging'] as $message) {
    
            // Skipping delivery messages
            if (!empty($message['delivery'])) {
                continue;
            }
    
            // Skipping read messages
            if (!empty($message['read'])) {
                continue;
            }
        }
    }
    

    或者,您可以在 Facebook 页面设置/Webhook 的页面订阅部分取消选择 message_readsmessage_deliveries 复选框。

    【讨论】:

      猜你喜欢
      • 2018-06-24
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 2017-05-02
      • 2018-01-21
      • 2016-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多