Tweeting from Python :)

I got this Itch when i was too reluctant to login to twitter to post … It was a pain . I also get pained by manually making Google Calendar entry . Luckily i found that Google has API’s (googlecl) to use it’s services . So i decided to write a Python App which could enable to me to update and check everything from terminal . So decided to start with Twitter , then google services . The problem i faced with Twitter was that it needed OAuth authentication which is serious pain . So i decided to write this tutorial .

First things comes to our mind is .. What is OAuth ??? It is nothing but a Open Authentication protocol which is being widely adopted . To name few Yahoo and Twitter require OAuth autentication to use it’s services . Say you have a twitter account . There is another website X which wants to access your tweets . Then the website X should know your login credentials . In order to over come this OAuth was introduced . With OAuth the website X can be authorized and it can access the twitter account with the access token given to it . The advantage is private information can be accessed by other applications without knowing the password and with only access token .

1) Now to begin with we first need to create Application Key . Visit this website
2) Once registered you will be given with loads of info . Save it carefully . The most important thing in that are Consumer Key and Secret.
3) I am pasting code for Python script which is used to get the Access Token from the consumer key and secret . This a three way handshake process . Don’t worry abt it.. Use the code i’m pasting here . Filling in the details and run the script . You will be given with a URL . Paste the url in the browser and following instructions to get a PIN . Now, paste the PIN in the command prompt . When the script finishes execution you will be given with the access token . Store it safely.

Script for getting Access Token

import urlparse
import oauth2 as oauth

consumer_key='' '  # Fill in your key 
consumer_secret=' ' # Fill in your secret

resp, content = client.request(request_token_url, "GET")

if resp['status'] != '200':
    raise Exception("Invalid response %s." % resp['status'])

request_token = dict(urlparse.parse_qsl(content))

print "Request Token:"
print "    - oauth_token        = %s" % request_token['oauth_token']
print "    - oauth_token_secret = %s" % request_token['oauth_token_secret']

# Step 2: Redirect to the provider. Since this is a CLI script we do not 
# redirect. In a web application you would redirect the user to the URL
# below.

print "Go to the following link in your browser:"
print "%s?oauth_token=%s" % (authorize_url, request_token['oauth_token'])

# After the user has granted access to you, the consumer, the provider will
# redirect you to whatever URL you have told them to redirect to. You can 
# usually define this in the oauth_callback argument as well.
accepted = 'n'
while accepted.lower() == 'n':
    accepted = raw_input('Have you authorized me? (y/n) ')

oauth_verifier = raw_input('What is the PIN? ')

# Step 3: Once the consumer has redirected the user back to the oauth_callback
# URL you can request the access token the user has approved. You use the 
# request token to sign this request. After this is done you throw away the
# request token and use the access token returned. You should store this 
# access token somewhere safe, like a database, for future use.
token = oauth.Token(request_token['oauth_token'],request_token['oauth_token_secret'])

client = oauth.Client(consumer, token)

resp, content = client.request(access_token_url, "POST")
access_token = dict(urlparse.parse_qsl(content))

#print "Access Token:"
print access_token.keys() # Save the output of the script which gives the access token
print access_token.values()
print "You may now access protected resources using the access tokens above." 

4) Once done use the key in ur application . Sample APP

import twitter

api = twitter.Api(consumer_key=' ',
                           consumer_secret=' ',
                            access_token_key=' ',
                            access_token_secret=' ')

friends=api.PostUpdate("First Tweet from PYTHON APP ")

Authenticating with OAuth is the main part . Once it’s done it’s just child play with python .

PS: I have used python-twitter API . Plz dnt download version 0.6 . Only 0.8 version has OAuth support . It’s still under development so it’s best to do a pull from the source .

sudo hg clone python-twitter
cd python-twitter


4 responses to this post.

  1. Posted by brasser on February 19, 2011 at 11:02 am

    he, good post.
    a little bit more examples pleasen, no one will understand this.

    does not work


  2. Posted by Andrej on March 25, 2011 at 6:01 pm

    Thanks a ton for this, worked great. Documentation on this sucks


  3. Posted by dude on May 29, 2011 at 10:49 pm

    it works, nice


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: