|
Implementing a Python Twitter Client with OAuth |
|
|
|
|
Written by Josh B
|
|
Friday, 03 September 2010 07:50 |
|
Tags: programming | python | twitter It looks like Twitter has finally switched from Basic Authentication to OAuth authentication. I may be a bit late to the Twitter party, but I've found that Twitter is suprisingly useful. It's not just for over-sexed celebs or over-paid BBC actors tedious thoughts. You can do useful things with it as well. The only problem is that OAuth can be a bit tricky.
Read more to find a quick and dirty Twitter Python client that will allow you to post to Twitter...
As the below code indicates, you will need to download and install Tweepy. You will also need to register you App with Twitter. It is from there you will obtain your Consumer Token and Consumer Secret keys
#!/usr/bin/env python
# mostly cobbled together from : http://code.google.com/p/tweepy/wiki/AuthTutorial
# from http://code.google.com/p/tweepy/ import tweepy import sys
filePath = '/tmp/twitter_tokens'
# register the application at http://twitter.com/oauth_clients consumer_token = '' consumer_secret = ''
authKey = '' authSecret = ''
# try and read the authKey / authSecret from a file... try: file_object = open(filePath) # read file details... lines = file_object.readlines( ) file_object.close () # parse... authKey = lines[0].rstrip('\n') authSecret = lines[1].rstrip('\n') print "access token : key : %s, secret : %s" % (authKey, authSecret) except IOError: print 'Had problems reading file...'
# set up auth first... auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
if(authKey == ''): # go and get authKey...! redirect_url = '' try: redirect_url = auth.get_authorization_url() except tweepy.TweepError: print 'Error! Failed to get request token. Aborting...!' sys.exit(1) print "please go to this url : %s" % redirect_url verifier = raw_input('Enter the PIN you are given at the above url : ') print "you entered PIN : %s" % verifier try: auth.get_access_token(verifier) except tweepy.TweepError: print 'Error! Failed to get access token. Aborting...!' sys.exit(1) print "access token : key : %s, secret : %s" % (auth.access_token.key, auth.access_token.secret) # store these items somewhere... toStore = [auth.access_token.key + "\n", auth.access_token.secret + "\n"] file_object = open(filePath, 'w') file_object.writelines (toStore) file_object.close( ) api = tweepy.API(auth) else: auth.set_access_token(authKey, authSecret)
# do something... api = tweepy.API(auth) api.update_status('it is sunny outside again, maybe rain later...?')
sys.exit(0)
|
|
Last Updated on Monday, 11 October 2010 18:41 |