README.md (19767B)
1 # twit 2 3 Twitter API Client for node 4 5 Supports both the **REST** and **Streaming** API. 6 7 # Installing 8 9 ```shell 10 npm install twit 11 ``` 12 13 ## Usage: 14 15 ```javascript 16 var Twit = require('twit') 17 18 var T = new Twit({ 19 consumer_key: '...', 20 consumer_secret: '...', 21 access_token: '...', 22 access_token_secret: '...', 23 timeout_ms: 60*1000, // optional HTTP request timeout to apply to all requests. 24 strictSSL: true, // optional - requires SSL certificates to be valid. 25 }) 26 27 // 28 // tweet 'hello world!' 29 // 30 T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) { 31 console.log(data) 32 }) 33 34 // 35 // search twitter for all tweets containing the word 'banana' since July 11, 2011 36 // 37 T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, function(err, data, response) { 38 console.log(data) 39 }) 40 41 // 42 // get the list of user id's that follow @tolga_tezel 43 // 44 T.get('followers/ids', { screen_name: 'tolga_tezel' }, function (err, data, response) { 45 console.log(data) 46 }) 47 48 // 49 // Twit has promise support; you can use the callback API, 50 // promise API, or both at the same time. 51 // 52 T.get('account/verify_credentials', { skip_status: true }) 53 .catch(function (err) { 54 console.log('caught error', err.stack) 55 }) 56 .then(function (result) { 57 // `result` is an Object with keys "data" and "resp". 58 // `data` and `resp` are the same objects as the ones passed 59 // to the callback. 60 // See https://github.com/ttezel/twit#tgetpath-params-callback 61 // for details. 62 63 console.log('data', result.data); 64 }) 65 66 // 67 // retweet a tweet with id '343360866131001345' 68 // 69 T.post('statuses/retweet/:id', { id: '343360866131001345' }, function (err, data, response) { 70 console.log(data) 71 }) 72 73 // 74 // destroy a tweet with id '343360866131001345' 75 // 76 T.post('statuses/destroy/:id', { id: '343360866131001345' }, function (err, data, response) { 77 console.log(data) 78 }) 79 80 // 81 // get `funny` twitter users 82 // 83 T.get('users/suggestions/:slug', { slug: 'funny' }, function (err, data, response) { 84 console.log(data) 85 }) 86 87 // 88 // post a tweet with media 89 // 90 var b64content = fs.readFileSync('/path/to/img', { encoding: 'base64' }) 91 92 // first we must post the media to Twitter 93 T.post('media/upload', { media_data: b64content }, function (err, data, response) { 94 // now we can assign alt text to the media, for use by screen readers and 95 // other text-based presentations and interpreters 96 var mediaIdStr = data.media_id_string 97 var altText = "Small flowers in a planter on a sunny balcony, blossoming." 98 var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } } 99 100 T.post('media/metadata/create', meta_params, function (err, data, response) { 101 if (!err) { 102 // now we can reference the media and post a tweet (media will attach to the tweet) 103 var params = { status: 'loving life #nofilter', media_ids: [mediaIdStr] } 104 105 T.post('statuses/update', params, function (err, data, response) { 106 console.log(data) 107 }) 108 } 109 }) 110 }) 111 112 // 113 // post media via the chunked media upload API. 114 // You can then use POST statuses/update to post a tweet with the media attached as in the example above using `media_id_string`. 115 // Note: You can also do this yourself manually using T.post() calls if you want more fine-grained 116 // control over the streaming. Example: https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js#L20 117 // 118 var filePath = '/absolute/path/to/file.mp4' 119 T.postMediaChunked({ file_path: filePath }, function (err, data, response) { 120 console.log(data) 121 }) 122 123 // 124 // stream a sample of public statuses 125 // 126 var stream = T.stream('statuses/sample') 127 128 stream.on('tweet', function (tweet) { 129 console.log(tweet) 130 }) 131 132 // 133 // filter the twitter public stream by the word 'mango'. 134 // 135 var stream = T.stream('statuses/filter', { track: 'mango' }) 136 137 stream.on('tweet', function (tweet) { 138 console.log(tweet) 139 }) 140 141 // 142 // filter the public stream by the latitude/longitude bounded box of San Francisco 143 // 144 var sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ] 145 146 var stream = T.stream('statuses/filter', { locations: sanFrancisco }) 147 148 stream.on('tweet', function (tweet) { 149 console.log(tweet) 150 }) 151 152 // 153 // filter the public stream by english tweets containing `#apple` 154 // 155 var stream = T.stream('statuses/filter', { track: '#apple', language: 'en' }) 156 157 stream.on('tweet', function (tweet) { 158 console.log(tweet) 159 }) 160 161 ``` 162 163 # twit API: 164 165 ## `var T = new Twit(config)` 166 167 Create a `Twit` instance that can be used to make requests to Twitter's APIs. 168 169 If authenticating with user context, `config` should be an object of the form: 170 ``` 171 { 172 consumer_key: '...' 173 , consumer_secret: '...' 174 , access_token: '...' 175 , access_token_secret: '...' 176 } 177 ``` 178 179 If authenticating with application context, `config` should be an object of the form: 180 ``` 181 { 182 consumer_key: '...' 183 , consumer_secret: '...' 184 , app_only_auth: true 185 } 186 ``` 187 Note that Application-only auth will not allow you to perform requests to API endpoints requiring 188 a user context, such as posting tweets. However, the endpoints available can have a higher rate limit. 189 190 ## `T.get(path, [params], callback)` 191 GET any of the REST API endpoints. 192 193 **path** 194 195 The endpoint to hit. When specifying `path` values, omit the **'.json'** at the end (i.e. use **'search/tweets'** instead of **'search/tweets.json'**). 196 197 **params** 198 199 (Optional) parameters for the request. 200 201 **callback** 202 203 `function (err, data, response)` 204 205 - `data` is the parsed data received from Twitter. 206 - `response` is the [http.IncomingMessage](http://nodejs.org/api/http.html# http_http_incomingmessage) received from Twitter. 207 208 ## `T.post(path, [params], callback)` 209 210 POST any of the REST API endpoints. Same usage as `T.get()`. 211 212 ## `T.postMediaChunked(params, callback)` 213 214 Helper function to post media via the POST media/upload (chunked) API. `params` is an object containing a `file_path` key. `file_path` is the absolute path to the file you want to upload. 215 216 ```js 217 var filePath = '/absolute/path/to/file.mp4' 218 T.postMediaChunked({ file_path: filePath }, function (err, data, response) { 219 console.log(data) 220 }) 221 ``` 222 223 You can also use the POST media/upload API via T.post() calls if you want more fine-grained control over the streaming; [see here for an example](https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js# L20). 224 225 ## `T.getAuth()` 226 Get the client's authentication tokens. 227 228 ## `T.setAuth(tokens)` 229 Update the client's authentication tokens. 230 231 ## `T.stream(path, [params])` 232 Use this with the Streaming API. 233 234 **path** 235 236 Streaming endpoint to hit. One of: 237 238 - **'statuses/filter'** 239 - **'statuses/sample'** 240 - **'statuses/firehose'** 241 - **'user'** 242 - **'site'** 243 244 For a description of each Streaming endpoint, see the [Twitter API docs](https://dev.twitter.com/streaming/overview). 245 246 **params** 247 248 (Optional) parameters for the request. Any Arrays passed in `params` get converted to comma-separated strings, allowing you to do requests like: 249 250 ```javascript 251 // 252 // I only want to see tweets about my favorite fruits 253 // 254 255 // same result as doing { track: 'bananas,oranges,strawberries' } 256 var stream = T.stream('statuses/filter', { track: ['bananas', 'oranges', 'strawberries'] }) 257 258 stream.on('tweet', function (tweet) { 259 //... 260 }) 261 ``` 262 263 # Using the Streaming API 264 265 `T.stream(path, [params])` keeps the connection alive, and returns an `EventEmitter`. 266 267 The following events are emitted: 268 269 ## event: 'message' 270 271 Emitted each time an object is received in the stream. This is a catch-all event that can be used to process any data received in the stream, rather than using the more specific events documented below. 272 New in version 2.1.0. 273 274 ```javascript 275 stream.on('message', function (msg) { 276 //... 277 }) 278 ``` 279 280 ## event: 'tweet' 281 282 Emitted each time a status (tweet) comes into the stream. 283 284 ```javascript 285 stream.on('tweet', function (tweet) { 286 //... 287 }) 288 ``` 289 290 ## event: 'delete' 291 292 Emitted each time a status (tweet) deletion message comes into the stream. 293 294 ```javascript 295 stream.on('delete', function (deleteMessage) { 296 //... 297 }) 298 ``` 299 300 ## event: 'limit' 301 302 Emitted each time a limitation message comes into the stream. 303 304 ```javascript 305 stream.on('limit', function (limitMessage) { 306 //... 307 }) 308 ``` 309 310 ## event: 'scrub_geo' 311 312 Emitted each time a location deletion message comes into the stream. 313 314 ```javascript 315 stream.on('scrub_geo', function (scrubGeoMessage) { 316 //... 317 }) 318 ``` 319 320 ## event: 'disconnect' 321 322 Emitted when a disconnect message comes from Twitter. This occurs if you have multiple streams connected to Twitter's API. Upon receiving a disconnect message from Twitter, `Twit` will close the connection and emit this event with the message details received from twitter. 323 324 ```javascript 325 stream.on('disconnect', function (disconnectMessage) { 326 //... 327 }) 328 ``` 329 330 ## event: 'connect' 331 332 Emitted when a connection attempt is made to Twitter. The http `request` object is emitted. 333 334 ```javascript 335 stream.on('connect', function (request) { 336 //... 337 }) 338 ``` 339 340 ## event: 'connected' 341 342 Emitted when the response is received from Twitter. The http `response` object is emitted. 343 344 ```javascript 345 stream.on('connected', function (response) { 346 //... 347 }) 348 ``` 349 350 ## event: 'reconnect' 351 352 Emitted when a reconnection attempt to Twitter is scheduled. If Twitter is having problems or we get rate limited, we schedule a reconnect according to Twitter's [reconnection guidelines](https://dev.twitter.com/streaming/overview/connecting). The last http `request` and `response` objects are emitted, along with the time (in milliseconds) left before the reconnect occurs. 353 354 ```javascript 355 stream.on('reconnect', function (request, response, connectInterval) { 356 //... 357 }) 358 ``` 359 360 ## event: 'warning' 361 362 This message is appropriate for clients using high-bandwidth connections, like the firehose. If your connection is falling behind, Twitter will queue messages for you, until your queue fills up, at which point they will disconnect you. 363 364 ```javascript 365 stream.on('warning', function (warning) { 366 //... 367 }) 368 ``` 369 370 ## event: 'status_withheld' 371 372 Emitted when Twitter sends back a `status_withheld` message in the stream. This means that a tweet was withheld in certain countries. 373 374 ```javascript 375 stream.on('status_withheld', function (withheldMsg) { 376 //... 377 }) 378 ``` 379 380 ## event: 'user_withheld' 381 382 Emitted when Twitter sends back a `user_withheld` message in the stream. This means that a Twitter user was withheld in certain countries. 383 384 ```javascript 385 stream.on('user_withheld', function (withheldMsg) { 386 //... 387 }) 388 ``` 389 390 ## event: 'friends' 391 392 Emitted when Twitter sends the ["friends" preamble](https://dev.twitter.com/streaming/overview/messages-types# user_stream_messsages) when connecting to a user stream. This message contains a list of the user's friends, represented as an array of user ids. If the [stringify_friend_ids](https://dev.twitter.com/streaming/overview/request-parameters#stringify_friend_id) parameter is set, the friends 393 list preamble will be returned as Strings (instead of Numbers). 394 395 ```javascript 396 var stream = T.stream('user', { stringify_friend_ids: true }) 397 stream.on('friends', function (friendsMsg) { 398 //... 399 }) 400 ``` 401 402 ## event: 'direct_message' 403 404 Emitted when a direct message is sent to the user. Unfortunately, Twitter has not documented this event for user streams. 405 406 ```javascript 407 stream.on('direct_message', function (directMsg) { 408 //... 409 }) 410 ``` 411 412 ## event: 'user_event' 413 414 Emitted when Twitter sends back a [User stream event](https://dev.twitter.com/streaming/overview/messages-types#Events_event). 415 See the Twitter docs for more information on each event's structure. 416 417 ```javascript 418 stream.on('user_event', function (eventMsg) { 419 //... 420 }) 421 ``` 422 423 In addition, the following user stream events are provided for you to listen on: 424 425 * `blocked` 426 * `unblocked` 427 * `favorite` 428 * `unfavorite` 429 * `follow` 430 * `unfollow` 431 * `mute` 432 * `unmute` 433 * `user_update` 434 * `list_created` 435 * `list_destroyed` 436 * `list_updated` 437 * `list_member_added` 438 * `list_member_removed` 439 * `list_user_subscribed` 440 * `list_user_unsubscribed` 441 * `quoted_tweet` 442 * `retweeted_retweet` 443 * `favorited_retweet` 444 * `unknown_user_event` (for an event that doesn't match any of the above) 445 446 ### Example: 447 448 ```javascript 449 stream.on('favorite', function (event) { 450 //... 451 }) 452 ``` 453 454 ## event: 'error' 455 456 Emitted when an API request or response error occurs. 457 An `Error` object is emitted, with properties: 458 459 ```js 460 { 461 message: '...', // error message 462 statusCode: '...', // statusCode from Twitter 463 code: '...', // error code from Twitter 464 twitterReply: '...', // raw response data from Twitter 465 allErrors: '...' // array of errors returned from Twitter 466 } 467 ``` 468 469 ## stream.stop() 470 471 Call this function on the stream to stop streaming (closes the connection with Twitter). 472 473 ## stream.start() 474 475 Call this function to restart the stream after you called `.stop()` on it. 476 Note: there is no need to call `.start()` to begin streaming. `Twit.stream` calls `.start()` for you. 477 478 ------- 479 480 # What do I have access to? 481 482 Anything in the Twitter API: 483 484 * REST API Endpoints: https://dev.twitter.com/rest/public 485 * Public stream endpoints: https://dev.twitter.com/streaming/public 486 * User stream endpoints: https://dev.twitter.com/streaming/userstreams 487 * Site stream endpoints: https://dev.twitter.com/streaming/sitestreams 488 489 ------- 490 491 Go here to create an app and get OAuth credentials (if you haven't already): https://apps.twitter.com/app/new 492 493 # Advanced 494 495 You may specify an array of trusted certificate fingerprints if you want to only trust a specific set of certificates. 496 When an HTTP response is received, it is verified that the certificate was signed, and the peer certificate's fingerprint must be one of the values you specified. By default, the node.js trusted "root" CAs will be used. 497 498 eg. 499 ```js 500 var twit = new Twit({ 501 consumer_key: '...', 502 consumer_secret: '...', 503 access_token: '...', 504 access_token_secret: '...', 505 trusted_cert_fingerprints: [ 506 '66:EA:47:62:D9:B1:4F:1A:AE:89:5F:68:BA:6B:8E:BB:F8:1D:BF:8E', 507 ] 508 }) 509 ``` 510 511 # Contributing 512 513 - Make your changes 514 - Make sure your code matches the style of the code around it 515 - Add tests that cover your feature/bugfix 516 - Run tests 517 - Submit a pull request 518 519 # How do I run the tests? 520 521 Create two files: `config1.js` and `config2.js` at the root of the `twit` folder. They should contain two different sets of oauth credentials for twit to use (two accounts are needed for testing interactions). They should both look something like this: 522 523 ``` 524 module.exports = { 525 consumer_key: '...' 526 , consumer_secret: '...' 527 , access_token: '...' 528 , access_token_secret: '...' 529 } 530 ``` 531 532 Then run the tests: 533 534 ``` 535 npm test 536 ``` 537 538 You can also run the example: 539 540 ``` 541 node examples/rtd2.js 542 ``` 543 544 ![iRTD2](http://dl.dropbox.com/u/32773572/RTD2_logo.png) 545 546 The example is a twitter bot named [RTD2](https://twitter.com/#!/iRTD2) written using `twit`. RTD2 tweets about **github** and curates its social graph. 547 548 ------- 549 550 [FAQ](https://github.com/ttezel/twit/wiki/FAQ) 551 552 ------- 553 554 ## License 555 556 (The MIT License) 557 558 Copyright (c) by Tolga Tezel <tolgatezel11@gmail.com> 559 560 Permission is hereby granted, free of charge, to any person obtaining a copy 561 of this software and associated documentation files (the "Software"), to deal 562 in the Software without restriction, including without limitation the rights 563 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 564 copies of the Software, and to permit persons to whom the Software is 565 furnished to do so, subject to the following conditions: 566 567 The above copyright notice and this permission notice shall be included in 568 all copies or substantial portions of the Software. 569 570 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 571 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 572 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 573 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 574 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 575 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 576 THE SOFTWARE. 577 578 ## Changelog 579 580 ### 2.2.11 581 * Fix media_category used for media uploads (thanks @BooDoo) 582 583 ### 2.2.10 584 * Update maximum Tweet characters to 280 (thanks @maziyarpanahi) 585 * For streaming requests, use request body for sending params (thanks @raine) 586 * Fix getBearerToken endpoint (thanks @williamcoates) 587 * Shared Parameter Feature For Media Upload (thanks @haroonabbasi) 588 * Don't include params in path for jsonpayload paths (thanks @egtoney) 589 * Add support for strictSSL request option (thanks @zdoc01) 590 591 ### 2.2.9 592 * Use JSON payload in request body for new DM endpoints. 593 594 ### 2.2.8 595 * Add support for HTTP DELETE; you can now `T.delete(...)`. 596 597 ### 2.2.7 598 * Don't attempt to reconnect to Twitter API when receiving HTTP status code 413 - request entity too large. 599 600 ### 2.2.6 601 * Fix zlib error when streaming 602 603 ### 2.2.4 604 * Fix 401 Unauthorized error on streaming connection reconnect after not being 605 connected for some time (eg. due to > 1min loss of network). 606 607 ### 2.2.2 608 * Emit `parser-error` instead of `error` event if Twitter sends back 609 an uncompressed HTTP response body. 610 611 ### 2.2.1 612 * Add promise support to Twit REST API calls. 613 614 ### 2.2.0 615 * Allow omission of `new` keyword; `var t = Twit(config)` works, and `var t = new Twit(config)` works too. 616 * Allow setting an array of trusted certificate fingerprints via `config.trusted_cert_fingerprints`. 617 * Automatically adjust timestamp for OAuth'ed HTTP requests 618 by recording the timestamp from Twitter HTTP responses, computing our local time offset, and applying the offset in the next HTTP request to Twitter. 619 620 ### 2.1.7 621 * Add `mime` as a dependency. 622 623 ### 2.1.6 624 * Emit `friends` event for `friends_str` message received when a user stream is requested with `stringify_friend_ids=true`. 625 * Handle receiving "Exceeded connection limit for user" message from Twitter while streaming. Emit `error` event for this case. 626 * Emit `retweeted_retweet` and `favorited_retweet` user events. 627 * Add MIT license to package.json (about time!) 628 629 ### 2.1.5 630 * Support config-based request timeout. 631 632 ### 2.1.4 633 * Support POST media/upload (chunked) and add `T.postMediaChunked()` to make it easy. 634 635 ### 2.1.3 636 * Fix bug in constructing HTTP requests for `account/update_profile_image` and `account/update_profile_background_image` paths. 637 638 ### 2.1.2 639 * Enable gzip on network traffic 640 * Add `quoted_tweet` event 641 642 ### 2.1.1 643 * Strict-mode fixes (Twit can now be run with strict mode) 644 * Fix handling of disconect message from Twitter 645 * If Twitter returns a non-JSON-parseable fragment during streaming, emit 'parser-error' instead of 'error' (to discard fragments like "Internal Server Error") 646 647 ### 2.1.0 648 * Add `message` event. 649 650 ### 2.0.0 651 * Implement Application-only auth 652 * Remove oauth module as a dependency 653 654 ### 1.1.20 655 * Implement support for POST /media/upload 656 * Reconnect logic fix for streaming; add stall abort/reconnect timeout on first connection attempt. 657 658 ### 1.1.14 659 * Emit `connected` event upon receiving the response from twitter 660 661 ### 1.0.0 662 * now to stop and start the stream, use `stream.stop()` and `stream.start()` instead of emitting the `start` and `stop` events 663 * If twitter sends a `disconnect` message, closes the stream and emits `disconnect` with the disconnect message received from twitter 664 665 ### 0.2.0 666 * Updated `twit` for usage with v1.1 of the Twitter API. 667 668 ### 0.1.5 669 670 * **BREAKING CHANGE** to `twit.stream()`. Does not take a callback anymore. It returns 671 immediately with the `EventEmitter` that you can listen on. The `Usage` section in 672 the Readme.md has been updated. Read it. 673 674 675 ### 0.1.4 676 677 * `twit.stream()` has signature `function (path, params, callback)`