Tweepy

Language: Python

Web

Tweepy was created by Joshua Roesslein in 2009 to simplify interaction with the Twitter API. It abstracts authentication, request handling, and rate limits, enabling developers to focus on building applications and collecting social media data without dealing with raw HTTP requests.

Tweepy is a Python library for accessing the Twitter API easily. It provides a convenient interface to retrieve tweets, post updates, manage followers, and interact with Twitter data programmatically.

Installation

pip: pip install tweepy
conda: conda install -c conda-forge tweepy

Usage

Tweepy allows you to authenticate with Twitter, access timelines, post tweets, search for tweets, follow users, and stream live data. It supports both the REST API and the streaming API with Pythonic syntax.

Authentication with API keys

import tweepy

consumer_key = 'YOUR_CONSUMER_KEY'
consumer_secret = 'YOUR_CONSUMER_SECRET'
access_token = 'YOUR_ACCESS_TOKEN'
access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET'

auth = tweepy.OAuth1UserHandler(consumer_key, consumer_secret, access_token, access_token_secret)
api = tweepy.API(auth)
print('Authentication successful')

Shows how to authenticate with Twitter using API keys and access tokens.

Posting a tweet

api.update_status('Hello Tweepy!')

Posts a simple tweet to your authenticated Twitter account.

Fetching user timeline

tweets = api.user_timeline(screen_name='twitter', count=5)
for tweet in tweets:
    print(tweet.text)

Retrieves the last 5 tweets from a specified user and prints their text.

Searching tweets

for tweet in tweepy.Cursor(api.search_tweets, q='Python', lang='en').items(10):
    print(tweet.created_at, tweet.text)

Searches for 10 recent English tweets containing the keyword 'Python'.

Streaming live tweets

class MyStream(tweepy.Stream):
    def on_status(self, status):
        print(status.text)

stream = MyStream(consumer_key, consumer_secret, access_token, access_token_secret)
stream.filter(track=['Python'], languages=['en'])

Streams live tweets containing the word 'Python' in English and prints them as they arrive.

Following a user

api.create_friendship(screen_name='twitter')

Follows a specified Twitter user.

Handling rate limits

api = tweepy.API(auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

Automatically waits and notifies when hitting Twitter API rate limits to prevent exceptions.

Error Handling

tweepy.errors.TweepyException: Catch general exceptions related to Twitter API requests.
tweepy.errors.RateLimitError: Wait until rate limits reset or use the `wait_on_rate_limit` parameter.
tweepy.errors.Unauthorized: Check that your API keys, access tokens, and permissions are correct.

Best Practices

Keep API keys and access tokens secure using environment variables.

Use cursors for paginated endpoints to handle large datasets efficiently.

Handle exceptions for rate limits and network errors gracefully.

Use streaming API for real-time tweet collection and REST API for historical data.

Respect Twitter’s terms of service and rate limits to avoid suspension.