0

我試圖從我的模型(user.rb)向Facebook發出直接POST請求,向Messenger中的此用戶發送簡單消息。但是,我得到這個錯誤:使用Ruby Net發佈到Facebook Messenger :: HTTP錯誤100

{"error":{"message":"(#100) param recipient must be non-empty.","type":"OAuthException","code":100,"fbtrace_id":"F07BNxzgciW"}} 

這裏是我的方法:

def send_message(msg) 
    url = "https://graph.facebook.com/v2.6/me/messages?access_token="+ENV['PAGE_ACCESS_TOKEN'] 
    data = { 
     'recipient': { 
     'id': self.facebook_id 
     }, 
     'message': { 
     'text': msg 
     } 
    } 
    #data = JSON.pretty_generate(data) 
    puts data 
    uri = URI(url) 
    res = Net::HTTP.post_form(uri, data) 
    puts res.body 
end 

好像數據是不正確的格式,所以用戶ID不beeing認可。

取消註釋#DATA線我得到這個錯誤,因爲數據是一個字符串,而不是一個哈希:

NoMethodError: undefined method `map' for #<String:0x000000034bd248> 

這是來自Facebook的文檔,我試圖重現請求示例:

curl -X POST -H "Content-Type: application/json" -d '{ 
    "recipient": { 
    "id": "USER_ID" 
    }, 
    "message": { 
    "text": "hello, world!" 
    } 
}' "https://graph.facebook.com/v2.6/me/messages?access_token=PAGE_ACCESS_TOKEN" 

回答

1

這種嘗試:

的Ruby/Rails:

uri = URI("https://graph.facebook.com/v2.6/me/messages?access_token="+ENV['PAGE_ACCESS_TOKEN']) 
req = Net::HTTP::Post.new(uri) 
req["Accept"] = "application/json" 
req["Content-Type"] = "application/json" 
req.body = { 
    'recipient': { 
    'id': self.facebook_id 
    }, 
    'message': { 
    'text': msg 
    } 
}.to_json 

res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| 
    http.request(req) 
end 
puts res.body 

這可以重構爲一個函數,然後在需要時調用。這個功能有點比所需先前請求

def http_post(url, payload='', headers={}, auth=false) #basic auth is passed as an array of ['user', 'password'] 
    uri = URI(url) 
    req = Net::HTTP::Post.new(uri) 
    headers.each do |k,v| 
     req[k.to_s] = v 
    end 
    req.body = payload.is_a?(Hash) ? payload.to_json : payload.to_s 
    req.basic_auth(*auth) if auth 
    res = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http| 
     log_this(req.inspect) 
     http.request(req) 
    end 
    return res 
    end 

# you can now use like: 
url = "https://graph.facebook.com/v2.6/me/messages?access_token="+ENV['PAGE_ACCESS_TOKEN'] 
headers = { 
    "Accept": "application/json" 
    "Content-Type": "application/json" 
} 
payload = { 
    'recipient': { 
    'id': self.facebook_id 
    }, 
    'message': { 
    'text': msg 
    } 
} 
response = http_post(url, payload, options) 

的捲曲度就可以做同樣的要求更先進:

curl -X POST -H "Content-Type: application/json" -H "Accept: application/json" -d "{ \"recipient\": { \"id\": \"substitute_with_user_id\" }, \"message\": { \"text\": \"Your message goes here\" } }" https://graph.facebook.com/v2.6/me/messages?access_token=substitute_with_your_access_token 

通常你不需要逃避(「\」 )雙引號,相反,您可以使用單引號(')作爲json主體的分隔符,因爲curl lib會在大多數使用它的操作系統中爲您執行它,但是在您需要的窗口中,並且實際上它會最終在引擎蓋下逃脫,這是我猜想的正確形式。

+0

太棒了!完美工作,你救了我的一天。謝謝! – mknarciso

+0

Micael,你可以在PHP中使用curl請求還是使用Facebook對象來轉換此代碼? –

+1

@YasirIjaz剛剛做到了 –