twit

repository·master·Indexed 26 days ago

https://github.com/ttezel/twit

A Node.js Twitter API client (version 2.2.11) supporting REST and Streaming APIs. It provides methods for making REST requests via T.get() and T.post(), chunked media uploads with T.postMediaChunked(), and a Streaming API implementation via T.stream() that returns an EventEmitter for handling real-time events such as tweets, deletions, and user-specific actions.

Tokens
2.1K
Snippets
7
Records
11
Agent score
38%

What's inside twit

  1. Initialize a Twit instance

    master

    Create a new Twit instance by passing a configuration object. You can authenticate using either User Context (for posting tweets, etc.) or Application Context (higher rate limits, but read-only for most endpoints).

    User Context Configuration

    var T = new Twit({
      consumer_key:         '...',
      consumer_secret:      '...',
      access_token:         '...',
      access_token_secret:  '...' 
    });

    Application Context Configuration

    var T = new Twit({
      consumer_key:         '...',
      consumer_secret:      '...',
      app_only_auth:        true
    });
    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
      strictSSL:            true,     // optional - requires SSL certificates to be valid
    })
  2. Configure trusted certificate fingerprints

    master

    For advanced security, you can specify an array of trusted certificate fingerprints in the Twit configuration. When an HTTP response is received, twit verifies that the certificate was signed and that the peer certificate's fingerprint matches one of the values provided. If not specified, the node.js trusted "root" CAs are used by default.

    var twit = new Twit({
      consumer_key:         '...',
      consumer_secret:      '...',
      access_token:         '...',
      access_token_secret:  '...',
      trusted_cert_fingerprints: [
        '66:EA:47:62:D9:B1:4F:1A:AE:89:5F:68:BA:6B:8E:BB:F8:1D:BF:8E',
      ]
    })
  3. Control the stream with stop() and start()

    master

    You can manually manage the lifecycle of a stream connection:

    • stream.stop(): Closes the connection with Twitter.
    • stream.start(): Restarts the stream after it has been stopped.

    Note: You do not need to call .start() to begin streaming initially; Twit.stream calls it for you automatically.

  4. Make REST API requests with T.get() and T.post()

    master

    Use T.get() and T.post() to interact with Twitter's REST API endpoints.

    Note: When specifying the path, omit the .json suffix (e.g., use search/tweets instead of search/tweets.json).

    Arguments:

    • path: The endpoint string.
    • params: (Optional) An object containing request parameters.
    • callback: A function with the signature function (err, data, response). data is the parsed JSON, and response is the http.IncomingMessage object.

    Promise Support: twit supports Promises. When using the Promise API, the resolved value is an object containing { data, resp } keys.

    // Example GET request
    T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, function(err, data, response) {
      console.log(data)
    })
    
    // Example POST request
    T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) {
      console.log(data)
    })
    
    // Example using Promise API
    T.get('account/verify_credentials', { skip_status: true })
      .then(function (result) {
        console.log('data', result.data);
      })
      .catch(function (err) {
        console.log('caught error', err.stack)
      });
  5. Upload media using T.postMediaChunked()

    master

    Use T.postMediaChunked() to upload large files via the chunked media upload API. The params object must contain a file_path key pointing to the absolute path of the file.

    Once uploaded, you can use the returned media_id_string to attach the media to a tweet via statuses/update.

    var filePath = '/absolute/path/to/file.mp4'
    T.postMediaChunked({ file_path: filePath }, function (err, data, response) {
      console.log(data)
    })
  6. Use the Streaming API with T.stream()

    master

    The T.stream(path, [params]) method initiates a connection to Twitter's Streaming API and returns an EventEmitter.

    Supported paths:

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

    Parameter handling: Arrays passed in params are automatically converted to comma-separated strings. For example, { track: ['bananas', 'oranges'] } becomes track=bananas,oranges in the request.

    // Example: Filtering stream by track
    var stream = T.stream('statuses/filter', { track: ['bananas', 'oranges', 'strawberries'] })
    
    stream.on('tweet', function (tweet) {
      console.log(tweet)
    })
  7. Handle stream errors

    master

    The error event is emitted when an API request or response error occurs. The emitted Error object contains the following properties:

    • message: The error message.
    • statusCode: The HTTP status code returned by Twitter.
    • code: The specific error code returned by Twitter.
    • twitterReply: The raw response data from Twitter.
    • allErrors: An array of errors returned from Twitter.
  8. Listen for User Stream events

    master

    When using the Streaming API, you can listen for the user_event to catch general Twitter User stream events. Additionally, twit provides specific event listeners for common user actions to simplify your implementation.

    Supported specific user events include:

    • blocked, unblocked
    • favorite, unfavorite
    • follow, unfollow
    • mute, unmute
    • user_update
    • list_created, list_destroyed, list_updated, list_member_added, list_member_removed, list_user_subscribed, list_user_unsubscribed
    • quoted_tweet
    • retweeted_retweet
    • favorited_retweet
    • unknown_user_event (fallback for unmatched events)
    stream.on('user_event', function (eventMsg) {
      //...
    })
    
    // Or listen for specific events:
    stream.on('favorite', function (event) {
      //...
    })
  9. Handle Streaming API events

    master

    The EventEmitter returned by T.stream() emits several events depending on the stream type and activity:

    EventDescription
    messageCatch-all event for any object received in the stream.
    tweetEmitted when a status (tweet) enters the stream.
    deleteEmitted when a status deletion message arrives.
    limitEmitted when a limitation message arrives.
    scrub_geoEmitted when a location deletion message arrives.
    disconnectEmitted when a disconnect message is received from Twitter.
    connectEmitted when a connection attempt is made (emits the http request object).
    connectedEmitted when the response is received (emits the http response object).
    reconnectEmitted when a reconnection is scheduled (emits request, response, and connectInterval).
    warningEmitted if the client is falling behind the stream.
    status_withheldEmitted when a tweet is withheld in certain countries.
    user_withheldEmitted when a user is withheld in certain countries.
    friendsEmitted during a user stream preamble (contains user IDs).
    direct_messageEmitted when a direct message is sent (for user streams).