【发布时间】:2018-03-06 02:52:47
【问题描述】:
所以我正在尝试创建一个非常简单的 Facebook Messenger 聊天机器人。我让它使用硬编码的响应,但我希望它能够读取发件人的消息并在找到该词时以特定方式响应 - 就像聊天机器人应该做的那样。我试图通过使用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);
}
【问题讨论】:
-
preg_match 不是这样工作的
-
@WizKid 好笑,PHP 允许括号作为分隔符...
-
首先,插入一些调试行并查看日志。
标签: php facebook preg-match chatbot messenger