New to Rails.
On Getting started for Facebook Messenger there is a simple script in node that can be used to send message from your app to Messenger. Can someone help on how can we implement it in Ruby on Rails.
I want to create a method in my controller that can send the message. Below is the code from Facebook, I am not sure how to implement the same in 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);
}
});
}
Replace the comment above with
sendTextMessage(sender, "Text received, echo: "+ text.substring(0, 200));
Here is my controller to receive the message.
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