Facebook PHP Messenger Bot-收到两条消息 [英] Facebook PHP Messenger Bot - receive two messages

查看:140
本文介绍了Facebook PHP Messenger Bot-收到两条消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于此脚本编写Messenger机器人:

I would like to write messenger bot based on this script:

<?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的响应,例如:

All works correctly but i receive two responses to variable $message, for example:

  1. 发送你好";
  2. $ message =你好";
  3. 接收消息:嗨";
  4. $ message =嗨";
  1. Send "Hello";
  2. $message = "Hello";
  3. Receive message: "Hi";
  4. $message = "Hi";

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

I would like to skip 3 and 4 points and receive only "Hello" message because i have to check if $message is my question or answer. Is it possible? Greetings

推荐答案

您应该跳过任何 read delivery 消息,例如:

You should skip any read and delivery messages, like this:

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;
        }
    }
}

或者,您可以取消选择 message_reads & "Facebook页面设置/Webhooks"的页面订阅"部分的 message_deliveries 复选框.

Or, you can deselect message_reads & message_deliveries checkboxes in Page Subscription section of your Facebook Page Settings/Webhooks.

这篇关于Facebook PHP Messenger Bot-收到两条消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆