views:

218

answers:

2
def send_to_twitter():
    msg = "I am a message that will be sent to Twitter"
    password_manager = urllib.request.HTTPPasswordMgr()
    password_manager.add_password("Twitter API",
    "http://twitter.com/statuses", "username", "password")
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
    page_opener = urllib.request.build_opener(http_handler)
    urllib.request.install_opener(page_opener)
    params = urllib.parse.urlencode( {'status': msg} )
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json", params)
    resp.read()

When I execute this code through IDLE, I get an error along the lines of;

urllib.error.HTTPError: HTTP Error 401: Unauthorized

What maybe wrong with my code?

+3  A: 

Twitter no longer supports HTTP Authentication. You should use oauth in stead.

tweepy seems to be a good library to start with if you want to do twitter from python: it's current, supports oath and looks very complete.

Ivo van der Wijk
+1 For Tweepy nice library built my own client around it :)
Ivo Wetzel
+1  A: 

Your are using the old HTTP Auth method. Upgrade using OAuth.

Go to the following link to setup your Twitter Application: twitter.com/apps/new (Tip: You can set your URL to 127.0.0.1 for testing purposes AND Remember to set application to Browser and specify Callback URL)

And you can continue from there.

Marc Uberstein