Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs.

Overview

Twython

Twython is a Python library providing an easy way to access Twitter data. Supports Python 3. It's been battle tested by companies, educational institutions and individuals alike. Try it today!

Note: As of Twython 3.7.0, there's a general call for maintainers put out. If you find the project useful and want to help out, reach out to Ryan with the info from the bottom of this README. Great open source project to get your feet wet with!

Features

  • Query data for:
    • User information
    • Twitter lists
    • Timelines
    • Direct Messages
    • and anything found in the docs
  • Image Uploading:
    • Update user status with an image
    • Change user avatar
    • Change user background image
    • Change user banner image
  • OAuth 2 Application Only (read-only) Support
  • Support for Twitter's Streaming API
  • Seamless Python 3 support!

Installation

Install Twython via pip:

$ pip install twython

Or, if you want the code that is currently on GitHub

git clone git://github.com/ryanmcgrath/twython.git
cd twython
python setup.py install

Documentation

Documentation is available at https://twython.readthedocs.io/en/latest/

Starting Out

First, you'll want to head over to https://apps.twitter.com and register an application!

After you register, grab your applications Consumer Key and Consumer Secret from the application details tab.

The most common type of authentication is Twitter user authentication using OAuth 1. If you're a web app planning to have users sign up with their Twitter account and interact with their timelines, updating their status, and stuff like that this is the authentication for you!

First, you'll want to import Twython

from twython import Twython

Obtain Authorization URL

Now, you'll want to create a Twython instance with your Consumer Key and Consumer Secret:

  • Only pass callback_url to get_authentication_tokens if your application is a Web Application
  • Desktop and Mobile Applications do not require a callback_url
APP_KEY = 'YOUR_APP_KEY'
APP_SECRET = 'YOUR_APP_SECRET'

twitter = Twython(APP_KEY, APP_SECRET)

auth = twitter.get_authentication_tokens(callback_url='http://mysite.com/callback')

From the auth variable, save the oauth_token and oauth_token_secret for later use (these are not the final auth tokens). In Django or other web frameworks, you might want to store it to a session variable

OAUTH_TOKEN = auth['oauth_token']
OAUTH_TOKEN_SECRET = auth['oauth_token_secret']

Send the user to the authentication url, you can obtain it by accessing

auth['auth_url']

Handling the Callback

If your application is a Desktop or Mobile Application oauth_verifier will be the PIN code

After they authorize your application to access some of their account details, they'll be redirected to the callback url you specified in get_authentication_tokens.

You'll want to extract the oauth_verifier from the url.

Django example:

oauth_verifier = request.GET['oauth_verifier']

Now that you have the oauth_verifier stored to a variable, you'll want to create a new instance of Twython and grab the final user tokens

twitter = Twython(
    APP_KEY, APP_SECRET,
    OAUTH_TOKEN, OAUTH_TOKEN_SECRET
)

final_step = twitter.get_authorized_tokens(oauth_verifier)

Once you have the final user tokens, store them in a database for later use::

    OAUTH_TOKEN = final_step['oauth_token']
    OAUTH_TOKEN_SECRET = final_step['oauth_token_secret']

For OAuth 2 (Application Only, read-only) authentication, see our documentation.

Dynamic Function Arguments

Keyword arguments to functions are mapped to the functions available for each endpoint in the Twitter API docs. Doing this allows us to be incredibly flexible in querying the Twitter API, so changes to the API aren't held up from you using them by this library.

Basic Usage

Function definitions (i.e. get_home_timeline()) can be found by reading over twython/endpoints.py

Create a Twython instance with your application keys and the users OAuth tokens

from twython import Twython
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

Authenticated Users Home Timeline

twitter.get_home_timeline()

Updating Status

This method makes use of dynamic arguments, read more about them.

twitter.update_status(status='See how easy using Twython is!')

Advanced Usage

Questions, Comments, etc?

My hope is that Twython is so simple that you'd never have to ask any questions, but if you feel the need to contact me for this (or other) reasons, you can hit me up at [email protected].

Or if I'm to busy to answer, feel free to ping [email protected] as well.

Follow us on Twitter:

Want to help?

Twython is useful, but ultimately only as useful as the people using it (say that ten times fast!). If you'd like to help, write example code, contribute patches, document things on the wiki, tweet about it. Your help is always appreciated!

Comments
  • ChunkedEncodingError

    ChunkedEncodingError

    Just spotted the following in the logs for a pair of my streamers:

    Traceback (most recent call last):
      File "/home/keyz/tweets/tweetstream.py", line 20, in <module>
        stream.statuses.filter(locations=location)
      File "/usr/local/lib/python2.7/dist-packages/twython/streaming/types.py", line 65, in filter
        self.streamer._request(url, 'POST', params=params)
      File "/usr/local/lib/python2.7/dist-packages/twython/streaming/api.py", line 134, in _request
        for line in response.iter_lines(self.chunk_size):
      File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 602, in iter_lines
        decode_unicode=decode_unicode):
      File "/usr/local/lib/python2.7/dist-packages/requests/models.py", line 575, in generate
        raise ChunkedEncodingError(e)
    requests.exceptions.ChunkedEncodingError: IncompleteRead(0 bytes read)
    

    The line in question is

    for line in response.iter_lines(self.chunk_size)
    

    in https://github.com/ryanmcgrath/twython/blob/master/twython/streaming/api.py

    Should there be some catch for this to pass it to on_error, rather than throwing an uncaught exception?

    Looks like the exception is a fairly new one, see https://github.com/kennethreitz/requests/pull/1498.

    I'd submit a patch, but I'm not sure of the best way to catch this. Putting a try block around the whole loop seems messy.

    opened by keyz182 54
  • Unable to run the Stream API sample

    Unable to run the Stream API sample

    Hi, I'm testing the stream API sample code here https://github.com/ryanmcgrath/twython, but keep getting this error: line 560, in stream TwythonError: 'Response was not valid JSON, unable to decode.' Any help is appreciated.

    opened by cfu1 21
  • Getting OAuth error when using updateStatusWithMedia (Fixed)

    Getting OAuth error when using updateStatusWithMedia (Fixed)

    I get the following error when using updateStatusWithMedia:

    {"request":"/1/statuses/update_with_media.json","error":"Could not authenticate with OAuth."}

    The updateStatus endpoint works fine, but updateStatusWithMedia generates an OAuth exception.

    opened by genghisu 19
  • Use a stub for the requests library in unit tests

    Use a stub for the requests library in unit tests

    The majority of the unit tests for Twython test the Twitter API rather than Twython. Using a requests stub would allow the unit tests to focus on the code in Twython and work around the issues with failing tests due to Twitter hiccups and rate limits.

    Here is an example using HTTMock (https://github.com/patrys/httmock):

    class TwythonAPITestCase(unittest.TestCase):
        def setUp(self):
            [snip]
    
        def _make_url_checker(self, path):
            def check_url(url, request):
                self.assertEqual(path, url.path)
                return "empty response"
            return check_url
    
        def test_get(self):
            """Test Twython generic GET request works"""
            with httmock.HTTMock(self._make_url_checker("/1.1/account/verify_credentials.json")):
                self.api.get('account/verify_credentials')
    

    In the example, I use a closure to create a url checker, but it could be expanded to check the request method and parameters.

    This shows how the unit tests can now focus on making sure the request (url, params, header) is correct and skip hitting the Twitter API entirely. For those functions that process the response, the mock can return a hard coded response.

    To run just this unit test: nosetests tests.test_core:TwythonAPITestCase.test_get

    What do you think?

    opened by cash 18
  • Error 401 when using TwythonStreamer

    Error 401 when using TwythonStreamer

    Hello, I know that recently a very similar issue was close, but I think it is different.

    What happens is that when I try to work with TwythonStreamer - exactly like tutorial, I'm receiving the error 401.

    The credentials are ok, since it works nicely with basic usage tutorial.

    I'm with:

    python=2.7.3 requests=1.2.0 requests_oauthlib=0.3.2 oauthlib=0.4.2

    ps: I've found a question at Stackoverflow with the same question http://stackoverflow.com/questions/17438943/twython-oauth1-issues-401-error-using-example-code

    opened by joncasdam 15
  • Getting 400 (Bad Request) Errors using App-Only Authentication

    Getting 400 (Bad Request) Errors using App-Only Authentication

    Just started getting these today. I am guessing Twitter made some kind of change that is breaking it. I tried creating a new app with new credentials and it still fails.

    Here's an example:

    t = twython.Twython('XXXX','XXXX');
    t.search(q='dogs');
    
    /Users/joeldrotleff/code/connectr/connectr_server/ENV/lib/python2.7/site-packages/twython/twython.pyc in _request(self, url, method, params, api_call)
        192             raise ExceptionType(error_message,
        193                                 error_code=response.status_code,
    --> 194                                 retry_after=response.headers.get('retry-after'))
        195 
        196         # if we have a json error here, then it's not an official Twitter API error
    
    TwythonAuthError: Twitter API returned a 400 (Bad Request), Bad Authentication data
    

    Sorry it's not more specific, I don't really know the ins and outs of twitter authentication.

    opened by joeldrotleff 15
  • WIP: 3.0.0

    WIP: 3.0.0

    3.0.0

    • Changed twython/twython.py to twython/api.py in attempt to make structure look a little neater
    • Removed all camelCase function access (anything like getHomeTimeline is now get_home_timeline)
    • Removed shorten_url. With the requests library, shortening a URL on your own is simple enough
    • twitter_token, twitter_secret and callback_url are no longer passed to Twython.__init__
      • twitter_token and twitter_secret have been replaced with app_key and app_secret respectively
      • callback_url is now passed through Twython.get_authentication_tokens
    • Update test_twython.py docstrings per http://www.python.org/dev/peps/pep-0257/
    • Removed get_list_memberships, method is Twitter API 1.0 deprecated
    • Developers can now pass an array as a parameter to Twitter API methods and they will be automatically joined by a comma and converted to a string
    • endpoints.py now contains EndpointsMixin (rather than the previous api_table dict) for Twython, which enables Twython to use functions declared in the Mixin.
    • Added OAuth 2 authentication (Application Only) for when you want to make read-only calls to Twitter without having to go through the whole user authentication ritual (see docs for usage)
    • Added obtain_access_token to obtain an OAuth 2 Application Only read-only access token
    • construct_api_url now accepts keyword arguments like other Twython methods (e.g. instead of passing {'q': 'twitter', 'result_type': 'recent'}, pass q='twitter', result_type='recent')
    • Pass client_args to the Twython __init__ to manipulate request variables. client_args accepts a dictionary of keywords and values that accepted by requests (http://docs.python-requests.org/en/latest/api/#sessionapi) [ex. headers, proxies, verify(SSL verification)] and the "request" section directly below it.
    • Added get_application_rate_limit_status API method for returning the current rate limits for the specified source
    • Added invalidate_token API method which allows registed apps to revoke an access token presenting its client credentials
    • get_lastfunction_header now accepts a default_return_value parameter. This means that if you pass a second value (ex. Twython.get_lastfunction_header('x-rate-limit-remaining', 0)) and the value is not found, it returns your default value

    To-do

    • [x] Add file encoding to all files # -*- coding: utf-8 -*-
    • [x] Add file description to all Twython api files
    • [x] Remove deprecated variables fixes #185
    • [x] Remove support for camelCase functions fixes #199
    • [x] Substitute api_table for actual functions (EndpointsMixin) fixes #211
    • [x] Better way to pass requests config fixes #213
    opened by michaelhelmick 15
  •  UnicodeDecodeError'ascii' codec can't decode byte 0xff in position 247: ordinal not in range(128)

    UnicodeDecodeError'ascii' codec can't decode byte 0xff in position 247: ordinal not in range(128)

    please help, update status with normal message is fine but with media, i get this error :(

    from twython import Twython

    twitter = Twython( twitter_token = '52IKIxxxx', twitter_secret = 'SvwK4xmxxxx', oauth_token = '5164xxxxxxx', oauth_token_secret = 'kVkrHxxxxxx' )

    twitter.updateStatus(status='hello tweet from raspberry pi 1.47am') twitter.updateStatusWithMedia("/home/pi/teddy.jpg", status='hello!')

    image of error http://i.stack.imgur.com/5W1Bq.png

    opened by husainihisan 15
  • Streaming is one post behind

    Streaming is one post behind

    Good Morning I am trying to stream tweets that are aimed at a user, so the line looks like stream.statuses.filter(track="@RexFuzzle") However I see that in order for it to update and print the output I need to tweet to the account twice and on the second tweet is prints the first one, on the third tweet is prints the second one... etc. Is this standard for streaming?

    opened by grantstephens 14
  • Using updateStatusWithMedia with in-memory image data

    Using updateStatusWithMedia with in-memory image data

    Back in 2.7, I could make the following call:

    t._media_update(settings.TWITTER_SHARE_URL,
        {'media[]': image_data}, status=message)
    

    But the internal _media_update function has since been removed, so I can't upgrade Twython. Any chance it could come back or some other solution for posting in-memory image data could be added?

    Or perhaps I'm missing something and there's a way to do this with the latest Twython?

    Thanks!

    opened by danxshap 14
  • Added oauth_verifier arg

    Added oauth_verifier arg

    Since Twitter now enforces OAuth 1.0a the oauth_verifier attached to the callback_url has to be passed to final authentication via GET. Added a new arg for this.

    opened by hansenrum 14
  • docs: Fix a few typos

    docs: Fix a few typos

    There are small typos in:

    • docs/usage/advanced_usage.rst
    • docs/usage/basic_usage.rst
    • docs/usage/special_functions.rst
    • docs/usage/starting_out.rst
    • tests/test_endpoints.py
    • twython/endpoints.py
    • twython/streaming/api.py

    Fixes:

    • Should read received rather than recieved.
    • Should read paginated rather than pagintated.
    • Should read multiple rather than mutiple.
    • Should read membership rather than memberhips.
    • Should read manipulate rather than maninpulate.
    • Should read explicitly rather than explicity.
    • Should read destroy rather than destory.
    • Should read authentication rather than autentication.
    • Should read actual rather than acutal.

    Semi-automated pull request generated by https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md

    opened by timgates42 0
  • Add support for Twitter API v2

    Add support for Twitter API v2

    As of 2021-11-15, new users can only use the v2 version of the API unless they are granted elevated access:

    Twitter API returned a 403 (Forbidden), You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve

    Unfortunately, twython appears to be hard-coded to v1, or at least I did not find out how to use the v2 endpoints. It would be great if support or docs for this could be added!

    opened by LinqLover 1
  • TwythonStreamer on_error in examples and documentation is wrong

    TwythonStreamer on_error in examples and documentation is wrong

    This pull request added headers to the on_error call: https://github.com/ryanmcgrath/twython/pull/504

    The issue is that all other the examples and documentation show on_error as taking two parameters, so they are all broken. I copied the code from here: https://twython.readthedocs.io/en/latest/usage/streaming_api.html

    Looking at the codebase, here are the places that need to be updated: https://github.com/ryanmcgrath/twython/blob/master/docs/usage/streaming_api.rst https://github.com/ryanmcgrath/twython/blob/master/examples/stream.py https://github.com/ryanmcgrath/twython/blob/master/tests/test_streaming.py

    I can try submitting a PR requests, though updating those seems fairly trivial.

    opened by EhsanKia 0
  •  'Twython' from partially initialized module 'twython' (most likely due to a circular import)

    'Twython' from partially initialized module 'twython' (most likely due to a circular import)

    python 3.8.2 twython 3.8.2

    ImportError: cannot import name 'Twython' from partially initialized module 'twython' (most likely due to a circular import)

    import sys import string from twython import Twython

    twitter = Twython('Insert Consumer Key Here', 'Insert Consumer Secret Key',oauth_version=2) Access_token = twitter.obtain_access_token() t = Twython('Insert Consumer Key', access_token=Access_token)

    user_timeline = t.search(q='@puremichigan', count=20, include_rts=1)

    for tweets in user_timeline['statuses']: print(tweets['text'] +"\n")

    opened by NilSagor 0
  • send_direct_message returning 404 page not exist

    send_direct_message returning 404 page not exist

    I'm trying to send DM with this it's returning 404 sorry page not exist.

    here's what I tried api.send_direct_message(type='message_create', recipient_id="id", message_data="test message"))

    opened by sherluck08 3
  • include_email param in verify_credentials not working

    include_email param in verify_credentials not working

    Hello Team,

    Thanks for the fantastic job, I am loving Twython!! However, I ran into a small issue, I hope you'd have seen it already, and might have a solution for me. "include_email" parameter isn't working for me, I am not able to get user email. Yes, I've enabled "Request email address" in "Advanced Permissions". I've tried the following variations:

    1. include_email=1
    2. include_email="1"
    3. include_email = True
    4. include_email = "true"
    5. include_email= "True"

    I don't see what else can I try. Can you please help?

    opened by ghost 0
Releases(v3.9.1)
  • v3.9.1(Jul 16, 2021)

  • 3.4.0(Apr 30, 2016)

    • Added upload_video endpoint
    • Fix quoted status checks in html_for_tweet
    • Fix html_for_tweet method response when hashtag/mention is a substring of another
    Source code(tar.gz)
    Source code(zip)
  • 3.3.0(Mar 21, 2016)

    3.3.0 (2015-18-07)

    • Added support for muting users
    • Fix typos in documentation
    • Updated documentation examples
    • Added dynamic filtering to streamer
    Source code(tar.gz)
    Source code(zip)
  • 3.1.2(Mar 21, 2016)

    3.1.2 (2013-12-05)

    • Fixed Changelog (HISTORY.rst)

    3.1.1 (2013-12-05)

    • Update requests version to 2.1.0.
    • Fixed: Streaming issue where Exceptions in handlers or on_success which subclass ValueError would previously be caught and reported as a JSON decoding problem, and on_error() would be called (with status_code=200)
    • Fixed issue where XML was returned when bad tokens were passed to get_authorized_tokens
    • Fixed import for setup causing installation to fail on some devices (eg. Nokia N9/MeeGo)

    3.1.0 (2013-09-25)

    • Added html_for_tweet static method. This method accepts a tweet object returned from a Twitter API call and will return a string with urls, mentions and hashtags in the tweet replaced with HTML.
    • Pass client_args to the streaming __init__, much like in core Twython (you can pass headers, timeout, hooks, proxies, etc.).
    • Streamer has new parameter handlers which accepts a list of strings related to functions that are apart of the Streaming class and start with "on_". i.e. ['delete'] is passed, when 'delete' is received from a stream response; on_delete will be called.
    • When an actual request error happens and a RequestException is raised, it is caught and a TwythonError is raised instead for convenience.
    • Added "cursor"-like functionality. Endpoints with the attribute iter_mode will be able to be passed to Twython.cursor and returned as a generator.
    • Twython.search_gen has been deprecated. Please use twitter.cursor(twitter.search, q='your_query') instead, where twitter is your Twython instance.
    • Added methods get_list_memberships, get_twitter_configuration, get_supported_languages, get_privacy_policy, get_tos
    • Added auth_endpoint parameter to Twython.__init__ for cases when the right parameters weren't being shown during the authentication step.
    • Fixed streaming issue where results wouldn't be returned for streams that weren't so active (See https://github.com/ryanmcgrath/twython/issues/202#issuecomment-19915708)
    • Streaming API now uses _transparent_params so when passed True or False or an array, etc. Twython formats it to meet Twitter parameter standards (i.e. ['ryanmcgrath', 'mikehelmick', 'twitterapi'] would convert to string 'ryanmcgrath,mikehelmick,twitterapi')
    Source code(tar.gz)
    Source code(zip)
Owner
Ryan McGrath
Privacy, Rust, Apple and everything in-between. Other tech stacks welcome too, as long as what we're building is cool.
Ryan McGrath
A high level library for building Discord bots.

Qord A high level library for building Discord bots. 🚧 This library is currently in development. Questions that you are having What is this? This is

Izhar Ahmad 16 May 14, 2022
An API wrapper for Henrik's Unofficial VALORANT API

ValorantAPI.py An API wrapper for Henrik's Unofficial VALORANT API Warning!! This project is still in beta and only contains barely anything yet. If y

Jakkaphat Chalermphanaphan 0 Feb 04, 2022
Download videos from Youtube and other platforms through a Telegram Bot

ytdl-bot Download videos from YouTube and other platforms through a Telegram Bot Usage: https://t.me/benny_ytdlbot Send link from YouTube directly to

Telegram Bot Collection 289 Jan 03, 2023
A Python script to backup all repos (public or private) of a user.

GithubBackupAllRepos A Python script to backup all repos (public or private) of a user. Features Clone public and private repos Load specified SSH key

Podalirius 15 Jan 03, 2023
Pdisk Uploader Bot

pdisk-bot pdisk uploader telegram bot How To Use Configs TG_BOT_TOKEN - Get bot token from @BotFather API_ID - From my.telegram.org API_HASH - From my

lokaman chendekar 25 Oct 21, 2022
ServiceX DID Finder Girder

ServiceX_DID_Finder_Girder Access datasets for ServiceX from yt Hub Finding datasets This DID finder is designed to take a collection id (https://gird

1 Dec 07, 2021
The official Discord Python framework for thenewboston blockchain.

Project Setup Follow the steps below to set up the project on your environment. Mac Setup Homebrew requires the Xcode command-line tools from Apple's

Bucky Roberts 18 Jul 15, 2022
Explorer is a Autonomous (self-hosted) Bittorrent Network Search Engine.

Explorer Explorer is a Autonomous (self-hosted) Bittorrent Network Search Engine. About The Project Screenshots Supported features Number Feature 1 DH

51 Jun 14, 2022
Assistant made in python to control your spotify via voice

Spotify-Assistant Assistant made in python to control your spotify via voice Overview 🚀 PLAY, PAUSE, NEXT, PREVIOUS, VOLUME COMMANDS 📝 Toast notific

Mauri 6 Jan 18, 2022
数字货币动态趋势网格,随着行情变动。目前实盘月化10%。目前支持币安,未来上线火币、OKEX。

数字货币动态趋势网格,随着行情变动。目前实盘月化10%。目前支持币安,未来上线火币、OKEX。

幸福村的码农 98 Dec 27, 2022
Useful tools for building interactions in Python

discord-interactions-python Types and helper functions for Discord Interactions webhooks. Installation Available via pypi: pip install discord-interac

Discord 77 Dec 07, 2022
4 Oct 28, 2021
Visionary-OS: open source discord bot

Visionary-OS Our Visionary open source discord bot. Our goal is to create a discord bot, which is hosted by us, but every member of our community can

8 Jan 27, 2022
Unofficial Python wrapper for official Hacker News API

haxor Unofficial Python wrapper for official Hacker News API. Installation pip install haxor Usage Import and initialization: from hackernews import H

147 Sep 18, 2022
100d002 - Simple program to calculate the tip amount and split the bill between all guests

Day 2 - Tip Calculator Simple program to calculate the tip amount and split the

Andre Schickhoff 1 Jan 24, 2022
A way to export your saved reddit posts to a Notion table.

reddit-saved-to-notion A way to export your saved reddit posts and comments to a Notion table.Uses notion-sdk-py and praw for interacting with Notion

19 Sep 12, 2022
A Python API For Questionnaire

Инструкция по разворачиванию приложения Окружение проекта: python 3.8 Django 2.2.10 djangorestframework Склонируйте репозиторий с помощью git: git clo

2 Feb 14, 2022
Pixiv 爬虫,使用 Python 实现。支持批量下载、上传到图床。

用 Python 实现的 Pixiv 爬虫,支持批量下载和上传。 随机图片 API: https://loliapi.ml/ Deploy Github Action 集成部署 建议使用本方法部署,相较于本地部署,无需搭建环境,全程在线上完成。并且使用国外服务器下载、上传,网络更加通畅。 Fork

18 Feb 26, 2022
Pls give vaccine.

Pls Give Vaccine A script to spam yourself with vaccine notifications. Explore the docs » View Demo · Report Bug · Request Feature Table of Contents A

Rohan Mukherjee 3 Oct 27, 2021