Language: Python
Web
python-twitter was created to simplify interaction with the Twitter API for Python developers. It abstracts API authentication, rate limits, and request handling, enabling developers to focus on building applications that interact with Twitter.
python-twitter is a Python wrapper around the Twitter API, providing a simple interface to access Twitter data, post tweets, and manage accounts programmatically.
pip install python-twitterconda install -c conda-forge python-twitterpython-twitter allows you to authenticate with Twitter using API credentials, read timelines, search tweets, post updates, manage followers, and interact with Twitter accounts via Python.
import twitter
api = twitter.Api(consumer_key='YOUR_CONSUMER_KEY',
consumer_secret='YOUR_CONSUMER_SECRET',
access_token_key='YOUR_ACCESS_TOKEN',
access_token_secret='YOUR_ACCESS_TOKEN_SECRET')
print(api.VerifyCredentials())Authenticates with Twitter using API credentials and verifies the account.
status = api.PostUpdate('Hello Twitter!')
print(status.text)Posts a tweet with the text 'Hello Twitter!' from the authenticated account.
timeline = api.GetHomeTimeline(count=5)
for tweet in timeline:
print(tweet.user.name, tweet.text)Fetches the latest 5 tweets from the authenticated user's home timeline.
search_results = api.GetSearch(term='Python', count=10)
for tweet in search_results:
print(tweet.user.screen_name, tweet.text)Searches for 10 recent tweets containing the keyword 'Python'.
user_timeline = api.GetUserTimeline(screen_name='twitter', count=5)
for tweet in user_timeline:
print(tweet.text)Retrieves the last 5 tweets from a specified user's timeline.
followers = api.GetFollowers(screen_name='twitter')
for user in followers:
print(user.screen_name)Fetches followers of a specific Twitter user and prints their screen names.
dms = api.GetDirectMessages(count=5)
for dm in dms:
print(dm.sender.screen_name, dm.text)Retrieves the latest 5 direct messages received by the authenticated account.
Keep API keys and tokens secure using environment variables.
Use Python-twitter’s built-in methods for pagination to handle large datasets.
Respect Twitter rate limits to prevent temporary bans.
Use try/except blocks to handle network or API errors gracefully.
Test code on development or test accounts before posting to live accounts.