A CLI tool and an API for fetching data from Twitter for free!
It is recommended to install the package globally, if you want to use it from the CLI. Use the following steps to install the package and ensure it's installed correctly:
npm install -g rettiwt-api.rettiwt help.For using the package in your own project, you can install it as a dependency.
Rettiwt-API can be used with or without logging in to Twitter. As such, the two authentication strategies are:
'Guest' authentication (without logging in) grants access to the following resources/actions:
'User' authentication (logging in) grants access to the following resources/actions:
By default, Rettiwt-API uses 'guest' authentication. If however, access to the full set of resources is required, 'user' authentication can be used. This is done by using the cookies associated with your Twitter/X account, and encoding them into an API_KEY for convenience. The said API_KEY can be obtained by using a Firefox extension or manually from your browser (Chrome/Chromium-Based/Firefox/Firefox-Based), as follows:
F12 on your keyboard.auth_token, ct0, twid. These server as your authentication credentials.Console of your browser developer tools, and execute the command: btoa("auth_token=<auth_token_value>;ct0=<ct0_value>;twid=<twid_value>;"). Substitute the values of the tokens with the values you copied.Get API Key button, this will generate the API_KEY and will show up in the text-area.API_KEY by either clicking on the Copy API Key button or manually from the text-area.API_KEY still remains valid.API_KEY for use.API_KEY created in this way should last 5 years from the date of login, as long as the credentials to the account aren't changed.API_KEY to last only as long as the Twitter/X account isn't logged out of (you may exit the browser as usual) or 5 years, whichever comes first. That's why it's recommended to use incognito/in-private mode, so that the API_KEY isn't accidentially revoked by logging out.The API_KEY generated by logging in is what allows Rettiwt-API to authenticate as a logged in user while interacting with the Twitter API ('user' authentication). As such it is a very sensitive information and therefore, must be stored securely. The following points must be kept in mind while using the API_KEY for 'user' authentication:
Rettiwt-API can be used as a dependency for your NodeJS project. In such a case, it is not required to install Rettiwt-API globally and you may install it locally in the root of your project using the command:
npm install --save rettiwt-api (using npm)
or
yarn add rettiwt-api (using yarn)
However, in this case, for accessing the CLI, you will be required to prepend the CLI commands with npx in order to tell NodeJS to use the locally installed package.
When used as a dependency, the Rettiwt class is entry point for accessing the Twitter API.
A new Rettiwt instance can be initialized using the following code snippets:
const rettiwt = new Rettiwt() (for 'guest' authentication)const rettiwt = new Rettiwt({ apiKey: API_KEY }) (for 'user' authentication)The Rettiwt class has five members:
dm member, for accessing resources related to direct messages.list member, for accessing resources related to lists.space member, for accessing resources related to spaces.tweet member, for accessing resources related to tweets.user member, for accessing resources related to users.For details regarding usage of these members for accessing the Twitter API, refer to features.
When initializing a new Rettiwt instance, it can be configures using various parameters, namely:
apiKey (string) - The API key to use for user authentication.proxy (string | AxiosProxyConfig) - The proxy server to use.timeout (number) - The timeout to use for HTTP requests used by Rettiwt.logging (boolean) - Whether to enable logging or not.errorHandler (interface) - The custom error handler to use.headers (object) - Custom HTTP headers to append to the default headers.delay (number/function) - The delay to use between concurrent requests, can either be a number in milliseconds, or a function that returns the number. Default is 0 (no delay).maxRetries (number) - The maximum number of retries to use in case when a random error 404 is encountered. Default is 0 (no retries).Of these parameters, the following are hot-swappable, using their respective setters:
apiKeyheadersproxyThe following example demonstrates changing the API key on the fly:
import { Rettiwt } from 'rettiwt-api';
// Initializing a new Rettiwt instance with API key 1
const rettiwt = new Rettiwt({ apiKey: '<API_KEY_1>' });
rettiwt.user.details().then((res) => {
console.log(res); // Returns details of the user associated with API_KEY_1
});
// Changing API key to API key 2
rettiwt.apiKey = '<API_KEY_2>';
rettiwt.user.details().then((res) => {
console.log(res); // Returns details of the user associated with API_KEY_2
});
The following examples may help you to get started using the library:
import { Rettiwt } from 'rettiwt-api';
// Creating a new Rettiwt instance
// Note that for accessing user details, 'guest' authentication can be used
const rettiwt = new Rettiwt();
// Fetching the details of the user whose username is <username>
rettiwt.user.details('<username>')
.then(details => {
...
})
.catch(error => {
...
});
import { Rettiwt } from 'rettiwt-api';
// Creating a new Rettiwt instance using the API_KEY
const rettiwt = new Rettiwt({ apiKey: API_KEY });
/**
* Fetching the list of tweets that:
* - are made by a user with username <username>,
* - contain the words <word1> and <word2>
*/
rettiwt.tweet.search({
fromUsers: ['<username>'],
includeWords: ['<word1>', '<word2>']
})
.then(data => {
...
})
.catch(err => {
...
});
For more information regarding the different available filter options, please refer to TweetFilter.
The previous example fetches the the list of tweets matching the given filter. Since no count is specified, in this case, a default of 20 such Tweets are fetched initially. The following example demonstrates how to use the cursor string obtained from the response object's next field, from the previous example, to fetch the next batch of tweets:
import { Rettiwt } from 'rettiwt-api';
// Creating a new Rettiwt instance using the API_KEY
const rettiwt = new Rettiwt({ apiKey: API_KEY });
/**
* Fetching the list of tweets that:
* - are made by a user with username <username>,
* - contain the words <word1> and <word2>
*
* 'data' is the response object received in the previous example.
*
* 'count' is a number less or equal to 20 (the quantity of tweets to return)
*/
rettiwt.tweet.search({
fromUsers: ['<username>'],
includeWords: ['<word1>', '<word2>']
}, count, data.next.value)
.then(data => {
...
})
.catch(err => {
...
});
import { Rettiwt } from 'rettiwt-api';
// Creating a new Rettiwt instance using the API_KEY
const rettiwt = new Rettiwt({ apiKey: API_KEY });
// Fetching the edit history of the tweet whose ID is <tweet_id>
rettiwt.tweet.history('<tweet_id>')
.then(tweets => {
...
})
.catch(err => {
...
});
Rettiwt allows configuring a response middleware, which provides access to the raw AxiosResponse object, as received from Twitter. The middleware is non-blocking in nature, and serves purely as an accessorial method.
This is especially helpful getting access to response headers like rate limit information.
The following example demonstrates using a custom response handler for getting rate limit information:
// Creating a new Rettiwt instance using guest auth
const rettiwt = new Rettiwt({
responseMiddleware: (res): void => {
console.log(`Rate limit: ${res.headers['x-rate-limit-limit']}`);
console.log(`Rate limit remaining: ${res.headers['x-rate-limit-remaining']}`);
console.log(`Rate limit reset timestamp (seconds): ${res.headers['x-rate-limit-reset']}`);
console.log('\n');
},
});
// Getting the details of user by username
rettiwt.user
.details('negmatico')
.then((res) => {
console.log(res.toJSON());
// Results in similar data being logged to console, as follows:
// Rate limit: 50
// Rate limit reamining: 49
// Rate limit reset timestamp (seconds): 1775416043
//
// {
// "createdAt": "2021-07-24T14:25:32.000Z",
// "description": "Coder, Gamer and Tech Enthusiast",
// "followersCount": 3,
// "followingsCount": 44,
// "fullName": "Rishikant Sahu",
// "id": "1418940387037782018",
// "isVerified": false,
// "likeCount": 762,
// "profileImage": "https://abs.twimg.com/sticky/default_profile_images/default_profile_normal.png",
// "statusesCount": 5,
// "userName": "negmatico"
// }
})
.catch((err) => {
console.log(err);
});
Out of the box, Rettiwt's error handling is bare-minimum, only able to parse basic error messages. For advanced scenarios, where full error response might be required, in order to diagnose error reason, it's recommended to use a custom error handler, by implementing the IErrorHandler interface, as follows:
```ts import { Rettiwt, IErrorHandler } from 'rettiwt-api';
// Implementing an error handler class CustomErrorHandler implements IErrorHandler { / * This is where you handle the error yourself. */ public handler(error: unknown): void { // The 'error' variable has the full, raw error response returned from Twitter. / * You custom error handling log
$ claude mcp add Rettiwt-API \
-- python -m otcore.mcp_server <graph>