Update twitter status using Python script

Recently I have written a Python script to update status message in twitter using their api. Let me share the code here:

import urllib
import urllib2
import base64
import httplib
import socket

## authenticate module is used for http basic authentication. found in 'urllib2 missing manual'
def authenticate(username, password):
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
top_level_url = 'http://twitter.com/'
password_mgr.add_password(None, top_level_url, username, password)
handler = urllib2.HTTPBasicAuthHandler(password_mgr)
opener = urllib2.build_opener(handler)

return opener

## updates twitter status given the status, user name (id or email) and password
def update_status(status, user, password):
data = {'status' : status}
data = urllib.urlencode(data)

url = 'http://twitter.com/statuses/update.xml'

opener = authenticate(user, password)
result = ''
try:
handle = opener.open(url, data = data)
result = handle.read()
handle.close()
return
except Exception, detail:
print "Err ", detail

#program starts from here
main()


Hope you will find it useful. Let me know if you have any suggestion to make my code better. It will be appreciated.

Comments

SMG said…
Comments using /* */ in Python? Why don't you just make these into docstrings?
Tamim Shahriar said…
Thanks. Now days I code in so many languages that sometimes things get mixed up. :)
Unknown said…
I getting the below error while executing
"NameError: name 'main' is not defined:
Emmanuel Dumont said…
well... indeed main() is not defined.
I'm replacing the main() call with a call like:
update_status('tweet message', 'tweeter_login', 'tweeter_passwd')
Where to compile this??
When compiling this in python shell it gives an error like this
Err HTTP Error 407: Proxy Authentication Required

how to get rid of this error??

Popular posts from this blog

Strip HTML tags using Python

lambda magic to find prime numbers

Convert text to ASCII and ASCII to text - Python code