### Get Home Timeline Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Fetches the authenticated user's home timeline, displaying the author ID and the first 80 characters of the tweet. ```kotlin import com.x_twitter_scraper.api.models.PaginatedTweets val timeline: PaginatedTweets = client.x().getHomeTimeline() timeline.tweets().forEach { t -> println("@${t.authorId()}: ${t.fullText()?.take(80)}") } ``` -------------------------------- ### Asynchronous Tweet Search and Concurrent Operations Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Shows how to switch to asynchronous execution using coroutines by calling `.async()` on the client. Includes an example of concurrent fan-out for fetching user tweets and likes. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClientAsync import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClientAsync import com.x_twitter_scraper.api.models.PaginatedTweets import com.x_twitter_scraper.api.models.x.tweets.TweetSearchParams import kotlinx.coroutines.runBlocking val asyncClient: XTwitterScraperClientAsync = XTwitterScraperOkHttpClientAsync.fromEnv() // Or from the sync client: val asyncClient = syncClient.async() runBlocking { val params = TweetSearchParams.builder().q("#kotlin").limit(10L).build() val tweets: PaginatedTweets = asyncClient.x().tweets().search(params) println("Async result: ${tweets.tweets().size} tweets") // Concurrent fan-out val (userTweets, liked) = listOf( asyncClient.x().users().retrieveTweets("44196397"), asyncClient.x().users().retrieveLikes("44196397") ).let { it[0] to it[1] } println("User tweets: ${userTweets.tweets().size}, Liked: ${liked.tweets().size}") } ``` -------------------------------- ### Get X Article Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Retrieves the full content of an X Article (formerly Twitter Notes) by its tweet ID. Displays the article's title and content length. ```kotlin import com.x_twitter_scraper.api.models.x.XGetArticleResponse val article: XGetArticleResponse = client.x().getArticle("1800000000000000000") println("Title: ${article.title()}") println("Body length: ${article.content()?.length}") ``` -------------------------------- ### Save Binary Response to File in Kotlin Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Save the content of an HttpResponse body to a file using Files.copy. Ensure to handle the InputStream properly, for example, using a 'use' block. ```kotlin import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption client.extractions().exportResults(params).use { Files.copy( it.body(), Paths.get(path), StandardCopyOption.REPLACE_EXISTING ) } ``` -------------------------------- ### Get Binary Response using HttpResponse in Kotlin Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Retrieve a binary response, such as non-JSON data, using the HttpResponse object. This is typically used for exports or downloads. ```kotlin import com.x_twitter_scraper.api.core.http.HttpResponse import com.x_twitter_scraper.api.models.extractions.ExtractionExportResultsParams val response: HttpResponse = client.extractions().exportResults("id") ``` -------------------------------- ### Get Trending Topics Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Fetches trending topics, optionally filtered by a WOEID (Where On Earth ID). Displays the trend name and tweet volume. ```kotlin import com.x_twitter_scraper.api.models.x.XGetTrendsResponse import com.x_twitter_scraper.api.models.x.XGetTrendsParams val trends: XGetTrendsResponse = client.x().getTrends( XGetTrendsParams.builder() .woeid(23424977L) // United States .build() ) trends.trends().take(5).forEach { t -> println("${t.name()} — tweet volume: ${t.tweetVolume()}") } ``` -------------------------------- ### Set Documented Parameters with Undocumented Values Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md To set a documented parameter with an undocumented value, pass a `JsonValue` object to its setter. This example shows setting `q` and `limit` for `TweetSearchParams`. ```kotlin import com.x_twitter_scraper.api.models.x.tweets.TweetSearchParams val params: TweetSearchParams = TweetSearchParams.builder() .q("from:elonmusk") .limit(10L) .build() ``` -------------------------------- ### Get Notifications Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Retrieves recent notifications for the authenticated account, showing the notification type and creation timestamp. ```kotlin import com.x_twitter_scraper.api.models.x.XGetNotificationsResponse val notifications: XGetNotificationsResponse = client.x().getNotifications() notifications.notifications().forEach { n -> println("${n.type()} — ${n.createdAt()}") } ``` -------------------------------- ### Configure X Twitter Scraper Client with Mixed Settings Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Initialize the client using a combination of environment variables/system properties and manual settings. Manual settings will override environment variables or system properties. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.builder() // Configures using the `xtwitterscraper.apiKey`, `xtwitterscraper.bearerToken` and `xtwitterscraper.baseUrl` system properties // Or configures using the `X_TWITTER_SCRAPER_API_KEY`, `X_TWITTER_SCRAPER_BEARER_TOKEN` and `X_TWITTER_SCRAPER_BASE_URL` environment variables .fromEnv() .apiKey("My API Key") .build() ``` -------------------------------- ### Configure X Twitter Scraper Client from Environment Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Initialize the client using environment variables or system properties for API key, bearer token, and base URL. This is a convenient way to configure the client without hardcoding credentials. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient // Configures using the `xtwitterscraper.apiKey`, `xtwitterscraper.bearerToken` and `xtwitterscraper.baseUrl` system properties // Or configures using the `X_TWITTER_SCRAPER_API_KEY`, `X_TWITTER_SCRAPER_BEARER_TOKEN` and `X_TWITTER_SCRAPER_BASE_URL` environment variables val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.fromEnv() ``` -------------------------------- ### Construct X Twitter Scraper Clients Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Demonstrates various ways to construct synchronous and asynchronous X Twitter Scraper clients using OkHttp. Clients can read credentials from environment variables or be configured manually via a builder. A single client instance should be reused. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.XTwitterScraperClientAsync import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClientAsync import java.net.InetSocketAddress import java.net.Proxy import java.time.Duration // ── Minimal: reads X_TWITTER_SCRAPER_API_KEY / X_TWITTER_SCRAPER_BEARER_TOKEN from env ── val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.fromEnv() // ── Fully manual builder ── val clientManual: XTwitterScraperClient = XTwitterScraperOkHttpClient.builder() .apiKey("My API Key") .bearerToken("My Bearer Token") .baseUrl("https://xquik.com/api/v1") // default base URL .maxRetries(4) .timeout(Duration.ofSeconds(30)) .maxIdleConnections(10) .keepAliveDuration(Duration.ofMinutes(2)) .proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress("proxy.example.com", 8080))) .responseValidation(true) // eagerly validate all response shapes .build() // ── Mix env + manual override ── val clientMixed: XTwitterScraperClient = XTwitterScraperOkHttpClient.builder() .fromEnv() .apiKey("override-key") .build() // ── Async client (suspend functions throughout) ── val asyncClient: XTwitterScraperClientAsync = XTwitterScraperOkHttpClientAsync.fromEnv() // ── Temporary per-request option override (shares pools with parent) ── val clientWithOptions: XTwitterScraperClient = client.withOptions { it.baseUrl("https://staging.example.com") it.maxRetries(0) } ``` -------------------------------- ### Access Undocumented Response Properties Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Retrieve undocumented properties from a response using the `_additionalProperties()` method. The example shows how to access and check the type of a `secretProperty`. ```kotlin import com.x_twitter_scraper.api.core.JsonBoolean import com.x_twitter_scraper.api.core.JsonNull import com.x_twitter_scraper.api.core.JsonNumber import com.x_twitter_scraper.api.core.JsonValue val additionalProperties: Map = client.x().tweets().search(params)._additionalProperties() val secretPropertyValue: JsonValue = additionalProperties.get("secretProperty") val result = when (secretPropertyValue) { is JsonNull -> "It's null!" is JsonBoolean -> "It's a boolean!" is JsonNumber -> "It's a number!" // Other types include `JsonMissing`, `JsonString`, `JsonArray`, and `JsonObject` else -> "It's something else!" } ``` -------------------------------- ### API Key Management: Create, List, and Revoke Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Demonstrates creating a new API key with a specified name, listing all existing API keys, and revoking a specific API key by its ID. Session authentication is required. ```kotlin import com.x_twitter_scraper.api.models.apikeys.ApiKeyCreateParams import com.x_twitter_scraper.api.models.apikeys.ApiKeyCreateResponse import com.x_twitter_scraper.api.models.apikeys.ApiKeyListResponse import com.x_twitter_scraper.api.models.apikeys.ApiKeyRevokeResponse // Create val newKey: ApiKeyCreateResponse = client.apiKeys().create( ApiKeyCreateParams.builder() .name("ci-bot-key") .build() ) println("Key: ${newKey.key()}") // List val keys: ApiKeyListResponse = client.apiKeys().list() keys.apiKeys().forEach { k -> println("${k.id()} — ${k.name()} — ${k.createdAt()}") } // Revoke val revoked: ApiKeyRevokeResponse = client.apiKeys().revoke(newKey.id()!!) println("Revoked: ${revoked.revoked()}") ``` -------------------------------- ### Build X Twitter Scraper Kotlin from Source Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Clone the repository and build the project using Gradle. This is the recommended approach until the artifact is available on Maven Central. ```bash git clone https://github.com/Xquik-dev/x-twitter-scraper-kotlin.git cd x-twitter-scraper-kotlin ./gradlew build ``` -------------------------------- ### File Uploads Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Demonstrates how to upload files using the SDK, supporting Path, InputStream, and ByteArray. It also shows how to specify a filename using MultipartField. ```APIDOC ## File Uploads The SDK defines methods that accept files. To upload a file, pass a [`Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html): ```kotlin import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse import java.nio.file.Paths val params: MediaUploadParams = MediaUploadParams.builder() .account("@elonmusk") .file(Paths.get("/path/to/file")) .build() val response: MediaUploadResponse = client.x().media().upload(params) ``` Or an arbitrary [`InputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html): ```kotlin import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse import java.net.URL val params: MediaUploadParams = MediaUploadParams.builder() .account("@elonmusk") .file(URL("https://example.com//path/to/file").openStream()) .build() val response: MediaUploadResponse = client.x().media().upload(params) ``` Or a `ByteArray`: ```kotlin import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse val params: MediaUploadParams = MediaUploadParams.builder() .account("@elonmusk") .file("content".toByteArray()) .build() val response: MediaUploadResponse = client.x().media().upload(params) ``` Note that when passing a non-`Path` its filename is unknown so it will not be included in the request. To manually set a filename, pass a [`MultipartField`](x-twitter-scraper-kotlin-core/src/main/kotlin/com/x_twitter_scraper/api/core/Values.kt): ```kotlin import com.x_twitter_scraper.api.core.MultipartField import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse import java.io.InputStream import java.net.URL val params: MediaUploadParams = MediaUploadParams.builder() .account("@elonmusk") .file(MultipartField.builder() .value(URL("https://example.com//path/to/file").openStream()) .filename("/path/to/file") .build()) .build() val response: MediaUploadResponse = client.x().media().upload(params) ``` ``` -------------------------------- ### Configure X Twitter Scraper Client Manually Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Initialize the client by manually providing the API key and bearer token. This method is useful for hardcoding credentials or when environment variables are not available. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.builder() .apiKey("My API Key") .bearerToken("My Bearer Token") .build() ``` -------------------------------- ### Modify Client Configuration Temporarily Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Use `withOptions()` to apply temporary configuration changes to a client without affecting the original instance. This is useful for testing or specific request needs. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient val clientWithOptions: XTwitterScraperClient = client.withOptions { it.baseUrl("https://example.com") it.maxRetries(42) } ``` -------------------------------- ### Account Monitoring - Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Set up real-time monitors for specific X account actions (new tweets, likes, follows) using `client.monitors()`. Requires `MonitorCreateParams` and `EventType` imports. ```kotlin import com.x_twitter_scraper.api.models.EventType import com.x_twitter_scraper.api.models.monitors.Monitor import com.x_twitter_scraper.api.models.monitors.MonitorCreateParams import com.x_twitter_scraper.api.models.monitors.MonitorCreateResponse import com.x_twitter_scraper.api.models.monitors.MonitorListResponse // Create a monitor for new tweets and likes from @elonmusk val createParams = MonitorCreateParams.builder() .username("elonmusk") .eventTypes(listOf(EventType.NEW_TWEET, EventType.LIKE)) .build() val created: MonitorCreateResponse = client.monitors().create(createParams) println("Monitor ID: ${created.id()}") // Retrieve monitor val monitor: Monitor = client.monitors().retrieve(created.id()!!) println("Active: ${monitor.active()}") // List all monitors val list: MonitorListResponse = client.monitors().list() list.monitors().forEach { m -> println("${m.id()} -> @${m.username()} (active=${m.active()})") } // Update val updated: Monitor = client.monitors().update(monitor.id()!!) // Deactivate client.monitors().deactivate(monitor.id()!!) println("Monitor deactivated") ``` -------------------------------- ### Test Local Maven Publication Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Build and publish the project to your local Maven repository for testing. Ensure the artifact is available before proceeding. ```bash ./gradlew publishToMavenLocal -PpublishLocal ``` -------------------------------- ### Search Tweets using X Twitter Scraper Kotlin Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Initialize the client using environment variables or system properties and perform a tweet search. The `q` parameter supports various search queries, and `limit` controls the number of results. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient import com.x_twitter_scraper.api.models.PaginatedTweets import com.x_twitter_scraper.api.models.x.tweets.TweetSearchParams // Configures using the `xtwitterscraper.apiKey`, `xtwitterscraper.bearerToken` and `xtwitterscraper.baseUrl` system properties // Or configures using the `X_TWITTER_SCRAPER_API_KEY`, `X_TWITTER_SCRAPER_BEARER_TOKEN` and `X_TWITTER_SCRAPER_BASE_URL` environment variables val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.fromEnv() val params: TweetSearchParams = TweetSearchParams.builder() .q("from:elonmusk") .limit(10L) .build() val paginatedTweets: PaginatedTweets = client.x().tweets().search(params) ``` -------------------------------- ### Binary Responses Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Explains how to handle binary responses from the SDK, which are useful for non-JSON data. It shows how to save the response content to a file or transfer it to an OutputStream. ```APIDOC ## Binary responses The SDK defines methods that return binary responses, which are used for API responses that shouldn't necessarily be parsed, like non-JSON data. These methods return [`HttpResponse`](x-twitter-scraper-kotlin-core/src/main/kotlin/com/x_twitter_scraper/api/core/http/HttpResponse.kt): ```kotlin import com.x_twitter_scraper.api.core.http.HttpResponse import com.x_twitter_scraper.api.models.extractions.ExtractionExportResultsParams val response: HttpResponse = client.extractions().exportResults("id") ``` To save the response content to a file, use the [`Files.copy(...)`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.io.InputStream-java.nio.file.Path-java.nio.file.CopyOption...-) method: ```kotlin import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption client.extractions().exportResults(params).use { Files.copy( it.body(), Paths.get(path), StandardCopyOption.REPLACE_EXISTING ) } ``` Or transfer the response content to any [`OutputStream`](https://docs.oracle.com/javase/8/docs/api/java/io/OutputStream.html): ```kotlin import java.nio.file.Files import java.nio.file.Paths client.extractions().exportResults(params).use { it.body().transferTo(Files.newOutputStream(Paths.get(path))) } ``` ``` -------------------------------- ### Create JsonValue Instances Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Demonstrates creating various `JsonValue` instances, including primitive types, arrays, objects, and complex nested structures, using the `JsonValue.from(...)` method. ```kotlin import com.x_twitter_scraper.api.core.JsonValue // Create primitive JSON values val nullValue: JsonValue = JsonValue.from(null) val booleanValue: JsonValue = JsonValue.from(true) val numberValue: JsonValue = JsonValue.from(42) val stringValue: JsonValue = JsonValue.from("Hello World!") // Create a JSON array value equivalent to `["Hello", "World"]` val arrayValue: JsonValue = JsonValue.from(listOf( "Hello", "World" )) // Create a JSON object value equivalent to `{ "a": 1, "b": 2 }` val objectValue: JsonValue = JsonValue.from(mapOf( "a" to 1, "b" to 2 )) // Create an arbitrarily nested JSON equivalent to: // { // "a": [1, 2], // "b": [3, 4] // } val complexValue: JsonValue = JsonValue.from(mapOf( "a" to listOf( 1, 2 ), "b" to listOf( 3, 4 ) )) ``` -------------------------------- ### Estimate and Run Bulk Extractions with X-Twitter Scraper Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Estimate the cost of an extraction job before running it. Then, initiate a job for tweet searches or follower crawls and poll for results. Finally, download the exported data. ```kotlin import com.x_twitter_scraper.api.models.extractions.ExtractionEstimateCostParams import com.x_twitter_scraper.api.models.extractions.ExtractionEstimateCostResponse import com.x_twitter_scraper.api.models.extractions.ExtractionRunParams import com.x_twitter_scraper.api.models.extractions.ExtractionRunResponse import com.x_twitter_scraper.api.models.extractions.ExtractionRetrieveResponse import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption // Estimate cost first val estimate: ExtractionEstimateCostResponse = client.extractions().estimateCost( ExtractionEstimateCostParams.builder() .toolType(ExtractionRunParams.ToolType.FOLLOWER_EXPLORER) .targetUsername("elonmusk") .build() ) println("Estimated credits: ${estimate.estimatedCredits()}") // Start extraction job val job: ExtractionRunResponse = client.extractions().run( ExtractionRunParams.builder() .toolType(ExtractionRunParams.ToolType.TWEET_SEARCH_EXTRACTOR) .searchQuery("kotlin coroutines") .exactPhrase("flow") .excludeWords("java") .build() ) println("Job ID: ${job.id()} — Status: ${job.status()}") // Poll job val result: ExtractionRetrieveResponse = client.extractions().retrieve(job.id()!!) println("Status: ${result.status()} — Rows: ${result.rowCount()}") // Download binary CSV/JSON export client.extractions().exportResults(job.id()!!).use { response -> Files.copy( response.body(), Paths.get("/tmp/extraction-results.csv"), StandardCopyOption.REPLACE_EXISTING ) } ``` -------------------------------- ### Like and Retweet Tweets - Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Use `client.x().tweets().like()` to like a tweet and `client.x().tweets().retweet()` to retweet. Requires `LikeService` and `RetweetService` imports. ```kotlin import com.x_twitter_scraper.api.services.blocking.x.tweets.LikeService import com.x_twitter_scraper.api.services.blocking.x.tweets.RetweetService val likeService: LikeService = client.x().tweets().like() val retweetService: RetweetService = client.x().tweets().retweet() // Like a tweet likeService.create(/* LikeCreateParams with account + tweetId */) // Retweet retweetService.create(/* RetweetCreateParams with account + tweetId */) ``` -------------------------------- ### Retrieve and Top-up Account Credits Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Retrieves the current account credit balance and demonstrates topping up the balance by a specified amount. Requires `CreditRetrieveBalanceResponse` and `CreditTopupBalanceResponse`. ```kotlin import com.x_twitter_scraper.api.models.credits.CreditRetrieveBalanceResponse import com.x_twitter_scraper.api.models.credits.CreditTopupBalanceParams import com.x_twitter_scraper.api.models.credits.CreditTopupBalanceResponse val balance: CreditRetrieveBalanceResponse = client.credits().retrieveBalance() println("Credits remaining: ${balance.balance()}") val topup: CreditTopupBalanceResponse = client.credits().topupBalance( CreditTopupBalanceParams.builder().amount(1000L).build() ) println("New balance: ${topup.balance()}") ``` -------------------------------- ### Upload File using Path in Kotlin Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Upload a file by providing its java.nio.file.Path. Ensure the path is correctly formatted. ```kotlin import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse import java.nio.file.Paths val params: MediaUploadParams = MediaUploadParams.builder() .account("@elonmusk") .file(Paths.get("/path/to/file")) .build() val response: MediaUploadResponse = client.x().media().upload(params) ``` -------------------------------- ### Run and Manage Giveaway Draws with X-Twitter Scraper Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Initiate a giveaway draw to select winners from tweet replies, retrieve draw details, list past draws, and export the draw data. ```kotlin import com.x_twitter_scraper.api.models.draws.DrawRunParams import com.x_twitter_scraper.api.models.draws.DrawRunResponse import com.x_twitter_scraper.api.models.draws.DrawRetrieveResponse import com.x_twitter_scraper.api.models.draws.DrawListResponse import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption // Run a draw (pick 3 winners from replies to a tweet) val draw: DrawRunResponse = client.draws().run( DrawRunParams.builder() .tweetId("1234567890123456789") .winnersCount(3L) .build() ) println("Draw ID: ${draw.id()}") draw.winners().forEach { w -> println("Winner: @${w.screenName()}") } // Get full draw details val detail: DrawRetrieveResponse = client.draws().retrieve(draw.id()!!) println("Total entries: ${detail.totalEntries()}") // List all past draws val list: DrawListResponse = client.draws().list() list.draws().forEach { d -> println("${d.id()} — ${d.createdAt()}") } // Export draw data as binary client.draws().export(draw.id()!!).use { response -> Files.copy( response.body(), Paths.get("/tmp/draw-${draw.id()}.csv"), StandardCopyOption.REPLACE_EXISTING ) } ``` -------------------------------- ### Upload Media using Local File Path Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Uploads a media file from a local file path. The filename is inferred automatically. Requires `MediaUploadParams`. ```kotlin import com.x_twitter_scraper.api.core.MultipartField import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse import java.io.InputStream import java.net.URL import java.nio.file.Paths // From a local file path (filename inferred automatically) val fromFile: MediaUploadResponse = client.x().media().upload( MediaUploadParams.builder() .account("@myhandle") .file(Paths.get("/tmp/banner.png")) .build() ) println("Media ID: ${fromFile.mediaId()}") ``` -------------------------------- ### Credits Management Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Retrieves the account credit balance and allows for topping up credits. ```APIDOC ## Credits — `client.credits()` Retrieves the account credit balance and tops it up. ```kotlin import com.x_twitter_scraper.api.models.credits.CreditRetrieveBalanceResponse import com.x_twitter_scraper.api.models.credits.CreditTopupBalanceParams import com.x_twitter_scraper.api.models.credits.CreditTopupBalanceResponse val balance: CreditRetrieveBalanceResponse = client.credits().retrieveBalance() println("Credits remaining: ${balance.balance()}") val topup: CreditTopupBalanceResponse = client.credits().topupBalance( CreditTopupBalanceParams.builder().amount(1000L).build() ) println("New balance: ${topup.balance()}") ``` ``` -------------------------------- ### Create Telegram Integration Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Creates a Telegram integration to send monitor events to a chat. Requires a valid chat ID and monitor ID. ```kotlin import com.x_twitter_scraper.api.models.integrations.Integration import com.x_twitter_scraper.api.models.integrations.IntegrationCreateParams val integration: Integration = client.integrations().create( IntegrationCreateParams.builder() .config( IntegrationCreateParams.Config.builder() .type("telegram") .chatId("-100123456789") .build() ) .monitorId("mon_abc123") .build() ) println("Integration: ${integration.id()}") ``` -------------------------------- ### Bulk Extraction Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Runs one of 20 extraction tool types as an async job and polls for results. This includes estimating costs, running jobs, polling for status, and downloading results. ```APIDOC ## Bulk Extraction — `client.extractions()` Runs one of 20 extraction tool types (follower crawls, tweet searches, community posts, etc.) as an async job and polls for results. ### Estimate Cost ```kotlin val estimate: ExtractionEstimateCostResponse = client.extractions().estimateCost( ExtractionEstimateCostParams.builder() .toolType(ExtractionRunParams.ToolType.FOLLOWER_EXPLORER) .targetUsername("elonmusk") .build() ) println("Estimated credits: ${estimate.estimatedCredits()}") ``` ### Run Extraction Job ```kotlin val job: ExtractionRunResponse = client.extractions().run( ExtractionRunParams.builder() .toolType(ExtractionRunParams.ToolType.TWEET_SEARCH_EXTRACTOR) .searchQuery("kotlin coroutines") .exactPhrase("flow") .excludeWords("java") .build() ) println("Job ID: ${job.id()} — Status: ${job.status()}") ``` ### Poll Job Status ```kotlin val result: ExtractionRetrieveResponse = client.extractions().retrieve(job.id()!!) println("Status: ${result.status()} — Rows: ${result.rowCount()}") ``` ### Export Results ```kotlin client.extractions().exportResults(job.id()!!).use { Files.copy( it.body(), Paths.get("/tmp/extraction-results.csv"), StandardCopyOption.REPLACE_EXISTING ) } ``` ``` -------------------------------- ### List and Retrieve Events - Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Retrieve activity events generated by monitors using `client.events().list()` with `EventListParams` or fetch a single event with `client.events().retrieve()`. Requires `EventListParams` and `EventListResponse` imports. ```kotlin import com.x_twitter_scraper.api.models.events.EventListParams import com.x_twitter_scraper.api.models.events.EventListResponse val params = EventListParams.builder() .monitorId("mon_abc123") .build() val events: EventListResponse = client.events().list(params) events.events().forEach { e -> println("${e.eventType()} at ${e.createdAt()} — tweet ${e.tweetId()}") } // Single event val event = client.events().retrieve("evt_xyz789") println(event.tweetId()) ``` -------------------------------- ### Configure Connection Pooling for Twitter Scraper Client Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Customize the underlying OkHttp connection pool settings, including the maximum number of idle connections and their keep-alive duration. This can optimize network performance. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient import java.time.Duration val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.builder() .fromEnv() // If `maxIdleConnections` is set, then `keepAliveDuration` must be set, and vice versa. .maxIdleConnections(10) .keepAliveDuration(Duration.ofMinutes(2)) .build() ``` -------------------------------- ### Handle X Twitter Scraper Exceptions in Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Demonstrates how to catch various exceptions thrown by the SDK, including network errors, API errors, and data validation issues. Ensure all relevant exception types are imported. ```kotlin import com.x_twitter_scraper.api.errors.BadRequestException import com.x_twitter_scraper.api.errors.InternalServerException import com.x_twitter_scraper.api.errors.NotFoundException import com.x_twitter_scraper.api.errors.PermissionDeniedException import com.x_twitter_scraper.api.errors.RateLimitException import com.x_twitter_scraper.api.errors.UnauthorizedException import com.x_twitter_scraper.api.errors.UnprocessableEntityException import com.x_twitter_scraper.api.errors.XTwitterScraperInvalidDataException import com.x_twitter_scraper.api.errors.XTwitterScraperIoException import com.x_twitter_scraper.api.errors.XTwitterScraperServiceException try { val tweet = client.x().tweets().retrieve("nonexistent-id") } catch (e: BadRequestException) { println("400 Bad Request: ${e.message()}") } catch (e: UnauthorizedException) { println("401 Unauthorized – check credentials") } catch (e: PermissionDeniedException) { println("403 Forbidden") } catch (e: NotFoundException) { println("404 Not Found: ${e.message()}") } catch (e: UnprocessableEntityException) { println("422 Unprocessable Entity: ${e.message()}") } catch (e: RateLimitException) { val retryAfter = e.headers().values("Retry-After").firstOrNull() println("429 Rate Limited. Retry after: $retryAfter seconds") } catch (e: InternalServerException) { println("5xx Server Error: ${e.statusCode()}") } catch (e: XTwitterScraperIoException) { println("Network error: ${e.message}") } catch (e: XTwitterScraperInvalidDataException) { println("Response shape mismatch: ${e.message}") } ``` -------------------------------- ### Enable Info Logging for X-Twitter Scraper Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Set the X_TWITTER_SCRAPER_LOG environment variable to 'info' to enable standard logging. This is useful for monitoring general SDK activity. ```sh export X_TWITTER_SCRAPER_LOG=info ``` -------------------------------- ### Configure Proxy for Twitter Scraper Client Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Route client requests through an HTTP proxy. This is essential for network environments that require proxying. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient import java.net.InetSocketAddress import java.net.Proxy val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.builder() .fromEnv() .proxy(Proxy( Proxy.Type.HTTP, InetSocketAddress( "https://example.com", 8080 ) )) .build() ``` -------------------------------- ### Manage Webhooks with X-Twitter Scraper Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Register, update, test, and list webhook endpoints for receiving event payloads. This includes creating a new webhook, testing its delivery, listing past deliveries, and deactivating it. ```kotlin import com.x_twitter_scraper.api.models.webhooks.Webhook import com.x_twitter_scraper.api.models.webhooks.WebhookCreateParams import com.x_twitter_scraper.api.models.webhooks.WebhookCreateResponse import com.x_twitter_scraper.api.models.webhooks.WebhookListDeliveriesResponse // Register a webhook val webhook: WebhookCreateResponse = client.webhooks().create( WebhookCreateParams.builder() .url("https://myapp.example.com/webhooks/xts") .build() ) println("Webhook ID: ${webhook.id()} — Secret: ${webhook.secret()}") // Update URL val updated: Webhook = client.webhooks().update(webhook.id()!!) // Test delivery val testResult = client.webhooks().test(webhook.id()!!) println("Test delivery status: ${testResult.success()}") // List past deliveries val deliveries: WebhookListDeliveriesResponse = client.webhooks().listDeliveries(webhook.id()!!) deliveries.deliveries().forEach { d -> println("${d.id()} — HTTP ${d.responseStatusCode()} — ${d.createdAt()}") } // List all webhooks val allHooks = client.webhooks().list() println("Total webhooks: ${allHooks.webhooks().size}") // Deactivate client.webhooks().deactivate(webhook.id()!!) ``` -------------------------------- ### Create and Delete Tweets Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Use `client.x().tweets().create()` with `TweetCreateParams` to post a new tweet and `client.x().tweets().delete()` with `TweetDeleteParams` to remove an existing tweet by its ID. Requires account handle for operations. ```kotlin import com.x_twitter_scraper.api.models.x.tweets.TweetCreateParams import com.x_twitter_scraper.api.models.x.tweets.TweetCreateResponse import com.x_twitter_scraper.api.models.x.tweets.TweetDeleteParams import com.x_twitter_scraper.api.models.x.tweets.TweetDeleteResponse // Create val createParams = TweetCreateParams.builder() .account("@myhandle") .text("Hello from the X Twitter Scraper Kotlin SDK! #kotlin") .build() val created: TweetCreateResponse = client.x().tweets().create(createParams) println("New tweet ID: ${created.id()}") // Delete val deleteParams = TweetDeleteParams.builder() .account("@myhandle") .build() val deleted: TweetDeleteResponse = client.x().tweets().delete(created.id()!!, deleteParams) println("Deleted: ${deleted.deleted()}") ``` -------------------------------- ### List Integration Deliveries Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Lists the delivery history for a specific integration. Requires the integration ID. ```kotlin // List delivery history val deliveries = client.integrations().listDeliveries(integration.id()!!) deliveries.deliveries().forEach { d -> println("${d.id()} — ${d.status()}") } ``` -------------------------------- ### Configure HTTPS Security for Twitter Scraper Client Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Customize HTTPS connection security by providing custom SSL socket factory, trust manager, and hostname verifier. Use with caution as it may override system defaults and optimizations. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.builder() .fromEnv() // If `sslSocketFactory` is set, then `trustManager` must be set, and vice versa. .sslSocketFactory(yourSSLSocketFactory) .trustManager(yourTrustManager) .hostnameVerifier(yourHostnameVerifier) .build() ``` -------------------------------- ### Webhooks Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Creates and manages webhook endpoints that receive event payloads from monitors. This includes creating, updating, testing, listing deliveries, listing all webhooks, and deactivating them. ```APIDOC ## Webhooks — `client.webhooks()` Creates and manages webhook endpoints that receive event payloads from monitors. ### Create Webhook ```kotlin val webhook: WebhookCreateResponse = client.webhooks().create( WebhookCreateParams.builder() .url("https://myapp.example.com/webhooks/xts") .build() ) println("Webhook ID: ${webhook.id()} — Secret: ${webhook.secret()}") ``` ### Update Webhook URL ```kotlin val updated: Webhook = client.webhooks().update(webhook.id()!!) ``` ### Test Webhook Delivery ```kotlin val testResult = client.webhooks().test(webhook.id()!!) println("Test delivery status: ${testResult.success()}") ``` ### List Webhook Deliveries ```kotlin val deliveries: WebhookListDeliveriesResponse = client.webhooks().listDeliveries(webhook.id()!!) deliveries.deliveries().forEach { d -> println("${d.id()} — HTTP ${d.responseStatusCode()} — ${d.createdAt()}") } ``` ### List All Webhooks ```kotlin val allHooks = client.webhooks().list() println("Total webhooks: ${allHooks.webhooks().size}") ``` ### Deactivate Webhook ```kotlin client.webhooks().deactivate(webhook.id()!!) ``` ``` -------------------------------- ### Verify Maven Central Artifact Availability Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Use curl to check if the library's metadata is available on Maven Central. This is a prerequisite for using standard dependency management. ```bash curl -f https://repo1.maven.org/maven2/com/x_twitter_scraper/api/x-twitter-scraper-kotlin/maven-metadata.xml ``` -------------------------------- ### Upload Media using URL Stream with Explicit Filename Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Uploads a media file from a URL stream and allows specifying an explicit filename using `MultipartField`. Requires `MediaUploadParams`. ```kotlin import com.x_twitter_scraper.api.core.MultipartField import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse import java.io.InputStream import java.net.URL import java.nio.file.Paths // From a URL stream with an explicit filename val fromUrl: MediaUploadResponse = client.x().media().upload( MediaUploadParams.builder() .account("@myhandle") .file( MultipartField.builder() .value(URL("https://example.com/image.jpg").openStream()) .filename("image.jpg") .build() ) .build() ) println("Media ID: ${fromUrl.mediaId()}") ``` -------------------------------- ### Raw Responses Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Details how to access raw HTTP responses, including headers and status codes, by prefixing calls with `withRawResponse()`. It also shows how to parse the response body. ```APIDOC ## Raw responses The SDK defines methods that deserialize responses into instances of Kotlin classes. However, these methods don't provide access to the response headers, status code, or the raw response body. To access this data, prefix any HTTP method call on a client or service with `withRawResponse()`: ```kotlin import com.x_twitter_scraper.api.core.http.Headers import com.x_twitter_scraper.api.core.http.HttpResponseFor import com.x_twitter_scraper.api.models.PaginatedTweets import com.x_twitter_scraper.api.models.x.tweets.TweetSearchParams val params: TweetSearchParams = TweetSearchParams.builder() .q("from:elonmusk") .limit(10L) .build() val paginatedTweets: HttpResponseFor = client.x().tweets().withRawResponse().search(params) val statusCode: Int = paginatedTweets.statusCode() val headers: Headers = paginatedTweets.headers() ``` You can still deserialize the response into an instance of a Kotlin class if needed: ```kotlin import com.x_twitter_scraper.api.models.PaginatedTweets val parsedPaginatedTweets: PaginatedTweets = paginatedTweets.parse() ``` ``` -------------------------------- ### API Key Management Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Manages API keys for session authentication, including creation, listing, and revocation. ```APIDOC ## API Key Management — `client.apiKeys()` Creates, lists, and revokes API keys (session authentication only). ```kotlin import com.x_twitter_scraper.api.models.apikeys.ApiKeyCreateParams import com.x_twitter_scraper.api.models.apikeys.ApiKeyCreateResponse import com.x_twitter_scraper.api.models.apikeys.ApiKeyListResponse import com.x_twitter_scraper.api.models.apikeys.ApiKeyRevokeResponse // Create val newKey: ApiKeyCreateResponse = client.apiKeys().create( ApiKeyCreateParams.builder() .name("ci-bot-key") .build() ) println("Key: ${newKey.key()}") // List val keys: ApiKeyListResponse = client.apiKeys().list() keys.apiKeys().forEach { k -> println("${k.id()} — ${k.name()} — ${k.createdAt()}") } // Revoke val revoked: ApiKeyRevokeResponse = client.apiKeys().revoke(newKey.id()!!) println("Revoked: ${revoked.revoked()}") ``` ``` -------------------------------- ### Retrieve User Profile - Kotlin Source: https://context7.com/xquik-dev/x-twitter-scraper-kotlin/llms.txt Fetches a single user's profile by their numeric ID using `client.x().users().retrieve()`. Requires `UserProfile` import. ```kotlin import com.x_twitter_scraper.api.models.x.users.UserProfile val user: UserProfile = client.x().users().retrieve("44196397") // @elonmusk println("Name: ${user.name()}") println("Followers: ${user.followersCount()}") println("Verified: ${user.verified()}") ``` -------------------------------- ### Perform Synchronous Tweet Search Asynchronously Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Initiate an asynchronous tweet search using a synchronous client's `async()` method. The client is configured via environment variables or system properties. This approach allows for non-blocking operations while using the synchronous client interface. ```kotlin import com.x_twitter_scraper.api.client.XTwitterScraperClient import com.x_twitter_scraper.api.client.okhttp.XTwitterScraperOkHttpClient import com.x_twitter_scraper.api.models.PaginatedTweets import com.x_twitter_scraper.api.models.x.tweets.TweetSearchParams // Configures using the `xtwitterscraper.apiKey`, `xtwitterscraper.bearerToken` and `xtwitterscraper.baseUrl` system properties // Or configures using the `X_TWITTER_SCRAPER_API_KEY`, `X_TWITTER_SCRAPER_BEARER_TOKEN` and `X_TWITTER_SCRAPER_BASE_URL` environment variables val client: XTwitterScraperClient = XTwitterScraperOkHttpClient.fromEnv() val params: TweetSearchParams = TweetSearchParams.builder() .q("from:elonmusk") .limit(10L) .build() val paginatedTweets: PaginatedTweets = client.async().x().tweets().search(params) ``` -------------------------------- ### Upload File using InputStream in Kotlin Source: https://github.com/xquik-dev/x-twitter-scraper-kotlin/blob/main/README.md Upload a file by providing an open java.io.InputStream. The filename will not be automatically included. ```kotlin import com.x_twitter_scraper.api.models.x.media.MediaUploadParams import com.x_twitter_scraper.api.models.x.media.MediaUploadResponse import java.net.URL val params: MediaUploadParams = MediaUploadParams.builder() .account("@elonmusk") .file(URL("https://example.com//path/to/file").openStream()) .build() val response: MediaUploadResponse = client.x().media().upload(params) ```