Try Live
Add Docs
Rankings
Pricing
Enterprise
Docs
Install
Theme
Install
Docs
Pricing
Enterprise
More...
More...
Try Live
Rankings
Create API Key
Add Docs
X Twitter Scraper Go
https://github.com/xquik-dev/x-twitter-scraper-go
Admin
X Twitter Scraper Go is a Go library that provides convenient access to the X Twitter Scraper REST
...
Tokens:
39,574
Snippets:
294
Trust Score:
5.5
Update:
5 days ago
Context
Skills
Chat
Benchmark
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# X Twitter Scraper Go The X Twitter Scraper Go library (`github.com/Xquik-dev/x-twitter-scraper-go`, imported as `xtwitterscraper`) is a Go SDK that provides convenient, type-safe access to the [X Twitter Scraper REST API](https://xquik.com). It is generated from an OpenAPI specification via [Stainless](https://www.stainless.com/) and requires Go 1.22+. Authentication is handled via an API key (`X_TWITTER_SCRAPER_API_KEY`) or bearer token (`X_TWITTER_SCRAPER_BEARER_TOKEN`) read automatically from the environment, or supplied explicitly via functional options. The SDK is organized as a tree of service objects accessed through the top-level `Client` struct. Core services include `X.Tweets`, `X.Users`, `X.Accounts`, `X.Dm`, `X.Media`, `X.Profile`, `X.Communities`, `X.Bookmarks`, `X.Lists`, `X.Followers`, `Monitors`, `Events`, `Extractions`, `Draws`, `Webhooks`, `Compose`, `Drafts`, `Styles`, `Radar`, `Trends`, `Credits`, and `APIKeys`. Optional fields use `param.Opt[T]` wrappers (set with helpers like `xtwitterscraper.String(...)`, `xtwitterscraper.Int(...)`), response structs carry a `.JSON` metadata field for null/omission checks, and automatic retries with exponential backoff are enabled by default. --- ## Installation ```sh go get -u 'github.com/Xquik-dev/x-twitter-scraper-go@v0.4.1' ``` --- ## Client Initialization `NewClient` constructs the top-level client, reading credentials from environment variables and accepting functional `option.RequestOption` overrides. ```go package main import ( "context" "fmt" "os" "github.com/Xquik-dev/x-twitter-scraper-go" "github.com/Xquik-dev/x-twitter-scraper-go/option" ) func main() { // API key from env: X_TWITTER_SCRAPER_API_KEY client := xtwitterscraper.NewClient() // Or supply explicitly and add a global header client = xtwitterscraper.NewClient( option.WithAPIKey(os.Getenv("MY_API_KEY")), option.WithHeader("X-Custom-Header", "my-app/1.0"), option.WithMaxRetries(3), ) _ = client fmt.Println("Client ready") } ``` --- ## client.X.Tweets.Search — Search Tweets Searches tweets using X query operators (e.g. `from:`, `#hashtag`, `lang:`). Returns a paginated `shared.PaginatedTweets` result. ```go package main import ( "context" "errors" "fmt" "github.com/Xquik-dev/x-twitter-scraper-go" "github.com/Xquik-dev/x-twitter-scraper-go/option" ) func main() { client := xtwitterscraper.NewClient(option.WithAPIKey("my-api-key")) result, err := client.X.Tweets.Search(context.TODO(), xtwitterscraper.XTweetSearchParams{ Q: "from:elonmusk lang:en", Limit: xtwitterscraper.Int(20), }) if err != nil { var apierr *xtwitterscraper.Error if errors.As(err, &apierr) { fmt.Println(string(apierr.DumpResponse(true))) } panic(err) } fmt.Printf("HasNextPage: %v\n", result.HasNextPage) for _, tweet := range result.Tweets { fmt.Printf("[%s] @%s: %s (likes=%d)\n", tweet.CreatedAt, tweet.Author.Username, tweet.Text, tweet.LikeCount) } } ``` --- ## client.X.Tweets.Get — Get a Single Tweet Retrieves a tweet by ID with full text, author info, engagement metrics, and attached media. ```go resp, err := client.X.Tweets.Get(context.TODO(), "1234567890123456789") if err != nil { panic(err) } tweet := resp.Tweet fmt.Printf("Text: %s\n", tweet.Text) fmt.Printf("Likes: %d\n", tweet.LikeCount) fmt.Printf("Retweets: %d\n", tweet.RetweetCount) fmt.Printf("Views: %d\n", tweet.ViewCount) fmt.Printf("Author: @%s (followers=%d)\n", resp.Author.Username, resp.Author.Followers) for _, m := range tweet.Media { fmt.Printf("Media [%s]: %s\n", m.Type, m.MediaURL) } ``` --- ## client.X.Tweets.New — Post a Tweet Creates a new tweet on behalf of the authenticated X account. Supports replies, quotes, and media attachments. ```go resp, err := client.X.Tweets.New(context.TODO(), xtwitterscraper.XTweetNewParams{ Account: "@myaccount", Text: "Hello from the X Twitter Scraper Go SDK! #golang", // ReplyToTweetID: xtwitterscraper.String("parent_tweet_id"), }) if err != nil { panic(err) } fmt.Printf("Posted tweet ID: %s (success=%v)\n", resp.TweetID, resp.Success) ``` --- ## client.X.Tweets.Delete — Delete a Tweet Deletes a tweet by its ID using the owning account's credentials. ```go resp, err := client.X.Tweets.Delete(context.TODO(), "1234567890123456789", xtwitterscraper.XTweetDeleteParams{Account: "@myaccount"}, ) if err != nil { panic(err) } fmt.Printf("Deleted: %v\n", resp.Success) ``` --- ## client.X.Tweets.GetReplies / GetQuotes / GetRetweeters / GetThread — Tweet Engagement Retrieves users or tweets that engaged with a specific tweet. All return paginated results. ```go tweetID := "1234567890123456789" // Replies replies, _ := client.X.Tweets.GetReplies(context.TODO(), tweetID, xtwitterscraper.XTweetGetRepliesParams{Limit: xtwitterscraper.Int(50)}) // Quote tweets quotes, _ := client.X.Tweets.GetQuotes(context.TODO(), tweetID, xtwitterscraper.XTweetGetQuotesParams{Limit: xtwitterscraper.Int(50)}) // Users who retweeted retweeters, _ := client.X.Tweets.GetRetweeters(context.TODO(), tweetID, xtwitterscraper.XTweetGetRetweetersParams{Limit: xtwitterscraper.Int(100)}) // Full conversation thread thread, _ := client.X.Tweets.GetThread(context.TODO(), tweetID, xtwitterscraper.XTweetGetThreadParams{}) fmt.Printf("Replies: %d, Quotes: %d, Retweeters: %d, Thread: %d\n", len(replies.Tweets), len(quotes.Tweets), len(retweeters.Users), len(thread.Tweets)) ``` --- ## client.X.Tweets.Like.New / Like.Delete — Like and Unlike a Tweet Likes or unlikes a tweet from a specified X account. ```go // Like likeResp, err := client.X.Tweets.Like.New(context.TODO(), "1234567890123456789", xtwitterscraper.XTweetLikeNewParams{Account: "@myaccount"}, ) fmt.Printf("Liked: %v\n", likeResp.Success) // Unlike unlikeResp, err := client.X.Tweets.Like.Delete(context.TODO(), "1234567890123456789", xtwitterscraper.XTweetLikeDeleteParams{Account: "@myaccount"}, ) fmt.Printf("Unliked: %v\n", unlikeResp.Success) _ = err ``` --- ## client.X.Tweets.Retweet.New / Retweet.Delete — Retweet and Undo Retweet Retweets or un-retweets a tweet from a specified X account. ```go // Retweet rt, _ := client.X.Tweets.Retweet.New(context.TODO(), "1234567890123456789", xtwitterscraper.XTweetRetweetNewParams{Account: "@myaccount"}, ) fmt.Printf("Retweeted: %v\n", rt.Success) // Undo retweet unrt, _ := client.X.Tweets.Retweet.Delete(context.TODO(), "1234567890123456789", xtwitterscraper.XTweetRetweetDeleteParams{Account: "@myaccount"}, ) fmt.Printf("Unretweeted: %v\n", unrt.Success) ``` --- ## client.X.Users.Get — Get a User Profile Retrieves a full user profile by user ID, including follower/following counts, bio, and verification status. ```go profile, err := client.X.Users.Get(context.TODO(), "44196397") // numeric user ID if err != nil { panic(err) } fmt.Printf("@%s — followers: %d, following: %d, verified: %v\n", profile.Username, profile.FollowersCount, profile.FollowingCount, profile.IsBlueVerified) ``` --- ## client.X.Users.GetBatch — Batch User Lookup Fetches multiple user profiles in a single request by a list of user IDs or usernames. ```go users, err := client.X.Users.GetBatch(context.TODO(), xtwitterscraper.XUserGetBatchParams{ UserIDs: []string{"44196397", "783214"}, }) if err != nil { panic(err) } for _, u := range users.Users { fmt.Printf("@%s (%s)\n", u.Username, u.ID) } ``` --- ## client.X.Users.GetTweets / GetMentions / GetMedia / GetLikes — User Timeline Endpoints Retrieves various timelines for a user: their own tweets, mentions, media tweets, or liked tweets. ```go userID := "44196397" // Tweets timeline tweets, _ := client.X.Users.GetTweets(context.TODO(), userID, xtwitterscraper.XUserGetTweetsParams{Limit: xtwitterscraper.Int(50)}) // Mentions mentions, _ := client.X.Users.GetMentions(context.TODO(), userID, xtwitterscraper.XUserGetMentionsParams{Limit: xtwitterscraper.Int(50)}) // Media tweets media, _ := client.X.Users.GetMedia(context.TODO(), userID, xtwitterscraper.XUserGetMediaParams{Limit: xtwitterscraper.Int(50)}) // Liked tweets likes, _ := client.X.Users.GetLikes(context.TODO(), userID, xtwitterscraper.XUserGetLikesParams{Limit: xtwitterscraper.Int(50)}) fmt.Printf("Tweets: %d, Mentions: %d, Media: %d, Likes: %d\n", len(tweets.Tweets), len(mentions.Tweets), len(media.Tweets), len(likes.Tweets)) ``` --- ## client.X.Users.GetFollowers / GetFollowing — Follower Graph Retrieves followers or following lists for a user, paginated. ```go userID := "44196397" followers, err := client.X.Users.GetFollowers(context.TODO(), userID, xtwitterscraper.XUserGetFollowersParams{Limit: xtwitterscraper.Int(100)}) if err != nil { panic(err) } fmt.Printf("Fetched %d followers (hasNext=%v)\n", len(followers.Users), followers.HasNextPage) following, _ := client.X.Users.GetFollowing(context.TODO(), userID, xtwitterscraper.XUserGetFollowingParams{Limit: xtwitterscraper.Int(100)}) fmt.Printf("Fetched %d following\n", len(following.Users)) ``` --- ## client.X.Users.Follow.New / Follow.DeleteAll — Follow and Unfollow Follows or unfollows a user from a given X account. ```go // Follow followResp, _ := client.X.Users.Follow.New(context.TODO(), "44196397", xtwitterscraper.XUserFollowNewParams{Account: "@myaccount"}, ) fmt.Printf("Followed: %v\n", followResp.Success) // Unfollow unfollowResp, _ := client.X.Users.Follow.DeleteAll(context.TODO(), "44196397", xtwitterscraper.XUserFollowDeleteAllParams{Account: "@myaccount"}, ) fmt.Printf("Unfollowed: %v\n", unfollowResp.Success) ``` --- ## client.X.Users.GetSearch — Search Users Searches for users by keyword. Returns paginated user profiles. ```go result, err := client.X.Users.GetSearch(context.TODO(), xtwitterscraper.XUserGetSearchParams{ Q: "golang developer", Limit: xtwitterscraper.Int(20), }) if err != nil { panic(err) } for _, u := range result.Users { fmt.Printf("@%s — %d followers\n", u.Username, u.FollowersCount) } ``` --- ## client.X.Followers.Check — Check Follow Relationship Checks whether one user follows another. ```go resp, err := client.X.Followers.Check(context.TODO(), xtwitterscraper.XFollowerCheckParams{ SourceUserID: "44196397", TargetUserID: "783214", }) if err != nil { panic(err) } fmt.Printf("Is following: %v\n", resp.IsFollowing) ``` --- ## client.X.Accounts.New / Get / List / Delete — Managed X Account CRUD Manages X accounts registered with the scraper service (add, inspect, list, remove). ```go // Register a new account newAcc, err := client.X.Accounts.New(context.TODO(), xtwitterscraper.XAccountNewParams{ AuthToken: "twitter_auth_token_here", CsrfToken: xtwitterscraper.String("csrf_token_here"), }) if err != nil { panic(err) } fmt.Printf("Added account: %s (id=%s)\n", newAcc.Username, newAcc.ID) // List all accounts accounts, _ := client.X.Accounts.List(context.TODO()) for _, acc := range accounts.Accounts { fmt.Printf(" @%s [%s]\n", acc.Username, acc.Status) } // Delete an account del, _ := client.X.Accounts.Delete(context.TODO(), newAcc.ID) fmt.Printf("Deleted: %v\n", del.Success) ``` --- ## client.X.Dm.Send / Dm.GetHistory — Direct Messages Sends a direct message to a user, or retrieves DM conversation history. ```go // Send a DM sendResp, err := client.X.Dm.Send(context.TODO(), "target_user_id", xtwitterscraper.XDmSendParams{ Account: "@myaccount", Text: "Hey, checking in via the API!", }, ) if err != nil { panic(err) } fmt.Printf("DM sent: %v\n", sendResp.Success) // Retrieve history history, _ := client.X.Dm.GetHistory(context.TODO(), "target_user_id", xtwitterscraper.XDmGetHistoryParams{ Account: "@myaccount", Limit: xtwitterscraper.Int(50), }, ) for _, msg := range history.Messages { fmt.Printf("[%s] %s\n", msg.CreatedAt, msg.Text) } ``` --- ## client.X.Media.Upload / Media.Download — Media Upload & Download Uploads a media file (image/video) for use in tweets, or downloads media from a tweet URL. ```go import ( "os" "strings" ) // Upload from filesystem file, _ := os.Open("/path/to/image.png") defer file.Close() uploadResp, err := client.X.Media.Upload(context.TODO(), xtwitterscraper.XMediaUploadParams{ Account: "@myaccount", File: file, }) if err != nil { panic(err) } fmt.Printf("Media ID: %s\n", uploadResp.MediaID) // Upload from a reader with custom name/type uploadResp2, _ := client.X.Media.Upload(context.TODO(), xtwitterscraper.XMediaUploadParams{ Account: "@myaccount", File: xtwitterscraper.File(strings.NewReader("...binary..."), "clip.mp4", "video/mp4"), }) fmt.Printf("Media ID: %s\n", uploadResp2.MediaID) // Download media dlResp, _ := client.X.Media.Download(context.TODO(), xtwitterscraper.XMediaDownloadParams{ URL: "https://pbs.twimg.com/media/example.jpg", }) fmt.Printf("Downloaded URL: %s\n", dlResp.URL) ``` --- ## client.X.Profile.Update / UpdateAvatar / UpdateBanner — Profile Management Updates profile bio/name or changes avatar/banner images for a managed account. ```go // Update bio and display name profileResp, _ := client.X.Profile.Update(context.TODO(), xtwitterscraper.XProfileUpdateParams{ Account: "@myaccount", Name: xtwitterscraper.String("My Bot"), Description: xtwitterscraper.String("Automated account powered by Go SDK"), }) fmt.Printf("Updated profile: %v\n", profileResp.Success) // Update avatar avatarFile, _ := os.Open("/path/to/avatar.png") defer avatarFile.Close() avatarResp, _ := client.X.Profile.UpdateAvatar(context.TODO(), xtwitterscraper.XProfileUpdateAvatarParams{ Account: "@myaccount", File: avatarFile, }) fmt.Printf("Avatar updated: %v\n", avatarResp.Success) ``` --- ## client.X.GetHomeTimeline — Home Timeline Fetches the authenticated account's home timeline. ```go timeline, err := client.X.GetHomeTimeline(context.TODO(), xtwitterscraper.XGetHomeTimelineParams{ Account: "@myaccount", Limit: xtwitterscraper.Int(50), }) if err != nil { panic(err) } for _, tweet := range timeline.Tweets { fmt.Printf("@%s: %s\n", tweet.Author.Username, tweet.Text) } ``` --- ## client.X.GetTrends / Trends.List — Trending Topics Fetches trending topics either from the X API (with account) or as aggregated regional trends. ```go // X API trends (requires account) xTrends, _ := client.X.GetTrends(context.TODO(), xtwitterscraper.XGetTrendsParams{ Account: "@myaccount", }) for _, t := range xTrends.Trends { fmt.Printf("Trend: %s\n", t.Name) } // Regional trends trends, _ := client.Trends.List(context.TODO(), xtwitterscraper.TrendListParams{ Country: xtwitterscraper.String("US"), }) for _, t := range trends.Trends { fmt.Printf("%s — tweet volume: %d\n", t.Name, t.TweetVolume) } ``` --- ## client.X.Communities — Community Operations Creates, queries, and manages X Communities, including member/moderator lists, searching communities, and browsing community tweets. ```go // Get community info info, _ := client.X.Communities.GetInfo(context.TODO(), "1234567890") fmt.Printf("Community: %s (%d members)\n", info.Name, info.MembersCount) // List community tweets tweets, _ := client.X.Communities.Tweets.ListByCommunity(context.TODO(), "1234567890", xtwitterscraper.XCommunityTweetListByCommunityParams{Limit: xtwitterscraper.Int(50)}, ) fmt.Printf("Community tweets: %d\n", len(tweets.Tweets)) // Join community joinResp, _ := client.X.Communities.Join.New(context.TODO(), "1234567890", xtwitterscraper.XCommunityJoinNewParams{Account: "@myaccount"}, ) fmt.Printf("Joined: %v\n", joinResp.Success) // Search communities results, _ := client.X.Communities.GetSearch(context.TODO(), xtwitterscraper.XCommunityGetSearchParams{Q: "golang"}, ) fmt.Printf("Found community tweets: %d\n", len(results.Tweets)) ``` --- ## client.X.Bookmarks.List / GetFolders — Bookmarks Retrieves bookmarked tweets or bookmark folder structure for an account. ```go bookmarks, err := client.X.Bookmarks.List(context.TODO(), xtwitterscraper.XBookmarkListParams{ Account: "@myaccount", Limit: xtwitterscraper.Int(50), }) if err != nil { panic(err) } fmt.Printf("Bookmarked tweets: %d\n", len(bookmarks.Tweets)) folders, _ := client.X.Bookmarks.GetFolders(context.TODO()) for _, f := range folders.Folders { fmt.Printf("Folder: %s\n", f.Name) } ``` --- ## client.X.Lists — X List Data Fetches followers, members, and tweets from an X List. ```go listID := "1234567890" members, _ := client.X.Lists.GetMembers(context.TODO(), listID, xtwitterscraper.XListGetMembersParams{Limit: xtwitterscraper.Int(100)}) fmt.Printf("List members: %d\n", len(members.Users)) listTweets, _ := client.X.Lists.GetTweets(context.TODO(), listID, xtwitterscraper.XListGetTweetsParams{Limit: xtwitterscraper.Int(50)}) fmt.Printf("List tweets: %d\n", len(listTweets.Tweets)) ``` --- ## client.Monitors — Real-Time Account Monitoring Creates and manages real-time monitors that watch X accounts for activity and emit events. ```go // Create a monitor mon, err := client.Monitors.New(context.TODO(), xtwitterscraper.MonitorNewParams{ XUsername: "@elonmusk", EventTypes: []string{"tweet", "retweet", "reply"}, }) if err != nil { panic(err) } fmt.Printf("Monitor created: %s\n", mon.ID) // List all monitors all, _ := client.Monitors.List(context.TODO()) for _, m := range all.Monitors { fmt.Printf(" [%s] @%s — active: %v\n", m.ID, m.XUsername, m.Active) } // Deactivate del, _ := client.Monitors.Deactivate(context.TODO(), mon.ID) fmt.Printf("Deactivated: %v\n", del.Success) ``` --- ## client.Events — Monitor Activity Events Lists or retrieves individual activity events captured from monitored accounts. ```go events, err := client.Events.List(context.TODO(), xtwitterscraper.EventListParams{ MonitorID: xtwitterscraper.String("monitor_abc123"), Limit: xtwitterscraper.Int(50), }) if err != nil { panic(err) } for _, e := range events.Events { fmt.Printf("[%s] type=%s tweetId=%s\n", e.CreatedAt, e.EventType, e.TweetID) } // Get a single event event, _ := client.Events.Get(context.TODO(), "event_id_here") fmt.Printf("Event detail: %+v\n", event) ``` --- ## client.Extractions.Run — Bulk Data Extraction Runs a bulk extraction job across up to 20 tool types (followers, following, search results, etc.). ```go job, err := client.Extractions.Run(context.TODO(), xtwitterscraper.ExtractionRunParams{ Tool: "followers", Input: "elonmusk", Limit: xtwitterscraper.Int(10000), }) if err != nil { panic(err) } fmt.Printf("Extraction job started: %s (status=%s)\n", job.ID, job.Status) // Poll status result, _ := client.Extractions.Get(context.TODO(), job.ID, xtwitterscraper.ExtractionGetParams{}) fmt.Printf("Status: %s, rows: %d\n", result.Status, result.RowCount) // Estimate cost before running estimate, _ := client.Extractions.EstimateCost(context.TODO(), xtwitterscraper.ExtractionEstimateCostParams{ Tool: "followers", Input: "elonmusk", Limit: xtwitterscraper.Int(10000), }) fmt.Printf("Estimated credits: %d\n", estimate.Credits) ``` --- ## client.Extractions.ExportResults — Export Extraction Data Downloads extraction results as a file (CSV, JSON, etc.). ```go import ( "io" "os" ) raw, err := client.Extractions.ExportResults(context.TODO(), "extraction_job_id", xtwitterscraper.ExtractionExportResultsParams{Format: xtwitterscraper.String("csv")}, ) if err != nil { panic(err) } defer raw.Body.Close() f, _ := os.Create("results.csv") defer f.Close() io.Copy(f, raw.Body) fmt.Println("Exported to results.csv") ``` --- ## client.Draws.Run — Giveaway Draws Runs a random winner draw from replies to a tweet, with optional eligibility filters. ```go draw, err := client.Draws.Run(context.TODO(), xtwitterscraper.DrawRunParams{ TweetID: "1234567890123456789", WinnerCount: xtwitterscraper.Int(3), MustFollow: xtwitterscraper.Bool(true), MustRetweet: xtwitterscraper.Bool(false), }) if err != nil { panic(err) } fmt.Printf("Draw ID: %s\n", draw.ID) for _, w := range draw.Winners { fmt.Printf(" Winner: @%s\n", w.Username) } ``` --- ## client.Webhooks — Webhook Management Creates and manages webhook endpoints that receive real-time POST notifications from monitors. ```go // Create webhook wh, err := client.Webhooks.New(context.TODO(), xtwitterscraper.WebhookNewParams{ URL: "https://my-server.example.com/webhook", Secret: xtwitterscraper.String("my-signing-secret"), }) if err != nil { panic(err) } fmt.Printf("Webhook created: %s\n", wh.ID) // Test delivery test, _ := client.Webhooks.Test(context.TODO(), wh.ID) fmt.Printf("Test delivery status: %s\n", test.Status) // List delivery history deliveries, _ := client.Webhooks.ListDeliveries(context.TODO(), wh.ID) for _, d := range deliveries.Deliveries { fmt.Printf(" [%s] status=%d\n", d.CreatedAt, d.ResponseStatus) } // Deactivate client.Webhooks.Deactivate(context.TODO(), wh.ID) ``` --- ## client.Compose — AI Tweet Composition Uses AI to compose tweet suggestions given a topic, style profile, or sample tweets. ```go resp, err := client.Compose.New(context.TODO(), xtwitterscraper.ComposeNewParams{ Topic: "The future of AI in software development", Style: xtwitterscraper.String("style_profile_id"), Count: xtwitterscraper.Int(5), }) if err != nil { panic(err) } for i, t := range resp.Tweets { fmt.Printf("[%d] %s\n", i+1, t.Text) } ``` --- ## client.Drafts — Draft Management Stores, retrieves, lists, and deletes AI-composed or manually written tweet drafts. ```go // Create a draft draft, _ := client.Drafts.New(context.TODO(), xtwitterscraper.DraftNewParams{ Text: "Exploring the limits of Go generics...", Account: xtwitterscraper.String("@myaccount"), }) fmt.Printf("Draft ID: %s\n", draft.ID) // List drafts list, _ := client.Drafts.List(context.TODO(), xtwitterscraper.DraftListParams{}) fmt.Printf("Total drafts: %d\n", len(list.Drafts)) // Get a specific draft d, _ := client.Drafts.Get(context.TODO(), draft.ID) fmt.Printf("Draft text: %s\n", d.Text) // Delete client.Drafts.Delete(context.TODO(), draft.ID) ``` --- ## client.Styles — Writing Style Profiles Analyzes X accounts to build writing style profiles, enabling AI composition that mimics a given author. ```go // Analyze a user's writing style style, err := client.Styles.Analyze(context.TODO(), xtwitterscraper.StyleAnalyzeParams{ XUsername: "@paulg", }) if err != nil { panic(err) } fmt.Printf("Style ID: %s — tone: %s\n", style.ID, style.Tone) // Compare two styles cmp, _ := client.Styles.Compare(context.TODO(), xtwitterscraper.StyleCompareParams{ StyleID1: style.ID, StyleID2: "other_style_id", }) fmt.Printf("Similarity score: %.2f\n", cmp.SimilarityScore) // Performance metrics perf, _ := client.Styles.GetPerformance(context.TODO(), style.ID) fmt.Printf("Avg likes: %.1f\n", perf.AvgLikes) ``` --- ## client.Radar.GetTrendingTopics — AI Radar Returns AI-curated trending topics relevant to a given style profile or niche. ```go topics, err := client.Radar.GetTrendingTopics(context.TODO(), xtwitterscraper.RadarGetTrendingTopicsParams{ StyleID: xtwitterscraper.String("style_profile_id"), Limit: xtwitterscraper.Int(10), }) if err != nil { panic(err) } for _, t := range topics.Topics { fmt.Printf("Topic: %s (score=%.2f)\n", t.Topic, t.Score) } ``` --- ## client.Credits — Credits and Billing Checks current credit balance and adds credits for API usage. ```go balance, err := client.Credits.GetBalance(context.TODO()) if err != nil { panic(err) } fmt.Printf("Credits remaining: %d\n", balance.Balance) topup, _ := client.Credits.TopupBalance(context.TODO(), xtwitterscraper.CreditTopupBalanceParams{ Amount: 1000, }) fmt.Printf("New balance: %d\n", topup.Balance) ``` --- ## client.APIKeys — API Key Management Creates, lists, and revokes API keys (session authentication only). ```go // Create a new API key key, err := client.APIKeys.New(context.TODO(), xtwitterscraper.APIKeyNewParams{ Name: "production-worker", }) if err != nil { panic(err) } fmt.Printf("New key: %s\n", key.Key) // List all keys keys, _ := client.APIKeys.List(context.TODO()) for _, k := range keys.APIKeys { fmt.Printf(" [%s] %s — created: %s\n", k.ID, k.Name, k.CreatedAt) } // Revoke a key rev, _ := client.APIKeys.Revoke(context.TODO(), key.ID) fmt.Printf("Revoked: %v\n", rev.Success) ``` --- ## client.Account — Account Settings Retrieves or updates the currently authenticated platform account's settings and linked X identity. ```go // Get account info acc, _ := client.Account.Get(context.TODO()) fmt.Printf("Account: %s, plan: %s\n", acc.Email, acc.Plan) // Link an X username setResp, _ := client.Account.SetXUsername(context.TODO(), xtwitterscraper.AccountSetXUsernameParams{ XUsername: "@myaccount", }) fmt.Printf("Linked: %v\n", setResp.Success) // Update locale locResp, _ := client.Account.UpdateLocale(context.TODO(), xtwitterscraper.AccountUpdateLocaleParams{ Locale: xtwitterscraper.String("en-US"), }) fmt.Printf("Locale updated: %v\n", locResp.Success) ``` --- ## Error Handling All SDK methods return a typed `*xtwitterscraper.Error` on non-2xx responses, carrying the HTTP status code, request, and response for debugging. ```go import "errors" _, err := client.X.Tweets.Search(context.TODO(), xtwitterscraper.XTweetSearchParams{ Q: "from:elonmusk", Limit: xtwitterscraper.Int(10), }) if err != nil { var apierr *xtwitterscraper.Error if errors.As(err, &apierr) { fmt.Printf("Status: %d\n", apierr.StatusCode) fmt.Printf("Request: %s\n", string(apierr.DumpRequest(true))) fmt.Printf("Response: %s\n", string(apierr.DumpResponse(true))) } else { // Transport-level error (e.g. *url.Error wrapping *net.OpError) fmt.Printf("Network error: %v\n", err) } } ``` --- ## Timeouts and Per-Retry Timeout Use `context.WithTimeout` for an overall request lifecycle timeout; use `option.WithRequestTimeout` to limit each individual retry attempt. ```go import "time" ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) defer cancel() result, err := client.X.Tweets.Search( ctx, xtwitterscraper.XTweetSearchParams{Q: "golang", Limit: xtwitterscraper.Int(20)}, option.WithRequestTimeout(15*time.Second), // per-retry timeout ) _ = result _ = err ``` --- ## Middleware Attach custom middleware (logging, tracing, auth injection) via `option.WithMiddleware`. Multiple middlewares run left-to-right. ```go import "time" func Logger(req *http.Request, next option.MiddlewareNext) (*http.Response, error) { start := time.Now() fmt.Printf("--> %s %s\n", req.Method, req.URL) res, err := next(req) fmt.Printf("<-- %s %s (%s)\n", req.Method, req.URL, time.Since(start)) return res, err } client := xtwitterscraper.NewClient( option.WithAPIKey("my-api-key"), option.WithMiddleware(Logger), ) ``` --- ## Accessing Raw HTTP Response Use `option.WithResponseInto` to capture the raw `*http.Response` alongside the typed result. ```go import "net/http" var rawResp *http.Response result, err := client.X.Tweets.Search( context.TODO(), xtwitterscraper.XTweetSearchParams{Q: "golang", Limit: xtwitterscraper.Int(10)}, option.WithResponseInto(&rawResp), ) if err != nil { panic(err) } fmt.Printf("X-RateLimit-Remaining: %s\n", rawResp.Header.Get("X-RateLimit-Remaining")) fmt.Printf("Tweets: %d\n", len(result.Tweets)) ``` --- ## Undocumented Endpoints For endpoints not yet in the SDK, use the raw HTTP verb methods on the client directly while still benefiting from auth, retries, and base URL. ```go var result map[string]any err := client.Get(context.Background(), "/some/undocumented/endpoint", map[string]string{"param": "value"}, &result, ) if err != nil { panic(err) } fmt.Printf("%+v\n", result) ``` --- The X Twitter Scraper Go SDK is well-suited for production use cases such as social media analytics pipelines, automated content moderation tools, brand monitoring dashboards, competitive intelligence systems, and community management bots. Its auto-retry logic, paginated result types, typed error handling, and functional options pattern make it straightforward to embed into microservices or scheduled jobs that need reliable, high-throughput access to X/Twitter data. Integration patterns that work particularly well include: combining `Monitors` + `Events` + `Webhooks` for event-driven architectures where a webhook fires on new tweets from watched accounts; chaining `Extractions.Run` → polling `Extractions.Get` → `Extractions.ExportResults` for large-scale async data pipelines; and using `Styles.Analyze` + `Radar.GetTrendingTopics` + `Compose.New` + `Drafts.New` as an AI-assisted content scheduling workflow. The SDK's idiomatic Go design (no generics required, simple struct params, `context.Context` on every call) means it drops naturally into any existing Go application without architectural changes.