0

I want to make a facebook post once a day using a ruby script and the Koala gem. I want to be able to set it up once and not have to keep changing the access toekns. After reading some posts and Facebook documentation around Access Tokens I implemented the following:

  • Created a Facebook App
  • Used the Graph API Explorer to get an access token for myself - this only lasts about 2 hours
  • Used the following script to exchange the short term token for a long term token which lasts 2 months
https://graph.facebook.com/oauth/access_token?             
    client_id=APP_ID&
    client_secret=APP_SECRET&
    grant_type=fb_exchange_token&
    fb_exchange_token=EXISTING_ACCESS_TOKEN 
  • Wrote the following rake task to post to my Facebook wall
token = "CAAFlZAPhVBO8..."
@graph = Koala::Facebook::API.new(token)
@graph.put_connections("me", "feed", :message => "My message!")

With all of this setup, my script actually works! It writes to my wall every day based on the scheduler.

My question is: with this setup I will have to manually go and create a new short term access token using the graph api explorer and then use that to get the long term access token every two months. Also, I will have to go in and manually change the token = "blah blah" statement in y script. Can this be avoided at all? I have given the app I created the permission to post to my wall. Is there a way to automatically get the new access tokens within the script using Koala (or other gems/libs)?

2 Answers2

0

Once a user has given your app publish_actions permission, you can also use your app access token to publish wall posts in their name – you will just have to exchange me for the actual user id (because without a user access token the API can’t know who “me” is supposed to be).

And the combination app_id|app_secret (pipe symbol in the middle) can serve as app access token.

CBroe
  • 91,630
  • 14
  • 92
  • 150
0

You can automate and not hard code the short term token. You can use omniauth-facebook gem to automate the omniauth login. Refer Github. Add this to your gemfile.

 gem 'omniauth-facebook', '1.4.0'

In config routes, match the callback

match '/auth/:provider/callback' => '[your controller]#[your function]'

Once you login successfully and land at the callback function, you will the token stored in the response in request.env["omniauth.auth"]["credentials"]["token"]

Use this token and exchange it with a long lived token each time the user logs in. You can safely assume that user logs in at least twice within the 60 days cap for long lived access token.

I am assuming you are using Ruby on Rails because you are using the Koala gem.

Lavixu
  • 1,348
  • 15
  • 20