Step 1) Create a Twitter Application
The new REST API v1.1 requires authorisation before we can make requests to twitter such as searching a timeline. To do this we must tell twitter about our application by creating an app in the developer centre. To do this:
- Browse to https://apps.twitter.com;
- Login to the account you are going to use;
- Give the app a name;
- Give it a short description;
- Give it a url – I used my twitter profile page!
- You don’t need to give it a callback as we are not using them.
- You also need to ask it to create some access tokens. Go to Key and Access Tokens > Click on generate Consumer Key and Secret.
- I would also go to Permissions > Access > Read Only unless you have a need to write to your Twitter account.
From this step you should be able to leave with four long randomised text strings a bit longer than the examples below:
- CONSUMER_KEY = “m7l4….mn3g”
- CONSUMER_SECRET = “ofzY3…..sCfYK”
- ACCESS_TOKEN = “1xxxxxxxx0-vx94….oJBN”
- ACCESS_SECRET = “Bdh9…..Uds4″
Step 2) Install the Twitter Package for Python.
Although the API has got more complicated there is now an official python twitter package which seems to be compatible with 2.7 to 3. The easiest way to install it is using pip (you can read about installing it on Macs and Windoze on the Pip Installation Page.
pip install twitter
Alternatively, you can install it manually with something like:
1. Go to https://pypi.python.org/pypi/twitter and download the latest version
2. Untar it with tar -xvf twitter-x.x.x.tar.gz
3. Move into the folder with cd twitter-x.x.x
4. Finally install it using python setup.py install.
5. You can then remove the install files carefully.
If you encounter an error trying this relating to setuptools it can be easily solved by installing them: sudo apt-get install python-setuptools or similar if you are on windows.
Step 3 Write the Program
We are now ready to write our twitter program. Create a new Python program file.
Import the time, twitter and simplejson packages adding any comments you need.
Create four globals for the Keys and Secrets from the twitter app you set up in step 1:
Create a twitter object that can be used to interact with the twitter api
Now write your program.
You will notice at the bottom that I’m sleeping for a few seconds. Twitter seems to have added some limits on the number of calls in any one window – 15 in 15mins or for us 1 a minute. Ignore this and your program could error as it gets blocked until the 15min window expires.