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.
pip install tweepyconda install -c conda-forge tweepyTweepy 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.
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.
api.update_status('Hello Tweepy!')Posts a simple tweet to your authenticated Twitter account.
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.
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'.
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.
api.create_friendship(screen_name='twitter')Follows a specified Twitter user.
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.
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.