### Add and Run Examples Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Place your custom example scripts in the 'examples/' directory. Make them executable and then run them using the Ruby interpreter. ```ruby #!/usr/bin/env ruby # frozen_string_literal: true require_relative "../lib/x_twitter_scraper" # ... ``` ```bash $ chmod +x './examples/.rb' # run the example against your api $ ruby './examples/.rb' ``` -------------------------------- ### Bootstrap Project Dependencies Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Run this command to install all necessary dependencies for the project. Ensure your Ruby environment is set up correctly. ```bash $ ./scripts/bootstrap ``` -------------------------------- ### Install Gem from Git Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Add this line to your Gemfile to install the gem directly from its GitHub repository. This is useful for using the latest development version. ```ruby gem "x-twitter-scraper", git: "https://github.com/Xquik-dev/x-twitter-scraper-ruby" ``` -------------------------------- ### Install X Twitter Scraper Gem Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Add this line to your application's Gemfile to install the gem. ```ruby gem "x-twitter-scraper", ">= 0.4.0" ``` -------------------------------- ### Retrieve and Update Account Information Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Get authenticated API account details, set the linked X username, and update the display locale. Ensure correct locale constants are used for updates. ```ruby # Get account info info = client.account.retrieve puts info.email puts info.plan ``` ```ruby # Set the linked X username client.account.set_x_username(username: "mybot") ``` ```ruby # Update display locale client.account.update_locale( locale: XTwitterScraper::AccountUpdateLocaleParams::Locale::EN ) ``` -------------------------------- ### Account Update Locale Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Updates the locale for the account. This is an example of a direct method call on the client. ```APIDOC ## Account Update Locale ### Description Updates the locale for the account. ### Method ```ruby client.account.update_locale(locale: :fr) ``` ``` -------------------------------- ### Writing Styles Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Analyze, store, and compare writing-style profiles derived from a user's recent tweets. Analyze a user's style, retrieve cached profiles, compare styles, get performance metrics, update custom styles, list, and delete profiles. ```APIDOC ## Analyze a user's writing style (fetches recent tweets) style = client.styles.analyze(username: "tenderlove") puts style.id puts style.characteristics.inspect ## Retrieve a cached style profile cached = client.styles.retrieve("tenderlove") ## Compare two style profiles comparison = client.styles.compare(username1: "tenderlove", username2: "dhh") puts comparison.similarity_score ## Get engagement performance metrics for a style profile's tweets perf = client.styles.get_performance("tenderlove") puts perf.avg_likes ## Store a custom style profile with hand-picked tweets client.styles.update("my-custom-style", label: "My Brand Voice", tweets: [ { text: "Ruby makes me happy." }, { text: "Convention over configuration is genius." } ] ) ## List all cached style profiles client.styles.list.data.each { |s| puts s.id } ## Delete a style profile client.styles.delete("my-custom-style") ``` -------------------------------- ### Preview Documentation Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Generate and preview the project's documentation locally. An optional port can be specified for the preview server. ```bash $ bundle exec rake docs:preview [PORT=8808] ``` -------------------------------- ### Client Initialization Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Creates the client instance with API key, optional OAuth bearer token, retry, timeout, and base URL configuration. ```APIDOC ## Client Initialization Creates the client instance with API key, optional OAuth bearer token, retry, timeout, and base URL configuration. ```ruby require "x_twitter_scraper" # Basic: reads X_TWITTER_SCRAPER_API_KEY env var automatically client = XTwitterScraper::Client.new # Explicit configuration client = XTwitterScraper::Client.new( api_key: "xq-live-abc123", # or set ENV["X_TWITTER_SCRAPER_API_KEY"] bearer_token: nil, # optional OAuth 2.1 token base_url: "https://xquik.com/api/v1", max_retries: 3, # default: 2 timeout: 30.0, # default: 60.0 seconds initial_retry_delay: 0.5, max_retry_delay: 8.0 ) ``` ``` -------------------------------- ### Initialize X Twitter Scraper Client Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Instantiate the client with API key, optional bearer token, and configuration for retries, timeouts, and base URL. Reads API key from environment variable by default. ```ruby require "x_twitter_scraper" # Basic: reads X_TWITTER_SCRAPER_API_KEY env var automatically client = XTwitterScraper::Client.new # Explicit configuration client = XTwitterScraper::Client.new( api_key: "xq-live-abc123", # or set ENV["X_TWITTER_SCRAPER_API_KEY"] bearer_token: nil, # optional OAuth 2.1 token base_url: "https://xquik.com/api/v1", max_retries: 3, # default: 2 timeout: 30.0, # default: 60.0 seconds initial_retry_delay: 0.5, max_retry_delay: 8.0 ) ``` -------------------------------- ### Get Tweet Engagement Data Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Retrieve engagement metrics for a given tweet, including favoriters, retweeters, replies, quote tweets, and the full thread context. Supports time window filtering for replies. ```ruby tweet_id = "1234567890123456789" # Get users who liked favoriters = client.x.tweets.get_favoriters(tweet_id, cursor: nil) favoriters.data.each { |u| puts u.screen_name } # Get retweeters retweeters = client.x.tweets.get_retweeters(tweet_id) # Get replies (with time window) replies = client.x.tweets.get_replies( tweet_id, since_time: "1700000000", until_time: "1710000000" ) # Get quote tweets quotes = client.x.tweets.get_quotes(tweet_id, include_replies: true) # Get full thread context thread = client.x.tweets.get_thread(tweet_id) thread.data.each { |t| puts t.text } ``` -------------------------------- ### Basic Usage of X Twitter Scraper Client Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Initialize the client with your API key and perform a tweet search. The API key is optional if set as an environment variable. ```ruby require "bundler/setup" require "x_twitter_scraper" x_twitter_scraper = XTwitterScraper::Client.new( api_key: ENV["X_TWITTER_SCRAPER_API_KEY"] # This is the default and can be omitted ) paginated_tweets = x_twitter_scraper.x.tweets.search(q: "from:elonmusk", limit: 10) puts(paginated_tweets.has_next_page) ``` -------------------------------- ### List Bookmarks and Retrieve Folders Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Use this to list bookmarks within a specific folder or retrieve all bookmark folders associated with an account. ```ruby folder_tweets = client.x.bookmarks.list(folder_id: "folder_abc123", cursor: nil) ``` ```ruby folders = client.x.bookmarks.retrieve_folders folders.data.each { |f| puts "#{f.id}: #{f.name}" } ``` -------------------------------- ### Run All Rake Commands Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Execute this command to display a list of all available Rake tasks and commands within the project. Use 'bundle exec rake' to ensure tasks run with the correct gem versions. ```bash $ bundle exec rake ``` -------------------------------- ### Lint and Typecheck Project Files Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Run this command to perform linting and type checking on the project's Ruby files using RuboCop and the configured type checkers (Sorbet/Steep). ```bash $ bundle exec rake lint ``` -------------------------------- ### Manage Account Monitors: Create, List, Update Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Create, list, update, and deactivate real-time monitors for X accounts to capture activity events like tweets, likes, and retweets. ```ruby # Create a monitor for an account's tweets and likes monitor = client.monitors.create( username: "elonmusk", event_types: [:tweet, :like, :retweet, :follow] ) puts monitor.id # List all monitors client.monitors.list.data.each { |m| puts "#{m.username}: active=#{m.is_active}" } # Update event types client.monitors.update(monitor.id, event_types: [:tweet], is_active: true) # Deactivate (soft-delete) client.monitors.deactivate(monitor.id) ``` -------------------------------- ### File Uploads with X Twitter Scraper Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Demonstrates various ways to upload files, including using Pathname, raw file content, StringIO, or a custom FilePart object for more control over filename and content type. ```ruby require "pathname" # Use `Pathname` to send the filename and/or avoid paging a large file into memory: response = x_twitter_scraper.x.media.upload(file: Pathname("/path/to/file")) # Alternatively, pass file contents or a `StringIO` directly: response = x_twitter_scraper.x.media.upload(file: File.read("/path/to/file")) # Or, to control the filename and/or content type: file = XTwitterScraper::FilePart.new(File.read("/path/to/file"), filename: "/path/to/file", content_type: "…") response = x_twitter_scraper.x.media.upload(file: file) puts(response.mediaId) ``` -------------------------------- ### Clone and Reference Local Repository Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Clone the repository locally and then reference it in your Gemfile using a local path. This is useful for development and testing changes. ```bash $ git clone -- 'https://github.com/Xquik-dev/x-twitter-scraper-ruby' '' ``` ```ruby gem "x-twitter-scraper", path: "" ``` -------------------------------- ### Push Integrations (Telegram) Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Set up Telegram integrations for push notifications when monitor events fire. Create, update, send test notifications, review delivery history, and delete integrations. ```APIDOC ## Create a Telegram integration integration = client.integrations.create( name: "My Telegram Alert", type: :telegram, config: { chat_id: "-1001234567890" }, event_types: [:tweet, :follow] ) puts integration.id ## Update with a custom message template and filters client.integrations.update( integration.id, message_template: { text: "New tweet from {{username}}: {{tweet_text}}" }, scope_all_monitors: true, silent_push: false, is_active: true ) ## Send a test push notification client.integrations.send_test(integration.id) ## Review delivery history client.integrations.list_deliveries(integration.id, limit: 10).data.each do |d| puts "#{d.created_at}: #{d.status}" end ## Delete client.integrations.delete(integration.id) ``` -------------------------------- ### Create and Manage Telegram Integrations Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Set up Telegram integrations for push notifications. Configure message templates and filters to customize alerts for specific monitors. ```ruby integration = client.integrations.create( name: "My Telegram Alert", type: :telegram, config: { chat_id: "-1001234567890" }, event_types: [:tweet, :follow] ) puts integration.id ``` ```ruby client.integrations.update( integration.id, message_template: { text: "New tweet from {{username}}: {{tweet_text}}" }, scope_all_monitors: true, silent_push: false, is_active: true ) ``` ```ruby client.integrations.send_test(integration.id) ``` ```ruby client.integrations.list_deliveries(integration.id, limit: 10).data.each do |d| puts "#{d.created_at}: #{d.status}" end ``` ```ruby client.integrations.delete(integration.id) ``` -------------------------------- ### Manage API Keys Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Manages API keys for session authentication. Includes creating, listing, and revoking keys. Note that the key value is only shown once upon creation. ```ruby # Create a new API key new_key = client.api_keys.create(name: "production-key") puts new_key.key # save this – only shown once ``` ```ruby # List all API keys (key values are redacted) client.api_keys.list.data.each { |k| puts "#{k.name}: created #{k.created_at}" } ``` ```ruby # Revoke a key client.api_keys.revoke("key_id_123") ``` -------------------------------- ### Profile Management Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Update text fields, avatar, and banner image for a connected X account. ```APIDOC ## Profile Management ### Description Updates text fields, avatar, and banner image for a connected X account. ### Methods - `client.x.profile.update` - `client.x.profile.update_avatar` - `client.x.profile.update_banner` ### Parameters for `update` - `account` (string) - Required - The X account to use. - `name` (string) - Optional - The new display name. - `description` (string) - Optional - The new bio. - `location` (string) - Optional - The new location. - `url` (string) - Optional - The new website URL. ### Parameters for `update_avatar` - `account` (string) - Required - The X account to use. - `file` (Pathname) - Required - Path to the avatar image file. ### Parameters for `update_banner` - `account` (string) - Required - The X account to use. - `file` (XTwitterScraper::FilePart) - Required - File object for the banner image. ### Example Usage ```ruby require "pathname" # Update profile text fields client.x.profile.update( account: "@mybot", name: "My Bot", description: "Automated updates powered by Ruby", location: "Internet", url: "https://example.com" ) # Upload avatar client.x.profile.update_avatar( account: "@mybot", file: Pathname("/path/to/avatar.png") ) # Upload banner client.x.profile.update_banner( account: "@mybot", file: XTwitterScraper::FilePart.new( File.read("/path/to/banner.jpg"), filename: "banner.jpg", content_type: "image/jpeg" ) ) ``` ``` -------------------------------- ### Run Project Tests Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Execute all defined tests for the project using Rake. This command ensures that the codebase is functioning as expected. ```bash $ bundle exec rake test ``` -------------------------------- ### Search Users and Manage Follows Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Search for users based on a query and perform follow/unfollow actions. Requires specifying the account performing the action. ```ruby # Search users by name/username results = client.x.users.retrieve_search(q: "ruby developer") ``` ```ruby # Follow / unfollow client.x.users.follow.create("987654321", account: "@mybot") client.x.users.follow.delete_all("987654321", account: "@mybot") ``` -------------------------------- ### Account Monitors Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Create and manage real-time monitors on X accounts to capture activity events like tweets, likes, retweets, and follows. ```APIDOC ## Account Monitors — `client.monitors` Creates and manages real-time monitors on X accounts to capture activity events. ```ruby # Create a monitor for an account's tweets and likes monitor = client.monitors.create( username: "elonmusk", event_types: [:tweet, :like, :retweet, :follow] ) puts monitor.id # List all monitors client.monitors.list.data.each { |m| puts "#{m.username}: active=#{m.is_active}" } # Update event types client.monitors.update(monitor.id, event_types: [:tweet], is_active: true) # Deactivate (soft-delete) client.monitors.deactivate(monitor.id) ``` ``` -------------------------------- ### Analyze and Manage Writing Styles Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Analyze a user's writing style, retrieve cached profiles, compare styles, and store custom profiles. This helps in understanding and maintaining a consistent brand voice. ```ruby # Analyze a user's writing style (fetches recent tweets) style = client.styles.analyze(username: "tenderlove") puts style.id puts style.characteristics.inspect ``` ```ruby # Retrieve a cached style profile cached = client.styles.retrieve("tenderlove") ``` ```ruby # Compare two style profiles comparison = client.styles.compare(username1: "tenderlove", username2: "dhh") puts comparison.similarity_score ``` ```ruby # Get engagement performance metrics for a style profile's tweets perf = client.styles.get_performance("tenderlove") puts perf.avg_likes ``` ```ruby # Store a custom style profile with hand-picked tweets client.styles.update("my-custom-style", label: "My Brand Voice", tweets: [ { text: "Ruby makes me happy." }, { text: "Convention over configuration is genius." } ] ) ``` ```ruby # List all cached style profiles client.styles.list.data.each { |s| puts s.id } ``` ```ruby # Delete a style profile client.styles.delete("my-custom-style") ``` -------------------------------- ### Account Management Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Retrieve the authenticated API account's profile, set the linked X username, and update the display locale. ```APIDOC ## Get account info info = client.account.retrieve puts info.email puts info.plan ## Set the linked X username client.account.set_x_username(username: "mybot") ## Update display locale client.account.update_locale( locale: XTwitterScraper::AccountUpdateLocaleParams::Locale::EN ) ``` -------------------------------- ### Configuring Timeouts for API Requests Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Set the `timeout` option during client initialization to configure the default request timeout in seconds, or set it to `nil` to disable timeouts. ```ruby # Configure the default for all requests: x_twitter_scraper = XTwitterScraper::Client.new( timeout: nil # default is 60 ) ``` -------------------------------- ### Manage Connected X Accounts Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Connect new X accounts, list existing ones, re-authenticate, retry failed logins, and disconnect accounts. Supports 2FA via TOTP secret. ```ruby # Connect a new X account account = client.x.accounts.create( email: "user@example.com", password: "secret", username: "mybot", proxy_country: "US", totp_secret: "JBSWY3DPEHPK3PXP" # optional 2FA ) puts account.id ``` ```ruby # List all connected accounts all = client.x.accounts.list all.data.each { |a| puts "#{a.username}: #{a.status}" } ``` ```ruby # Re-authenticate after password change client.x.accounts.reauth(account.id, password: "newsecret") ``` ```ruby # Bulk-retry failed logins client.x.accounts.bulk_retry ``` ```ruby # Disconnect an account client.x.accounts.delete(account.id) ``` -------------------------------- ### Handling API Errors with X Twitter Scraper Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Illustrates how to catch specific API errors like connection issues, rate limits, or general status errors using begin-rescue blocks. ```ruby begin tweet = x_twitter_scraper.x.tweets.search(q: "from:elonmusk", limit: 10) rescue XTwitterScraper::Errors::APIConnectionError => e puts("The server could not be reached") puts(e.cause) # an underlying Exception, likely raised within `net/http` rescue XTwitterScraper::Errors::RateLimitError => e puts("A 429 status code was received; we should back off a bit.") rescue XTwitterScraper::Errors::APIStatusError => e puts("Another non-200-range status code was received") puts(e.status) end ``` -------------------------------- ### Manage X Communities: Create, Retrieve, Search Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Create, delete, retrieve information about, and search tweets within X communities. Supports joining and leaving communities. ```ruby # Create a community community = client.x.communities.create( account: "@mybot", name: "Ruby Developers", description: "All things Ruby" ) puts community.id # Get community details, members, moderators info = client.x.communities.retrieve_info(community.id) members = client.x.communities.retrieve_members(community.id, cursor: nil) mods = client.x.communities.retrieve_moderators(community.id) # Search tweets across communities tweets = client.x.communities.retrieve_search(q: "Ractors", query_type: "Latest") # Join/leave community via client.x.communities.join client.x.communities.join.create(community.id, account: "@mybot") # Delete community (requires confirmation) client.x.communities.delete(community.id, account: "@mybot", community_name: "Ruby Developers") ``` -------------------------------- ### Retrieve Activity Events from Monitors Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt List and retrieve activity events captured by monitors. Supports filtering by event type, monitor ID, and time range. ```ruby # List recent tweet events across all monitors events = client.events.list( event_type: :tweet, limit: 50, after: nil ) events.data.each { |e| puts "#{e.event_type} at #{e.created_at}" } # Filter events from a specific monitor monitor_events = client.events.list(monitor_id: "monitor_123", limit: 20) # Get a single event event = client.events.retrieve("event_456") puts event.tweet&.text ``` -------------------------------- ### Create, List, Update, and Manage Webhooks Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Manage webhook subscriptions for tweet and like events. Ensure the webhook URL is publicly accessible and configured to receive POST requests. ```ruby webhook = client.webhooks.create( url: "https://myapp.example.com/webhooks/x", event_types: [:tweet, :like, :retweet] ) puts webhook.id ``` ```ruby client.webhooks.list.data.each { |w| puts "#{w.url}: active=#{w.is_active}" } ``` ```ruby client.webhooks.update(webhook.id, event_types: [:tweet, :like, :retweet, :follow], is_active: true) ``` ```ruby deliveries = client.webhooks.list_deliveries(webhook.id) deliveries.data.each { |d| puts "#{d.created_at}: #{d.status_code}" } ``` ```ruby client.webhooks.test_(webhook.id) ``` ```ruby client.webhooks.deactivate(webhook.id) ``` -------------------------------- ### Retrieve Trending Topics from Various Sources Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Fetch trending topics from sources like Hacker News, Reddit, and GitHub for content inspiration. Specify region, category, and timeframes for tailored results. ```ruby # Get trending topics from Hacker News (tech, last 24 hours) topics = client.radar.retrieve_trending_topics( source: :hacker_news, category: "tech", region: "us", hours: 24, count: 10 ) topics.data.each { |t| puts "#{t.title} – #{t.url}" } ``` ```ruby # Get Reddit trends globally reddit_trends = client.radar.retrieve_trending_topics(source: :reddit, region: "global") ``` ```ruby # Get GitHub trending repos github_trends = client.radar.retrieve_trending_topics(source: :github) ``` -------------------------------- ### Run Bulk Data Extractions Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Run bulk data extraction jobs for various X data types like tweet searches, user followers, and list members. Supports cost estimation and result retrieval. ```ruby # Estimate cost before running estimate = client.extractions.estimate_cost( tool_type: :tweet_search_extractor, search_query: "ruby programming", exact_phrase: "Ruby on Rails" ) puts "Estimated credits: #{estimate.estimated_credits}" # Run an extraction job job = client.extractions.run( tool_type: :user_followers_extractor, target_username: "matz" ) puts "Job ID: #{job.id}, status: #{job.status}" # Poll and retrieve results (keyset-paginated) results = client.extractions.retrieve(job.id, limit: 500) results.data.each { |row| puts row } # Export to CSV csv_io = client.extractions.export_results(job.id, format_: :csv) File.write("followers.csv", csv_io.read) # List all jobs, filter by status client.extractions.list(status: :completed, tool_type: :tweet_search_extractor) ``` -------------------------------- ### Bulk Extractions Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Run bulk data extraction jobs using various tool types, such as follower lists and search results. Supports cost estimation, job running, result retrieval, and export to CSV. ```APIDOC ## Bulk Extractions — `client.extractions` Runs bulk data extraction jobs using one of 20 tool types (follower lists, search results, list members, etc.). ```ruby # Estimate cost before running estimate = client.extractions.estimate_cost( tool_type: :tweet_search_extractor, search_query: "ruby programming", exact_phrase: "Ruby on Rails" ) puts "Estimated credits: #{estimate.estimated_credits}" # Run an extraction job job = client.extractions.run( tool_type: :user_followers_extractor, target_username: "matz" ) puts "Job ID: #{job.id}, status: #{job.status}" # Poll and retrieve results (keyset-paginated) results = client.extractions.retrieve(job.id, limit: 500) results.data.each { |row| puts row } # Export to CSV csv_io = client.extractions.export_results(job.id, format_: :csv) File.write("followers.csv", csv_io.read) # List all jobs, filter by status client.extractions.list(status: :completed, tool_type: :tweet_search_extractor) ``` ``` -------------------------------- ### User Lookups Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Retrieve user profiles, followers, following, likes, media, mentions, and perform user searches. ```APIDOC ## User Lookups ### Description Retrieves user profiles, followers, following, likes, media, mentions, and performs user search. ### Methods - `client.x.users.retrieve` - `client.x.users.retrieve_batch` - `client.x.users.retrieve_followers` - `client.x.users.retrieve_tweets` - `client.x.users.retrieve_mentions` - `client.x.users.retrieve_likes` - `client.x.users.retrieve_media` - `client.x.users.retrieve_search` - `client.x.users.follow.create` - `client.x.users.follow.delete_all` ### Parameters for `retrieve` - `user_identifier` (string) - Required - Username or user ID. ### Parameters for `retrieve_batch` - `ids` (string) - Required - Comma-separated user IDs (max 100). ### Parameters for `retrieve_followers` - `user_identifier` (string) - Required - Username or user ID. - `page_size` (integer) - Optional - Number of results per page (20-200). - `cursor` (string) - Optional - Cursor for pagination. ### Parameters for `retrieve_tweets` - `user_identifier` (string) - Required - Username or user ID. - `include_replies` (boolean) - Optional - Whether to include replies. ### Parameters for `retrieve_mentions` - `user_identifier` (string) - Required - Username or user ID. - `since_time` (string) - Optional - Timestamp to retrieve mentions since. ### Parameters for `retrieve_likes` - `user_identifier` (string) - Required - Username or user ID. ### Parameters for `retrieve_media` - `user_identifier` (string) - Required - Username or user ID. ### Parameters for `retrieve_search` - `q` (string) - Required - The search query. ### Parameters for `follow.create` - `user_id` (string) - Required - The ID of the user to follow. - `account` (string) - Required - The X account to use. ### Parameters for `follow.delete_all` - `user_id` (string) - Required - The ID of the user to unfollow. - `account` (string) - Required - The X account to use. ### Example Usage ```ruby # Look up a user profile user = client.x.users.retrieve("elonmusk") puts "#{user.name} – #{user.followers_count} followers" # Get followers followers = client.x.users.retrieve_followers("elonmusk", page_size: 200) while followers.has_next_page followers = client.x.users.retrieve_followers("elonmusk", cursor: followers.next_cursor) end # Search users results = client.x.users.retrieve_search(q: "ruby developer") ``` ``` -------------------------------- ### Retrieve User Profiles and Followers Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Look up individual user profiles by username or ID, perform batch lookups, and retrieve followers. Supports pagination for follower lists. ```ruby # Look up a user profile by username or ID user = client.x.users.retrieve("elonmusk") puts "#{user.name} – #{user.followers_count} followers" ``` ```ruby # Batch lookup (comma-separated IDs, max 100) users = client.x.users.retrieve_batch(ids: "123,456,789") ``` ```ruby # Get followers (paginated, 20-200 per page) followers = client.x.users.retrieve_followers("elonmusk", page_size: 200) while followers.has_next_page followers = client.x.users.retrieve_followers("elonmusk", cursor: followers.next_cursor) end ``` -------------------------------- ### Send Undocumented Parameters and Read Properties Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Send undocumented parameters and read undocumented response properties using `extra_query`, `extra_body`, and `extra_headers` within `request_options`. Note that `extra_` parameters override documented ones. ```ruby paginated_tweets = x_twitter_scraper.x.tweets.search( q: "from:elonmusk", limit: 10, request_options: { extra_query: {my_query_parameter: value}, extra_body: {my_body_parameter: value}, extra_headers: {"my-header": value} } ) puts(paginated_tweets[:my_undocumented_property]) ``` -------------------------------- ### Provide Typesafe Request Parameters with Sorbet Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Use Sorbet RBI definitions for typesafe request parameters. You can pass parameters directly as a hash or by splatting a Params class instance. ```ruby x_twitter_scraper.x.tweets.search(q: "from:elonmusk", limit: 10) ``` ```ruby # Hashes work, but are not typesafe: x_twitter_scraper.x.tweets.search(q: "from:elonmusk", limit: 10) # You can also splat a full Params class: params = XTwitterScraper::X::TweetSearchParams.new(q: "from:elonmusk", limit: 10) x_twitter_scraper.x.tweets.search(**params) ``` -------------------------------- ### API Key Management Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Manages API keys for session authentication. Allows creating, listing, and revoking keys. ```APIDOC ## API Key Management — `client.api_keys` ### Description Creates, lists, and revokes API keys (session auth only). ### Create API Key ```ruby # Create a new API key new_key = client.api_keys.create(name: "production-key") puts new_key.key # save this – only shown once ``` ### List API Keys ```ruby # List all API keys (key values are redacted) client.api_keys.list.data.each { |k| puts "#{k.name}: created #{k.created_at}" } ``` ### Revoke API Key ```ruby # Revoke a key client.api_keys.revoke("key_id_123") ``` ``` -------------------------------- ### Connected X Account Management Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Manage connected X accounts, including connecting new accounts, listing, retrieving, disconnecting, and re-authenticating them. ```APIDOC ## Connected X Account Management ### Description Connects, lists, retrieves, disconnects, and re-authenticates X accounts for write-action use. ### Methods - `client.x.accounts.create` - `client.x.accounts.list` - `client.x.accounts.reauth` - `client.x.accounts.bulk_retry` - `client.x.accounts.delete` ### Parameters for `create` - `email` (string) - Required - User's email address. - `password` (string) - Required - User's password. - `username` (string) - Required - Desired username for the account. - `proxy_country` (string) - Required - Country code for the proxy. - `totp_secret` (string) - Optional - Two-factor authentication secret. ### Parameters for `reauth` - `account_id` (string) - Required - The ID of the account to re-authenticate. - `password` (string) - Required - The new password. ### Parameters for `delete` - `account_id` (string) - Required - The ID of the account to disconnect. ### Example Usage ```ruby # Connect a new X account account = client.x.accounts.create( email: "user@example.com", password: "secret", username: "mybot", proxy_country: "US", totp_secret: "JBSWY3DPEHPK3PXP" ) puts account.id # List all connected accounts all = client.x.accounts.list all.data.each { |a| puts "#{a.username}: #{a.status}" } # Re-authenticate an account client.x.accounts.reauth(account.id, password: "newsecret") # Disconnect an account client.x.accounts.delete(account.id) ``` ``` -------------------------------- ### Manage Credits Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Manages credits used for extractions and draws. Allows checking the current balance and topping up credits. ```ruby # Check balance balance = client.credits.retrieve_balance puts "Available credits: #{balance.balance}" ``` ```ruby # Top up result = client.credits.topup_balance(amount: 1000) puts "New balance: #{result.balance}" ``` -------------------------------- ### Configuring Retries for API Requests Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Set the `max_retries` option during client initialization to configure the default number of retries for all requests, or specify it per-request using `request_options`. ```ruby # Configure the default for all requests: x_twitter_scraper = XTwitterScraper::Client.new( max_retries: 0 # default is 2 ) # Or, configure per-request: x_twitter_scraper.x.tweets.search(q: "from:elonmusk", limit: 10, request_options: {max_retries: 5}) ``` -------------------------------- ### Credits Management Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Manages credits used for extractions and draws. Allows checking balance and topping up. ```APIDOC ## Credits — `client.credits` ### Description Checks the credit balance and tops up credits used for extractions and draws. ### Retrieve Balance ```ruby # Check balance balance = client.credits.retrieve_balance puts "Available credits: #{balance.balance}" ``` ### Top Up Balance ```ruby # Top up result = client.credits.topup_balance(amount: 1000) puts "New balance: #{result.balance}" ``` ``` -------------------------------- ### Check X Follower Relationship Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Checks if one X user follows another. Returns a boolean indicating the follow status. ```ruby result = client.x.followers.check(source: "rubyist42", target: "matz") puts result.is_following # => true / false ``` -------------------------------- ### Events Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt List and retrieve activity events captured by monitors. Supports filtering by event type, monitor ID, and time. ```APIDOC ## Events — `client.events` Lists and retrieves activity events captured by monitors. ```ruby # List recent tweet events across all monitors events = client.events.list( event_type: :tweet, limit: 50, after: nil ) events.data.each { |e| puts "#{e.event_type} at #{e.created_at}" } # Filter events from a specific monitor monitor_events = client.events.list(monitor_id: "monitor_123", limit: 20) # Get a single event event = client.events.retrieve("event_456") puts event.tweet&.text ``` ``` -------------------------------- ### Manage X Lists: Members, Followers, Tweets Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Retrieve members, followers, or tweets from a specified X list. Supports filtering tweets by time. ```ruby list_id = "1234567890" # Members and followers of a list members = client.x.lists.retrieve_members(list_id) followers = client.x.lists.retrieve_followers(list_id) # Tweets from a list (with time filter) tweets = client.x.lists.retrieve_tweets( list_id, include_replies: false, since_time: "1700000000" ) tweets.data.each { |t| puts t.text } ``` -------------------------------- ### Format and Fix Lint Issues Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/CONTRIBUTING.md Automatically format Ruby files and fix any linting issues detected by RuboCop. This command helps maintain code style consistency. ```bash $ bundle exec rake format ``` -------------------------------- ### Update Profile Information and Media Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Modify profile details such as bio, name, location, and URL. Upload new avatar and banner images, with specific file size limits. ```ruby require "pathname" # Update bio, name, location, URL client.x.profile.update( account: "@mybot", name: "My Bot", description: "Automated updates powered by Ruby", location: "Internet", url: "https://example.com" ) ``` ```ruby # Upload avatar (max 716 KB) client.x.profile.update_avatar( account: "@mybot", file: Pathname("/path/to/avatar.png") ) ``` ```ruby # Upload banner (max 2 MB) client.x.profile.update_banner( account: "@mybot", file: XTwitterScraper::FilePart.new( File.read("/path/to/banner.jpg"), filename: "banner.jpg", content_type: "image/jpeg" ) ) ``` -------------------------------- ### Tweet Write Actions Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Perform actions such as creating, deleting, liking, unliking, retweeting, and unretweeting tweets using a connected X account. ```APIDOC ## Tweet Write Actions ### Description Creates and deletes tweets, and performs like/unlike and retweet/unretweet actions using a connected X account. ### Methods - `client.x.tweets.create` - `client.x.tweets.delete` - `client.x.tweets.like.create` - `client.x.tweets.like.delete` - `client.x.tweets.retweet.create` - `client.x.tweets.retweet.delete` ### Parameters for `create` - `account` (string) - Required - The X account to use. - `text` (string) - Required - The content of the tweet. - `reply_to_tweet_id` (string) - Optional - The ID of the tweet to reply to. - `media_ids` (array of strings) - Optional - IDs of media to attach. ### Parameters for `delete`, `like.create`, `like.delete`, `retweet.create`, `retweet.delete` - `tweet_id` (string) - Required - The ID of the tweet to act upon. - `account` (string) - Required - The X account to use. ### Example Usage ```ruby # Post a tweet new_tweet = client.x.tweets.create( account: "@mybot", text: "Hello from X Twitter Scraper! #ruby", reply_to_tweet_id: "9876543210987654321", media_ids: ["media_id_here"] ) puts new_tweet.tweet_id # Delete a tweet client.x.tweets.delete("1234567890", account: "@mybot") # Like a tweet client.x.tweets.like.create("1234567890", account: "@mybot") # Retweet a tweet client.x.tweets.retweet.create("1234567890", account: "@mybot") ``` ``` -------------------------------- ### Bookmarks Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Retrieve bookmarked tweets and bookmark folders for the authenticated account. ```APIDOC ## Bookmarks ### Description Retrieves bookmarked tweets and bookmark folders for the authenticated account. ### Methods - `client.x.bookmarks.list` ### Example Usage ```ruby # List bookmarks bookmarks = client.x.bookmarks.list bookmarks.data.each { |t| puts t.text } ``` ``` -------------------------------- ### Followers Check Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Checks whether one X user follows another. This is useful for verifying relationships between accounts. ```APIDOC ## Followers Check — `client.x.followers.check` Checks whether one X user follows another. ```ruby result = client.x.followers.check(source: "rubyist42", target: "matz") puts result.is_following # => true / false ``` ``` -------------------------------- ### Custom HTTP Requests Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Sends arbitrary HTTP requests while retaining SDK features like auth, retry, and timeouts. Supports injecting extra query parameters, body fields, or headers. ```ruby # Inject undocumented params on a documented endpoint tweets = client.x.tweets.search( q: "ruby", request_options: { extra_query: { experimental_flag: true }, extra_headers: { "x-trace-id" => "abc-123" } } ) ``` ```ruby # Access undocumented response fields puts tweets[:undocumented_field] ``` ```ruby # Call an entirely undocumented endpoint response = client.request( method: :post, path: "/internal/batch-action", query: { version: "2" }, headers: { "x-feature-flag" => "beta" }, body: { ids: ["1", "2", "3"] } ) ``` -------------------------------- ### Retrieve Bookmarks Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Fetch bookmarked tweets for the authenticated account. Supports pagination for bookmark lists. ```ruby # List bookmarks (paginated) bookmarks = client.x.bookmarks.list bookmarks.data.each { |t| puts t.text } ``` -------------------------------- ### BaseModel Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md All parameter and response objects inherit from `XTwitterScraper::Internal::Type::BaseModel`, providing convenient access to fields and structural equivalence. ```APIDOC ## BaseModel ### Description All parameter and response objects inherit from `XTwitterScraper::Internal::Type::BaseModel`, which provides several conveniences, including: 1. **Field Access**: All fields, including unknown ones, are accessible with `obj[:prop]` syntax, and can be destructured with `obj => {prop: prop}` or pattern-matching syntax. 2. **Structural Equivalence**: If two API calls return the same values, comparing the responses with `==` will return `true`. 3. **Pretty Printing**: Both instances and the classes themselves can be pretty-printed. 4. **Helpers**: Includes methods such as `#to_h`, `#deep_to_h`, `#to_json`, and `#to_yaml`. ``` -------------------------------- ### Fetch X (Twitter) Trends by WOEID Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Retrieve trending topics for specific geographic regions using WOEID codes. Customize the number of trends to fetch. ```ruby # Worldwide trends (top 30) trends = client.trends.list trends.data.each { |t| puts "#{t.name}: #{t.tweet_volume}" } ``` ```ruby # US-specific trends us_trends = client.trends.list(woeid: 23424977, count: 20) ``` ```ruby # UK trends uk_trends = client.trends.list(woeid: 23424975) ``` ```ruby # Turkey trends tr_trends = client.trends.list(woeid: 23424969) ``` -------------------------------- ### Making Custom or Undocumented Requests Source: https://github.com/xquik-dev/x-twitter-scraper-ruby/blob/main/README.md Allows sending undocumented parameters to any endpoint and reading undocumented response properties. You can also make requests to undocumented endpoints using the `client.request` method. ```APIDOC ## Making Custom or Undocumented Requests ### Description Allows sending undocumented parameters to any endpoint and reading undocumented response properties. You can also make requests to undocumented endpoints using the `client.request` method. ### Undocumented Properties You can send undocumented parameters and read undocumented response properties by using `extra_query`, `extra_body`, and `extra_headers` within `request_options`. #### Request Example (Undocumented Properties) ```ruby paginated_tweets = x_twitter_scraper.x.tweets.search( q: "from:elonmusk", limit: 10, request_options: { extra_query: {my_query_parameter: value}, extra_body: {my_body_parameter: value}, extra_headers: {"my-header": value} } ) puts(paginated_tweets[:my_undocumented_property]) ``` ### Undocumented Endpoints To make requests to undocumented endpoints while retaining benefits like authentication and retries, use the `client.request` method. #### Request Example (Undocumented Endpoints) ```ruby response = client.request( method: :post, path: '/undocumented/endpoint', query: {"dog": "woof"}, headers: {"useful-header": "interesting-value"}, body: {"hello": "world"} ) ``` ### Parameters for `client.request` #### Method - **method** (Symbol) - Required - The HTTP method (e.g., `:post`, `:get`). #### Path - **path** (String) - Required - The endpoint path. #### Query - **query** (Hash) - Optional - Query parameters for the request. #### Headers - **headers** (Hash) - Optional - Headers for the request. #### Body - **body** (Hash) - Optional - The request body. ``` -------------------------------- ### Run Giveaway Draws Source: https://context7.com/xquik-dev/x-twitter-scraper-ruby/llms.txt Run randomized giveaway draws from tweet replies with configurable eligibility filters such as minimum followers, account age, and required hashtags or mentions. ```ruby # Run a draw draw = client.draws.run( tweet_url: "https://twitter.com/user/status/1234567890", winner_count: 3, backup_count: 5, must_follow_username: "mybot", must_retweet: true, filter_min_followers: 100, filter_account_age_days: 30, unique_authors_only: true, required_hashtags: ["giveaway"], required_mentions: ["mybot"] ) puts draw.id # Get draw details detail = client.draws.retrieve(draw.id) detail.winners.each { |w| puts w.username } # Export winners as CSV csv = client.draws.export(draw.id, format_: :csv, type: :winners) File.write("winners.csv", csv.read) # List all draws client.draws.list(limit: 20).data.each { |d| puts d.id } ```