Update: Facebook Chat API has been deprecating and this hack does not work anymore.

You want to send private messages (invite friends to your application) with Facebook API but did not find any solution on Stack Overflow (1, 2, 3, 4, 5, 6, 7, …) because Facebook Graph API does not allow to send/reply/delete messages, only allows to  view a message!?

Here is the trick.

It’s possible to send messages using  Facebook Chat API, and if the Facebook friend is offline the message will be displayed in the normal message UI on Facebook, otherwise in the chat window. To be able to send chat messages we need to ask for  xmpp_login permissions in the Facebook application.

If we are using Devise with OmniAuth in Ruby on Rails framework, we can ask for xmpp_login permissions in initializers/devise.rb with:

config.omniauth :facebook, ENV['FACEBOOK_APP_ID'], ENV['FACEBOOK_APP_SECRET'], :scope => 'xmpp_login'

Sending a message is easy using the  xmpp4r_facebook gem like this:

sender_chat_id = "-#{sender_uid}@chat.facebook.com"
receiver_chat_id = "-#{receiver_uid}@chat.facebook.com"
message_body = "message body"
message_subject = "message subject"

jabber_message = Jabber::Message.new(receiver_chat_id, message_body)
jabber_message.subject = message_subject

client = Jabber::Client.new(Jabber::JID.new(sender_chat_id))
   ENV.fetch('FACEBOOK_APP_ID'), facebook_auth.token,
   ENV.fetch('FACEBOOK_APP_SECRET')), nil)

But… first we need to register Facebook application to get the APP ID and APP SECRET. Then we need to authenticate the user on Facebook with OmniAuth to get their uid - sender_uid and then we need to import their contacts to get a single receiver_uid  that the sender wants to message. We can use the  koala gem for importing Facebook contacts.

For Twitter and Linkedin we can use twitter and linkedin gems for both import and private messaging.