SkillAgentSearch skills...

Twit

Twitter API Client for node (REST & Streaming API)

Install / Use

/learn @ttezel/Twit
About this skill

Quality Score

0/100

Supported Platforms

Universal

README

twit

Twitter API Client for node

Supports both the REST and Streaming API.

Installing

npm install twit

Usage:

var Twit = require('twit')

var T = new Twit({
  consumer_key:         '...',
  consumer_secret:      '...',
  access_token:         '...',
  access_token_secret:  '...',
  timeout_ms:           60*1000,  // optional HTTP request timeout to apply to all requests.
  strictSSL:            true,     // optional - requires SSL certificates to be valid.
})

//
//  tweet 'hello world!'
//
T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
  console.log(data)
})

//
//  search twitter for all tweets containing the word 'banana' since July 11, 2011
//
T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, function(err, data, response) {
  console.log(data)
})

//
//  get the list of user id's that follow @tolga_tezel
//
T.get('followers/ids', { screen_name: 'tolga_tezel' },  function (err, data, response) {
  console.log(data)
})

//
// Twit has promise support; you can use the callback API,
// promise API, or both at the same time.
//
T.get('account/verify_credentials', { skip_status: true })
  .catch(function (err) {
    console.log('caught error', err.stack)
  })
  .then(function (result) {
    // `result` is an Object with keys "data" and "resp".
    // `data` and `resp` are the same objects as the ones passed
    // to the callback.
    // See https://github.com/ttezel/twit#tgetpath-params-callback
    // for details.

    console.log('data', result.data);
  })

//
//  retweet a tweet with id '343360866131001345'
//
T.post('statuses/retweet/:id', { id: '343360866131001345' }, function (err, data, response) {
  console.log(data)
})

//
//  destroy a tweet with id '343360866131001345'
//
T.post('statuses/destroy/:id', { id: '343360866131001345' }, function (err, data, response) {
  console.log(data)
})

//
// get `funny` twitter users
//
T.get('users/suggestions/:slug', { slug: 'funny' }, function (err, data, response) {
  console.log(data)
})

//
// post a tweet with media
//
var b64content = fs.readFileSync('/path/to/img', { encoding: 'base64' })

// first we must post the media to Twitter
T.post('media/upload', { media_data: b64content }, function (err, data, response) {
  // now we can assign alt text to the media, for use by screen readers and
  // other text-based presentations and interpreters
  var mediaIdStr = data.media_id_string
  var altText = "Small flowers in a planter on a sunny balcony, blossoming."
  var meta_params = { media_id: mediaIdStr, alt_text: { text: altText } }

  T.post('media/metadata/create', meta_params, function (err, data, response) {
    if (!err) {
      // now we can reference the media and post a tweet (media will attach to the tweet)
      var params = { status: 'loving life #nofilter', media_ids: [mediaIdStr] }

      T.post('statuses/update', params, function (err, data, response) {
        console.log(data)
      })
    }
  })
})

//
// post media via the chunked media upload API.
// You can then use POST statuses/update to post a tweet with the media attached as in the example above using `media_id_string`.
// Note: You can also do this yourself manually using T.post() calls if you want more fine-grained
// control over the streaming. Example: https://github.com/ttezel/twit/blob/master/tests/rest_chunked_upload.js#L20
//
var filePath = '/absolute/path/to/file.mp4'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
  console.log(data)
})

//
//  stream a sample of public statuses
//
var stream = T.stream('statuses/sample')

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

//
//  filter the twitter public stream by the word 'mango'.
//
var stream = T.stream('statuses/filter', { track: 'mango' })

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

//
// filter the public stream by the latitude/longitude bounded box of San Francisco
//
var sanFrancisco = [ '-122.75', '36.8', '-121.75', '37.8' ]

var stream = T.stream('statuses/filter', { locations: sanFrancisco })

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

//
// filter the public stream by english tweets containing `#apple`
//
var stream = T.stream('statuses/filter', { track: '#apple', language: 'en' })

stream.on('tweet', function (tweet) {
  console.log(tweet)
})

twit API:

var T = new Twit(config)

Create a Twit instance that can be used to make requests to Twitter's APIs.

If authenticating with user context, config should be an object of the form:

{
    consumer_key:         '...'
  , consumer_secret:      '...'
  , access_token:         '...'
  , access_token_secret:  '...'
}

If authenticating with application context, config should be an object of the form:

{
    consumer_key:         '...'
  , consumer_secret:      '...'
  , app_only_auth:        true
}

Note that Application-only auth will not allow you to perform requests to API endpoints requiring a user context, such as posting tweets. However, the endpoints available can have a higher rate limit.

T.get(path, [params], callback)

GET any of the REST API endpoints.

path

The endpoint to hit. When specifying path values, omit the '.json' at the end (i.e. use 'search/tweets' instead of 'search/tweets.json').

params

(Optional) parameters for the request.

callback

function (err, data, response)

  • data is the parsed data received from Twitter.
  • response is the [http.IncomingMessage](http://nodejs.org/api/http.html# http_http_incomingmessage) received from Twitter.

T.post(path, [params], callback)

POST any of the REST API endpoints. Same usage as T.get().

T.postMediaChunked(params, callback)

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.

var filePath = '/absolute/path/to/file.mp4'
T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
  console.log(data)
})

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).

T.getAuth()

Get the client's authentication tokens.

T.setAuth(tokens)

Update the client's authentication tokens.

T.stream(path, [params])

Use this with the Streaming API.

path

Streaming endpoint to hit. One of:

  • 'statuses/filter'
  • 'statuses/sample'
  • 'statuses/firehose'
  • 'user'
  • 'site'

For a description of each Streaming endpoint, see the Twitter API docs.

params

(Optional) parameters for the request. Any Arrays passed in params get converted to comma-separated strings, allowing you to do requests like:

//
// I only want to see tweets about my favorite fruits
//

// same result as doing { track: 'bananas,oranges,strawberries' }
var stream = T.stream('statuses/filter', { track: ['bananas', 'oranges', 'strawberries'] })

stream.on('tweet', function (tweet) {
  //...
})

Using the Streaming API

T.stream(path, [params]) keeps the connection alive, and returns an EventEmitter.

The following events are emitted:

event: 'message'

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. New in version 2.1.0.

stream.on('message', function (msg) {
  //...
})

event: 'tweet'

Emitted each time a status (tweet) comes into the stream.

stream.on('tweet', function (tweet) {
  //...
})

event: 'delete'

Emitted each time a status (tweet) deletion message comes into the stream.

stream.on('delete', function (deleteMessage) {
  //...
})

event: 'limit'

Emitted each time a limitation message comes into the stream.

stream.on('limit', function (limitMessage) {
  //...
})

event: 'scrub_geo'

Emitted each time a location deletion message comes into the stream.

stream.on('scrub_geo', function (scrubGeoMessage) {
  //...
})

event: 'disconnect'

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.

stream.on('disconnect', function (disconnectMessage) {
  //...
})

event: 'connect'

Emitted when a connection attempt is made to Twitter. The http request object is emitted.

stream.on('connect', function (request) {
  //...
})

event: 'connected'

Emitted when the response is received from Twitter. The http response object is emitted.

stream.on('connected', function (response) {
  //...
})

event: 'reconnect'

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. The last http request and response objects are emitted, along with the time (in milliseconds) left before the reconnect occurs.

stream.on('reconnect', function (request, response, connectInterval) {
  //...
})

event: 'warning'

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.

stream.on('warning', function (warning) {
  //...
})

event: 'status

Related Skills

View on GitHub
GitHub Stars4.3k
CategoryDevelopment
Updated11h ago
Forks548

Languages

JavaScript

Security Score

80/100

Audited on Mar 30, 2026

No findings