Python has several packages that you can use to interact with Twitter. These packages can be useful for creating Twitter bots or for downloading large amounts of data for offline analysis. One of the more popular Python Twitter packages is called Tweepy. You will learn how to use Tweepy with Twitter in this article.

Tweepy gives you access to Twitter’s API, which exposes the following (plus lots more!):

  • Tweets
  • Retweets
  • Likes
  • Direct messages
  • Followers

This allows you to do a lot with Tweepy. Let’s get started!

Getting Started

The first thing that you need to do is create a Twitter account and get the credentials you will need to access Twitter. To do that, you will need to apply for a developer account here.

Once that is created, you can get or generate the following:

  • Tweets
  • Retweets
  • Likes
  • Direct messages
  • Followers

If you ever lose these items, you can go back to your developer account and regenerate new ones. You can also revoke the old ones.

Note: By default, the access token you receive is read-only. If you would like to send tweets with Tweepy, you will need to make sure you set the **Application Type **to “Read and Write.”

Installing Tweepy

Next, you will need to install the Tweepy package. This is accomplished by using pip:

pip install tweepy

Now that you have Tweepy installed, you can start using it!

Using Tweepy

You can use Tweepy to do pretty much anything on Twitter programmatically. For example, you can use Tweepy to get and send tweets. You can use it to access information about a user. You can retweet, follow/unfollow, post, and much more.

Let’s look at an example of getting your user’s home timeline:

import tweepy
 
consumer_key = 'CONSUMER_KEY'
consumer_secret = 'CONSUMER_SECRET'
access_token = 'ACCESS_TOKEN'
access_secret = 'ACCESS_SECRET'
 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
 
api = tweepy.API(auth)
 
tweets = api.home_timeline()
for tweet in tweets:
    print('{real_name} (@{name}) said {tweet}\n\n'.format(
        real_name=tweet.author.name, name=tweet.author.screen_name,
        tweet=tweet.text))

The first few lines of code here are where you would put your credentials that you found on your Twitter developer profile page. It is not actually recommended to hard-code these values in your code, but I am doing that here for simplicity. If you were to create code to be shared, you would want to have the user’s of your code export their credentials to their environment and use Python’s os.getenv() or via command line arguments using argparse.

Next, you log in to Twitter by creating a OAuthHandler() object and setting the access token with the aptly named set_access_token() function. Then, you can create an API() instance that will allow you to access Twitter.

In this case, you call home_timeline(), which returns the first twenty tweets in your home timeline. These tweets can be from your friends, followers or users that Twitter has decided to promote in your timeline. Here, you print out the the author’s name, Twitter handle, and the text of their tweet.

Let’s find out how you get information about yourself using the api object you created earlier:

>>> me = api.me()
>>> me.screen_name
'driscollis'
>>> me.name
'Mike Driscoll'
>>> me.description
('Author of books, blogger @mousevspython and Python enthusiast. Also part of '
 'the tutorial team @realpython')

You can use the api to get information about yourself. The code above demonstrates getting your screen name, actual name, and the description you have set on Twitter. You can get much more then this. For example, you can get your followers, timeline, etc.

Getting Tweets

Getting tweets is also quite easy to do using Tweepy. You can get your own tweets or someone else’s if you know their username.

Let’s start by getting your tweets:

import tweepy
 
consumer_key = 'CONSUMER_KEY'
consumer_secret = 'CONSUMER_SECRET'
access_token = 'ACCESS_TOKEN'
access_secret = 'ACCESS_SECRET'
 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
 
api = tweepy.API(auth)
my_tweets = api.user_timeline()
for t in my_tweets:
    print(t.text)

Here, you connect to Twitter, as you did in the previous section. Then, you call user_timeline() to get a list of objects that you can iterate over. In this case, you end up printing out only the text of the tweet.

Let’s try getting a specific user. In this case, we will use a fairly popular programmer, Kelly Vaughn:

>>> user = api.get_user('kvlly')
>>> user.screen_name
'kvlly'
>>> user.name
'Kelly Vaughn '
>>> for t in tweets:
        print(t.text)

She tweets a LOT, so I won’t be reproducing her tweets here. However, as you can see, it’s quite easy to get a user. All you need to do is pass get_user() a valid Twitter user name; you’ll then have access to anything that is publicly available about that user.

Sending Tweets

Reading tweets is fun, but what about sending them? Tweepy can do this task for you as well.

Let’s find out how:

import tweepy
 
consumer_key = 'CONSUMER_KEY'
consumer_secret = 'CONSUMER_SECRET'
access_token = 'ACCESS_TOKEN'
access_secret = 'ACCESS_SECRET'
 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
 
api = tweepy.API(auth)
 
api.update_status("This is your tweet message")

The main bit of code you should focus on here is the very last line: update_status(). Here, you pass in a string, which is the tweet message itself. As long as there are no errors, you should see the tweet in your Twitter timeline.

Now, let’s learn how to send a tweet with a photo attached to it:

import tweepy
 
consumer_key = 'CONSUMER_KEY'
consumer_secret = 'CONSUMER_SECRET'
access_token = 'ACCESS_TOKEN'
access_secret = 'ACCESS_SECRET'
 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
 
api = tweepy.API(auth)
 
api.update_with_media('/path/to/an/image.jpg',
                      "This is your tweet message")

In this case, you need to use the update_with_media() method, which takes a path to the image you want to upload and a string, which is the tweet message.

Listing Followers

The last topic that I am going to cover is how to list your followers on Twitter.

Let’s take a look:

import tweepy
 
consumer_key = 'CONSUMER_KEY'
consumer_secret = 'CONSUMER_SECRET'
access_token = 'ACCESS_TOKEN'
access_secret = 'ACCESS_SECRET'
 
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
 
api = tweepy.API(auth)
 
followers = api.followers()
for follower in followers:
    print(follower.screen_name)

This code will list the latest 20 followers for your account. All you need to do is call followers() to get the list. If you need to get more than just the latest 20, you can use the count parameter to specify how many results you want.

Wrapping Up

There is much more that you can do with Tweepy. For example, you can get likes, send and read direct messages, and upload media. It’s a quite nice and easy-to-use package. You can also use Tweepy to read and write to Twitter in real-time, which allows you to create a Twitter bots. If you haven’t given Tweepy a try yet, you should definitely give it a go. It’s a lot of fun!

 ===================================================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ Complete Python Bootcamp: Go from zero to hero in Python 3

☞ Python for Time Series Data Analysis

☞ The complete beginner’s guide to JSON

☞ The Complete Guide to JSON Web Tokens

☞ Python Programming For Beginners From Scratch

#python

Using Twitter With Python and Tweepy
5 Likes60.70 GEEK