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
This library is for simplified work with the sms-man.com API

SMSMAN Public API Python This is a lightweight library that works as a connector to Sms-Man public API Installation pip install smsman Documentation h

13 Nov 19, 2022
A Twitter bot developed in Python using the Tweepy library and hosted in AWS.

Twitter Cameroon: @atangana_aron A Twitter bot developed in Python using the Tweepy library and hosted in AWS. https://twitter.com/atangana_aron Cost

1 Jan 30, 2022
Messing around with GitHub API to look at omicron build times

gh-workflow-runs This is a very simple tool to dump out basic information about workflow runs for a GitHub repo. The structure is based on gh-subscrip

David Pacheco 1 Nov 30, 2021
This is a walkthrough about understanding the #BoF machine present in the #OSCP exam.

Buffer Overflow methodology Introduction These are 7 simple python scripts and a methodology to ease (not automate !) the exploitation. Each script ta

3isenHeiM 53 Dec 08, 2022
Anime Streams Scrapper for Telegram Publicly Available for everyone to use

AniRocks Project Structure: ╭─ bot ├──── plugins: directory stored all the plugins ├──── utils: a directory of Utilities to help bot Client to create

ポキ 11 Oct 28, 2022
Slack Developer Kit for Python

Python Slack SDK The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you

SlackAPI 3.5k Jan 02, 2023
A Flask inspired, decorator based API wrapper for Python-Slack.

A Flask inspired, decorator based API wrapper for Python-Slack. About Tangerine is a lightweight Slackbot framework that abstracts away all the boiler

Nick Ficano 149 Jun 30, 2022
BanAllBot - Telegram Code To Ban All Group Members very fast

BanAllBot Telegram Code To Ban All Group Members very fast FORK AND KANG WITH CR

27 May 13, 2022
Discord Remote Administration Tool fully written in Python3.

DiscordRAT Discord Remote Administration Tool fully written in Python3. This is a RAT controlled over Discord with over 50 post exploitation modules.

hozzywozzy 2 Feb 06, 2022
Campsite Reservation Cancellation Finder (Yellowstone National Park)

yellowstone-camping yellowstone-camping is a Campsite Reservation Cancellation Finder for Yellowstone National Park. This simple Python application wi

Justin Flannery 7 Aug 05, 2022
Python Business Transactions Library - ContractsPY

Python Business Transactions Library - ContractsPY Declare and define business transactions in Python. Use the contracts library to validate business

Arzu Huseynov 7 Jun 21, 2022
Maintained Fork of Jishaku For nextcord

Onami a debugging and utility extension for nextcord bots Read the documentation online. Fork Onami is a actively maintained fork of Jishaku for nextc

RPS 11 Dec 14, 2022
A simple bot to upload file to various cloud servers.

Cloudsy Bot A simple bot to upload file to various cloud servers. Variables API_HASH Your API Hash from my.telegram.org API_ID Your API ID from my.tel

Flying Santas 8 Oct 31, 2022
This is a Innexia Chat Bot Open Source Code 🤬

⚡ Innexia ⚡ A Powerful, Smart And Simple Chat Bot ... Written with Python... Available on Telegram as @InnexiaChatBot ❤️ Support ⭐️ Thanks to everyone

Dark Cyber 4 Oct 02, 2022
A python script to download twitter space, only works on running spaces (for now).

A python script to download twitter space, only works on running spaces (for now).

279 Jan 02, 2023
This bot will send you an email or notify you via telegram & discord if dolar/lira parity breaks a record.

Dolar Rekor Kırdı Mı? This bot will send you an email or notify you via Telegram & Discord if Dolar/Lira parity breaks a record. Mailgun can be used a

Yiğit Göktuğ Budanur 2 Oct 14, 2021
A modular Telegram Python bot running on python3 with a sqlalchemy database

Nao Tomori Robot Found Me On Telegram As Nao Tomori 🌼 A modular Telegram Python bot running on python3 with a sqlalchemy database. How to setup/deplo

Sena 84 Jan 04, 2023
A python package that fetches tweets and user information in a very pythonic manner.

Tweetsy Tweetsy uses Twitter's underlying API to fetch user information and tweets and present it in a human-friendly way. What makes Tweetsy special

Sakirul Alam 5 Nov 12, 2022
A script to find the people whom you follow, but they don't follow you back

insta-non-followers A script to find the people whom you follow, but they don't follow you back Dependencies: python3 libraries - instaloader, getpass

Ritvik 5 Jul 03, 2022
Remedy when Amazon ECR is not running basic scans for container CVEs.

Welcome to your CDK Python project! This is a blank project for Python development with CDK. The cdk.json file tells the CDK Toolkit how to execute yo

4n6ir 4 Nov 05, 2022