### Run Twit RTD2 Example Bot Source: https://github.com/ttezel/twit/blob/master/README.md Execute this Node.js command to run the `rtd2.js` example script, which demonstrates a Twitter bot built using the `twit` library. This example showcases basic usage of the library. ```Shell node examples/rtd2.js ``` -------------------------------- ### Install twit via npm Source: https://github.com/ttezel/twit/blob/master/README.md This command installs the 'twit' library, a Twitter API client for Node.js, using the Node Package Manager (npm). ```shell npm install twit ``` -------------------------------- ### Get Followers IDs (followers/ids) Source: https://github.com/ttezel/twit/blob/master/README.md This example retrieves a list of user IDs that follow a specific Twitter handle. It uses the 'followers/ids' endpoint with the `screen_name` parameter. ```javascript T.get('followers/ids', { screen_name: 'tolga_tezel' }, function (err, data, response) { console.log(data) }) ``` -------------------------------- ### Use Promise-based API for Account Verification Source: https://github.com/ttezel/twit/blob/master/README.md Twit supports Promises in addition to callbacks. This example verifies account credentials using `T.get` and handles the response with `.catch()` for errors and `.then()` for successful data retrieval. The `result` object contains both `data` and `resp`. ```javascript 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); }) ``` -------------------------------- ### Post a Tweet with Media Source: https://github.com/ttezel/twit/blob/master/README.md This multi-step example demonstrates how to upload an image and then attach it to a tweet. First, the image content is read as base64 and uploaded to Twitter's media endpoint. Then, metadata (like alt text) is created for the uploaded media. Finally, a tweet is posted referencing the media ID. ```javascript 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 Chunked Upload API Source: https://github.com/ttezel/twit/blob/master/README.md This example shows how to upload large media files using Twit's built-in chunked media upload helper. It takes a file path and handles the chunking process automatically. The returned `media_id_string` can then be used to attach the media to a tweet. ```javascript var filePath = '/absolute/path/to/file.mp4' T.postMediaChunked({ file_path: filePath }, function (err, data, response) { console.log(data) }) ``` -------------------------------- ### Perform GET Request to Twitter REST API Source: https://github.com/ttezel/twit/blob/master/README.md Executes a GET request to a specified Twitter REST API endpoint. Parameters are optional, and the callback receives error, parsed data, and the raw HTTP response. ```APIDOC T.get(path, [params], callback) path: string - The API endpoint (omit '.json'). params: object (optional) - Request parameters. callback: function(err, data, response) err: Error object if request fails. data: Parsed data from Twitter. response: http.IncomingMessage from Twitter. ``` -------------------------------- ### Post a Tweet (statuses/update) Source: https://github.com/ttezel/twit/blob/master/README.md This example shows how to post a new tweet using the `T.post` method to the 'statuses/update' endpoint. The tweet content is passed in the `status` parameter. A callback function handles the API response, including any errors or data. ```javascript T.post('statuses/update', { status: 'hello world!' }, function(err, data, response) { console.log(data) }) ``` -------------------------------- ### Get User Suggestions by Category (users/suggestions/:slug) Source: https://github.com/ttezel/twit/blob/master/README.md This snippet retrieves a list of suggested Twitter users based on a category slug, such as 'funny'. It uses the `T.get` method with the 'users/suggestions/:slug' endpoint. ```javascript T.get('users/suggestions/:slug', { slug: 'funny' }, function (err, data, response) { console.log(data) }) ``` -------------------------------- ### Handle Specific User Stream Event (e.g., 'favorite') Source: https://github.com/ttezel/twit/blob/master/README.md Example of handling a specific user stream event, such as 'favorite'. Other supported user stream events include `blocked`, `unblocked`, `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`, and `unknown_user_event` for unhandled events. ```javascript stream.on('favorite', function (event) { //... }) ``` -------------------------------- ### Filter Public Stream by Keyword Source: https://github.com/ttezel/twit/blob/master/README.md This example shows how to filter the public Twitter stream to receive only tweets containing a specific keyword, such as 'mango'. It sets up a stream and logs matching tweets. ```javascript var stream = T.stream('statuses/filter', { track: 'mango' }) stream.on('tweet', function (tweet) { console.log(tweet) }) ``` -------------------------------- ### Filter Public Stream by Keyword and Language Source: https://github.com/ttezel/twit/blob/master/README.md This example shows how to filter the public Twitter stream for tweets containing a specific hashtag ('#apple') and written in a particular language ('en' for English). ```javascript var stream = T.stream('statuses/filter', { track: '#apple', language: 'en' }) stream.on('tweet', function (tweet) { console.log(tweet) }) ``` -------------------------------- ### Destroy a Tweet (statuses/destroy/:id) Source: https://github.com/ttezel/twit/blob/master/README.md This example shows how to delete a tweet by its ID. It uses the `T.post` method to the 'statuses/destroy/:id' endpoint, providing the ID of the tweet to be destroyed. ```javascript T.post('statuses/destroy/:id', { id: '343360866131001345' }, function (err, data, response) { console.log(data) }) ``` -------------------------------- ### Execute Twit Project Tests Source: https://github.com/ttezel/twit/blob/master/README.md Run this command in your terminal to initiate the test suite for the Twit project. Ensure that the necessary `config.js` files with OAuth credentials are set up as described in the contribution guidelines. ```Shell npm test ``` -------------------------------- ### Initialize Twit Client Instance Source: https://github.com/ttezel/twit/blob/master/README.md Creates a new Twit instance for interacting with Twitter's APIs. Configuration varies based on authentication context (user or application-only), requiring consumer keys, secrets, and optionally access tokens. ```APIDOC Twit(config) config (User Context): { consumer_key: '...' , consumer_secret: '...' , access_token: '...' , access_token_secret: '...' } config (Application Context): { consumer_key: '...' , consumer_secret: '...' , app_only_auth: true } ``` -------------------------------- ### Initialize Twit Client with API Keys Source: https://github.com/ttezel/twit/blob/master/README.md This snippet demonstrates how to import the 'twit' module and initialize a new Twit client instance. It requires your Twitter API consumer keys and access tokens. Optional parameters like `timeout_ms` and `strictSSL` can be configured for HTTP requests. ```javascript 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. }) ``` -------------------------------- ### Stream a Sample of Public Statuses Source: https://github.com/ttezel/twit/blob/master/README.md This snippet demonstrates how to open a streaming connection to Twitter's public sample stream. It listens for incoming tweets and logs each one to the console. ```javascript var stream = T.stream('statuses/sample') stream.on('tweet', function (tweet) { console.log(tweet) }) ``` -------------------------------- ### Initialize Twitter Streaming API Connection Source: https://github.com/ttezel/twit/blob/master/README.md Establishes a persistent connection to Twitter's Streaming API. Supports various endpoints and automatically converts array parameters into comma-separated strings for convenience. ```APIDOC T.stream(path, [params]) path: string - Streaming endpoint ('statuses/filter', 'statuses/sample', 'statuses/firehose', 'user', 'site'). params: object (optional) - Request parameters (arrays converted to comma-separated strings). ``` ```JavaScript // // 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) { //... }) ``` -------------------------------- ### Available Twitter API Endpoints Source: https://github.com/ttezel/twit/blob/master/README.md An overview of the various Twitter API endpoints accessible, including REST API, Public stream, User stream, and Site stream endpoints. ```APIDOC REST API Endpoints: https://dev.twitter.com/rest/public Public stream endpoints: https://dev.twitter.com/streaming/public User stream endpoints: https://dev.twitter.com/streaming/userstreams Site stream endpoints: https://dev.twitter.com/streaming/sitestreams ``` -------------------------------- ### Configure Twit OAuth Credentials for Testing Source: https://github.com/ttezel/twit/blob/master/README.md This JavaScript module exports an object containing OAuth credentials. Two such files (`config1.js` and `config2.js`) are required at the root of the `twit` folder for testing purposes, each with distinct credentials for different Twitter accounts. ```JavaScript module.exports = { consumer_key: '...' , consumer_secret: '...' , access_token: '...' , access_token_secret: '...' } ``` -------------------------------- ### Retrieve Client Authentication Tokens Source: https://github.com/ttezel/twit/blob/master/README.md Returns the authentication tokens currently configured for the Twit client instance. ```APIDOC T.getAuth(): object ``` -------------------------------- ### Upload Media via Chunked API Source: https://github.com/ttezel/twit/blob/master/README.md A helper function to upload media files using Twitter's chunked media upload API. Requires the absolute `file_path` of the media to be uploaded. ```APIDOC T.postMediaChunked(params, callback) params: object - Contains 'file_path' (absolute path to media file). callback: function(err, data, response) ``` ```JavaScript var filePath = '/absolute/path/to/file.mp4' T.postMediaChunked({ file_path: filePath }, function (err, data, response) { console.log(data) }) ``` -------------------------------- ### Restart Twitter Stream Connection Source: https://github.com/ttezel/twit/blob/master/README.md Call this function to re-establish the stream connection after it has been explicitly stopped using `.stop()`. Note that there is no need to call `.start()` to initiate streaming initially, as `Twit.stream` handles this automatically. ```APIDOC stream.start() ``` -------------------------------- ### Perform POST Request to Twitter REST API Source: https://github.com/ttezel/twit/blob/master/README.md Executes a POST request to a specified Twitter REST API endpoint. Usage is identical to `T.get()`. ```APIDOC T.post(path, [params], callback) path: string - The API endpoint. params: object (optional) - Request parameters. callback: function(err, data, response) ``` -------------------------------- ### Handle 'warning' Event on Twitter Stream Source: https://github.com/ttezel/twit/blob/master/README.md This message is relevant for clients using high-bandwidth connections, such as the firehose. If your connection falls behind, Twitter will queue messages until the queue fills up, at which point it will disconnect you. ```javascript stream.on('warning', function (warning) { //... }) ``` -------------------------------- ### Handle Generic 'user_event' on Twitter Stream Source: https://github.com/ttezel/twit/blob/master/README.md Emitted when Twitter sends back a generic User stream event. Refer to the Twitter documentation for more information on the structure of each specific event. ```javascript stream.on('user_event', function (eventMsg) { //... }) ``` -------------------------------- ### Update Client Authentication Tokens Source: https://github.com/ttezel/twit/blob/master/README.md Sets or updates the authentication tokens used by the Twit client instance. ```APIDOC T.setAuth(tokens) tokens: object - New authentication tokens. ``` -------------------------------- ### Handle Twit Streaming API Events Source: https://github.com/ttezel/twit/blob/master/README.md The `T.stream()` method returns an `EventEmitter` that emits various events related to the streaming connection and incoming data, such as general messages, tweets, deletions, rate limits, location deletions, and connection status changes. ```JavaScript stream.on('message', function (msg) { //... }) stream.on('tweet', function (tweet) { //... }) stream.on('delete', function (deleteMessage) { //... }) stream.on('limit', function (limitMessage) { //... }) stream.on('scrub_geo', function (scrubGeoMessage) { //... }) stream.on('disconnect', function (disconnectMessage) { //... }) stream.on('connect', function (request) { //... }) stream.on('connected', function (response) { //... }) ``` -------------------------------- ### Retweet a Tweet (statuses/retweet/:id) Source: https://github.com/ttezel/twit/blob/master/README.md This snippet demonstrates how to retweet an existing tweet by its ID. It uses the `T.post` method with the 'statuses/retweet/:id' endpoint, passing the tweet's ID. ```javascript T.post('statuses/retweet/:id', { id: '343360866131001345' }, function (err, data, response) { console.log(data) }) ``` -------------------------------- ### Search Tweets (search/tweets) Source: https://github.com/ttezel/twit/blob/master/README.md This snippet demonstrates how to search for tweets using the 'search/tweets' endpoint. It queries for tweets containing 'banana' since a specific date and limits the results to 100. The results are logged in the callback. ```javascript T.get('search/tweets', { q: 'banana since:2011-07-11', count: 100 }, function(err, data, response) { console.log(data) }) ``` -------------------------------- ### Handle 'friends' Event on Twitter User Stream Source: https://github.com/ttezel/twit/blob/master/README.md Emitted when Twitter sends the "friends" preamble upon 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` parameter is set, the friends list preamble will be returned as Strings instead of Numbers. ```javascript var stream = T.stream('user', { stringify_friend_ids: true }) stream.on('friends', function (friendsMsg) { //... }) ``` -------------------------------- ### Configure Trusted Certificate Fingerprints for Twit Source: https://github.com/ttezel/twit/blob/master/README.md Allows specifying an array of trusted certificate fingerprints to enforce trust only for a specific set of certificates. When an HTTP response is received, the peer certificate's fingerprint must match one of the provided values. By default, Node.js's trusted "root" CAs are used. ```js 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', ] }) ``` -------------------------------- ### Filter Public Stream by Geographic Location Source: https://github.com/ttezel/twit/blob/master/README.md This snippet demonstrates filtering the public Twitter stream to receive tweets originating from a specific geographic bounding box, in this case, San Francisco. It defines the coordinates and sets up the stream. ```javascript 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) }) ``` -------------------------------- ### Handle 'reconnect' Event on Twitter Stream Source: https://github.com/ttezel/twit/blob/master/README.md Emitted when a reconnection attempt to Twitter is scheduled. If Twitter is experiencing issues or rate limits are hit, a reconnect is scheduled 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. ```javascript stream.on('reconnect', function (request, response, connectInterval) { //... }) ``` -------------------------------- ### Handle 'direct_message' Event on Twitter Stream Source: https://github.com/ttezel/twit/blob/master/README.md Emitted when a direct message is sent to the user. Note that Twitter has not officially documented this event for user streams. ```javascript stream.on('direct_message', function (directMsg) { //... }) ``` -------------------------------- ### Stop Twitter Stream Connection Source: https://github.com/ttezel/twit/blob/master/README.md Call this function on the stream object to terminate the streaming connection with Twitter. ```APIDOC stream.stop() ``` -------------------------------- ### Twitter Stream Error Object Structure Source: https://github.com/ttezel/twit/blob/master/README.md Describes the properties of the Error object emitted when an API request or response error occurs on a Twitter stream. This object provides details like the error message, HTTP status code, Twitter-specific error code, raw Twitter response data, and an array of all errors returned. ```APIDOC { message: '...', // error message statusCode: '...', // statusCode from Twitter code: '...', // error code from Twitter twitterReply: '...', // raw response data from Twitter allErrors: '...' // array of errors returned from Twitter } ``` -------------------------------- ### Handle 'user_withheld' Event on Twitter Stream Source: https://github.com/ttezel/twit/blob/master/README.md Emitted when Twitter sends back a `user_withheld` message in the stream, indicating that a Twitter user was withheld in certain countries. ```javascript stream.on('user_withheld', function (withheldMsg) { //... }) ``` -------------------------------- ### Handle 'status_withheld' Event on Twitter Stream Source: https://github.com/ttezel/twit/blob/master/README.md Emitted when Twitter sends back a `status_withheld` message in the stream, indicating that a tweet was withheld in certain countries. ```javascript stream.on('status_withheld', function (withheldMsg) { //... }) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.