]>
Commit | Line | Data |
---|---|---|
fdbae010 | 1 | Python Twitter Tools |
a65893e4 | 2 | ==================== |
fdbae010 | 3 | |
bcd1bc9c | 4 | [![Build Status](https://travis-ci.org/sixohsix/twitter.svg)](https://travis-ci.org/sixohsix/twitter) [![Coverage Status](https://coveralls.io/repos/sixohsix/twitter/badge.png?branch=master)](https://coveralls.io/r/sixohsix/twitter?branch=master) |
9ae71d46 | 5 | |
f1a8ed67 | 6 | The Minimalist Twitter API for Python is a Python API for Twitter, |
7 | everyone's favorite Web 2.0 Facebook-style status updater for people | |
8 | on the go. | |
fdbae010 | 9 | |
7fdf6529 | 10 | Also included is a Twitter command-line tool for getting your friends' |
f1a8ed67 | 11 | tweets and setting your own tweet from the safety and security of your |
5b8b1ead | 12 | favorite shell and an IRC bot that can announce Twitter updates to an |
f1a8ed67 | 13 | IRC channel. |
fdbae010 | 14 | |
5f47b302 | 15 | For more information, after installing the `twitter` package: |
fdbae010 | 16 | |
7fdf6529 | 17 | * import the `twitter` package and run `help()` on it |
fdbae010 | 18 | * run `twitter -h` for command-line tool help |
a65893e4 | 19 | |
51e0b8f1 MV |
20 | twitter - The Command-Line Tool |
21 | ------------------------------- | |
a65893e4 | 22 | |
30913a4e | 23 | The command-line tool lets you do some awesome things: |
a65893e4 | 24 | |
30913a4e | 25 | * view your tweets, recent replies, and tweets in lists |
a65893e4 MV |
26 | * view the public timeline |
27 | * follow and unfollow (leave) friends | |
28 | * various output formats for tweet information | |
51e0b8f1 | 29 | |
a65893e4 MV |
30 | The bottom line: type `twitter`, receive tweets. |
31 | ||
51e0b8f1 MV |
32 | twitterbot - The IRC Bot |
33 | ------------------------ | |
a65893e4 | 34 | |
7fdf6529 | 35 | The IRC bot is associated with a Twitter account (either your own account or an |
a65893e4 MV |
36 | account you create for the bot). The bot announces all tweets from friends |
37 | it is following. It can be made to follow or leave friends through IRC /msg | |
38 | commands. | |
39 | ||
5f47b302 | 40 | |
7fdf6529 Z |
41 | `twitter-log` |
42 | ------------- | |
5f47b302 MV |
43 | |
44 | `twitter-log` is a simple command-line tool that dumps all public | |
45 | tweets from a given user in a simple text format. It is useful to get | |
46 | a complete offsite backup of all your tweets. Run `twitter-log` and | |
47 | read the instructions. | |
48 | ||
7fdf6529 Z |
49 | `twitter-archiver` and `twitter-follow` |
50 | --------------------------------------- | |
30913a4e MV |
51 | |
52 | twitter-archiver will log all the tweets posted by any user since they | |
53 | started posting. twitter-follow will print a list of all of all the | |
54 | followers of a user (or all the users that user follows). | |
55 | ||
5f47b302 | 56 | |
7fdf6529 | 57 | Programming with the Twitter API classes |
51e0b8f1 MV |
58 | ======================================== |
59 | ||
7fdf6529 | 60 | The `Twitter` and `TwitterStream` classes are the key to building your own |
51e0b8f1 MV |
61 | Twitter-enabled applications. |
62 | ||
63 | ||
7fdf6529 Z |
64 | The `Twitter` class |
65 | ------------------- | |
51e0b8f1 MV |
66 | |
67 | The minimalist yet fully featured Twitter API class. | |
68 | ||
69 | Get RESTful data by accessing members of this class. The result | |
70 | is decoded python objects (lists and dicts). | |
71 | ||
72 | The Twitter API is documented at: | |
73 | ||
76bb7360 | 74 | **[https://dev.twitter.com/overview/documentation](https://dev.twitter.com/overview/documentation)** |
51e0b8f1 | 75 | |
d4f3123e | 76 | Examples: |
7fdf6529 | 77 | |
bcbd4e2b | 78 | ```python |
814d84f5 | 79 | from twitter import * |
51e0b8f1 | 80 | |
814d84f5 | 81 | t = Twitter( |
bdad9dd1 | 82 | auth=OAuth(token, token_key, con_secret, con_secret_key)) |
51e0b8f1 | 83 | |
814d84f5 MG |
84 | # Get your "home" timeline |
85 | t.statuses.home_timeline() | |
51e0b8f1 | 86 | |
814d84f5 | 87 | # Get a particular friend's timeline |
aaf199d3 | 88 | t.statuses.user_timeline(screen_name="billybob") |
51e0b8f1 | 89 | |
ae2bf888 HN |
90 | # to pass in GET/POST parameters, such as `count` |
91 | t.statuses.home_timeline(count=5) | |
92 | ||
93 | # to pass in the GET/POST parameter `id` you need to use `_id` | |
94 | t.statuses.oembed(_id=1234567890) | |
95 | ||
814d84f5 MG |
96 | # Update your status |
97 | t.statuses.update( | |
98 | status="Using @sixohsix's sweet Python Twitter Tools.") | |
51e0b8f1 | 99 | |
814d84f5 MG |
100 | # Send a direct message |
101 | t.direct_messages.new( | |
102 | user="billybob", | |
103 | text="I think yer swell!") | |
d09c0dd3 | 104 | |
814d84f5 | 105 | # Get the members of tamtar's list "Things That Are Rad" |
fec0468d | 106 | t.lists.members(owner_screen_name="tamtar", slug="things-that-are-rad") |
a5aab114 | 107 | |
814d84f5 | 108 | # An *optional* `_timeout` parameter can also be used for API |
d4f3123e MV |
109 | # calls which take much more time than normal or twitter stops |
110 | # responding for some reason: | |
111 | t.users.lookup( | |
112 | screen_name=','.join(A_LIST_OF_100_SCREEN_NAMES), _timeout=1) | |
51e0b8f1 | 113 | |
ae2bf888 HN |
114 | # Overriding Method: GET/POST |
115 | # you should not need to use this method as this library properly | |
116 | # detects whether GET or POST should be used, Nevertheless | |
117 | # to force a particular method, use `_method` | |
118 | t.statuses.oembed(_id=1234567890, _method='GET') | |
5a412b39 | 119 | |
cd830ea5 R |
120 | # Send images along with your tweets: |
121 | # - first just read images from the web or from files the regular way: | |
5a412b39 | 122 | with open("example.png", "rb") as imagefile: |
cd830ea5 R |
123 | imagedata = imagefile.read() |
124 | # - then upload medias one by one on Twitter's dedicated server | |
125 | # and collect each one's id: | |
126 | t_up = Twitter(domain='upload.twitter.com', | |
127 | auth=OAuth(token, token_key, con_secret, con_secret_key)) | |
f778d83a R |
128 | id_img1 = t_up.media.upload(media=imagedata)["media_id_string"] |
129 | id_img2 = t_up.media.upload(media=imagedata)["media_id_string"] | |
cd830ea5 R |
130 | # - finally send your tweet with the list of media ids: |
131 | t.statuses.update(status="PTT ★", media_ids=",".join([id_img1, id_img2])) | |
132 | ||
133 | # Or send a tweet with an image (or set a logo/banner similarily) | |
134 | # using the old deprecated method that will probably disappear some day | |
135 | params = {"media[]": imagedata, "status": "PTT ★"} | |
136 | # Or for an image encoded as base64: | |
137 | params = {"media[]": base64_image, "status": "PTT ★", "_base64": True} | |
5a412b39 | 138 | t.statuses.update_with_media(**params) |
ae2bf888 | 139 | ``` |
51e0b8f1 | 140 | |
d4f3123e MV |
141 | Searching Twitter: |
142 | ```python | |
814d84f5 MG |
143 | # Search for the latest tweets about #pycon |
144 | t.search.tweets(q="#pycon") | |
145 | ``` | |
51e0b8f1 | 146 | |
16c4e7d4 BB |
147 | |
148 | Retrying after reaching the API rate limit | |
149 | ------------------------------------------ | |
150 | ||
151 | Simply create the `Twitter` instance with the argument `retry=True`, then the | |
7fdf6529 Z |
152 | HTTP error codes `429`, `502`, `503`, and `504` will cause a retry of the last |
153 | request. | |
154 | ||
155 | If `retry` is an integer, it defines the maximum number of retry attempts. | |
16c4e7d4 BB |
156 | |
157 | ||
51e0b8f1 MV |
158 | Using the data returned |
159 | ----------------------- | |
160 | ||
161 | Twitter API calls return decoded JSON. This is converted into | |
d4f3123e | 162 | a bunch of Python lists, dicts, ints, and strings. For example: |
51e0b8f1 | 163 | |
814d84f5 MG |
164 | ```python |
165 | x = twitter.statuses.home_timeline() | |
51e0b8f1 | 166 | |
814d84f5 MG |
167 | # The first 'tweet' in the timeline |
168 | x[0] | |
51e0b8f1 | 169 | |
814d84f5 MG |
170 | # The screen name of the user who wrote the first 'tweet' |
171 | x[0]['user']['screen_name'] | |
172 | ``` | |
51e0b8f1 MV |
173 | |
174 | Getting raw XML data | |
175 | -------------------- | |
176 | ||
177 | If you prefer to get your Twitter data in XML format, pass | |
7fdf6529 | 178 | `format="xml"` to the `Twitter` object when you instantiate it: |
51e0b8f1 | 179 | |
814d84f5 MG |
180 | ```python |
181 | twitter = Twitter(format="xml") | |
182 | ``` | |
51e0b8f1 MV |
183 | |
184 | The output will not be parsed in any way. It will be a raw string | |
185 | of XML. | |
186 | ||
7fdf6529 Z |
187 | The `TwitterStream` class |
188 | ------------------------- | |
51e0b8f1 | 189 | |
7fdf6529 Z |
190 | The `TwitterStream` object is an interface to the Twitter Stream |
191 | API. This can be used pretty much the same as the `Twitter` class, | |
d4f3123e MV |
192 | except the result of calling a method will be an iterator that |
193 | yields objects decoded from the stream. For example:: | |
51e0b8f1 | 194 | |
814d84f5 | 195 | ```python |
d4f3123e | 196 | twitter_stream = TwitterStream(auth=OAuth(...)) |
814d84f5 | 197 | iterator = twitter_stream.statuses.sample() |
51e0b8f1 | 198 | |
814d84f5 | 199 | for tweet in iterator: |
d4f3123e | 200 | ...do something with this tweet... |
814d84f5 | 201 | ``` |
51e0b8f1 | 202 | |
7fdf6529 | 203 | Per default the `TwitterStream` object uses |
84e6e1e4 | 204 | [public streams](https://dev.twitter.com/docs/streaming-apis/streams/public). |
205 | If you want to use one of the other | |
206 | [streaming APIs](https://dev.twitter.com/docs/streaming-apis), specify the URL | |
207 | manually: | |
208 | ||
209 | - [Public streams](https://dev.twitter.com/docs/streaming-apis/streams/public): stream.twitter.com | |
210 | - [User streams](https://dev.twitter.com/docs/streaming-apis/streams/user): userstream.twitter.com | |
211 | - [Site streams](https://dev.twitter.com/docs/streaming-apis/streams/site): sitestream.twitter.com | |
212 | ||
213 | Note that you require the proper | |
214 | [permissions](https://dev.twitter.com/docs/application-permission-model) to | |
7fdf6529 | 215 | access these streams. (E.g., for direct messages, your |
84e6e1e4 | 216 | [application](https://dev.twitter.com/apps) needs the "Read, Write & Direct |
7fdf6529 | 217 | Messages" permission.) |
84e6e1e4 | 218 | |
9ae71d46 | 219 | The following example demonstrates how to retrieve all new direct messages |
84e6e1e4 | 220 | from the user stream: |
221 | ||
222 | ```python | |
223 | auth = OAuth( | |
224 | consumer_key='[your consumer key]', | |
225 | consumer_secret='[your consumer secret]', | |
226 | token='[your token]', | |
227 | token_secret='[your token secret]' | |
228 | ) | |
229 | twitter_userstream = TwitterStream(auth=auth, domain='userstream.twitter.com') | |
230 | for msg in twitter_userstream.user(): | |
231 | if 'direct_message' in msg: | |
232 | print msg['direct_message']['text'] | |
233 | ``` | |
234 | ||
7fdf6529 Z |
235 | The iterator will `yield` until the TCP connection breaks. When the |
236 | connection breaks, the iterator yields `{'hangup': True}` (and | |
237 | raises `StopIteration` if iterated again). | |
d4f3123e MV |
238 | |
239 | Similarly, if the stream does not produce heartbeats for more than | |
7fdf6529 Z |
240 | 90 seconds, the iterator yields `{'hangup': True, |
241 | 'heartbeat_timeout': True}` (and raises `StopIteration` if | |
242 | iterated again). | |
d4f3123e MV |
243 | |
244 | The `timeout` parameter controls the maximum time between | |
245 | yields. If it is nonzero, then the iterator will yield either | |
246 | stream data or `{'timeout': True}` within the timeout period. This | |
247 | is useful if you want your program to do other stuff in between | |
248 | waiting for tweets. | |
249 | ||
7fdf6529 Z |
250 | The `block` parameter sets the stream to be fully non-blocking. |
251 | In this mode, the iterator always yields immediately. It returns | |
252 | stream data, or `None`. | |
d4f3123e | 253 | |
7fdf6529 Z |
254 | Note that `timeout` supercedes this argument, so it should also be |
255 | set `None` to use this mode, and non-blocking can potentially lead | |
256 | to 100% CPU usage. | |
51e0b8f1 | 257 | |
7fdf6529 Z |
258 | Twitter `Response` Objects |
259 | -------------------------- | |
260 | ||
261 | Response from a Twitter request. Behaves like a list or a string | |
262 | (depending on requested format), but it has a few other interesting | |
51e0b8f1 MV |
263 | attributes. |
264 | ||
265 | `headers` gives you access to the response headers as an | |
7fdf6529 Z |
266 | `httplib.HTTPHeaders` instance. Use `response.headers.get('h')` |
267 | to retrieve a header. | |
51e0b8f1 MV |
268 | |
269 | Authentication | |
270 | -------------- | |
271 | ||
272 | You can authenticate with Twitter in three ways: NoAuth, OAuth, or | |
7fdf6529 | 273 | OAuth2 (app-only). Get `help()` on these classes to learn how to use them. |
51e0b8f1 | 274 | |
d4f3123e | 275 | OAuth and OAuth2 are probably the most useful. |
51e0b8f1 MV |
276 | |
277 | ||
278 | Working with OAuth | |
279 | ------------------ | |
280 | ||
281 | Visit the Twitter developer page and create a new application: | |
282 | ||
5d5d68cc | 283 | **[https://dev.twitter.com/apps/new](https://dev.twitter.com/apps/new)** |
51e0b8f1 | 284 | |
7fdf6529 | 285 | This will get you a `CONSUMER_KEY` and `CONSUMER_SECRET`. |
51e0b8f1 MV |
286 | |
287 | When users run your application they have to authenticate your app | |
7fdf6529 Z |
288 | with their Twitter account. A few HTTP calls to Twitter are required |
289 | to do this. Please see the `twitter.oauth_dance` module to see how this | |
51e0b8f1 | 290 | is done. If you are making a command-line app, you can use the |
7fdf6529 | 291 | `oauth_dance()` function directly. |
51e0b8f1 | 292 | |
7fdf6529 | 293 | Performing the "oauth dance" gets you an oauth token and oauth secret |
51e0b8f1 | 294 | that authenticate the user with Twitter. You should save these for |
7fdf6529 | 295 | later, so that the user doesn't have to do the oauth dance again. |
51e0b8f1 | 296 | |
7fdf6529 Z |
297 | `read_token_file` and `write_token_file` are utility methods to read and |
298 | write OAuth `token` and `secret` key values. The values are stored as | |
51e0b8f1 MV |
299 | strings in the file. Not terribly exciting. |
300 | ||
7fdf6529 | 301 | Finally, you can use the `OAuth` authenticator to connect to Twitter. In |
d4f3123e | 302 | code it all goes like this: |
51e0b8f1 | 303 | |
814d84f5 MG |
304 | ```python |
305 | from twitter import * | |
51e0b8f1 | 306 | |
814d84f5 MG |
307 | MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials') |
308 | if not os.path.exists(MY_TWITTER_CREDS): | |
309 | oauth_dance("My App Name", CONSUMER_KEY, CONSUMER_SECRET, | |
310 | MY_TWITTER_CREDS) | |
51e0b8f1 | 311 | |
814d84f5 | 312 | oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) |
51e0b8f1 | 313 | |
814d84f5 | 314 | twitter = Twitter(auth=OAuth( |
d4f3123e | 315 | oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)) |
51e0b8f1 | 316 | |
814d84f5 | 317 | # Now work with Twitter |
04e76c4d | 318 | twitter.statuses.update(status='Hello, world!') |
814d84f5 | 319 | ``` |
51e0b8f1 | 320 | |
7fdf6529 Z |
321 | Working with `OAuth2` |
322 | --------------------- | |
d4f3123e MV |
323 | |
324 | Twitter only supports the application-only flow of OAuth2 for certain | |
325 | API endpoints. This OAuth2 authenticator only supports the application-only | |
326 | flow right now. | |
327 | ||
328 | To authenticate with OAuth2, visit the Twitter developer page and create a new | |
329 | application: | |
330 | ||
331 | **[https://dev.twitter.com/apps/new](https://dev.twitter.com/apps/new)** | |
332 | ||
7fdf6529 | 333 | This will get you a `CONSUMER_KEY` and `CONSUMER_SECRET`. |
d4f3123e | 334 | |
7fdf6529 Z |
335 | Exchange your `CONSUMER_KEY` and `CONSUMER_SECRET` for a bearer token using the |
336 | `oauth2_dance` function. | |
d4f3123e | 337 | |
7fdf6529 | 338 | Finally, you can use the `OAuth2` authenticator and your bearer token to connect |
d4f3123e MV |
339 | to Twitter. In code it goes like this:: |
340 | ||
341 | ```python | |
342 | twitter = Twitter(auth=OAuth2(bearer_token=BEARER_TOKEN)) | |
343 | ||
344 | # Now work with Twitter | |
345 | twitter.search.tweets(q='keyword') | |
346 | ``` | |
51e0b8f1 MV |
347 | |
348 | License | |
349 | ======= | |
350 | ||
8be9a740 | 351 | Python Twitter Tools are released under an MIT License. |