Wednesday, 16 September 2015

Python Facebook Data tutorial - Post to Facebook page in 4 steps

In this tutorial, you will learn how to post to a Facebook page's wall (acting as the page) using Python. It includes step by step instructions to create a new page, register an app with Facebook and some python code. 

I have a similar Python tutorial for Twitter.

Step 1

  • First, create a new Facebook page. Select appropriate page type, fill in description and other relevant fields.
  • On the new page, go to About tab, and note the Facebook Page ID.
  • We will post to this page's wall, acting as the page.

Step 2

  • Now create a Facebook App which will be used to access Facebook's Graph API.
  • Go to Facebook Apps dashboard -> Click Add a New App -> Choose platform WWW -> Choose a new name for your app -> Click Create New Facebook App ID -> Create a New App ID -> Choose Category (I chose "Entertainment") -> Click Create App ID again.
  • Go back to Apps dashboard -> Select the new app -> Settings -> Basic -> Enter Contact Email. This is required to take your app out of the sandbox.
  • Go to Status & Review -> Do you want to make this app and all its live features available to the general public? -> Toggle the button to Yes -> Make App Public? ->Yes. This will enable others to see posts by your app in their timelines - otherwise, only you will see the wall posts by the app. This took me some very frustating hours to figure out! These two stackoverflow posts were very helpful.
  • Now - you should see a green dot next to app's name, and the text This app is public and available to all users.
  • Make a note of the App ID and App Secret (Click Show next to it; you will be asked to re-enter your Facebook password).

Step 3

  • In this step we will obtain obtain Facebook OAuth token. A long-lived token at that! Read about Facebook access tokens. Some more helpful articles about Facebook token process.
  • Go to Graph API Explorer -> In the Application drop down -> Select the app created in Step 2 -> Click Get Access Token -> In Permissions popup go to Extended Permissionstab -> Select manage_pages, and publish_actions These permissions will allow your app to publish posts acting as the page -> Click Get Access Token -> You will see a message saying "{App} would like to post publicly to Facebook for you. Who do you want to share these posts with?" -> I chose Public for maximum visibility - as I wanted to post to a public page.
  • You might be asked to Turn On Platform if you disabled it previously, enable it! If you mess this step up, just go to your App Settings - remove the app and try again.
  • Make a note of the short-lived token shown in Graph API Explorer.
  • Facebook has deprecated offline access, the next best thing is long-lived token which expires in 60 days. We will convert the short-lived access token noted above to a long-lived token. This helped me figure it out.

For that, fill in the values in the URL below and open it in a browser:
  • You should see access_token={...}&expires={...}. This new access_token is the long-lived token we will use in our Python script.
  • long-lived token will also expire eventually, be prepared to perform this Step 3 again before that happens! If you do not want to deal with that just save the page_access_tokencomputed in Step 4 - and you can use it forever, as according to Facebook's documentationa page access token obtained from long-lived user token will not have any expiry time.

Step 4

  • We will use Facebook Python SDK to access Facebook's Graph API. You can install it using pip: pip install facebook-sdk (again, use of virtualenv is highly recommended).

Finally, this python script will post to Facebook page's wall:
import facebook

def main():
  # Fill in the values noted in previous steps here
  cfg = {
    "page_id"      : "VALUE",  # Step 1
    "access_token" : "VALUE"   # Step 3

  api = get_api(cfg)
  msg = "Hello, Kalyan! have a nice day"
  status = api.put_wall_post(msg)

def get_api(cfg):
  graph = facebook.GraphAPI(cfg['access_token'])
  # Get page token to post as the page. You can skip 
  # the following if you want to post as yourself. 
  resp = graph.get_object('me/accounts')
  page_access_token = None
  for page in resp['data']:
    if page['id'] == cfg['page_id']:
      page_access_token = page['access_token']
  graph = facebook.GraphAPI(page_access_token)
  return graph
  # You can also skip the above if you get a page token:
  # and make that long-lived token as in Step 3

if __name__ == "__main__":

Next steps
Allow multiple people to log-in to the app? I am not sure how to exactly do it, but here are a few pointers:
  • First step would be to add a login dialogue - instead of Step 3. This will be a popup from which will show which permissions your app is requesting.
  • The 'login' API call will return a short-lived token. This is the tricky part, user is viewing a page right now, how will your app get the auth token? Might be easier to do using their Javascript login flow. Other option is to give a redirect URL - which will be called when the popup is closed (and token added as a parameter).
  • Once you get the short-lived token, you can follow the tutorial - convert to long-livedand store that in a database - sqlite3 works very well for small prototypes.
  • Read these two links to understand more: - Manual login flow, Web login flow (javascript).
  • If required, renew the long-lived token for your users.
Post to your own wall or wall of a friend?
  • You can post to your own wall, read the first example here.
  • Posting to friend's wall has been deprecated, most probably due to SPAM :) Read here.

Python Twitter Data Tutorial - 5 Easy steps to tweet a message from python script

In this tutorial, you will learn how to send tweets using Python. I will try to keep it as simple as possible. 

UPDATE: I wrote a similar Python tutorial for Facebook.

Step 1

  • You must add your mobile phone to your Twitter profile before creating an application.
  • Go to: Settings -> Add Phone -> Add number -> Confirm -> Save.
  • Do not forget to turn off all text notifications.

Step 2

  • Set up a new app
  • Go to: Twitter Apps -> Create New App -> Leave Callback URL empty -> Create your Twitter application.
  • You should see "Your application has been created. Please take a moment to review and adjust your application's settings".

Step 3

  • By default, app's access level is read-only. To send out tweets, it requires writepermission.
  • Go to: Permissions tab -> What type of access does your application need? -> ChooseRead and Write -> Update settings.
  • You should see "The permission settings have been successfully updated. It may take a moment for the changes to reflect."

Step 4

  • Time to get the keys and access tokens for OAuth.
  • Go to: Keys and Access Tokens tab . You'll see this under "Your Access Token" : You haven't authorized this application for your own account yet. By creating your access token here, you will have everything you need to make API calls right away. The access token generated will be assigned your application's current permission level.
  • Click Create my access token
  • You should see "Your application access token has been successfully generated. It may take a moment for changes you've made to reflect. Refresh if your changes are not yet indicated. This access token can be used to make API requests on your own account's behalf. Do not share your access token secret with anyone."
  • Verify that you see access token/secret - and the permission is set to "read and write".
  • From this page, note down the Access TokenAccess Token SecretConsumer Key (API Key)Consumer Secret (API Secret). Consumer Key/Secret help twitter identify the app and Access Token/Secret help twitter identify the user (that is you).

Step 5

  • We will use tweepy to access Twitter's API. You can install it using pip: pip install tweepy(try to setup a virtualenv for this - they are very useful).

Finally, this simple python script sends out a tweet:
import tweepy

def get_api(cfg):
  auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])
  auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])
  return tweepy.API(auth)

def main():
  # Fill in the values noted in previous step here
  cfg = { 
    "consumer_key"        : "VALUE",
    "consumer_secret"     : "VALUE",
    "access_token"        : "VALUE",
    "access_token_secret" : "VALUE" 

  api = get_api(cfg)
  tweet = "Hello, Kalyan! .. Have a nice day"
  status = api.update_status(status=tweet) 
  # Yes, tweet is called 'status' rather confusing

if __name__ == "__main__":

Related Posts Plugin for WordPress, Blogger...