4

How do I update FB Status using Python & GraphAPI? This question has been asked before, but many of the solutions have been deprecated and the requirement of GraphAPI seems to have rendered many solutions irrelevant.

I have fiddled around with the fbpy, Facebook, OAuth, and oauth2 packages, and have looked through their examples, but I still cannot figure out how to get them working. I have no trust in any of the code or the packages I have been using and am wondering if anyone has any definitive solutions that they know will work.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
Edward Shen
  • 41
  • 1
  • 2
  • If you have a similar function to file_get_contents and know to use curl, I can give you a step by step of how to do it. Since I am not a python guy, I cant give you the exact codes. Working with FB is infact easy if you get a start. – Kishor Nov 14 '12 at 09:22

4 Answers4

4

First you need to do is understand login flows. You should understand if you easily want to switch through the different Facebook libraries. Therefore it can have code that is very verbose to code that is very simple based on implementation.

The next thing is that there are different ways to implement handling OAuth and different ways to display and launch your web app in Python. There is no way to authorize without hitting a browser. Otherwise you would have to keep copy pasting the access_token to the code.

Let's say you chose web.py to handle your web app presentation and requests.py to handle the Graph API HTTP calls.

import web, requests

Then setup the URL we want all request to go through

url = (
'/', 'index'
)

Now get your application id, secret and post-login URL you would like to use

app_id = "YOUR_APP_ID"
app_secret = "APP_SECRET"
post_login_url = "http://0.0.0.0:8080/"

This code will have one class index to handle the logic. In this class we want to deal with the authorization code Facebook will return after logging in

Login Flow

user_data = web.input(code=None)
code = user_data.code

From here setup a conditional to check the code

if not code:
    # we are not authorized
    # send to oauth dialog
else:
    # authorized, get access_token

Within the "not authorized" branch, send the user to the dialog

dialog_url = ( "http://www.facebook.com/dialog/oauth?" +
                           "client_id=" + app_id +
                           "&redirect_uri=" + post_login_url +
                           "&scope=publish_stream" )

return "<script>top.location.href='" + dialog_url + "'</script>"

Else we can extract the access_token using the code received

token_url = ( "https://graph.facebook.com/oauth/access_token?" +
                          "client_id=" + app_id +
                          "&redirect_uri=" + post_login_url +
                          "&client_secret=" + app_secret +
                          "&code=" + code )
            response = requests.get(token_url).content

            params = {}
            result = response.split("&", 1)
            for p in result:
                (k,v) = p.split("=")
                params[k] = v

            access_token = params['access_token']

From here you can choose how you want to deal with the call to update the status, for example a form,

graph_url = ( "https://graph.facebook.com/me/feed?" +
"access_token=" + access_token )

return ( '<html><body>' + '\n' +
         '<form enctype="multipart/form-data" action="' +
         graph_url + ' "method="POST">' + '\n' +
         'Say something: ' + '\n' +
         '<input name="message" type="text" value=""><br/><br/>' + '\n' +
         '<input type="submit" value="Send"/><br/>' + '\n' +
         '</form>' + '\n' +
         '</body></html>' )

Or using face.py

from facepy import GraphAPI
graph = GraphAPI(access_token)
try:
    graph.post(
            path = 'me/feed',
            message = 'Your message here'
    )
except GraphAPI.OAuthError, e:
    print e.message

So in the end you can get a slimmed down version like

import web
from facepy import GraphAPI
from urlparse import parse_qs

url = ('/', 'index')

app_id = "YOUR_APP_ID"
app_secret = "APP_SECRET"
post_login_url = "http://0.0.0.0:8080/"

user_data = web.input(code=None)

if not user_data.code:
    dialog_url = ( "http://www.facebook.com/dialog/oauth?" +
                               "client_id=" + app_id +
                               "&redirect_uri=" + post_login_url +
                               "&scope=publish_stream" )

    return "<script>top.location.href='" + dialog_url + "'</script>"
else:
    graph = GraphAPI()
    response = graph.get(
        path='oauth/access_token',
        client_id=app_id,
        client_secret=app_secret,
        redirect_uri=post_login_url,
        code=code
    )
    data = parse_qs(response)
    graph = GraphAPI(data['access_token'][0])
    graph.post(path = 'me/feed', message = 'Your message here')

For more info see

* Facebook API - User Feed: http://developers.facebook.com/docs/reference/api/user/#feed
* Publish a Facebook Photo in Python – The Basic Sauce: http://philippeharewood.com/facebook/publish-a-facebook-photo-in-python-the-basic-sauce/
* Facebook and Python – The Basic Sauce: http://philippeharewood.com/facebook/facebook-and-python-the-basic-sauce/

phwd
  • 19,975
  • 5
  • 50
  • 78
  • Thank you for your detailed and thought out response, phwd. Both you and Pedro above seem to be using facepy, so I will as well. I was trying to whip up something quick for my friend and did not expect to have to thumb through docs as much as I did to make this happen (automating status messages on facebook after polling an inbox for specific e-mails). This was much more help than I expected or deserved; thanks again! – Edward Shen Nov 16 '12 at 21:47
3

One possible (tested!) solution using facepy:

  1. Create a new application or use an existing one previously created.
  2. Generate a user access token using the Graph API explorer with the status_update extended permission for the application.
  3. Use the user access token created in the previous step with facepy:

    from facepy import GraphAPI
    
    ACCESS_TOKEN = 'access-token-copied-from-graph-api-explorer-on-web-browser'
    
    graph = GraphAPI(ACCESS_TOKEN)
    graph.post('me/feed', message='Hello World!')
    
Pedro Romano
  • 10,973
  • 4
  • 46
  • 50
  • Thanks for the snippet. I actually tried this exact snippet. The part I am having a problem with is getting OAuth to work correctly. It seems like there is an OAuth and OAuth2 package, with OAuth2 being the newer package. Apart from already having issues that the package has outdated examples (they import OAuth from Oauth, when the package's name is OAuth2...), the examples provided seem overly complex for such a simple task (165 lines... although a chunk of it is admittedly comments). Without being able to put a valid oauth_access_token, I am left wondering what I'm doing wrong... – Edward Shen Nov 14 '12 at 19:06
  • Refactored answer (tested correctly working) using 'facepy' and including instruction on how to generate the user access token. – Pedro Romano Nov 15 '12 at 01:54
2

You can try this blog too. It's using fbconsole app.

The code from the blog:

from urllib import urlretrieve
import imp
urlretrieve('https://raw.github.com/gist/1194123/fbconsole.py', '.fbconsole.py')
fb = imp.load_source('fb', '.fbconsole.py')
fb.AUTH_SCOPE = ['publish_stream']
fb.authenticate()
status = fb.graph_post("/me/feed", {"message":"Your message here"})
gkiko
  • 2,283
  • 3
  • 30
  • 50
1

This is how I got it to work. You absolutely don't need to create any app for this. I'll describe how to post status updates to your profile and to a facebook page of yours.

First, to post a status update to your profile:

Go to https://developers.facebook.com/tools/explorer.
You'll see a textbox with Access Token written before it. Click on the button 'Get Access Token' beside this textbox. It will open a pop up asking you for various permissions for the access token. Basically these permissions define what all you can do through the Graph API using this token. Check the tick boxes beside all the permissions you need one of which will be updating your status.
Now go ahead and install the facepy module. Best way would be to use pip install.
After this pase the following code snippet in any .py file:

from facepy import GraphAPI

access_token = 'YOUR_GENERATED_ACCESS_TOKEN'
apiConnection = GraphAPI(access_token)
apiConnection.post(path='me/feed',
                            message='YOUR_DESIRED_STATUS_UPDATE_HERE')

Now execute this .py file the standard python way and check your facebook. You should see YOUR_DESIRED_STATUS_UPDATE_HERE posted to your facebook profile.

Next, to do the same thing with a facebook page of yours:

The procedure is almost exactly the same except for generating your access token.
Now you can't use the same access token to post to your facebook page. You need to generate a new one, which might be a little tricky for someone new to the Graph API. Here's what you need to do:

Go to the same developers.facebook.com/tools/explorer page.

Find a dropdown showing 'Graph API Explorer' and click on it. From the dropdown, select your page you want to post updates from. Generate a new access token for this page. The process is described here: . Do not forget to check the manage_pages permission in the extended permissions tab.

Now use this token in the same code as you used earlier and run it.

Go to your facebook page. You should YOUR_DESIRED_STATUS_UPDATE posted to your page.

Hope this helps!

Chandan
  • 11
  • 2