Rails的新手。
开始使用Facebook Messenger时,节点中有一个简单的脚本,可用于将消息从您的应用程序发送到Messenger。有人可以帮助我们如何在Ruby on Rails中实现它。
我想在我的控制器中创建一个可以发送消息的方法。以下是来自Facebook的代码,我不知道如何在Rails中实现相同的功能。
var token = "<page_access_token>";
function sendTextMessage(sender, text) {
messageData = {
text:text
}
request({
url: 'https://graph.facebook.com/v2.6/me/messages',
qs: {access_token:token},
method: 'POST',
json: {
recipient: {id:sender},
message: messageData,
}
}, function(error, response, body) {
if (error) {
console.log('Error sending message: ', error);
} else if (response.body.error) {
console.log('Error: ', response.body.error);
}
});
}
用
替换上面的评论sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
这是我的控制器接收消息。
def apply_message
@message = params["entry"][0]["messaging"][0]["message"]["text"]
@sender_id = params["entry"][0]["messaging"][0]["sender"]["id"]
if User.where(:fb_id => @sender_id.to_s ).present? #if sender exists
# Send him a message saying "Hello World" Just like below
else
uri = URI.parse("https://graph.facebook.com/v2.6/me/messages?access_token=tocken_goes_here")
http = Net::HTTP.new(uri.host, uri.port)
json_data={
"recipient":{
"id":"@sender_id"
},
"message":{
"text":"Do you have an account with us?"
}
}
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
req = Net::HTTP::Post.new(uri.request_uri)
req.set_form_data(json_data)
response = http.request(req)
end
end
答案 0 :(得分:2)
创建FB模型:
class FacebookBot
def send_message(data)
url = URI.parse("https://graph.facebook.com/v2.6/me/messages?access_token=Token_here")
http = Net::HTTP.new(url.host, 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE #only for development.
begin
request = Net::HTTP::Post.new(url.request_uri)
request["Content-Type"] = "application/json"
request.body = data.to_json
response = http.request(request)
body = JSON(response.body)
return { ret: body["error"].nil?, body: body }
rescue => e
raise e
end
end
def send_text_message(sender, text)
data = {
recipient: { id: sender },
message: { text: text }
}
send_message(data)
end
def send_generic_message(sender, mes)
data = {
recipient: { id: sender },
message: mes
}
send_message(data)
end
end
现在我可以发送消息:
res = FacebookBot.new.send_text_message(sender, "Hi thanks for messaging")
享受。 :)