2016-04-22 145 views
3

迴應我在PHP中有着相對簡單的Facebook Messenger的機器人爲研究目的:Fecebook Messenger的機器人並不總是以用戶

$access_token = "xxxxxxx"; 
$challenge = $_REQUEST['hub_challenge']; 
$verify_token = $_REQUEST['hub_verify_token']; 

if ($verify_token === 'MY_VERIFICATION_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']; 

$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token.'; 

$ch = curl_init($url); 

if($message=="hi") 
{ 
     $jsonData = '{ 
     "recipient":{ 
       "id":"'.$sender.'" 
     }, 
    "message":{ 
      "text":"hello!" 
    } 
    }'; 
} 

$jsonDataEncoded = $jsonData; 

curl_setopt($ch, CURLOPT_POST, 1); 

curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded); 

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json')); 

$result = curl_exec($ch); 

和我的cron作業是一樣的開發者指南

curl -ik -X POST "https://graph.facebook.com/v2.6/me/subscribed_apps?access_token=xxxxxx" 

所以基本上,除了連接和一個響應之外什麼也沒有。 當我親自發送「hi」(作爲頁面所有者和應用程序所有者)時,我的機器人總是響應正確,但是當其他人試圖說hi-bot有時會迴應,有時候不會(通常不會)

此外,當我訪問我的腳本的URL,它給我的錯誤:

{"error":{"message":"(#100) The parameter recipient is required","type":"OAuthException","code":100,"fbtrace_id":"DvrO1UEw5BJ"}} 

請幫我設置這種權利。

+0

「*爲研究目的*」不錯*免責聲明*;) – Marcus

回答

4

只有列爲管理員開發商在您的應用程序角色(https://developers.facebook.com/apps/YOUR_APP_ID/roles/測試儀用戶可以與您的聊天機器人網絡掛接互動。除非您的應用獲得Facebook的批准並公開發布,否則其他用戶無法使用。從Docs

When you're ready to release your app to the public, it must go through an approval process. This will walk you through the submission process and also acceptable and unacceptable usage.

關於第二個問題,臉譜發送一個API調用到您的網絡掛接在JSON數據包括發件人ID在HTTP請求體 & 接收者ID的形式。但是當你手動訪問你的webhook時,你的請求體中沒有這些參數,所以$ sender在你的情況下將是空的。這就是爲什麼Facebook API的CURL請求失敗,並且出現「參數收件人是必需的」錯誤,因爲"recipient":{"id":"'.$sender.'"},將爲空。

如果您想嘗試手動您的網絡掛接,用實際收件人ID,是這樣的:

curl命令:

curl -i -X POST -H 'Content-Type: application/json' -d '{"object":"page","entry":[{"id":43674671559,"time":1460620433256,"messaging":[{"sender":{"id":853241244787916},"recipient":{"id":43674671559},"timestamp":1460620433123,"message":{"mid":"mid.1460620432888:f8e3412003d2d1cd93","seq":12604,"text":"Testing Chat Bot .."}}]}]}' https://YOUR_WEBHOOK_URL_HERE 
6

,如果你忘了設置內容這也可能發生型也是如此。

+0

此修復程序爲我工作,謝謝! – Juto

+0

我有完全相同的問題,這對我有用。 –

相關問題