How to Connect to Twitter with Python

There are several 3rd party packages that wrap Twitter’s API. We’ll be looking at tweepy and twitter. The tweepy documentation is a bit more extensive than twitter’s, but I felt that the twitter package had more concrete examples. Let’s spend some time going over how to use these packages!


Getting Started

To get started using Twitter’s API, you will need to create a Twitter application. To do that, you’ll have to go to their developer’s site and create a new application. After your application is created, you will need to get your API keys (or generate some). You will also need to generate your access tokens.

Since neither of these packages are included with Python, you will need to install them as well. To install tweepy, just do the following:

pip install tweepy

To install twitter, you can do the same kind of thing:

pip install twitter

Now you should be ready to go!


Posting a Status Update

One of the basics that you should be able to do with these packages is post an update to your Twitter account. Let’s see how these two packages work in that regard. We will start with tweepy.

import tweepy

auth = tweepy.OAuthHandler(key, secret)
auth.set_access_token(token, token_secret)
client = tweepy.API(auth)
client.update_status("#Python Rocks!")

Well that was pretty straight-forward. We had to create an OAuth handler with our keys and then set the access tokens. Finally we created an object that represents Twitter’s API and updated out status. This method worked great for me. Now let’s see if we can get the twitter package to work.

import twitter

auth=twitter.OAuth(token, token_secret, key, secret)
client = twitter.Twitter(auth=auth)
client.statuses.update(status="#Python Rocks!")

This code is pretty simple too. In fact, I think the twitter package’s OAuth implementation is cleaner than tweepy’s.

Note: I sometimes got the following error while using the twitter package: Bad Authentication data, code 215. I’m not entirely sure why as when you look that error up, it’s supposed to be caused because you’re using Twitter’s old API. If that was the case, then it should never work.

Next we’ll look at how to get our timeline.


Getting Timelines

Getting your own Twitter timeline is really easy in both packages. Let’s take a look at tweepy’s implementation:

import tweepy

auth = tweepy.OAuthHandler(key, secret)
auth.set_access_token(token, token_secret)
client = tweepy.API(auth)

timeline = client.home_timeline()

for item in timeline:
    text = "%s says '%s'" % (item.user.screen_name, item.text)
    print text

So here we get authenticated and then we call the home_timeline() method. This returns an iterable of objects that we can loop over and extract various bits of data from. In this case, we just extract the screen name and the text of the Tweet. Let’s see how the twitter package does this:

import twitter

auth=twitter.OAuth(token, token_secret, key, secret)
client = twitter.Twitter(auth=auth)

timeline = client.statuses.home_timeline()
for item in timeline:
    text = "%s says '%s'" % (item["user"]["screen_name"],
                             item["text"])
    print text

The twitter package is pretty similar. The primary difference is that it returns a list of dictionaries.

What if you wanted to get someone else’s timeline. In tweepy, you’d do something like this:

import tweepy

auth = tweepy.OAuthHandler(key, secret)
auth.set_access_token(token, token_secret)
client = tweepy.API(auth)

user = client.get_user(screen_name='pydanny')
timeline = user.timeline()

The twitter package is a little different:

import twitter

auth=twitter.OAuth(token, token_secret, key, secret)
client = twitter.Twitter(auth=auth)

user_timeline = client.statuses.user_timeline(screen_name='pydanny')

In this case, I think the twitter package is a bit cleaner although one might argue that tweepy’s implementation is more intuitive.


Getting Your Friends and Followers

Just about everyone has friends (people they follow) and followers on Tritter. In this section we will look at how to access those items. The twitter package doesn’t really have a good example to follow to find your Twitter friends and followers so in this section we’ll just focus on tweepy.

import tweepy

auth = tweepy.OAuthHandler(key, secret)
auth.set_access_token(token, token_secret)
client = tweepy.API(auth)

friends = client.friends()

for friend in friends:
    print friend.name

If you run the code above, you will notice that the maximum number of friends that it prints out will be 20. If you want to print out ALL your friends, then you need to use a cursor. There are two ways to use the cursor. You can use it to return pages or a specific number of items. In my case, I have 32 people that I follow, so I went with the items way of doing things:

for friend in tweepy.Cursor(client.friends).items(200):
    print friend.name

This piece of code will iterate over up to 200 items. If you have a LOT of friends or you want to iterate over someone else’s friends, but don’t know how many they have, then using the pages method makes more sense. Let’s take a look at how that might work:

for page in tweepy.Cursor(client.friends).pages():
    for friend in page:
        print friend.name

That was pretty easy. Getting a list of your followers is exactly the same:

followers = client.followers()
for follower in followers:
    print follower.name

This too will return just 20 items. I have a lot of followers, so if I wanted to get a list of them, I would have to use one of the cursor methods mentioned above.


Wrapping Up

These packages provide a lot more functionality than this article covers. I particularly recommend looking at tweepy as it’s quite a bit more intuitive and easier to figure out using Python’s introspection tools than the twitter package is. You could easily take tweepy and create a user interface around it to keep you up-to-date with your friends if you didn’t already have a bunch of those applications already. On the other hand, that would still be a good program to write for a beginner.


Additional Reading