Package: twython
TwythonTwythonis 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!FeaturesQuery data for:User informationTwitter listsTimelinesDirect Messagesand anything found inthe docsImage Uploading:Update user status with an imageChange user avatarChange user background imageChange user banner imageOAuth 2 Application Only (read-only) SupportSupport for Twitter's Streaming APISeamless Python 3 support!InstallationInstall Twython via pip:$pipinstalltwythonIf 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:gitclonegit://github.com/ryanmcgrath/twython.gitcdtwython
pythonsetup.pyinstallDocumentationDocumentation is available athttps://twython.readthedocs.io/en/latest/Starting OutFirst, you'll want to head over tohttps://apps.twitter.comand register an application!After you register, grab your applicationsConsumer KeyandConsumer Secretfrom 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 thisisthe authentication for you!First, you'll want to import TwythonfromtwythonimportTwythonObtain Authorization URLNow, you'll want to create a Twython instance with yourConsumer KeyandConsumer Secret:Only passcallback_urltoget_authentication_tokensif your application is a Web ApplicationDesktop and Mobile Applicationsdo notrequire a callback_urlAPP_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 theauthvariable, save theoauth_tokenandoauth_token_secretfor later use (these are not the final auth tokens). In Django or other web frameworks, you might want to store it to a session variableOAUTH_TOKEN=auth['oauth_token']OAUTH_TOKEN_SECRET=auth['oauth_token_secret']Send the user to the authentication url, you can obtain it by accessingauth['auth_url']Handling the CallbackIf your application is a Desktop or Mobile Applicationoauth_verifierwill be the PIN codeAfter they authorize your application to access some of their account details, they'll be redirected to the callback url you specified inget_authentication_tokens.You'll want to extract theoauth_verifierfrom the url.Django example:oauth_verifier=request.GET['oauth_verifier']Now that you have theoauth_verifierstored to a variable, you'll want to create a new instance of Twython and grab the final user tokenstwitter=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, seeour documentation.Dynamic Function ArgumentsKeyword 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 UsageFunction definitions (i.e. get_home_timeline()) can be found by reading over twython/endpoints.pyCreate a Twython instance with your application keys and the users OAuth tokensfromtwythonimportTwythontwitter=Twython(APP_KEY,APP_SECRET,OAUTH_TOKEN,OAUTH_TOKEN_SECRET)Authenticated Users Home Timelinetwitter.get_home_timeline()Updating StatusThis method makes use of dynamic arguments,read more about them.twitter.update_status(status='See how easy using Twython is!')Advanced UsageAdvanced Twython UsageStreaming with TwythonQuestions, Comments, etc?My hope is that Twython is so simple that you'd neverhaveto ask any questions, but if you feel the need to contact me for this (or other) reasons, you can hit me up atryan@venodesigns.net.Or if I'm to busy to answer, feel free to pingmikeh@ydekproductions.comas well.Follow us on Twitter:@ryanmcgrath@mikehelmickWant 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!History3.8.0 (2020-04-02)Bump release with latest patches from GitHub.Fix Direct Messages with patches from @manuelcortez.3.7.0 (2018-07-05)Fixes for cursoring API endpointsImprovehtml_for_tweet()parsingDocumentation cleanupDocumentation for cursor'sreturn_pageskeyword argumentUpdate links to Twitter API in documentationAddedcreate_metadataendpointRaise error for when cursor is not provided a callable3.6.0 (2017-23-08)Improve replacing of entities with links inhtml_for_tweet()Update classifiers for PyPI3.5.0 (2017-06-06)Added support for "symbols" inTwython.html_for_tweet()Added support for extended tweets inTwython.html_for_tweet()You can now check progress of video uploads to Twitter when usingTwython.upload_video()3.4.0 (2016-30-04)Addedupload_videoendpointFix quoted status checks inhtml_for_tweetFixhtml_for_tweetmethod response when hashtag/mention is a substring of another3.3.0 (2015-18-07)Added support for muting usersFix typos in documentationUpdated documentation examplesAdded dynamic filtering to streamer3.2.0 (2014-10-30)PEP8'd some codeAddedlookup_statusfunction toendpoints.pyAdded keyword argument tocursorto return full pages rather than individual resultscursornow uses while loop rather than recursionFixed issue where Twython was unnecessarily disabling compressionUsingresponsesto mock API calls in testsFixed some typos in  documentationAddedretry_afterattribute toTwythonRateLimitErrorAddedupload_mediamethod toTwythonin favor ofupdate_with_mediaDeprecatingupdate_with_mediaper Twitter API 1.1 (https://dev.twitter.com/rest/reference/post/statuses/update_with_media)Unpinrequestsandrequests-oauthlibinrequirements.txt3.1.2 (2013-12-05)Fixed Changelog (HISTORY.rst)3.1.1 (2013-12-05)Updaterequestsversion to 2.1.0.Fixed: Streaming issue whereExceptionsin handlers oron_successwhich subclassValueErrorwould previously be caught and reported as a JSON decoding problem, andon_error()would be called (with status_code=200)Fixed issue where XML was returned when bad tokens were passed toget_authorized_tokensFixed import forsetupcausing installation to fail on some devices (eg. Nokia N9/MeeGo)3.1.0 (2013-09-25)Addedhtml_for_tweetstatic 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.Passclient_argsto the streaming__init__, much like in core Twython (you can pass headers, timeout, hooks, proxies, etc.).Streamer has new parameterhandlerswhich 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_deletewill be called.When an actual request error happens and aRequestExceptionis raised, it is caught and aTwythonErroris raised instead for convenience.Added "cursor"-like functionality. Endpoints with the attributeiter_modewill be able to be passed toTwython.cursorand returned as a generator.Twython.search_genhas been deprecated. Please usetwitter.cursor(twitter.search, q='your_query')instead, wheretwitteris yourTwythoninstance.Added methodsget_list_memberships,get_twitter_configuration,get_supported_languages,get_privacy_policy,get_tosAddedauth_endpointparameter toTwython.__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 (Seehttps://github.com/ryanmcgrath/twython/issues/202#issuecomment-19915708)Streaming API now uses_transparent_paramsso when passedTrueorFalseor an array, etc. Twython formats it to meet Twitter parameter standards (i.e. ['ryanmcgrath', 'mikehelmick', 'twitterapi'] would convert to string 'ryanmcgrath,mikehelmick,twitterapi')3.0.0 (2013-06-18)Changedtwython/twython.pytotwython/api.pyin attempt to make structure look a little neaterRemoved all camelCase function access (anything likegetHomeTimelineis nowget_home_timeline)Removedshorten_url. With therequestslibrary, shortening a URL on your own is simple enoughtwitter_token,twitter_secretandcallback_urlare no longer passed toTwython.__init__twitter_tokenandtwitter_secrethave been replaced withapp_keyandapp_secretrespectivelycallback_urlis now passed throughTwython.get_authentication_tokensUpdatetest_twython.pydocstrings perhttp://www.python.org/dev/peps/pep-0257/Removedget_list_memberships, method is Twitter API 1.0 deprecatedDevelopers 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 stringendpoints.pynow containsEndpointsMixin(rather than the previousapi_tabledict) 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)Addedobtain_access_tokento obtain an OAuth 2 Application Only read-only access tokenconstruct_api_urlnow accepts keyword arguments like other Twython methods (e.g. instead of passing{'q': 'twitter', 'result_type': 'recent'}, passq='twitter', result_type='recent')Passclient_argsto the Twython__init__to manipulate request variables.client_argsaccepts a dictionary of keywords and values that accepted byrequests(Session API <http://docs.python-requests.org/en/latest/api/#sessionapi>_) [ex. headers, proxies, verify(SSL verification)] and the "request" section directly below it.Addedget_application_rate_limit_statusAPI method for returning the current rate limits for the specified sourceAddedinvalidate_tokenAPI method which allows registed apps to revoke an access token presenting its client credentialsget_lastfunction_headernow accepts adefault_return_valueparameter. 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 value2.10.1 (2013-05-29)More test coverage!Fixsearch_genFixedget_lastfunction_headerto actually do what its docstring says, returnsNoneif header is not foundUpdated some internal API code,__init__didn't need to haveself.authandself.headersbecause they were never used anywhere else but the__init__Addeddisconnectmethod toTwythonStreamer, allowing users to disconnect as they desireUpdatedTwythonStreamErrordocstring, also allow importing it fromtwythonNo longer raiseTwythonStreamErrorwhen stream line can't be decoded. Instead, sends signal toTwythonStreamer.on_errorAllow for (int, long, float) params to be passed to Twython Twitter API functions in Python 2, and (int, float) in Python 32.10.0 (2013-05-21)Addedget_retweeters_idsmethodFixedTwythonDeprecationWarningon camelCase functions if the camelCase was the same as the PEP8 function (i.e.Twython.retweetdid not change)Fixed error message bubbling when error message returned from Twitter was not an array (i.e. if you try to retweet something twice, the error is not found at index 0)Added "transparent" parameters for making requests, meaning users can pass bool values (True, False) to Twython methods and we convert your params in the background to satisfy the Twitter API. Also, file objects can now be passed seamlessly (see examples in README and in /examples dir for details)Callback URL is optional inget_authentication_tokensto accomedate those using OOB authorization (non web clients)Not part of the python package, but tests are now available along with Travis CI hooksAdded__repr__definition for Twython, when calling only returning <Twython: APP_KEY>Cleaned upTwython.construct_api_url, uses "transparent" parameters (see 4th bullet in this version for explaination)Updaterequestsandrequests-oauthlibrequirements, fixing posting files AND post data together, making authenticated requests in general in Python 3.32.9.1 (2013-05-04)"PEP8" all the functions. Switch functions from camelCase() to underscore_funcs(). (i.e.updateStatus()is nowupdate_status())2.9.0 (2013-05-04)Fixed streaming issue #144, addedTwythonStreamerto aid users in a friendly streaming experience (streaming examples inexamplesand README's have been updated as well)Twythonnow requiresrequests-oauthlib0.3.1, fixes #154 (unable to upload media when sending POST data with the file)2.8.0 (2013-04-29)Added aHISTORY.rstto start tracking history of changesUpdatedtwitter_endpoints.pytoendpoints.pyfor cleanlinessRemoved twython3k directory, no longer neededAddedcompat.pyfor compatability with Python 2.6 and greaterAdded some ascii art, moved description of Twython and__author__to__init__.pyAddedversion.pyto store the current Twython version, instead of repeating it twice -- it also had to go into it's own file because of dependencies ofrequestsandrequests-oauthlib, install would fail because those libraries weren't installed yet (on fresh install of Twython)Removedfind_packages()fromsetup.py, only one package (we can just define it)added quick publish method for Ryan and I:python setup.py publishis faster to type and easier to remember thanpython setup.py sdist uploadRemovedbase_urlfromendpoints.pybecause we're just repeating it inTwython.__init__Twython.get_authentication_tokens()now takescallback_urlargument rather than passing thecallback_urlthroughTwython.__init__,callback_urlis only used in theget_authentication_tokensmethod and nowhere else (kept in init though for backwards compatability)Updated README to better reflect current Twython codebaseAddedwarnings.simplefilter('default')line intwython.pyfor Python 2.7 and greater to display Deprecation Warnings in consoleAdded Deprecation Warnings for usage oftwitter_token,twitter_secretandcallback_urlinTwython.__init__Headers now always include the User-Agent as Twython vXX unless User-Agent is overwrittenRemoved senseless TwythonError thrown if method is not GET or POST, who cares -- if the user passes something other than GET or POST just let Twitter return the error that they messed upRemoved conversion to unicode of (int, bool) params passed to a requests.requestsisn't greedy about variables that can't be converted to unicode anymoreRemovedbulkUserLookup(please uselookupUserinstead), removedgetProfileImageUrl(will be completely removed from Twitter API on May 7th, 2013)Updated shortenUrl to actually work for those using it, but it is being deprecated sincerequestsmakes it easy for developers to implement their own url shortening in their app (seehttps://github.com/ryanmcgrath/twython/issues/184)Twython Deprecation Warnings will now be seen in shell when using Python 2.7 and greaterTwython now takesssl_verifyparameter, defaults True. Set False if you're having development server issuesRemoved internal_media_updatefunction, we could have always just usedself.post2.7.3 (2013-04-12)Fixed issue where Twython Exceptions were not being logged correctly2.7.2 (2013-04-08)FixedAttributeErrorwhen trying to decode the JSON response viaResponse.json()2.7.1 (2013-04-08)RemovedsimplejsondependencyFixeddestroyDirectMessage,createBlock,destroyBlockendpoints intwitter_endpoints.pyAddedgetProfileBannerSizesmethod totwitter_endpoints.pyMade oauth_verifier argument required inget_authorized_tokensUpdateupdateProfileBannerImageto use v1.1 endpoint2.7.0 (2013-04-04)NewshowOwnedListsmethod2.7.0 (2013-03-31)Added missing slash togetMentionsTimelineintwitter_endpoints.py2.6.0 (2013-03-29)Updatedtwitter_endpoints.pyto better reflect order of API endpoints on the Twitter API v1.1 docs site