Registry / communication / twython

twython

JSON →
library3.9.1pypypi✓ verified 86d ago

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.

pip install twython
INSTALL
IMPORT
SIG · TWYTHON
T
twython
communicationpythonv3.9.1
Install
2.3s avg
Import
671ms
Disk
21MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v3.9.1 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.920 runs
installs and imports cleanly · install 0.0s · import 0.713s · 23.1MB
glibc
py 3.103.920 runs
installs and imports cleanly · install 2.3s · import 0.628s · 24MB
21MB installed
● package 21MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Twython
from twython import Twython
import twython twython.Twython()
While 'import twython' works, direct import of Twython is idiomatic and often used for clarity. Very old examples (Python 2 era) might use `twython.setup()` which is no longer correct.
TwythonStreamer
from twython import TwythonStreamer
Used for interacting with the Twitter Streaming API.

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}")
Debug
Known issues
breakingPython 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.
fix
Upgrade your Python environment to 3.5 or later. If Python 2.7 is mandatory, install the last compatible version: `pip install twython==3.7.0`.
affects: >=3.7.0
breakingAs 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`.
fix
If your code explicitly caught `StopIteration` from Twython's internal generators, you may now need to catch `RuntimeError` instead, or adjust logic to expect a normal return/exit from iteration where `StopIteration` was previously used as a flow control mechanism. Review Python's PEP 479 for more details.
affects: >=3.9.1 (Python >=3.7)
gotchaTwitter'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.
fix
Refer to the Twitter Developer documentation for the API version you are targeting (e.g., v1.1 or v2) to ensure correct parameter usage and handling of responses.
affects: All
Errors
Common errors & fixes
JSONDecodeError: Expecting value
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.
fix
Implement 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
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.
fix
Implement 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)
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.
fix
If 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.
Upgrade
Version history
3.9.1latest on PyPI · released Jul 16, 2021
Audit
Dependencies
requestsrequiredHTTP client for API interactions.
requests-oauthlibrequiredHandles OAuth 1.0a and OAuth 2 authentication flows.
Agent activity
30 hits · last 30 days
node
28
OpenAI (training)
1
Resources
twython — pip install twython · libregistry