Tweepy-A Python Library

Tweepy-A Python Library

Introduction

Tweepy is a Python library to extract tweets from Twitter. It is useful to create Twitter bots and for automation of tasks. With the help of Tweepy we can

  • create and delete tweet
  • view tweets on your timeline
  • send direct messages and delete them
  • search for users or topics that are trending

And further with the help of TextBlob and other libraries we will be able do the sentiment analysis.

Installation

There are two methods to install Tweepy.The first is using pip.This is the easiest method.

pip install tweepy

The second method is to import from Github.

git clone https://github.com/tweepy/tweepy.git
cd tweepy
pip install

Hello Tweepy

To see if Tweepy is working fine we will first try to extract the tweets from your Twitter timeline. For this we will have to get access to the twitter developer account. The steps on 'how to' can be accessed here. Once you have the Developer account you will have access to Consumer Key,Consumer Secret,Access Token,Access Token Secret. Note that these will be passed as parameters. And remember not to publish these credentials anywhere like Github.

import tweepy

#Store the values of the following as a string.
#You will pass them as parameters

consumerKey=' '
consumerSecret=' '
accessToken=' '
accessTokenSecret=' '
auth = tweepy.OAuthHandler(consumerKey, consumerSecret)
auth.set_access_token(accessToken, accessTokenSecret)

api = tweepy.API(auth)

timeline_tweets = api.home_timeline()
for tweet in timeline_tweets:
    print(tweet.text)

Some API References that are commonly used

Timeline Methods

API.home_timeline([since_id][, max_id][, count][, page])

Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user’s friends. These are the tweets that appear on the user's timeline.

API.user_timeline([id/user_id/screen_name][, since_id][, max_id][, count][, page])

If we have the id of another user then we will be able to retrieve the timeline Returns the 20 most recent statuses posted from the authenticating user or the user specified. It’s also possible to request another user’s timeline via the id parameter.

API.mentions_timeline([since_id][, max_id][, count])

Returns the 20 most recent mentions, including retweets.

Search Methods

API.search(q[, geocode][, lang][, locale][, result_type][, count][, until][, since_id][, max_id][, include_entities])

Returns a collection of relevant Tweets matching a specified query. This is one of the API methods that come handy. This lets us retrieve tweets with a lot of parameters like language,count(no of tweets),start and end date etc.

There are many more useful api methods that can be used.You can learn more about them from here.

References

Any feedback or constructive criticism is welcomed. You can either find me on Twitter @malavika1501 or email me