Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, oauth2 packages, and have looked through their examples, but still cannot figure out how to get it working. I have no trust in any of the code nor the packages I have been using, and am wondering if anyone has any definitive solutions that they know will work. Thanks.

like image 961
Edward Shen Avatar asked Dec 27 '22 14:12

Edward Shen


2 Answers

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/

like image 50
phwd Avatar answered Dec 29 '22 03:12

phwd


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!')
    
like image 30
Pedro Romano Avatar answered Dec 29 '22 03:12

Pedro Romano