![Oracle Drags Its Feet in the JavaScript Trademark Dispute](https://cdn.sanity.io/images/cgdhsj6q/production/919c3b22c24f93884c548d60cbb338e819ff2435-1024x1024.webp?w=400&fit=max&auto=format)
Security News
Oracle Drags Its Feet in the JavaScript Trademark Dispute
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs
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!
Install Twython via pip:
$ pip install twython
If you're on a legacy project that needs Python 2.7 support, you can install the last version of Twython that supported 2.7:
pip install twython==3.7.0`
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 is available at https://twython.readthedocs.io/en/latest/
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
Now, you'll want to create a Twython instance with your Consumer Key
and Consumer Secret
:
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']
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.
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.
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)
twitter.get_home_timeline()
This method makes use of dynamic arguments, read more about them.
twitter.update_status(status='See how easy using Twython is!')
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 ryan@venodesigns.net.
Or if I'm to busy to answer, feel free to ping mikeh@ydekproductions.com as well.
Follow us on Twitter:
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!
html_for_tweet()
parsingreturn_pages
keyword argumentcreate_metadata
endpointhtml_for_tweet()
Twython.html_for_tweet()
Twython.html_for_tweet()
Twython.upload_video()
upload_video
endpointhtml_for_tweet
html_for_tweet
method response when hashtag/mention is a substring of anotherlookup_status
function to endpoints.py
cursor
to return full pages rather than individual resultscursor
now uses while loop rather than recursionresponses
to mock API calls in testsretry_after
attribute to TwythonRateLimitError
upload_media
method to Twython
in favor of update_with_media
update_with_media
per Twitter API 1.1 (https://dev.twitter.com/rest/reference/post/statuses/update_with_media)requests
and requests-oauthlib
in requirements.txt
requests
version to 2.1.0.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)get_authorized_tokens
setup
causing installation to fail on some devices (eg. Nokia N9/MeeGo)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.client_args
to the streaming __init__
, much like in core Twython (you can pass headers, timeout, hooks, proxies, etc.).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.RequestException
is raised, it is caught and a TwythonError
is raised instead for convenience.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.get_list_memberships
, get_twitter_configuration
, get_supported_languages
, get_privacy_policy
, get_tos
auth_endpoint
parameter to Twython.__init__
for cases when the right parameters weren't being shown during the authentication step._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')twython/twython.py
to twython/api.py
in attempt to make structure look a little neatergetHomeTimeline
is now get_home_timeline
)shorten_url
. With the requests
library, shortening a URL on your own is simple enoughtwitter_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
respectivelycallback_url
is now passed through Twython.get_authentication_tokens
test_twython.py
docstrings per http://www.python.org/dev/peps/pep-0257/get_list_memberships
, method is Twitter API 1.0 deprecatedendpoints.py
now contains EndpointsMixin
(rather than the previous api_table
dict) for Twython, which enables Twython to use functions declared in the Mixin.obtain_access_token
to obtain an OAuth 2 Application Only read-only access tokenconstruct_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'
)client_args
to the Twython __init__
to manipulate request variables. client_args
accepts a dictionary of keywords and values that accepted by requests
(Session API <http://docs.python-requests.org/en/latest/api/#sessionapi>
_) [ex. headers, proxies, verify(SSL verification)] and the "request" section directly below it.get_application_rate_limit_status
API method for returning the current rate limits for the specified sourceinvalidate_token
API method which allows registed apps to revoke an access token presenting its client credentialsget_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 valuesearch_gen
get_lastfunction_header
to actually do what its docstring says, returns None
if header is not found__init__
didn't need to have self.auth
and self.headers
because they were never used anywhere else but the __init__
disconnect
method to TwythonStreamer
, allowing users to disconnect as they desireTwythonStreamError
docstring, also allow importing it from twython
TwythonStreamError
when stream line can't be decoded. Instead, sends signal to TwythonStreamer.on_error
get_retweeters_ids
methodTwythonDeprecationWarning
on camelCase functions if the camelCase was the same as the PEP8 function (i.e. Twython.retweet
did not change)get_authentication_tokens
to accomedate those using OOB authorization (non web clients)__repr__
definition for Twython, when calling only returning <Twython: APP_KEY>Twython.construct_api_url
, uses "transparent" parameters (see 4th bullet in this version for explaination)requests
and requests-oauthlib
requirements, fixing posting files AND post data together, making authenticated requests in general in Python 3.3updateStatus()
is now update_status()
)TwythonStreamer
to aid users in a friendly streaming experience (streaming examples in examples
and README's have been updated as well)Twython
now requires requests-oauthlib
0.3.1, fixes #154 (unable to upload media when sending POST data with the file)HISTORY.rst
to start tracking history of changestwitter_endpoints.py
to endpoints.py
for cleanlinesscompat.py
for compatability with Python 2.6 and greater__author__
to __init__.py
version.py
to store the current Twython version, instead of repeating it twice -- it also had to go into it's own file because of dependencies of requests
and requests-oauthlib
, install would fail because those libraries weren't installed yet (on fresh install of Twython)find_packages()
from setup.py
, only one package (we can just define it)python setup.py publish
is faster to type and easier to remember than python setup.py sdist upload
base_url
from endpoints.py
because we're just repeating it in Twython.__init__
Twython.get_authentication_tokens()
now takes callback_url
argument rather than passing the callback_url
through Twython.__init__
, callback_url
is only used in the get_authentication_tokens
method and nowhere else (kept in init though for backwards compatability)warnings.simplefilter('default')
line in twython.py
for Python 2.7 and greater to display Deprecation Warnings in consoletwitter_token
, twitter_secret
and callback_url
in Twython.__init__
requests
isn't greedy about variables that can't be converted to unicode anymorebulkUserLookup
(please use lookupUser
instead), removed getProfileImageUrl
(will be completely removed from Twitter API on May 7th, 2013)requests
makes it easy for developers to implement their own url shortening in their app (see https://github.com/ryanmcgrath/twython/issues/184)ssl_verify
parameter, defaults True. Set False if you're having development server issues_media_update
function, we could have always just used self.post
AttributeError
when trying to decode the JSON response via Response.json()
simplejson
dependencydestroyDirectMessage
, createBlock
, destroyBlock
endpoints in twitter_endpoints.py
getProfileBannerSizes
method to twitter_endpoints.py
get_authorized_tokens
updateProfileBannerImage
to use v1.1 endpointshowOwnedLists
methodgetMentionsTimeline
in twitter_endpoints.py
twitter_endpoints.py
to better reflect order of API endpoints on the Twitter API v1.1 docs siteFAQs
Actively maintained, pure Python wrapper for the Twitter API. Supports both normal and streaming Twitter APIs
We found that twython demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Oracle seeks to dismiss fraud claims in the JavaScript trademark dispute, delaying the case and avoiding questions about its right to the name.
Security News
The Linux Foundation is warning open source developers that compliance with global sanctions is mandatory, highlighting legal risks and restrictions on contributions.
Security News
Maven Central now validates Sigstore signatures, making it easier for developers to verify the provenance of Java packages.