Twitter from the command line in Python using OAuth

Issuing Twitter updates from the command line used to be a simple affair: just use curl or its equivalent. Very soon, that will no longer be the case because basic authentication is scheduled to be removed from the Twitter API in June 2010. Instead, all Twitter clients will need to use more secure authentication based on OAuth.

Configuring an app to use OAuth properly requires a bit of legwork. My goal with this post is to save people some time by showing the complete step-by-step process of building a Python script that can tweet from the command line using OAuth. I’ve intentionally skipped over the details of how OAuth works and what all the different authentication tokens mean. This post is just about getting things done.

Step 1: Download Tweepy

Tweepy is an awesome Twitter library for Python. Much of this post is based on information I found in the Tweepy documentation.

Download Tweepy from GitHub and install it on your system.

Step 2: Register a new client app with Twitter

Navigate to http://twitter.com/oauth_clients and click on Register a new application. You might have to log in to the Twitter site first, if you’re not already.

Fill in the registration fields as follows:

Twitter app details

Note: whatever you specify for Application Name will be the “via” name your followers see in the details of tweets issued from your command line app:

Twitter app via

When finished on the registration page, click Save.

Next page:

Twitter app details

Keep this browser window open. We’ll need the information in the next step.

Step 3: Connect the app to your Twitter account

Next, the app needs to be authorized to connect to your account so it can send tweets under your name.

We’ll create a one-off utility script to do this. Save the following Python code as a script on your local system.

#!/usr/bin/env python
 
import tweepy
 
CONSUMER_KEY = 'paste your Consumer Key here'
CONSUMER_SECRET = 'paste your Consumer Secret here'
 
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth_url = auth.get_authorization_url()
print 'Please authorize: ' + auth_url
verifier = raw_input('PIN: ').strip()
auth.get_access_token(verifier)
print "ACCESS_KEY = '%s'" % auth.access_token.key
print "ACCESS_SECRET = '%s'" % auth.access_token.secret

Paste the Consumer Key and Consumer Secret from the end of step 2 into this script, replacing the CONSUMER_KEY and CONSUMER_SECRET constants. Then save and run on your system.

You should see a prompt like this:

Please authorize: <URL>
PIN:

Open that URL in your browser. You should see the standard OAuth Twitter connection screen:

Twitter connect to account

Click Allow.

Twitter will then provide you with a PIN code that authenticates the connection between the client app and your Twitter account.

Twitter granted access to account

Enter this PIN into the prompt from the Python registration script:

PIN: 2781961

The script will then print out another key/secret pair:

ACCESS_KEY = '124242RCyi3g0cZ4r5BWL047rsh0S0yv5VxAGwTKCOsHAb'
ACCESS_SECRET = 'kaTXiC489qo8y6haTBSlwOqR1syG83tzPG2StdQ'

But the values will be different each time.

Keep this information on your screen because we’ll need it in the next step.

Step 4: Create the command line script

Save the following Python code as a script on your local system.

#!/usr/bin/env python
 
import sys
import tweepy
 
CONSUMER_KEY = 'paste your Consumer Key here'
CONSUMER_SECRET = 'paste your Consumer Secret here'
ACCESS_KEY = 'paste your Access Key here'
ACCESS_SECRET = 'paste your Access Secret here'
 
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)
api = tweepy.API(auth)
api.update_status(sys.argv[1])

Paste the Access Key and Access Secret from the end of step 3 into this script, replacing the ACCESS_KEY and ACCESS_SECRET constants.

You’ll also need to paste in the CONSUMER_KEY and CONSUMER_VALUES from step 2, just as we did in the registration script.

Save the final script as mycommandlineapp or whatever you want to name it.

Step 5: Send a test tweet from the command line

Finally, we’re all set up. Our command line app is registered as a Twitter client and the app is connected to our Twitter user account.

Try sending a test tweet from the command line. Don’t forget to enclose the text in quotes.

$ ./mycommandlineapp 'Hello from the command line'

If this is successful, there won’t be any output on the command line, but there will be a new tweet in your timeline.

Twitter command line tweet

For more posts like this, follow me on Twitter -or- subscribe to my blog feed.

This entry was posted in Howto, Python, Twitter. Bookmark the permalink.
  • simply amazing and simple!
  • Ashwinmorey
    Hi,

    Great tutorial. But I am working behind a proxy, how can I use tweepy behing proxy.

    thanks
  • Colin
    Many thanks for this blog. My old curl script stopped working in the last few days. I was up and running again within 15 minutes.

    Colin
  • Very very good...
  • Hello, I followed all the steps above and still can't manage to get it running. Here's the error message "C:\Documents and Settings\evans\Desktop>python myTweepy.py
    Traceback (most recent call last):
    File "myTweepy.py", line 3, in <module>
    import tweepy
    File "tweepy.py", line 8, in <module>
    AttributeError: 'module' object has no attribute 'OAuthHandler'" when running the first script to authenticate with my credentials.

    Any tips on how to get it working would be appreciated.</module></module>
  • BigAluminum
    This is a great post - helped me bring my servers into the thrall of our new OAuth overlords.
    One thing you may want to add for mac users - you will have to install the django framework if you haven't already - tweepy will complain about not being able to load json libraries otherwise.
  • I run everything on a Mac and I don't have Django installed. I think you just need a recent version of Python, maybe 2.5 or above?
  • verifier = raw_input('PIN: ').strip()
    auth.get_access_token(verifier)

    Hi , In case we wont to run it from web ....what step will be there in place of "verifier = raw_input('PIN: ').strip()"
  • omab
    You made an excellent post here, sadly I found it later after hours of scratching my head against authentication. Thanks a lot.
  • Very good article, simple and well-explained (and correct). Many thanks for helping in my migration.
  • Thank you for detailed post. I successfully posted a tweet with my own python code! Alah.. I'm even a total python newbie! Thanks again for your kind post.
  • BillSeitz
    You can also make use of oacurl http://code.google.com/p/oacurl/
  • rossp
    Great article, thanks! I've just updated www.djangosites.org to use this rather than the API for pushing new listings to the @djangosites Twitter account.

    Much appreciated :)
  • This can be done with curl, with no OAuth installation necessary. Simply add the following to your .bashrc or whatever shell config file you have, replacing username:password with your username and password:

    function tweet {
    curl --basic --user username:password --data status="$1" http://twitter.com/statuses/update.xml
    }


    After restarting your shell, you can then tweet by doing:

    tweet "This is a new status update."

    It'll say "via API", not "via mycustomappname", but it otherwise works.
  • That method will cease to work after June 2010 (i.e. this month) when Twitter removes basic authentication support from the API.
  • Ah, so it will--you are correct. I'd forgotten about that. Thanks for the simple writeup on how to replace my method. :)
  • A cool one. :)

    ( http://masnun.com )
  • brixtonasias
    Nice and very detailed post. Is tweepy somehow bind to the command line or is it usable for all kind of apps?
  • Thanks. Tweepy's not bound to the command line, it can be used in any kind of Python app.
blog comments powered by Disqus