Retrieving Tweets with Tweepy

File handling | Python Methods and Functions

Steps to get keys:
— Sign in to Twitter for Developers. 
— Go to "Create Application"
— Fill in the application details. 
— Click Create Twitter App. 
— The details of your new application will be displayed along with the consumer key and consumer secret. 
— To get an access token, click Generate My Access Token. The page will refresh and generate an access token.

Tweepy — this is one of the libraries that needs to be installed using pip. Now, in order to authorize our application to access Twitter on our behalf, we need to use the OAuth interface. Tweepy provides a convenient Cursor interface for iterating over different types of objects. Twitter allows a maximum of 3200 tweets to be retrieved.

These are all prerequisites and must be used before receiving tweets from a user.

Code (with explanation):

import tweepy

# Populate X with the credentials received
# following the above procedure.




access_secret =

# Function to retrieve tweets

def get_tweets (username):


# Authorization by consumer key and consumer secret

auth = tweepy.OAuthHandler ( consumer_key, consumer_secret)


# Access to user's access key and access secret

  auth.set_access_token (access_key, access_secret)


# API call

api = tweepy.API (auth)


# 200 tweets to be retrieved

number_of_tweets = 200

tweets = api.user_timeline (screen_name = username)


  # Empty array

tmp = [] 


# create an array of tweet information: username,

# tweet id, date / time, text

  tweets_for_csv = [tweet.text for tweet in tweets] # CSV file created

for j in tweets_for_csv:


# Add tweets to an empty tmp array

tmp.append (j) 


# Print tweets

print (tmp)


# Driver code

if __ name__ = = '__main__' :


# Here goes the Twitter handle for the user for

# whose tweets should be retrieved.

get_tweets ( "twitter-handle"

The above script will generate all the tweets of a specific user and will be added to an empty tmp array. Here Tweepy is presented as a tool for accessing Twitter data in a fairly simple way with Python. There are different types of data that we can collect, with an obvious focus on the tweet object. Once we have gathered some data, the possibilities for analytic applications are endless.

One such use of tweet extraction is to analyze feelings or emotions. User emotions can be derived from tweets by tokenizing each word and applying machine learning algorithms to that data. This detection of emotions or feelings is used all over the world and will be widely used in the future.

This article is provided by Ayush Govil . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.