{"id":8732,"library":"twython","title":"Twython","description":"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.","status":"active","version":"3.9.1","language":"en","source_language":"en","source_url":"https://github.com/ryanmcgrath/twython","tags":["twitter","api","social media","oauth","rest api","streaming api"],"install":[{"cmd":"pip install twython","lang":"bash","label":"Latest stable release"}],"dependencies":[{"reason":"HTTP client for API interactions.","package":"requests","optional":false},{"reason":"Handles OAuth 1.0a and OAuth 2 authentication flows.","package":"requests-oauthlib","optional":false}],"imports":[{"note":"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.","wrong":"import twython\ntwython.Twython()","symbol":"Twython","correct":"from twython import Twython"},{"note":"Used for interacting with the Twitter Streaming API.","symbol":"TwythonStreamer","correct":"from twython import TwythonStreamer"}],"quickstart":{"code":"import os\nfrom twython import Twython\n\n# Get your Twitter API credentials from environment variables\nAPP_KEY = os.environ.get('TWYTHON_APP_KEY', 'YOUR_APP_KEY')\nAPP_SECRET = os.environ.get('TWYTHON_APP_SECRET', 'YOUR_APP_SECRET')\nACCESS_TOKEN = os.environ.get('TWYTHON_ACCESS_TOKEN', 'YOUR_ACCESS_TOKEN')\nACCESS_TOKEN_SECRET = os.environ.get('TWYTHON_ACCESS_TOKEN_SECRET', 'YOUR_ACCESS_TOKEN_SECRET')\n\nif not all([APP_KEY, APP_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET]):\n    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.\")\nelse:\n    try:\n        # Initialize Twython with your credentials (OAuth 1.0a for user actions)\n        twitter = Twython(APP_KEY, APP_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET)\n\n        # Post a tweet\n        message = \"Hello from Twython! #PythonAPI\"\n        response = twitter.update_status(status=message)\n        print(f\"Successfully tweeted: {response['text']} (ID: {response['id_str']})\")\n\n        # Get home timeline (example of a GET request)\n        timeline = twitter.get_home_timeline(count=1)\n        if timeline:\n            print(f\"Latest tweet on your home timeline: {timeline[0]['text']}\")\n\n    except Exception as e:\n        print(f\"An error occurred: {e}\")","lang":"python","description":"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."},"warnings":[{"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`.","message":"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.","severity":"breaking","affected_versions":">=3.7.0"},{"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.","message":"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`.","severity":"breaking","affected_versions":">=3.9.1 (Python >=3.7)"},{"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.","message":"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.","severity":"gotcha","affected_versions":"All"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"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.","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.","error":"JSONDecodeError: Expecting value"},{"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.","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.","error":"requests.exceptions.ChunkedEncodingError"},{"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.","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.","error":"ModuleNotFoundError: No module named 'twython' (when using NLTK twitter corpus)"}]}