在PHP中搜索特定Word的FB Messenger消息

问题描述 投票:0回答:1

所以我正在尝试创建一个非常简单的Facebook Messenger Chatbot。我让它使用硬编码响应,但我希望它能够读取发件人的消息并以特定的方式响应,如果它找到了这个词 - 就像聊天机器人应该如何。我试图通过使用preg_match()这样做,但当我使用我当前的代码时,机器人根本没有回复。这是我的代码:

<?php
/**
 * Webhook for Facebook Messenger Bot
 */
$access_token = "{mytoken}";
$verify_token = "{mytoken2}";

$hub_verify_token = null;
if (isset($_REQUEST['hub_challenge'])) {
    $challenge = $_REQUEST['hub_challenge'];
    $hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token == $verify_token) {
    echo $challenge;
}

$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];
$message = $input['entry'][0]['messaging'][0]['message']['text'];

// perform a case-Insensitive search for the word "time"
if (preg_match('[hi|hello|sup]', $message)) {
    $answer = "Hiya!";
}
else {
    $answer = "IDK.";
}

// send the response back to sender
// 'text': 'Hiya!'

$jsonData = "{
    'recipient': {
        'id': $sender
    },
    'message': {
        'text': $answer
    }
}";

// initiate cURL.
$ch = curl_init("https://graph.facebook.com/v2.6/me/messages?access_token=$access_token");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
if (!empty($input['entry'][0]['messaging'][0]['message'])) {
    curl_exec($ch);
}
php facebook preg-match chatbot messenger
1个回答
0
投票

你知道你是否真的从Messenger平台接收消息?您的webhook验证以echo结尾,实际上您需要使用状态代码200来响应平台。您还可以检查您的Facebook Apps信息中心,以确定您的webhook是否已经过验证并正在发送消息。

文档:https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup

一旦您知道您的webhook已经过验证并且您正在接收消息,请从固定回复开始,然后进行动态响应。正如@Toto建议的那样,添加日志记录对调试代码非常有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.