Package: twitter
Python Twitter ToolsThe Minimalist Twitter API for Python is a Python API for Twitter,
everyone's favorite Web 2.0 Facebook-style status updater for people
on the go.Also included is a Twitter command-line tool for getting your friends'
tweets and setting your own tweet from the safety and security of your
favorite shell and an IRC bot that can announce Twitter updates to an
IRC channel.For more information:install thepackagepip install twitterimport thetwitterpackage and runhelp()on itruntwitter -hfor command-line tool helptwitter - The Command-Line ToolThe command-line tool lets you do some awesome things:view your tweets, recent replies, and tweets in listsview the public timelinefollow and unfollow (leave) friendsvarious output formats for tweet informationThe bottom line: typetwitter, receive tweets.twitterbot - The IRC BotThe IRC bot is associated with a Twitter account (either your own account or an
account you create for the bot). The bot announces all tweets from friends
it is following. It can be made to follow or leave friends through IRC /msg
commands.twitter-logtwitter-logis a simple command-line tool that dumps all public
tweets from a given user in a simple text format. It is useful to get
a complete offsite backup of all your tweets. Runtwitter-logand
read the instructions.twitter-archiverandtwitter-followtwitter-archiver will log all the tweets posted by any user since they
started posting. twitter-follow will print a list of all of all the
followers of a user (or all the users that user follows).Programming with the Twitter API classesTheTwitterandTwitterStreamclasses are the key to building your own
Twitter-enabled applications.TheTwitterclassThe minimalist yet fully featured Twitter API class.Get RESTful data by accessing members of this class. The result
is decoded python objects (lists and dicts).The Twitter API is documented at:https://developer.twitter.com/en/docsThe list of most accessible functions is listed at:https://developer.twitter.com/en/docs/api-reference-indexExamples:fromtwitterimport*t=Twitter(auth=OAuth(token,token_secret,consumer_key,consumer_secret))# Get your "home" timelinet.statuses.home_timeline()# Get a particular friend's timelinet.statuses.user_timeline(screen_name="boogheta")# to pass in GET/POST parameters, such as `count`t.statuses.home_timeline(count=5)# to pass in the GET/POST parameter `id` you need to use `_id`t.statuses.show(_id=1234567890)# Update your statust.statuses.update(status="Using @boogheta's sweet Python Twitter Tools.")# Send a direct messaget.direct_messages.events.new(_json={"event":{"type":"message_create","message_create":{"target":{"recipient_id":t.users.show(screen_name="boogheta")["id"]},"message_data":{"text":"I think yer swell!"}}}})# Get the members of maxmunnecke's list "network analysis tools" (grab the list_id within the url) https://twitter.com/i/lists/1130857490764091392t.lists.members(owner_screen_name="maxmunnecke",list_id="1130857490764091392")# Favorite/like a statusstatus=t.statuses.home_timeline()[0]ifnotstatus['favorited']:t.favorites.create(_id=status['id'])# An *optional* `_timeout` parameter can also be used for API# calls which take much more time than normal or twitter stops# responding for some reason:t.users.lookup(screen_name=','.join(A_LIST_OF_100_SCREEN_NAMES),_timeout=1)# Overriding Method: GET/POST# you should not need to use this method as this library properly# detects whether GET or POST should be used, Nevertheless# to force a particular method, use `_method`t.statuses.oembed(_id=1234567890,_method='GET')# Send images along with your tweets:# - first just read images from the web or from files the regular way:withopen("example.png","rb")asimagefile:imagedata=imagefile.read()# - then upload medias one by one on Twitter's dedicated server#   and collect each one's id:t_upload=Twitter(domain='upload.twitter.com',auth=OAuth(token,token_secret,consumer_key,consumer_secret))id_img1=t_upload.media.upload(media=imagedata)["media_id_string"]id_img2=t_upload.media.upload(media=imagedata)["media_id_string"]# - finally send your tweet with the list of media ids:t.statuses.update(status="PTT ★",media_ids=",".join([id_img1,id_img2]))# Or send a tweet with an image (or set a logo/banner similarly)# using the old deprecated method that will probably disappear some dayparams={"media[]":imagedata,"status":"PTT ★"}# Or for an image encoded as base64:params={"media[]":base64_image,"status":"PTT ★","_base64":True}t.statuses.update_with_media(**params)# Attach text metadata to medias sent, using the upload.twitter.com route# using the _json workaround to send json arguments as POST body# (warning: to be done before attaching the media to a tweet)t_upload.media.metadata.create(_json={"media_id":id_img1,"alt_text":{"text":"metadata generated via PTT!"}})# or with the shortcut arguments ("alt_text" and "text" work):t_upload.media.metadata.create(media_id=id_img1,text="metadata generated via PTT!")Searching Twitter:# Search for the latest tweets about #pycont.search.tweets(q="#pycon")# Search for the latest tweets about #pycon, using [extended mode](https://developer.twitter.com/en/docs/tweets/tweet-updates)t.search.tweets(q="#pycon",tweet_mode='extended')Retrying after reaching the API rate limitSimply create theTwitterinstance with the argumentretry=True, then the
HTTP error codes429,502,503, and504will cause a retry of the last
request.Ifretryis an integer, it defines the maximum number of retry attempts.Using the data returnedTwitter API calls return decoded JSON. This is converted into
a bunch of Python lists, dicts, ints, and strings. For example:x=twitter.statuses.home_timeline()# The first 'tweet' in the timelinex[0]# The screen name of the user who wrote the first 'tweet'x[0]['user']['screen_name']Getting raw XML dataIf you prefer to get your Twitter data in XML format, passformat="xml"to theTwitterobject when you instantiate it:twitter=Twitter(format="xml")The output will not be parsed in any way. It will be a raw string
of XML.TheTwitterStreamclassTheTwitterStreamobject is an interface to the Twitter Stream
API. This can be used pretty much the same as theTwitterclass,
except the result of calling a method will be an iterator that
yields objects decoded from the stream. For example::twitter_stream=TwitterStream(auth=OAuth(...))iterator=twitter_stream.statuses.sample()fortweetiniterator:...dosomethingwiththistweet...Per default theTwitterStreamobject usespublic streams.
If you want to use one of the otherstreaming APIs, specify the URL
manually.The iterator willyielduntil the TCP connection breaks. When the
connection breaks, the iterator yields{'hangup': True}(and
raisesStopIterationif iterated again).Similarly, if the stream does not produce heartbeats for more than
90 seconds, the iterator yields{'hangup': True, 'heartbeat_timeout': True}(and raisesStopIterationif
iterated again).Thetimeoutparameter controls the maximum time between
yields. If it is nonzero, then the iterator will yield either
stream data or{'timeout': True}within the timeout period. This
is useful if you want your program to do other stuff in between
waiting for tweets.Theblockparameter sets the stream to be fully non-blocking.
In this mode, the iterator always yields immediately. It returns
stream data, orNone.Note thattimeoutsupercedes this argument, so it should also be
setNoneto use this mode, and non-blocking can potentially lead
to 100% CPU usage.TwitterResponseObjectsResponse from a Twitter request. Behaves like a list or a string
(depending on requested format), but it has a few other interesting
attributes.headersgives you access to the response headers as anhttplib.HTTPHeadersinstance. Useresponse.headers.get('h')to retrieve a header.AuthenticationYou can authenticate with Twitter in three ways: NoAuth, OAuth, or
OAuth2 (app-only). Gethelp()on these classes to learn how to use them.OAuth and OAuth2 are probably the most useful.Working with OAuthVisit the Twitter developer page and create a new application:https://dev.twitter.com/apps/newThis will get you aCONSUMER_KEYandCONSUMER_SECRET.When users run your application they have to authenticate your app
with their Twitter account. A few HTTP calls to Twitter are required
to do this. Please see thetwitter.oauth_dancemodule to see how this
is done. If you are making a command-line app, you can use theoauth_dance()function directly.Performing the "oauth dance" gets you an oauth token and oauth secret
that authenticate the user with Twitter. You should save these for
later, so that the user doesn't have to do the oauth dance again.read_token_fileandwrite_token_fileare utility methods to read and
write OAuthtokenandsecretkey values. The values are stored as
strings in the file. Not terribly exciting.Finally, you can use theOAuthauthenticator to connect to Twitter. In
code it all goes like this:fromtwitterimport*MY_TWITTER_CREDS=os.path.expanduser('~/.my_app_credentials')ifnotos.path.exists(MY_TWITTER_CREDS):oauth_dance("My App Name",CONSUMER_KEY,CONSUMER_SECRET,MY_TWITTER_CREDS)oauth_token,oauth_secret=read_token_file(MY_TWITTER_CREDS)twitter=Twitter(auth=OAuth(oauth_token,oauth_secret,CONSUMER_KEY,CONSUMER_SECRET))# Now work with Twittertwitter.statuses.update(status='Hello, world!')Working withOAuth2Twitter only supports the application-only flow of OAuth2 for certain
API endpoints. This OAuth2 authenticator only supports the application-only
flow right now.To authenticate with OAuth2, visit the Twitter developer page and create a new
application:https://dev.twitter.com/apps/newThis will get you aCONSUMER_KEYandCONSUMER_SECRET.Exchange yourCONSUMER_KEYandCONSUMER_SECRETfor a bearer token using theoauth2_dancefunction.Finally, you can use theOAuth2authenticator and your bearer token to connect
to Twitter. In code it goes like this::twitter=Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN))# Now work with Twittertwitter.search.tweets(q='keyword')LicensePython Twitter Tools are released under an MIT License.