python-twitter

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.

Installation

pip: pip install python-twitter
conda: conda install -c conda-forge python-twitter

Usage

python-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.

Authentication with API keys

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.

Posting a tweet

status = api.PostUpdate('Hello Twitter!')
print(status.text)

Posts a tweet with the text 'Hello Twitter!' from the authenticated account.

Reading the home timeline

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.

Searching tweets

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'.

Retrieving user timeline

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.

Getting followers

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.

Direct messages

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.

Error Handling

twitter.TwitterError: Catch exceptions for failed API requests and inspect the error message for troubleshooting.
HTTPError: Ensure network connectivity and correct endpoint usage.
RateLimitError: Wait until rate limits reset or reduce API request frequency.

Best Practices

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.