Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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 dialogelse:# 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' +
         '<formenctype="multipart/form-data"action="' +
         graph_url + ' "method="POST">' + '\n' +
         'Say something: ' + '\n' +
         '<inputname="message"type="text"value=""><br/><br/>' + '\n' +
         '<inputtype="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/

Solution 2:

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 importGraphAPIACCESS_TOKEN='access-token-copied-from-graph-api-explorer-on-web-browser'
    
    graph = GraphAPI(ACCESS_TOKEN)
    graph.post('me/feed', message='Hello World!')
    

Solution 3:

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"})

Solution 4:

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 importGraphAPIaccess_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!

Post a Comment for "How Do I Update Fb Status Using Python & Graphapi?"