### Add and Run Examples Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/CONTRIBUTING.md Instructions for adding new examples and running them. Make sure to make the example file executable before running. ```ts // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```sh $ chmod +x examples/.ts # run the example against your api $ pnpm tsn -T examples/.ts ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/CONTRIBUTING.md Installs project dependencies and builds the project output. Ensure you have pnpm installed. ```sh $ pnpm install $ pnpm build ``` -------------------------------- ### Install Webhook for Real-time Events Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Use `client.webhooks.create` to install a webhook. This allows receiving real-time events from X. ```typescript client.webhooks.create ``` -------------------------------- ### Install from Git Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/CONTRIBUTING.md Installs the package directly from a Git repository using npm. ```sh $ npm install git+ssh://git@github.com:Xquik-dev/x-twitter-scraper-typescript.git ``` -------------------------------- ### Install Xquik TypeScript SDK Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Install the SDK using npm. This command adds the `x-twitter-scraper` package to your project dependencies. ```sh npm install x-twitter-scraper ``` -------------------------------- ### Retrieve and Update Account Information Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Get account details like email, plan, and credit balance using client.account.retrieve. Link an X username with client.account.setXUsername and update locale and timezone settings with client.account.updateLocale. ```typescript // Get account info const info = await client.account.retrieve(); console.log(info.email, info.plan, info.creditsBalance); // Link an X username to your account await client.account.setXUsername({ username: 'myxusername' }); // Update locale / timezone await client.account.updateLocale({ locale: 'en-US', timezone: 'America/New_York' }); ``` -------------------------------- ### Configure Proxy with Deno Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Use Deno.createHttpClient with proxy configuration and pass it to fetchOptions for Deno runtime. ```typescript import XTwitterScraper from 'npm:x-twitter-scraper'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new XTwitterScraper({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### client.x.tweets.retrieve — Get Tweet by ID Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Fetch a single tweet by its ID, including its full text, engagement metrics, media attachments, and author details. ```APIDOC ## client.x.tweets.retrieve — Get Tweet by ID Fetch a single tweet with full text, engagement metrics, media attachments, and author details. ```ts const { tweet, author } = await client.x.tweets.retrieve('1234567890123456789'); // TweetDetail fields console.log(tweet.text); // tweet body console.log(tweet.likeCount); // engagement metrics console.log(tweet.retweetCount); console.log(tweet.viewCount); console.log(tweet.isNoteTweet); // true for long-form (Note Tweet, up to 25k chars) console.log(tweet.media); // [{ type: 'photo', mediaUrl: '...' }] console.log(tweet.conversationId); // root tweet ID for reply chains // TweetAuthor fields console.log(author?.username); // e.g. 'elonmusk' console.log(author?.followers); console.log(author?.verified); ``` ``` -------------------------------- ### Accessing Raw Response Data Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Describes how to access the raw `Response` object from `fetch()` using the `.asResponse()` method, and how to get both the parsed data and the raw `Response` using `.withResponse()`. ```APIDOC ## Accessing raw Response data (e.g., headers) The "raw" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return. This method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic. You can also use the `.withResponse()` method to get the raw `Response` along with the parsed data. Unlike `.asResponse()` this method consumes the body, returning once it is parsed. ```ts const client = new XTwitterScraper(); const response = await client.x.tweets.search({ q: 'from:elonmusk', limit: 10 }).asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.statusText); // access the underlying Response object const { data: paginatedTweets, response: raw } = await client.x.tweets .search({ q: 'from:elonmusk', limit: 10 }) .withResponse(); console.log(raw.headers.get('X-My-Header')); console.log(paginatedTweets.has_next_page); ``` ``` -------------------------------- ### Connect X Accounts with TypeScript SDK Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Use `client.x.accounts.create` to connect X accounts. This is the initial step for interacting with X data workflows. ```typescript client.x.accounts.create ``` -------------------------------- ### Get Parsed Data and Raw Response Together Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Obtain both the parsed data and the raw HTTP response for a request by chaining the .withResponse() method. This allows access to response status and headers alongside the data. ```typescript // Parsed data + raw response together const { data, response } = await client.x.tweets .search({ q: 'TypeScript', limit: 10 }) .withResponse(); console.log(data.tweets.length, response.status); ``` -------------------------------- ### File Uploads Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Demonstrates various ways to upload files using the `client.x.media.upload` method, supporting different input types like `fs.ReadStream`, `File` objects, `fetch` Responses, and buffers via the `toFile` helper. ```APIDOC ## File Uploads Request parameters that correspond to file uploads can be passed in many different forms: - `File` (or an object with the same structure) - a `fetch` `Response` (or an object with the same structure) - an `fs.ReadStream` - the return value of our `toFile` helper ```ts import fs from 'fs'; import XTwitterScraper, { toFile } from 'x-twitter-scraper'; const client = new XTwitterScraper(); // If you have access to Node `fs` we recommend using `fs.createReadStream()`: await client.x.media.upload({ account: '@elonmusk', file: fs.createReadStream('/path/to/file') }); // Or if you have the web `File` API you can pass a `File` instance: await client.x.media.upload({ account: '@elonmusk', file: new File(['my bytes'], 'file') }); // You can also pass a `fetch` `Response`: await client.x.media.upload({ account: '@elonmusk', file: await fetch('https://somesite/file') }); // Finally, if none of the above are convenient, you can use our `toFile` helper: await client.x.media.upload({ account: '@elonmusk', file: await toFile(Buffer.from('my bytes'), 'file'), }); await client.x.media.upload({ account: '@elonmusk', file: await toFile(new Uint8Array([0, 1, 2]), 'file'), }); ``` ``` -------------------------------- ### Run Tests Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/CONTRIBUTING.md Executes the project's test suite using pnpm. ```sh $ pnpm run test ``` -------------------------------- ### Search Tweets with Pagination Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Search public tweets using X query syntax with cursor-based pagination. Configure parameters like query, limit, queryType, and date filters. The example demonstrates fetching all tweets until no next page is available. ```typescript import XTwitterScraper, { type XTwitterScraper as NS } from 'x-twitter-scraper'; const client = new XTwitterScraper(); // Typed params const params: NS.X.TweetSearchParams = { q: 'from:OpenAI lang:en -is:retweet', limit: 100, queryType: 'Latest', sinceTime: '2024-01-01T00:00:00Z', untilTime: '2024-12-31T23:59:59Z', }; let cursor: string | undefined; const allTweets: NS.SearchTweet[] = []; do { const page: NS.PaginatedTweets = await client.x.tweets.search({ ...params, cursor, }); allTweets.push(...page.tweets); cursor = page.has_next_page ? page.next_cursor : undefined; console.log(`Fetched ${allTweets.length} tweets so far`); } while (cursor); // Each SearchTweet has: id, text, author, likeCount, retweetCount, viewCount, createdAt console.log(allTweets[0]); ``` -------------------------------- ### Check and Top-Up Credit Balance Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Retrieve the current credit balance and currency using client.credits.retrieveBalance. Add credits to the account by specifying the amount with client.credits.topupBalance. ```typescript // Check balance const { balance, currency } = await client.credits.retrieveBalance(); console.log(`Balance: ${balance} ${currency}`); // Top up balance const topup = await client.credits.topupBalance({ amount: 100 }); console.log(topup); ``` -------------------------------- ### Upload Media Files with X-Twitter-Scraper Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Demonstrates various ways to upload media files using the `client.x.media.upload` method. Supports `fs.ReadStream`, web `File` API, `fetch` `Response`, and a custom `toFile` helper. ```typescript import fs from 'fs'; import XTwitterScraper, { toFile } from 'x-twitter-scraper'; const client = new XTwitterScraper(); // If you have access to Node `fs` we recommend using `fs.createReadStream()`: await client.x.media.upload({ account: '@elonmusk', file: fs.createReadStream('/path/to/file') }); // Or if you have the web `File` API you can pass a `File` instance: await client.x.media.upload({ account: '@elonmusk', file: new File(['my bytes'], 'file') }); // You can also pass a `fetch` `Response`: await client.x.media.upload({ account: '@elonmusk', file: await fetch('https://somesite/file') }); // Finally, if none of the above are convenient, you can use our `toFile` helper: await client.x.media.upload({ account: '@elonmusk', file: await toFile(Buffer.from('my bytes'), 'file'), }); await client.x.media.upload({ account: '@elonmusk', file: await toFile(new Uint8Array([0, 1, 2]), 'file'), }); ``` -------------------------------- ### Configure Proxy with Bun Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Set the proxy option directly in fetchOptions for Bun runtime. ```typescript import XTwitterScraper from 'x-twitter-scraper'; const client = new XTwitterScraper({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Advanced: Configure Proxies and Logging Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Configure the scraper to use a proxy server via fetchOptions and a dispatcher like undici.ProxyAgent. Initialize with a custom logger and set the log level. ```typescript import XTwitterScraper from 'x-twitter-scraper'; import pino from 'pino'; import * as undici from 'undici'; const logger = pino(); const proxyAgent = new undici.ProxyAgent('http://proxy.example.com:8888'); const client = new XTwitterScraper({ apiKey: process.env['X_TWITTER_SCRAPER_API_KEY'], logger: logger.child({ name: 'XTwitterScraper' }), logLevel: 'debug', fetchOptions: { dispatcher: proxyAgent }, // Node.js undici proxy }); ``` -------------------------------- ### Create and Manage Real-Time Account Monitors Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Set up monitors to track specific events (tweets, replies, retweets, quote tweets) for X accounts. Supports creating, listing, retrieving, updating (pausing/resuming), and deactivating monitors. ```typescript // Create a monitor (event types: 'tweet.new' | 'tweet.reply' | 'tweet.retweet' | 'tweet.quote') const monitor = await client.monitors.create({ username: 'elonmusk', // without @ eventTypes: ['tweet.new', 'tweet.reply'], }); console.log('Monitor ID:', monitor.id); // List all monitors const { monitors, total } = await client.monitors.list(); console.log(`${total} monitors active`); // Get one monitor const m = await client.monitors.retrieve(monitor.id); console.log(m.isActive, m.eventTypes); // Update — pause monitor await client.monitors.update(monitor.id, { isActive: false }); // Resume and add event types await client.monitors.update(monitor.id, { isActive: true, eventTypes: ['tweet.new', 'tweet.reply', 'tweet.retweet', 'tweet.quote'], }); // Deactivate (soft delete) const res = await client.monitors.deactivate(monitor.id); console.log(res.success); // true ``` -------------------------------- ### Basic Tweet Search with Xquik SDK Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Initialize the client with your API key and perform a tweet search. The `limit` option controls the number of results per page. Access pagination information via `has_next_page`. ```javascript import XTwitterScraper from 'x-twitter-scraper'; const client = new XTwitterScraper({ apiKey: process.env['X_TWITTER_SCRAPER_API_KEY'], // This is the default and can be omitted }); const paginatedTweets = await client.x.tweets.search({ q: 'from:elonmusk', limit: 10 }); console.log(paginatedTweets.has_next_page); ``` -------------------------------- ### Account Info and Locale Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Retrieve account metadata, link an X username, and update locale settings. ```APIDOC ## client.account.retrieve ### Description Retrieves account information. ### Method `account.retrieve()` ### Response #### Success Response (200) - **email** (string) - The account's email address. - **plan** (string) - The account's subscription plan. - **creditsBalance** (number) - The account's current credit balance. ## client.account.setXUsername ### Description Links an X username to the Xquik account. ### Method `account.setXUsername(options: { username: string })` ### Parameters - **username** (string) - Required - The X username to link. ## client.account.updateLocale ### Description Updates the account's locale and timezone settings. ### Method `account.updateLocale(options: { locale: string, timezone: string })` ### Parameters - **locale** (string) - Required - The locale setting (e.g., 'en-US'). - **timezone** (string) - Required - The timezone setting (e.g., 'America/New_York'). ``` -------------------------------- ### Advanced: Raw Response, Logging, Proxies, and Custom Fetch Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Demonstrates advanced usage including accessing raw HTTP responses, configuring logging, using proxies, and overriding the fetch implementation. ```APIDOC ## client.x.tweets.search(...).asResponse() ### Description Searches for tweets and returns the raw HTTP response, including headers. ### Method `x.tweets.search(options: { q: string, limit?: number }).asResponse()` ### Parameters - **q** (string) - Required - The search query. - **limit** (number) - Optional - The maximum number of tweets to retrieve. ### Response #### Success Response (200) - **headers** (Headers) - The response headers. ## client.x.tweets.search(...).withResponse() ### Description Searches for tweets and returns both the parsed data and the raw HTTP response. ### Method `x.tweets.search(options: { q: string, limit?: number }).withResponse()` ### Parameters - **q** (string) - Required - The search query. - **limit** (number) - Optional - The maximum number of tweets to retrieve. ### Response #### Success Response (200) - **data** (Object) - The parsed tweet data. - **response** (Object) - The raw HTTP response object. ## client.x.tweets.search(query, options) ### Description Searches for tweets with per-request timeout and retry overrides. ### Method `x.tweets.search(query: { q: string }, options: { timeout?: number, maxRetries?: number })` ### Parameters - **query** (Object) - Required - The search query object. - **q** (string) - Required - The search query. - **options** (Object) - Optional - Request-specific options. - **timeout** (number) - Optional - Request timeout in milliseconds. - **maxRetries** (number) - Optional - Maximum number of retries. ## client.post(path, options) ### Description Makes a POST request to a custom, potentially undocumented, endpoint. ### Method `post(path: string, options: { body?: Object, query?: Object })` ### Parameters - **path** (string) - Required - The path of the endpoint. - **options** (Object) - Optional - Request options. - **body** (Object) - Optional - The request body. - **query** (Object) - Optional - The query parameters. ``` -------------------------------- ### Analyze and Compare Writing Styles Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Analyze the writing style of an X username using client.styles.analyze. Compare two styles with client.styles.compare and retrieve performance metrics for a specific style using client.styles.getPerformance. ```typescript // Analyze writing style from an account const style = await client.styles.analyze({ username: 'elonmusk' }); console.log('Style ID:', style.id); // Compare two styles const comparison = await client.styles.compare({ styleId1: 'style_aaa', styleId2: 'style_bbb', }); console.log(comparison); // Get performance metrics for a style const perf = await client.styles.getPerformance('style_abc123'); console.log(perf); ``` -------------------------------- ### Configure Proxy with Node.js (undici) Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Provide custom fetchOptions with a ProxyAgent for Node.js runtime. Requires undici. ```typescript import XTwitterScraper from 'x-twitter-scraper'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new XTwitterScraper({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### Bookmarks Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/api.md Methods for managing X bookmarks. ```APIDOC ## GET /x/bookmarks ### Description Retrieves a list of bookmarked tweets. ### Method GET ### Endpoint /x/bookmarks ### Query Parameters - **params** (object) - Required - Parameters for listing bookmarks (e.g., pagination). ### Response #### Success Response (200) - **PaginatedTweets** (object) - A paginated list of bookmarked tweets. ``` ```APIDOC ## GET /x/bookmarks/folders ### Description Retrieves bookmark folders. ### Method GET ### Endpoint /x/bookmarks/folders ### Response #### Success Response (200) - **BookmarkRetrieveFoldersResponse** (object) - The response object containing bookmark folders. ``` -------------------------------- ### client.x.communities Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Create, join, search, and query members and posts of X Communities. ```APIDOC ## client.x.communities — Communities Create, join, search, and query members and posts of X Communities. ### retrieveSearch Searches for communities. #### Parameters - **options** (object) - Required - Search options. - **q** (string) - Required - The search query. ### retrieveInfo Gets information about a specific community. #### Parameters - **communityId** (string) - Required - The ID of the community. ### retrieveMembers Retrieves members of a community. #### Parameters - **communityId** (string) - Required - The ID of the community. - **options** (object) - Optional - Options for pagination. - **cursor** (string | undefined) - The cursor for pagination. ### join.create Joins a community. #### Parameters - **communityId** (string) - Required - The ID of the community. - **options** (object) - Required - Join options. - **account** (string) - Required - The account to join with (e.g., '@mybot'). ### join.deleteAll Leaves a community. #### Parameters - **communityId** (string) - Required - The ID of the community. - **options** (object) - Required - Leave options. - **account** (string) - Required - The account to leave with (e.g., '@mybot'). ### tweets.listByCommunity Lists posts within a community. #### Parameters - **communityId** (string) - Required - The ID of the community. ``` -------------------------------- ### Client Initialization Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Instantiate the XTwitterScraper client with an API key or Bearer token. Options like timeout and maxRetries can be configured. Error handling patterns using APIError and RateLimitError are also demonstrated. ```APIDOC ## Client Initialization Instantiate `XTwitterScraper` with an API key or Bearer token; all options can be overridden per-request. ```ts import XTwitterScraper from 'x-twitter-scraper'; // API key from env (X_TWITTER_SCRAPER_API_KEY) — default const client = new XTwitterScraper({ apiKey: process.env['X_TWITTER_SCRAPER_API_KEY'], // Or use OAuth 2.1: // bearerToken: process.env['X_TWITTER_SCRAPER_BEARER_TOKEN'], timeout: 30_000, // ms, default 60 000 maxRetries: 3, // default 2 logLevel: 'debug', // 'debug' | 'info' | 'warn' | 'error' | 'off' }); // Fork a client with different options for one code path const readOnlyClient = client.withOptions({ maxRetries: 0 }); // Error handling pattern used throughout the SDK import XTwitterScraper, { APIError, RateLimitError } from 'x-twitter-scraper'; try { const result = await client.x.tweets.search({ q: 'TypeScript', limit: 50 }); console.log(result.tweets.length, 'tweets'); } catch (err) { if (err instanceof RateLimitError) { console.error('Rate limited — retry after cooling down'); } else if (err instanceof APIError) { console.error(err.status, err.name, err.headers); } } ``` ``` -------------------------------- ### Link Local Repository with pnpm Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/CONTRIBUTING.md Links a local clone of the repository to another project using pnpm. This is useful for development. ```sh # With pnpm $ pnpm link --global $ cd ../my-package $ pnpm link --global x-twitter-scraper ``` -------------------------------- ### AI-Enhanced Social Automation with TypeScript SDK Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Pair `client.compose.create` with `client.styles.analyze` to draft on-brand content, and `client.x.tweets.create` to publish it. This enables AI-driven content creation and publishing within the SDK. ```typescript client.compose.create client.styles.analyze client.x.tweets.create ``` -------------------------------- ### Credit Balance and Top-Up Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Check your current credit balance and add more credits to your Xquik account. ```APIDOC ## client.credits.retrieveBalance ### Description Retrieves the current credit balance for the account. ### Method `credits.retrieveBalance()` ### Response #### Success Response (200) - **balance** (number) - The current credit balance. - **currency** (string) - The currency of the balance. ## client.credits.topupBalance ### Description Adds credits to the account balance. ### Method `credits.topupBalance(options: { amount: number })` ### Parameters - **amount** (number) - Required - The amount of credits to add. ### Response #### Success Response (200) - (Object) - The result of the top-up operation. ``` -------------------------------- ### Bulk Data Pipeline ETL Loop with TypeScript SDK Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Implement a complete ETL loop for bulk data extraction using `client.extractions.run`, polling with `client.extractions.retrieve`, and exporting results with `client.extractions.exportResults`. Supports CSV, XLSX, and PDF formats. ```typescript client.extractions.run client.extractions.retrieve client.extractions.exportResults({ format: 'csv' }) ``` -------------------------------- ### Accounts Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/api.md Methods for managing X accounts. ```APIDOC ## POST /x/accounts ### Description Creates a new X account. ### Method POST ### Endpoint /x/accounts ### Request Body - **params** (object) - Required - Parameters for creating an account. ### Response #### Success Response (200) - **AccountCreateResponse** (object) - The response object for account creation. ``` ```APIDOC ## GET /x/accounts/{id} ### Description Retrieves details for a specific X account. ### Method GET ### Endpoint /x/accounts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the account. ### Response #### Success Response (200) - **XAccountDetail** (object) - The detailed information of the X account. ``` ```APIDOC ## GET /x/accounts ### Description Retrieves a list of X accounts. ### Method GET ### Endpoint /x/accounts ### Response #### Success Response (200) - **AccountListResponse** (object) - The response object containing a list of X accounts. ``` ```APIDOC ## DELETE /x/accounts/{id} ### Description Deletes an X account by its ID. ### Method DELETE ### Endpoint /x/accounts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the account to delete. ### Response #### Success Response (200) - **AccountDeleteResponse** (object) - The response object for account deletion. ``` ```APIDOC ## POST /x/accounts/bulk-retry ### Description Performs a bulk retry operation for accounts. ### Method POST ### Endpoint /x/accounts/bulk-retry ### Response #### Success Response (200) - **AccountBulkRetryResponse** (object) - The response object for the bulk retry operation. ``` ```APIDOC ## POST /x/accounts/{id}/reauth ### Description Reauthenticates a specific X account. ### Method POST ### Endpoint /x/accounts/{id}/reauth ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the account to reauthenticate. #### Request Body - **params** (object) - Required - Parameters for reauthentication. ### Response #### Success Response (200) - **AccountReauthResponse** (object) - The response object for the reauthentication. ``` -------------------------------- ### Manage API Keys Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Create new programmatic API keys with a name using client.apiKeys.create. List all existing keys with client.apiKeys.list and revoke a specific key by its ID using client.apiKeys.revoke. ```typescript // Create a new API key const created = await client.apiKeys.create({ name: 'production-bot' }); console.log('New key:', created.key); // shown only once // List all keys const keys = await client.apiKeys.list(); keys.forEach((k: NS.APIKey) => console.log(k.id, k.name, k.createdAt)); // Revoke a key const revoked = await client.apiKeys.revoke('key_id_to_revoke'); console.log(revoked.success); ``` -------------------------------- ### X Core Methods Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/api.md Access core X platform functionalities, including articles, timelines, notifications, and trends. ```APIDOC ## GET /x/articles/{tweetId} ### Description Retrieves detailed information about a specific X article identified by its tweet ID. ### Method GET ### Endpoint /x/articles/{tweetId} ### Parameters #### Path Parameters - **tweetId** (string) - Required - The ID of the tweet associated with the article. ### Response #### Success Response (200) - **XGetArticleResponse** (object) - Detailed information about the X article. ``` ```APIDOC ## GET /x/timeline ### Description Retrieves the user's home timeline, a paginated list of tweets. ### Method GET ### Endpoint /x/timeline ### Query Parameters - **params** (object) - Optional - Parameters for pagination and filtering. ### Response #### Success Response (200) - **PaginatedTweets** (object) - A paginated list of tweets from the home timeline. ``` ```APIDOC ## GET /x/notifications ### Description Retrieves a paginated list of the user's notifications. ### Method GET ### Endpoint /x/notifications ### Query Parameters - **params** (object) - Optional - Parameters for pagination and filtering. ### Response #### Success Response (200) - **XGetNotificationsResponse** (object) - A paginated list of notifications. ``` ```APIDOC ## GET /x/trends ### Description Retrieves trending topics on X. ### Method GET ### Endpoint /x/trends ### Query Parameters - **params** (object) - Optional - Parameters for filtering trends (e.g., by location). ### Response #### Success Response (200) - **XGetTrendsResponse** (object) - A list of trending topics. ``` -------------------------------- ### Initialize X Twitter Scraper Client Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Instantiate the XTwitterScraper client with an API key or Bearer token. Options like timeout and maxRetries can be configured. Forking a client with different options is also demonstrated. ```typescript import XTwitterScraper from 'x-twitter-scraper'; // API key from env (X_TWITTER_SCRAPER_API_KEY) — default const client = new XTwitterScraper({ apiKey: process.env['X_TWITTER_SCRAPER_API_KEY'], // Or use OAuth 2.1: // bearerToken: process.env['X_TWITTER_SCRAPER_BEARER_TOKEN'], timeout: 30_000, // ms, default 60 000 maxRetries: 3, // default 2 logLevel: 'debug', // 'debug' | 'info' | 'warn' | 'error' | 'off' }); // Fork a client with different options for one code path const readOnlyClient = client.withOptions({ maxRetries: 0 }); ``` ```typescript import XTwitterScraper, { APIError, RateLimitError } from 'x-twitter-scraper'; try { const result = await client.x.tweets.search({ q: 'TypeScript', limit: 50 }); console.log(result.tweets.length, 'tweets'); } catch (err) { if (err instanceof RateLimitError) { console.error('Rate limited — retry after cooling down'); } else if (err instanceof APIError) { console.error(err.status, err.name, err.headers); } } ``` -------------------------------- ### Manage Support Tickets Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Create new support tickets with subject, message, and category using client.support.tickets.create. Reply to tickets, update their status, and list all tickets. ```typescript // Create a ticket const ticket = await client.support.tickets.create({ subject: 'Extraction job stuck in running state', message: 'Job ID extr_abc123 has been running for over 2 hours.', category: 'extraction', }); console.log('Ticket ID:', ticket.id); // Reply to a ticket await client.support.tickets.reply(ticket.id, { message: 'Attaching the job logs for reference.', }); // Update ticket status await client.support.tickets.update(ticket.id, { status: 'open' }); // List all tickets const tickets = await client.support.tickets.list(); tickets.forEach((t: any) => console.log(t.id, t.subject, t.status)); ``` -------------------------------- ### client.x.accounts Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Add, list, remove, and re-authenticate X accounts connected to your Xquik workspace. ```APIDOC ## client.x.accounts — Managed X Accounts Add, list, remove, and re-authenticate X accounts connected to your Xquik workspace. ### list Lists all connected X accounts. ### create Adds a new X account. #### Parameters - **options** (object) - Required - Account creation options. - **username** (string) - Required - The username of the account. - **authFields** (object) - Optional - Additional authentication fields. ### retrieve Gets details for a specific X account. #### Parameters - **accountId** (string) - Required - The ID of the account. ### reauth Re-authenticates a stale X account. #### Parameters - **accountId** (string) - Required - The ID of the account. - **options** (object) - Optional - Re-authentication options. ### bulkRetry Retries authentication for all failed accounts in bulk. ### delete Removes an X account. #### Parameters - **accountId** (string) - Required - The ID of the account. ``` -------------------------------- ### APIKeys Methods Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/api.md Methods for managing API keys, including creation, listing, and revocation. ```APIDOC ## POST /api-keys ### Description Creates a new API key. ### Method POST ### Endpoint /api-keys ### Parameters #### Request Body - **params** (object) - Required - Parameters for creating the API key. ### Request Example { "example": "{ ...params }" } ### Response #### Success Response (200) - **APIKeyCreateResponse** (object) - Response containing the newly created API key details. ### Response Example { "example": "APIKeyCreateResponse" } ``` ```APIDOC ## GET /api-keys ### Description Lists all available API keys. ### Method GET ### Endpoint /api-keys ### Response #### Success Response (200) - **APIKeyListResponse** (object) - Response containing a list of API keys. ### Response Example { "example": "APIKeyListResponse" } ``` ```APIDOC ## DELETE /api-keys/{id} ### Description Revokes an existing API key by its ID. ### Method DELETE ### Endpoint /api-keys/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the API key to revoke. ### Response #### Success Response (200) - **APIKeyRevokeResponse** (object) - Response indicating the revocation status. ### Response Example { "example": "APIKeyRevokeResponse" } ``` -------------------------------- ### Configure Custom Fetch Options Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Set custom `fetch` options during client instantiation using `fetchOptions`. These can be overridden by request-specific options. ```typescript import XTwitterScraper from 'x-twitter-scraper'; const client = new XTwitterScraper({ fetchOptions: { // `RequestInit` options }, }); ``` -------------------------------- ### Timeouts Configuration Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/README.md Explains the default request timeout of 1 minute and how to configure it using the `timeout` option, either globally for all requests or overridden on a per-request basis. Timeouts result in an `APIConnectionTimeoutError`. ```APIDOC ### Timeouts Requests time out after 1 minute by default. You can configure this with a `timeout` option: ```ts // Configure the default for all requests: const client = new XTwitterScraper({ timeout: 20 * 1000, // 20 seconds (default is 1 minute) }); // Override per-request: await client.x.tweets.search({ q: 'from:elonmusk', limit: 10 }, { timeout: 5 * 1000, }); ``` On timeout, an `APIConnectionTimeoutError` is thrown. Note that requests which time out will be [retried twice by default](#retries). ``` -------------------------------- ### Communities Source: https://github.com/xquik-dev/x-twitter-scraper-typescript/blob/main/api.md Methods for managing and interacting with X communities. ```APIDOC ## POST /x/communities ### Description Creates a new community. ### Method POST ### Endpoint /x/communities ### Request Body - **params** (object) - Required - Parameters for creating a community. ### Response #### Success Response (200) - **CommunityCreateResponse** (object) - The response object for community creation. ``` ```APIDOC ## DELETE /x/communities/{id} ### Description Deletes a community by its ID. ### Method DELETE ### Endpoint /x/communities/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the community to delete. #### Request Body - **params** (object) - Required - Parameters for deleting a community. ### Response #### Success Response (200) - **CommunityDeleteResponse** (object) - The response object for community deletion. ``` ```APIDOC ## GET /x/communities/{id}/info ### Description Retrieves information about a specific community. ### Method GET ### Endpoint /x/communities/{id}/info ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the community. ### Response #### Success Response (200) - **CommunityRetrieveInfoResponse** (object) - The response object containing community information. ``` ```APIDOC ## GET /x/communities/{id}/members ### Description Retrieves members of a specific community. ### Method GET ### Endpoint /x/communities/{id}/members ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the community. #### Query Parameters - **params** (object) - Optional - Parameters for retrieving members (e.g., pagination). ### Response #### Success Response (200) - **PaginatedUsers** (object) - A paginated list of users who are members of the community. ``` ```APIDOC ## GET /x/communities/{id}/moderators ### Description Retrieves moderators of a specific community. ### Method GET ### Endpoint /x/communities/{id}/moderators ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the community. #### Query Parameters - **params** (object) - Optional - Parameters for retrieving moderators (e.g., pagination). ### Response #### Success Response (200) - **PaginatedUsers** (object) - A paginated list of users who are moderators of the community. ``` ```APIDOC ## GET /x/communities/search ### Description Searches for communities. ### Method GET ### Endpoint /x/communities/search ### Query Parameters - **params** (object) - Required - Parameters for searching communities. ### Response #### Success Response (200) - **PaginatedTweets** (object) - A paginated list of tweets related to the community search. ``` ```APIDOC ## POST /x/communities/{id}/join ### Description Joins a community. ### Method POST ### Endpoint /x/communities/{id}/join ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the community to join. #### Request Body - **params** (object) - Required - Parameters for joining the community. ### Response #### Success Response (200) - **CommunityActionResult** (object) - The result of the join action. ``` ```APIDOC ## DELETE /x/communities/{id}/join ### Description Leaves a community. ### Method DELETE ### Endpoint /x/communities/{id}/join ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the community to leave. #### Request Body - **params** (object) - Required - Parameters for leaving the community. ### Response #### Success Response (200) - **CommunityActionResult** (object) - The result of the leave action. ``` ```APIDOC ## GET /x/communities/tweets ### Description Retrieves a list of tweets from communities. ### Method GET ### Endpoint /x/communities/tweets ### Query Parameters - **params** (object) - Required - Parameters for listing tweets (e.g., pagination). ### Response #### Success Response (200) - **PaginatedTweets** (object) - A paginated list of tweets from communities. ``` ```APIDOC ## GET /x/communities/{id}/tweets ### Description Retrieves a list of tweets from a specific community. ### Method GET ### Endpoint /x/communities/{id}/tweets ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the community. #### Query Parameters - **params** (object) - Required - Parameters for listing tweets (e.g., pagination). ### Response #### Success Response (200) - **PaginatedTweets** (object) - A paginated list of tweets from the specified community. ``` -------------------------------- ### API Key Management Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Manage programmatic API keys for your account, including creation, listing, and revocation. ```APIDOC ## client.apiKeys.create ### Description Creates a new programmatic API key. ### Method `apiKeys.create(options: { name: string })` ### Parameters - **name** (string) - Required - A name for the API key. ### Response #### Success Response (200) - **key** (string) - The newly created API key (shown only once). ## client.apiKeys.list ### Description Lists all existing API keys for the account. ### Method `apiKeys.list()` ### Response #### Success Response (200) - (Array) - A list of API key objects, each containing id, name, and createdAt. ## client.apiKeys.revoke ### Description Revokes an existing API key. ### Method `apiKeys.revoke(keyId: string)` ### Parameters - **keyId** (string) - Required - The ID of the API key to revoke. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the revocation was successful. ``` -------------------------------- ### Create, Validate, and Manage Webhooks Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Register HTTPS endpoints for real-time event deliveries. Includes creating webhooks, validating incoming payloads using HMAC, listing, updating, testing, inspecting delivery history, and deactivating webhooks. ```typescript const wh = await client.webhooks.create({ url: 'https://api.example.com/xquik-webhook', eventTypes: ['tweet.new', 'tweet.reply'], }); console.log('Webhook ID:', wh.id); console.log('Signing secret (save this!):', wh.secret); ``` ```typescript import crypto from 'crypto'; function verifyWebhook(body: string, signature: string, secret: string): boolean { const expected = crypto.createHmac('sha256', secret).update(body).digest('hex'); return crypto.timingSafeEqual(Buffer.from(signature), Buffer.from(expected)); } ``` ```typescript const { webhooks } = await client.webhooks.list(); webhooks.forEach(w => console.log(w.id, w.url, w.isActive)); ``` ```typescript await client.webhooks.update(wh.id, { url: 'https://api.example.com/webhook-v2' }); ``` ```typescript const test = await client.webhooks.test(wh.id); console.log(test.success, test.statusCode); // true, 200 ``` ```typescript const { deliveries } = await client.webhooks.listDeliveries(wh.id); deliveries.forEach(d => console.log(d.status, d.attempts, d.lastStatusCode)); ``` ```typescript await client.webhooks.deactivate(wh.id); ``` -------------------------------- ### Run and Manage Bulk Data Extraction Jobs Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Launch asynchronous extraction jobs for various data types and export results. Includes estimating costs, running jobs, polling for completion, exporting results in different formats (CSV, JSON, etc.), and listing job history. ```typescript const estimate = await client.extractions.estimateCost({ toolType: 'follower_explorer', targetUsername: 'elonmusk', }); console.log(`Requires ${estimate.creditsRequired} credits, have ${estimate.creditsAvailable}`); console.log(`Estimated ${estimate.estimatedResults} results`); ``` ```typescript const job = await client.extractions.run({ toolType: 'reply_extractor', targetTweetId: '1234567890123456789', }); console.log('Job ID:', job.id, 'Status:', job.status); // 'running' ``` ```typescript let result; while (true) { result = await client.extractions.retrieve(job.id, { limit: 100 }); const jobMeta = result.job as { status: string }; if (jobMeta.status === 'completed' || jobMeta.status === 'failed') break; await new Promise(r => setTimeout(r, 3000)); } console.log(`Got ${result.results.length} results, hasMore: ${result.hasMore}`); ``` ```typescript const csvBlob = await (await client.extractions.exportResults(job.id, { format: 'csv' })).blob(); // Also: 'json' | 'xlsx' | 'pdf' | 'txt' | 'md' | 'md-document' ``` ```typescript const { extractions } = await client.extractions.list({ status: 'completed', limit: 20 }); extractions.forEach(e => console.log(e.toolType, e.totalResults, e.completedAt)); ``` -------------------------------- ### client.x.lists Source: https://context7.com/xquik-dev/x-twitter-scraper-typescript/llms.txt Fetch members, followers, and tweets for any X List. ```APIDOC ## client.x.lists — X List Data Fetch members, followers, and tweets for any X List. ### retrieveMembers Retrieves members of an X List. #### Parameters - **listId** (string) - Required - The ID of the list. - **options** (object) - Optional - Options for pagination. - **cursor** (string | undefined) - The cursor for pagination. ### retrieveFollowers Retrieves accounts following an X List. #### Parameters - **listId** (string) - Required - The ID of the list. ### retrieveTweets Retrieves tweets from the timeline of an X List. #### Parameters - **listId** (string) - Required - The ID of the list. ```