2 回答

TA貢獻(xiàn)2021條經(jīng)驗 獲得超8個贊
這可能不是您正在尋找的答案,但我在開發(fā)自己的聊天機(jī)器人時也遇到了同樣的問題。有兩種解決方案的組合可以解決此問題:
解決方案 1:如果沒有輸入,或者沒有消息文本和有效負(fù)載,則代碼退出。這是我的代碼的摘錄:
$input = json_decode(file_get_contents('php://input'), true);
if(empty($input))
exit();
$messageText = $input['entry'][0]['messaging'][0]['message']['text'];
$messagePayload = $input['entry'][0]['messaging'][0]['postback']['payload'];
if(empty($messageText) && empty($messagePayload)) {
exit();
}
這是必要的,因為聊天機(jī)器人似乎只是一遍又一遍地用空請求向我的入口點(diǎn)發(fā)送垃圾郵件。然而...
解決方案 2:我將所有消息 id-s 保存在數(shù)據(jù)庫中,如果一個已經(jīng)在處理中,則退出。這是必要的,因為我在 API 中不斷收到某些消息 2 或 3 次,并且我不得不避免兩次回答相同的消息。這是一個簡短的摘錄:
$mid = $input['entry'][0]['messaging'][0]['message']['mid'];
$received = $this->user->isReceived($mid); // To avoid reacting to the same message twice
if($received) {
exit();
} else {
$this->user->logMsg($mid);
}
在isReceived函數(shù)中,我檢查消息 id-s 的自定義表是否已包含此消息。在logMsg函數(shù)中,我存儲了 id。然而,它們有點(diǎn)復(fù)雜并且依賴于框架,因此您必須自己編寫這些函數(shù),因為您認(rèn)為它們適合您的項目。
祝你好運(yùn),我希望有人提出更好的解決方案。

TA貢獻(xiàn)1847條經(jīng)驗 獲得超7個贊
try {
// Returns a `FacebookFacebookResponse` object
$response = $fb->get(
'/{to_id}?fields=conversations{messages{message}}',
$accesstoken
);
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
$idchk = $response->getGraphNode();
$datachk = json_decode($idchk);
if (($data->object == "page")&&(strpos($idchk,'hey')=="")) {
try {
$response = $fb->post(
'/me/messages',
array (
'recipient' => '{
"id": "{to_id}"
}',
'message' => '{
"text": "hey"
}'
),
$accesstoken
);
exit;
} catch(FacebookExceptionsFacebookResponseException $e) {
echo 'Graph returned an error: ' . $e->getMessage();
exit;
} catch(FacebookExceptionsFacebookSDKException $e) {
echo 'Facebook SDK returned an error: ' . $e->getMessage();
}}
exit;
- 2 回答
- 0 關(guān)注
- 139 瀏覽
添加回答
舉報