Twython
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
-
JSONDecodeError: Expecting value
cause This error typically occurs when the Twitter API returns a response that is not valid JSON. This can happen if the API call resulted in an error page, rate limit exceeded message, or malformed data instead of the expected JSON.fixImplement robust error handling, checking the HTTP status code of the response before attempting JSON decoding. Print or log the raw response content to debug what Twitter actually returned. Ensure all required parameters are correctly provided for the API endpoint. -
requests.exceptions.ChunkedEncodingError
cause This error can occur when consuming the streaming API if Twitter's servers respond with an unexpected number of bytes, indicating a broken or incomplete chunked transfer encoding.fixImplement a `try-except` block around your streaming loop to catch this error. A common strategy is to log the error and then attempt to re-establish the stream connection to recover from transient network or server issues. -
ModuleNotFoundError: No module named 'twython' (when using NLTK twitter corpus)
cause This specific error often arises when trying to use NLTK's `nltk.twitter.common` module which internally attempts to import `twython`, but `twython` is either not installed or not discoverable in the Python path.fixIf your intention is to use NLTK's Twitter utilities, ensure `twython` is installed via `pip install twython`. If you only need NLTK's internal `json2csv` function and not full `twython` functionality, import it directly as `from nltk.twitter.common import json2csv` to avoid the implicit `twython` dependency check at import time.
Warnings
- breaking Python 2.7 support was officially dropped in Twython 3.7.0. Subsequent versions, including 3.9.1, require Python 3.5 or newer. Using Twython on Python 2.7 will lead to installation failures or runtime errors.
- breaking As of Twython 3.9.1, the library changed from raising `StopIteration` to returning instead. This aligns with PEP 479, which by default in Python 3.7+ transforms a `StopIteration` raised inside a generator into a `RuntimeError`.
- gotcha Twitter's API endpoints and their parameters can change. While Twython uses dynamic arguments to offer flexibility, always consult the official Twitter API documentation for the most up-to-date parameters and expected responses for specific endpoints.
Install
-
pip install twython
Imports
- Twython
import twython twython.Twython()
from twython import Twython
- TwythonStreamer
from twython import TwythonStreamer
Quickstart
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}")