Introduction To The Tweepy Module

Ever wondered how to use twitter with python? You can do this by using the tweepy module.

Rohan Mathur
DataX Journal
4 min readJul 9, 2020

--

We will look into the basics of how you can like, tweet & retweet from just a few lines of code.

First things first, you would obviously need to create a twitter account. So head on to their site & make one!
Now, for using the tweepy module, you will need access to their twitter API. This can be a pretty long task so bear with me before we start coding. After that, you have the whole of twitter at your hands! You will need to head on to their twitter developer site & apply for a twitter developer account.

After applying, fill out the necessary details & you will be asked to answer a few questions on why you need access to their API. Twitter has a strict policy about their uses & I urge you all to fill it out accordingly instead of giving one-liners, otherwise, they will reject your application. (P.S — Mine got rejected 4 times before being approved). Within a day, you should be having your application approved.

After that, you can head on to your developer account & finally create an app (Not literally, but register for a project). When you complete this, you will have access to 4 important things — API Key, API Secret, Access Token & Access Token Secret. These 4 values will help you access whichever tweet you want to access.

Phew! Enough of the theory part, let’s start coding!

For this blog, I am using a Jupyter Notebook for my code. Let’s install the tweepy module first.

pip install tweepy

Now, go ahead & copy those 4 access keys & store them into 4 variables. Also, import the given libraries below which we will use.

import tweepy 
import pandas as pd
consumer_key= “XXX”
consumer_secret = “XXX”
access_token =”XXX"
access_token_secret= “XXX”
# Do not share the access codes with anyone else! It can lead to privacy invasion & maybe even hacking of your account

Tweeting

Let’s go ahead & actually give out our first tweet using this module. The code for that will be as follows -

auth = tweepy.OAuthHandler(consumer_key, consumer_secret) # authentication of access token and secret auth.set_access_token(access_token, access_token_secret) 
api = tweepy.API(auth)
tweet1 =”Hello! This is my first tweet using python script”api.update_status(status=”Hello! This is my first tweet using python script”)

After running that, head on to your twitter account & then your profile. You will see your tweet! Let’s see mine.

It works!

Extracting Tweets

Let’s look at how you can extract tweets. In the following code, I have searched for the keyword — “#datascience” & have collected the first 5 tweets, specifying a date since when it was tweeted. I have then proceeded with printing out the tweet, the user who tweeted & the twitter link.

search_words = "#datascience" + " -filter:retweets"
#Extracting tweets that are not retweeted
date_since = "2020-07-09"# Collect tweets
tweets = tweepy.Cursor(api.search,
q=search_words,
lang="en",
since=date_since).items(5)
users_locs = []
for tweet in tweets:
text = tweet.text #Stores the actual tweet

username = tweet.user.screen_name #Gets the user who tweeted

id1 = tweet.id #Gets the unique tweet ID

tweet_link = "https://twitter.com/" + username + "/status/" + str(id1)
#Creates an actual tweet link that can be accessed

users_locs.append([text, username, id1,tweet_link])

#Creates a list with all the details

Let’s create a dataframe to observe it in a cleaner way.

tweet_text = pd.DataFrame(data=users_locs, 
columns=[‘Tweet’,’User’, ‘ID’,’Twitter Link’])
tweet_text
Dataframe

Liking & Retweeting

Let’s look at how you can like a tweet. Here I will be liking my own tweet for testing.

target = “RohanMathur_17”USER= api.get_user(target)
print(“Name: “ + USER.name)
print(“Following count: “ + str(USER.friends_count))
print(“Followers count: “ + str(USER.followers_count))
tweet = api.user_timeline(id = api.me().id, count = 1)[0]
#Getting the latest tweet
print(tweet.text)
print(tweet.id)

Let’s crosscheck.

Yup! That seems to be my details. Let us write a small code to like the tweet.

api.create_favorite(tweet.id)

As simple as that! Let’s crosscheck again —

The like button is pressed. Hence the tweet was liked

Onto retweeting. Again, all you need is the tweet id. I will be retweeting my own tweet here.

api.retweet(tweet.id)
Retweeting

That’s it! Pretty simple right? Those were just the basics of the tweepy module. Add a few more lines in there & you can even create a bot for liking, retweeting & even following users.

Thanks for reading! If you liked the explanation, do give a clap.

--

--