Twython

3.9.1 · active · verified Thu Apr 16

Twython is an actively maintained, pure Python wrapper for the Twitter API, supporting both normal (REST) and streaming Twitter APIs. It simplifies interaction with Twitter's various endpoints, handling authentication and data parsing. The library is currently at version 3.9.1, with releases occurring infrequently but actively to adapt to API changes and Python advancements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates authenticating with Twython using OAuth 1.0a credentials (Application Key, Application Secret, Access Token, and Access Token Secret) and then performing basic actions: posting a tweet and fetching the home timeline. Ensure your Twitter Developer account and application are set up, and generate your access tokens. Store your credentials securely, preferably as environment variables, as shown.

import os
from twython import Twython

# Get your Twitter API credentials from environment variables
APP_KEY = os.environ.get('TWYTHON_APP_KEY', 'YOUR_APP_KEY')
APP_SECRET = os.environ.get('TWYTHON_APP_SECRET', 'YOUR_APP_SECRET')
ACCESS_TOKEN = os.environ.get('TWYTHON_ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN')
ACCESS_TOKEN_SECRET = os.environ.get('TWYTHON_ACCESS_TOKEN_SECRET', 'YOUR_ACCESS_TOKEN_SECRET')

if not all([APP_KEY, APP_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET]):
    print("Error: Twitter API credentials not set. Please set TWYTHON_APP_KEY, TWYTHON_APP_SECRET, TWYTHON_ACCESS_TOKEN, and TWYTHON_ACCESS_TOKEN_SECRET environment variables.")
else:
    try:
        # Initialize Twython with your credentials (OAuth 1.0a for user actions)
        twitter = Twython(APP_KEY, APP_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

        # Post a tweet
        message = "Hello from Twython! #PythonAPI"
        response = twitter.update_status(status=message)
        print(f"Successfully tweeted: {response['text']} (ID: {response['id_str']})")

        # Get home timeline (example of a GET request)
        timeline = twitter.get_home_timeline(count=1)
        if timeline:
            print(f"Latest tweet on your home timeline: {timeline[0]['text']}")

    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →