Emu
Emu

Reputation: 5905

fb_graph post on a facebook group as a group member from rails app

Currently, I've a rails app. If user is authenticated with facebook then he can post something on my application. After the post was saved, my rails app will post the user's post to my facebook group. Is it possible?

I'm using fb_graph gem. And after the user's post I've done a after_create callback to post on facebook. Here is the callback code:

def post_story_to_facebook
    if self.user.authentications.pluck(:provider).include?('facebook')
      page = FbGraph::Group.new('ct.dhk.group') # group name 
      # where should I declare the user who is posting? 
      page.feed!(
          :message => 'Updating via FbGraph',
          :link => 'https://domain.tld',
          :name => 'PageName',
          :description => 'This is a test post to be deleted'
      )
    end
  end

The above method is not working and I don't know how can I post behalf of the user?

Upvotes: 1

Views: 213

Answers (1)

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

We had a similar working tested code. You need to store the facebook_user_access_token in your User model (if you don't have one, add a new attribute, and update that every time the user gets authenticated through OAuth, or only if token is renewed). See the following.

post = Post.find(1) # your post
facebook_page_id = '1234567890' # your Facebook group id
facebook_user_access_token = current_user.facebook_user_access_token # the current user's Facebook user access token

page = FbGraph::Page.new(facebook_page_id)
facebook_page_access_token = page.get_access_token(access_token: facebook_user_access_token)

me = FbGraph::User.me(facebook_page_access_token)

me.feed!(
  message: post.title,
  link: post_url(post),
  description: post.content,
  picture: post.main_image.url
)

UPDATE:

Haven't tested, but looking at this and this

suggests that the following could work:

group = FbGraph::Group.new(GROUP_ID)
group.feed!({
  access_token: USER_ACCESS_TOKEN_WITH_PROPER_PERMISSIONS,
  message: post.content
})

Unfortunately, I do not yet have the time to test things out. Can you try if this will work?

Upvotes: 2

Related Questions