Install twit via npm
masterInstall the twit Twitter API client for Node.js using npm:
npm install twitrepository·master·Indexed 26 days ago
https://github.com/ttezel/twitA 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.
Install the twit Twitter API client for Node.js using npm:
npm install twitCreate 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).
var T = new Twit({
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...'
});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
})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',
]
})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.
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)
});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)
})The T.stream(path, [params]) method initiates a connection to Twitter's Streaming API and returns an EventEmitter.
Supported paths:
statuses/filterstatuses/samplestatuses/firehoseusersiteParameter 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)
})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.T.getAuth() to retrieve the current client's authentication tokens, and T.setAuth(tokens) to update them.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, unblockedfavorite, unfavoritefollow, unfollowmute, unmuteuser_updatelist_created, list_destroyed, list_updated, list_member_added, list_member_removed, list_user_subscribed, list_user_unsubscribedquoted_tweetretweeted_retweetfavorited_retweetunknown_user_event (fallback for unmatched events)stream.on('user_event', function (eventMsg) {
//...
})
// Or listen for specific events:
stream.on('favorite', function (event) {
//...
})The EventEmitter returned by T.stream() emits several events depending on the stream type and activity:
| Event | Description |
|---|---|
message | Catch-all event for any object received in the stream. |
tweet | Emitted when a status (tweet) enters the stream. |
delete | Emitted when a status deletion message arrives. |
limit | Emitted when a limitation message arrives. |
scrub_geo | Emitted when a location deletion message arrives. |
disconnect | Emitted when a disconnect message is received from Twitter. |
connect | Emitted when a connection attempt is made (emits the http request object). |
connected | Emitted when the response is received (emits the http response object). |
reconnect | Emitted when a reconnection is scheduled (emits request, response, and connectInterval). |
warning | Emitted if the client is falling behind the stream. |
status_withheld | Emitted when a tweet is withheld in certain countries. |
user_withheld | Emitted when a user is withheld in certain countries. |
friends | Emitted during a user stream preamble (contains user IDs). |
direct_message | Emitted when a direct message is sent (for user streams). |