### Add and Run Examples Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/CONTRIBUTING.md Create new example files in the 'examples/' directory and make them executable. These examples can then be run against your API. ```python # add an example to examples/.py #!/usr/bin/env -S uv run python … ``` ```sh chmod +x examples/.py # run the example against your api $ ./examples/.py ``` -------------------------------- ### Build and Install Wheel Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/CONTRIBUTING.md Build a distributable wheel file for the package and then install it. This is an efficient way to install the package locally. ```sh uv build # or $ python -m build ``` ```sh pip install ./path-to-wheel-file.whl ``` -------------------------------- ### HTTP GET Method Example Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Demonstrates the use of the `retrieve()` method for GET requests, typically used to fetch a specific resource by its ID. ```python client.x.tweets.retrieve(id) ``` -------------------------------- ### Install from Git Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/CONTRIBUTING.md Install the repository directly from a Git SSH URL. This is useful for using the latest development version. ```sh pip install git+ssh://git@github.com/Xquik-dev/x-twitter-scraper-python.git ``` -------------------------------- ### Install X Twitter Scraper Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/README.md Install the library using pip. This is the first step before using any of its features. ```bash pip install x_twitter_scraper ``` -------------------------------- ### Install x-twitter-scraper with aiohttp support Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/README.md Install the library with the aiohttp extra for improved concurrency performance in async operations. ```sh # install from PyPI pip install x_twitter_scraper[aiohttp] ``` -------------------------------- ### Install Dependencies with pip Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/CONTRIBUTING.md Install development dependencies using pip. This is an alternative to using uv for managing your environment. ```sh pip install -r requirements-dev.lock ``` -------------------------------- ### Configuration Validation Example Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Shows how the SDK validates configuration at initialization. An invalid negative timeout raises a ValueError. ```python try: client = XTwitterScraper( timeout=-5 # Invalid: negative timeout ) except ValueError as e: print(f"Configuration error: {e}") ``` -------------------------------- ### HTTP POST Method Example Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Illustrates the `create()` method for POST requests, used for creating new resources. ```python client.x.tweets.create() ``` -------------------------------- ### HTTP DELETE Method Example Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Provides an example of the `delete()` method for DELETE requests, used to remove a resource by its ID. ```python client.x.tweets.delete(id) ``` -------------------------------- ### Example: Fetching Paginated Tweets Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/TYPES.md Demonstrates how to search for tweets and handle pagination using the `next_cursor`. ```python response = client.x.tweets.search(q="python", limit=50) print(f"Got {len(response.tweets)} tweets") if response.has_next_page: next_response = client.x.tweets.search( q="python", limit=50, cursor=response.next_cursor ) ``` -------------------------------- ### Bootstrap Environment with uv Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/CONTRIBUTING.md Run this script to set up the development environment using uv. It automatically provisions the correct Python version and installs dependencies. ```sh ./scripts/bootstrap ``` -------------------------------- ### Get Installed X-Twitter-Scraper-Python Version Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/README.md Use this snippet to check the currently installed version of the library at runtime. Ensure the library is imported before accessing its version attribute. ```python import x_twitter_scraper print(x_twitter_scraper.__version__) ``` -------------------------------- ### Sync Dependencies with uv Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/CONTRIBUTING.md Install all project dependencies, including extras, using uv. This command ensures all necessary packages are available for development. ```sh uv sync --all-extras ``` -------------------------------- ### Create Real-time Monitors and Get Events Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/README.md Shows how to set up a real-time monitor with a webhook URL and retrieve events associated with that monitor. The monitor ID is required to fetch events. ```python # Create monitor with webhook monitor = client.monitors.create( account="@myaccount", webhook_url="https://example.com/webhook" ) # Get events events = client.events.list(monitor_id=monitor.id) ``` -------------------------------- ### Configuration Precedence Example Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Demonstrates how explicit parameters override client constructor parameters. The default timeout is 60s, but can be overridden for a client instance or a specific call. ```python # Default timeout: 60s client = XTwitterScraper(api_key="key") # Override to 30s for this client instance client2 = client.with_options(timeout=30.0) # Override to 10s for this specific call result = client.x.tweets.search(q="query", timeout=10.0) ``` -------------------------------- ### Import and Initialize XTwitterScraper Client Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Demonstrates how to import the XTwitterScraper class and initialize a client with an API key. This setup is required before accessing any API resources. ```python from x_twitter_scraper import XTwitterScraper client = XTwitterScraper(api_key="your-key") tweets_api = client.x.tweets ``` -------------------------------- ### Asynchronous Client Usage Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Provides an example of initializing and using the asynchronous client to fetch and process tweets concurrently. ```python async with AsyncXTwitterScraper(api_key="key") as client: tweets = await client.x.tweets.search(q="query") for tweet in tweets.tweets: await process(tweet) ``` -------------------------------- ### Import DM Resource Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/dm_resource.md Import the XTwitterScraper class and initialize the client to access the DM API. This setup is required before using any DM-related methods. ```python from x_twitter_scraper import XTwitterScraper client = XTwitterScraper(api_key="your-key") dm_api = client.x.dm ``` -------------------------------- ### retrieve Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Get details of an existing monitor using its unique ID. This allows you to check the configuration and status of a specific monitor. ```APIDOC ## retrieve ### Description Get details of an existing monitor using its unique ID. This allows you to check the configuration and status of a specific monitor. ### Method GET ### Endpoint /monitors/{id} ### Parameters #### Path Parameters - **id** (str) - Required - Monitor ID #### Query Parameters None #### Request Body None ### Request Example ```json { "id": "monitor_id" } ``` ### Response #### Success Response (200) - **Monitor** - Monitor configuration and status #### Response Example ```json { "id": "monitor_id", "account": "@monitored_account", "webhook_url": "https://example.com/webhook", "event_types": ["tweet_created", "user_followed"], "is_active": true } ``` ``` -------------------------------- ### Get User Profile Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/README.md Retrieve a user's profile information by their username. The follower count is then printed. ```python user = client.x.users.retrieve("@elonmusk") print(f"Followers: {user.public_metrics.followers_count}") ``` -------------------------------- ### HTTP PUT/PATCH Method Example Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Shows the `update()` method for PUT or PATCH requests, used to modify an existing resource identified by its ID. ```python client.monitors.update(id) ``` -------------------------------- ### List All Active Monitors Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Retrieve a list of all currently active monitors associated with your account. This is useful for auditing and managing your monitoring setup. ```python response = client.monitors.list() print(f"Active monitors: {len(response.monitors)}") for monitor in response.monitors: print(f"- @{monitor.account}: {monitor.event_types}") ``` -------------------------------- ### Create Monitor and Handle Existing Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Demonstrates how to create a monitor and gracefully handle the case where a monitor for the specified account already exists by retrieving the existing one. ```python try: monitor = client.monitors.create( account="@myaccount", webhook_url="https://example.com/webhook" ) except x_twitter_scraper.ConflictError: # Get existing monitor instead monitors = client.monitors.list() monitor = next((m for m in monitors.monitors if m.account == "@myaccount"), None) ``` -------------------------------- ### Example Flask Server for Webhooks Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md This snippet demonstrates how to set up a Flask server to receive and process webhook events from the X Twitter Scraper. It includes signature verification using HMAC-SHA256 and handles different event types like 'tweet_created' and 'user_followed'. Ensure you replace 'your-key' and 'your-secret' with your actual API key and webhook secret. ```python from flask import Flask, request import hmac import hashlib from x_twitter_scraper import XTwitterScraper app = Flask(__name__) client = XTwitterScraper(api_key="your-key") WEBHOOK_SECRET = "your-secret" @app.post("/twitter-webhook") def handle_webhook(): body = request.get_data() signature = request.headers.get("X-Webhook-Signature") # Verify signature expected = hmac.new( WEBHOOK_SECRET.encode(), body, hashlib.sha256 ).hexdigest() if not hmac.compare_digest(signature, expected): return {"error": "Invalid signature"}, 401 data = request.json event = data["event"] if event["type"] == "tweet_created": print(f"New tweet: {event['data']['text']}") # Store in database, send notification, etc. elif event["type"] == "user_followed": print(f"New follower: {event['data']['user_id']}") return {"ok": True} if __name__ == "__main__": app.run(port=5000, ssl_context="adhoc") ``` -------------------------------- ### Send Link to Tweet via DM Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/dm_resource.md Example of sending a direct message that includes a link to a tweet. This requires retrieving the tweet first to get its URL. ```python tweet = client.x.tweets.retrieve("tweet_id") client.x.dm.send( account="@myaccount", recipient_id="@friend", text=f"Check this out: {tweet.url}" ) ``` -------------------------------- ### create Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Create a real-time monitor for an X account. You can specify the account to monitor, a webhook URL for notifications, and the specific events to track. ```APIDOC ## create ### Description Create a real-time monitor for an X account. You can specify the account to monitor, a webhook URL for notifications, and the specific events to track. ### Method POST ### Endpoint /monitors ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **account** (str) - Required - X account (@username or account ID) to monitor - **webhook_url** (str) - Optional - Webhook endpoint URL to receive events (HTTPS required) - **events** (list[str]) - Optional - Event types to monitor (see Event Types below) ### Request Example ```json { "account": "@myaccount", "webhook_url": "https://example.com/webhook", "events": ["tweet_created", "tweet_deleted", "user_followed"] } ``` ### Response #### Success Response (200) - **MonitorCreateResponse** - Created monitor with ID #### Response Example ```json { "id": "monitor_id", "account": "@myaccount", "webhook_url": "https://example.com/webhook", "event_types": ["tweet_created", "tweet_deleted", "user_followed"] } ``` ### Event Types - `tweet_created`: User posts a tweet - `tweet_deleted`: User deletes a tweet - `tweet_liked`: User likes a tweet - `tweet_unliked`: User removes like from a tweet - `retweet_created`: User retweets a tweet - `retweet_deleted`: User removes a retweet - `user_followed`: User follows another account - `user_unfollowed`: User unfollows an account - `dm_sent`: User sends a DM (if accessible) ``` -------------------------------- ### Get User Info Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Retrieves information about a specific user and their followers. ```APIDOC ## Get User Info ### Description Retrieves user information by username and fetches their followers. ### Method `client.x.users.retrieve` and `client.x.users.retrieve_followers` ### Parameters for `retrieve` - **username** (string) - Required - The username of the user (e.g., "@username"). ### Parameters for `retrieve_followers` - **user_id** (string) - Required - The ID of the user whose followers to retrieve. ``` -------------------------------- ### Create X Account Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Creates a new X account. Accepts optional parameters for configuration. ```python client.x.accounts.create(**params) ``` -------------------------------- ### Get Article Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves a specific article using its tweet ID. ```APIDOC ## GET /x/articles/{tweetId} ### Description Retrieves a specific article associated with a given tweet ID. ### Method GET ### Endpoint /x/articles/{tweetId} ### Parameters #### Path Parameters - **tweetId** (string) - Required - The ID of the tweet for which to retrieve the article. ``` -------------------------------- ### retrieve Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Get a single tweet with full text, author, metrics, and media. ```APIDOC ## retrieve ### Description Get a single tweet with full text, author, metrics, and media. ### Method GET ### Endpoint /x/tweets/{id} ### Parameters #### Path Parameters - **id** (str) - Required - Tweet ID ### Response #### Success Response (200) - **text** (str) - The full text of the tweet - **author** (object) - Information about the tweet author - **username** (str) - The author's username - **public_metrics** (object) - Public engagement metrics for the tweet - **like_count** (int) - The number of likes - **media** (list[object]) - Media attached to the tweet #### Response Example ```json { "text": "Example tweet content.", "author": { "username": "exampleuser" }, "public_metrics": { "like_count": 100 }, "media": [] } ``` ### Errors - **NotFoundError** - Tweet doesn't exist or is deleted - **AuthenticationError** - Missing credentials ``` -------------------------------- ### Create New Client Instance with Modified Options Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Use `with_options` for inline usage to create a new client with modified options. For persistent clients with different configurations, use `copy`. ```python # Inline usage with with_options (alias for copy) tweets = client.with_options(timeout=30.0).x.tweets.search(q="python") # Persistent client with different configuration debug_client = client.copy(timeout=10.0, max_retries=0) ``` -------------------------------- ### Get Replies Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves a list of replies to a specific tweet. Supports pagination. ```APIDOC ## GET /x/tweets/{id}/replies ### Description Retrieves a list of replies made to a specific tweet. This endpoint supports pagination. ### Method GET ### Endpoint /x/tweets/{id}/replies ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the tweet. #### Query Parameters - **params** (object) - Optional - Parameters for pagination of the replies list. Refer to `tweet_get_replies_params.py` for available options. ``` -------------------------------- ### Get Quotes Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves a list of quotes for a specific tweet. Supports pagination. ```APIDOC ## GET /x/tweets/{id}/quotes ### Description Retrieves a list of quotes for a specific tweet. This endpoint supports pagination. ### Method GET ### Endpoint /x/tweets/{id}/quotes ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the tweet. #### Query Parameters - **params** (object) - Optional - Parameters for pagination of the quotes list. Refer to `tweet_get_quotes_params.py` for available options. ``` -------------------------------- ### Get Retweeters Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves a list of users who retweeted a specific tweet. Supports pagination. ```APIDOC ## GET /x/tweets/{id}/retweeters ### Description Retrieves a list of users who have retweeted a specific tweet. This endpoint supports pagination. ### Method GET ### Endpoint /x/tweets/{id}/retweeters ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the tweet. #### Query Parameters - **params** (object) - Optional - Parameters for pagination of the retweeters list. Refer to `tweet_get_retweeters_params.py` for available options. ``` -------------------------------- ### Get Favoriters Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves a list of users who favorited a specific tweet. Supports pagination. ```APIDOC ## GET /x/tweets/{id}/favoriters ### Description Retrieves a list of users who have favorited a specific tweet. This endpoint supports pagination. ### Method GET ### Endpoint /x/tweets/{id}/favoriters ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the tweet. #### Query Parameters - **params** (object) - Optional - Parameters for pagination of the favoriters list. Refer to `tweet_get_favoriters_params.py` for available options. ``` -------------------------------- ### Get Trends Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves trending topics on X. Supports parameters for filtering and pagination. ```APIDOC ## GET /x/trends ### Description Retrieves trending topics and hashtags on the X platform. This endpoint can be customized using various parameters. ### Method GET ### Endpoint /x/trends ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination of trends. Refer to `x_get_trends_params.py` for available options. ``` -------------------------------- ### Context Manager Usage Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Demonstrates how to use the client instances as context managers with the `with` statement for both synchronous and asynchronous operations, ensuring automatic resource cleanup. ```APIDOC ## Context Manager Both clients support `with` statement for automatic resource cleanup: ### Synchronous Usage ```python with XTwitterScraper(api_key="key") as client: tweets = client.x.tweets.search(q="python") ``` ### Asynchronous Usage ```python async with AsyncXTwitterScraper(api_key="key") as client: tweets = await client.x.tweets.search(q="python") ``` ``` -------------------------------- ### Configure Proxy for httpx Client Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Set up a proxy for the httpx client, including authentication credentials. This allows requests to be routed through a specified proxy server. ```python import httpx from x_twitter_scraper import XTwitterScraper, DefaultHttpxClient client = XTwitterScraper( api_key="key", http_client=DefaultHttpxClient( proxy="http://user:pass@proxy.example.com:8080" ) ) ``` -------------------------------- ### Get Notifications Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves a list of notifications for the user. Supports parameters for filtering and pagination. ```APIDOC ## GET /x/notifications ### Description Fetches a list of notifications for the authenticated user. This endpoint allows for customization through various parameters. ### Method GET ### Endpoint /x/notifications ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination of notifications. Refer to `x_get_notifications_params.py` for available options. ``` -------------------------------- ### Get Thread Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves the entire thread of tweets connected to a specific tweet. Supports pagination. ```APIDOC ## GET /x/tweets/{id}/thread ### Description Retrieves the full thread of tweets associated with a given tweet ID. This endpoint supports pagination. ### Method GET ### Endpoint /x/tweets/{id}/thread ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the tweet that starts the thread. #### Query Parameters - **params** (object) - Optional - Parameters for pagination of the thread. Refer to `tweet_get_thread_params.py` for available options. ``` -------------------------------- ### Monitor Account and List Events Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Create a monitor for a specific user and then list events associated with that monitor. A webhook URL is required for monitor creation. ```python monitor = client.monitors.create(account="@user", webhook_url="https://...") events = client.events.list(monitor_id=monitor.id) ``` -------------------------------- ### Upload Media and Create Tweets with Media Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/README.md Demonstrates how to upload media files and then create a tweet that includes the uploaded media. Requires the `Path` object for file handling. ```python # Upload media media = client.x.media.upload(account="@myaccount", file=Path("image.jpg")) # Create tweet with media tweet = client.x.tweets.create( account="@myaccount", text="Check this out!", media_ids=[media.media_id] ) ``` -------------------------------- ### Get Trends Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieve a list of current trends. This method accepts optional parameters for filtering and customization. ```python client.trends.list(**params) -> TrendListResponse ``` -------------------------------- ### Create a Monitor for All Events Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Use this snippet to create a new monitor that tracks all possible events for a given X account and sends notifications to a specified webhook URL. Ensure the webhook URL is HTTPS. ```python monitor = client.monitors.create( account="@myaccount", webhook_url="https://example.com/webhook" ) print(f"Monitor ID: {monitor.id}") ``` -------------------------------- ### Get Style Performance Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves performance metrics for a specific style by its ID. Returns a StyleGetPerformanceResponse object. ```python client.styles.get_performance(id) -> StyleGetPerformanceResponse ``` -------------------------------- ### Asynchronous HTTP Client with Default httpx Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Initialize an asynchronous scraper using the default asynchronous httpx client. ```python from x_twitter_scraper import AsyncXTwitterScraper, DefaultAsyncHttpxClient client = AsyncXTwitterScraper( api_key="key", http_client=DefaultAsyncHttpxClient() ) ``` -------------------------------- ### Create a Monitor Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Creates a new monitor with the specified parameters. Returns a MonitorCreateResponse object. ```python client.monitors.create(**params) -> MonitorCreateResponse ``` -------------------------------- ### Run an Extraction Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Initiate a new extraction job with specified parameters. ```python client.extractions.run(**params) -> ExtractionRunResponse ``` -------------------------------- ### Get Tweet Thread Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Retrieves the full conversation thread for a given tweet, including replies and the parent tweet. ```APIDOC ## GET /tweets/{id}/thread ### Description Get the full conversation thread for a tweet (replies and parent tweets). ### Method GET ### Endpoint /tweets/{id}/thread ### Parameters #### Path Parameters - **id** (str) - Required - The ID of the tweet to retrieve the thread for. #### Query Parameters - **cursor** (str) - Optional - Pagination cursor for fetching subsequent parts of the thread. ### Request Example ```python thread = client.x.tweets.get_thread("1234567890") for tweet in thread.tweets: print(f"@{tweet.author.username}: {tweet.text}") ``` ### Response #### Success Response (200) - **tweets** (PaginatedTweets) - A list of tweets forming the conversation thread. ``` -------------------------------- ### Create a Monitor for Specific Events Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Create a monitor for an X account, but only receive notifications for a predefined list of events. This is useful for filtering specific activities. Requires a valid webhook URL. ```python monitor = client.monitors.create( account="@myaccount", webhook_url="https://example.com/webhook", events=["tweet_created", "tweet_deleted", "user_followed"] ) ``` -------------------------------- ### Get Tweet Retweeters Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Retrieve a list of users who have retweeted a specific tweet. Supports pagination using a cursor. ```python users = client.x.tweets.get_retweeters("1234567890") print(f"Retweeted by {len(users.users)} users") ``` -------------------------------- ### Client Methods: copy and with_options Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Creates a new client instance with modified options. `with_options` is an alias for `copy` and is suitable for inline usage. This method allows overriding various client configurations such as API key, bearer token, base URL, timeout, HTTP client, retry settings, and default headers or query parameters. ```APIDOC ## Client Methods: copy / with_options ### Description Creates a new client instance with modified options. Use `with_options` for inline usage. ### Method Signature ```python def copy( self, *, api_key: str | None = None, bearer_token: str | None = None, base_url: str | httpx.URL | None = None, timeout: float | Timeout | None | NotGiven = not_given, http_client: httpx.Client | None = None, max_retries: int | NotGiven = not_given, default_headers: Mapping[str, str] | None = None, set_default_headers: Mapping[str, str] | None = None, default_query: Mapping[str, object] | None = None, set_default_query: Mapping[str, object] | None = None, ) -> Self ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - `api_key` (str | None) - Override API key - `bearer_token` (str | None) - Override bearer token - `base_url` (str | httpx.URL | None) - Override base URL - `timeout` (float | Timeout | None | NotGiven) - Override timeout - `http_client` (httpx.Client | None) - Override HTTP client - `max_retries` (int | NotGiven) - Override max retries - `default_headers` (Mapping[str, str] | None) - Merge headers with existing defaults - `set_default_headers` (Mapping[str, str] | None) - Replace all default headers - `default_query` (Mapping[str, object] | None) - Merge query params with existing defaults - `set_default_query` (Mapping[str, object] | None) - Replace all default query params ### Request Example ```python # Inline usage with with_options (alias for copy) tweets = client.with_options(timeout=30.0).x.tweets.search(q="python") # Persistent client with different configuration debug_client = client.copy(timeout=10.0, max_retries=0) ``` ### Response #### Success Response (200) Returns a new client instance (`Self`) with the specified options applied. #### Response Example None provided. ``` -------------------------------- ### Get Tweet Favoriters Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Retrieve a list of users who have liked a specific tweet. Supports pagination using a cursor. ```python users = client.x.tweets.get_favoriters("1234567890") print(f"Liked by {len(users.users)} users") for user in users.users: print(f"@{user.username}") ``` -------------------------------- ### Initialize XTwitterScraper with Environment Variable Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Initialize the synchronous client using an API key read from an environment variable. ```python import os from x_twitter_scraper import XTwitterScraper client = XTwitterScraper( api_key=os.environ.get("X_TWITTER_SCRAPER_API_KEY") ) ``` -------------------------------- ### Make Undocumented POST Requests Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/README.md Use `client.post` for undocumented endpoints. Specify `cast_to=httpx.Response` to get the raw response object. ```python import httpx response = client.post( "/foo", cast_to=httpx.Response, body={"my_param": True}, ) print(response.headers.get("x-foo")) ``` -------------------------------- ### Load Configuration from .env File Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Load API keys and base URLs from a .env file using the python-dotenv library. This is a convenient way to manage credentials and configuration settings. ```bash # .env file X_TWITTER_SCRAPER_API_KEY=sk_live_xxxxxxxxxxxx X_TWITTER_SCRAPER_BASE_URL=https://xquik.com/api/v1 ``` -------------------------------- ### Custom Synchronous httpx Client Configuration Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Set up a custom httpx client for a synchronous scraper, specifying proxy and local address. ```python import httpx from x_twitter_scraper import XTwitterScraper custom_httpx = httpx.Client( proxy="http://proxy.example.com:8080", transport=httpx.HTTPTransport(local_address="0.0.0.0") ) client = XTwitterScraper(api_key="key", http_client=custom_httpx) ``` -------------------------------- ### Get Trends Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Fetches a list of current trends. This method accepts optional parameters to filter or modify the trend list. ```APIDOC ## GET /trends ### Description Fetches a list of current trends. This method accepts optional parameters to filter or modify the trend list. ### Method GET ### Endpoint /trends ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering or modifying the trend list. ### Response #### Success Response (200) - **TrendListResponse** (object) - The response containing the list of trends. ``` -------------------------------- ### Load Configuration from .env File (Python) Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Instantiate the scraper after loading environment variables from a .env file. The client will automatically pick up credentials and base URL from the environment. ```python from dotenv import load_dotenv from x_twitter_scraper import XTwitterScraper load_dotenv() client = XTwitterScraper() # Loads from environment ``` -------------------------------- ### Retrieve and Process Direct Messages Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/dm_resource.md Fetch all direct messages exchanged with a specific user and process them, for example, to count unread messages. ```python conversation = client.x.dm.retrieve_with_user( account="@myaccount", user_id="@friend" ) unread = [m for m in conversation.messages if not m.read] print(f"Unread messages: {len(unread)}") for msg in unread: print(f"[{msg.created_at}] {msg.text}") ``` -------------------------------- ### Retrieve User Mentions Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/users_resource.md Fetches tweets that mention a specific user. Use this to get a list of all tweets where a particular user has been tagged. ```python mentions = client.x.users.retrieve_mentions("1234567890") print(f"Mentioned in {len(mentions.tweets)} tweets") ``` -------------------------------- ### Configure File Upload Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Use this snippet to upload files, such as videos or images, to your X account. Ensure the file type and size comply with the supported formats. The timeout may need to be increased for larger files. ```python from pathlib import Path from x_twitter_scraper import XTwitterScraper client = XTwitterScraper(api_key="key", timeout=120.0) # Longer for uploads # Upload file response = client.x.media.upload( account="@myaccount", file=Path("large_video.mp4") ) ``` -------------------------------- ### Run a Draw Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Initiate a new draw with specified parameters. ```python client.draws.run(**params) -> DrawRunResponse ``` -------------------------------- ### Create Subscription Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Creates a new subscription. No parameters are required. ```python client.subscribe.create() ``` -------------------------------- ### List X Accounts Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves a list of all configured X accounts. ```python client.x.accounts.list() ``` -------------------------------- ### Get Tweet Replies Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Retrieve replies to a specific tweet. Supports pagination and time-based filtering using 'since_time' and 'until_time' Unix timestamps. ```python replies = client.x.tweets.get_replies("1234567890") print(f"Found {len(replies.tweets)} replies") ``` -------------------------------- ### Import and Initialize XTwitterScraper Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/users_resource.md Import the necessary class and initialize the scraper client with your API key. Then, access the users API. ```python from x_twitter_scraper import XTwitterScraper client = XTwitterScraper(api_key="your-key") users_api = client.x.users ``` -------------------------------- ### Run Tests Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/CONTRIBUTING.md Execute the project's test suite using the provided script. Ensure all tests pass before submitting changes. ```sh ./scripts/test ``` -------------------------------- ### Webhook Payload Structure and Verification Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Details the structure of webhook payloads sent by the API for events and provides a Python example for HMAC signature verification. ```APIDOC ## Webhook Integration ### Webhook Payload Structure When an event occurs, the API sends a POST request to your webhook URL with this structure: ```json { "event": { "id": "event_id", "type": "tweet_created", "account_id": "user_id", "created_at": "2024-06-20T10:30:00Z", "data": { "tweet_id": "123456", "text": "Hello world", "url": "https://twitter.com/user/status/123456" } }, "signature": "sha256_signature", "timestamp": "2024-06-20T10:30:00Z" } ``` ### HMAC Verification All webhooks include an `X-Webhook-Signature` header with HMAC-SHA256 signature: ```python import hmac import hashlib def verify_webhook(request_body: bytes, signature: str, secret: str) -> bool: expected = hmac.new( secret.encode(), request_body, hashlib.sha256 ).hexdigest() return hmac.compare_digest(signature, expected) # In your Flask/FastAPI handler @app.post("/webhook") def webhook(): body = request.get_data() signature = request.headers.get("X-Webhook-Signature") secret = "your_webhook_secret" if not verify_webhook(body, signature, secret): return {"error": "Invalid signature"}, 401 event = request.json["event"] print(f"Event: {event['type']} from @{event['account_id']}") return {"ok": True} ``` ``` -------------------------------- ### Get Tweet Quotes Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Retrieve quote tweets (quote retweets) for a specific tweet. Supports pagination and time-based filtering. Can optionally include replies. ```python quotes = client.x.tweets.get_quotes("1234567890") print(f"Found {len(quotes.tweets)} quote tweets") ``` -------------------------------- ### Initialize XTwitterScraper with Custom Base URL Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Initialize the synchronous client with a custom API base URL. ```python client = XTwitterScraper( api_key="your-api-key", base_url="https://custom.api.example.com/v1" ) ``` -------------------------------- ### Get Home Timeline Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Fetches the user's home timeline, which includes tweets from followed users. Supports various parameters for filtering and pagination. ```APIDOC ## GET /x/timeline ### Description Retrieves the user's home timeline, which consists of tweets from users they follow. This endpoint supports various parameters for customization. ### Method GET ### Endpoint /x/timeline ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination of the timeline. Refer to `x_get_home_timeline_params.py` for available options. ``` -------------------------------- ### Retrieve Monitor Details Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Fetch the configuration and current status of an existing monitor using its unique ID. This helps in verifying monitor settings and activity. ```python monitor = client.monitors.retrieve("monitor_id") print(f"Monitoring @{monitor.account}") print(f"Active: {monitor.is_active}") print(f"Events: {monitor.event_types}") ``` -------------------------------- ### Configure HTTP Client with Proxies and Transports Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/README.md Initialize `XTwitterScraper` with a custom `httpx.Client` instance to configure proxies, transports, or other advanced HTTP settings. ```python import httpx from x_twitter_scraper import XTwitterScraper, DefaultHttpxClient client = XTwitterScraper( # Or use the `X_TWITTER_SCRAPER_BASE_URL` env var base_url="http://my.test.server.example.com:8083", http_client=DefaultHttpxClient( proxy="http://my.test.proxy.example.com", transport=httpx.HTTPTransport(local_address="0.0.0.0"), ), ) ``` -------------------------------- ### Create a Webhook Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Register a new webhook endpoint with specified parameters. ```python client.webhooks.create(**params) -> WebhookCreateResponse ``` -------------------------------- ### Get Full Tweet Thread Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/tweets_resource.md Fetches the complete conversation thread for a given tweet ID, including replies and parent tweets. Use this to reconstruct conversations. ```python thread = client.x.tweets.get_thread("1234567890") for tweet in thread.tweets: print(f"@{tweet.author.username}: {tweet.text}") ``` -------------------------------- ### Import XTwitterScraper Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Import the necessary client class from the SDK. ```python from x_twitter_scraper import XTwitterScraper ``` -------------------------------- ### Writing Style Profiles Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Manage and analyze writing style profiles, including retrieving, updating, listing, deleting, analyzing, comparing styles, and getting performance metrics. ```APIDOC ## Writing Style Profiles ### `client.styles.retrieve()` #### Description Get style profile. ### `client.styles.update()` #### Description Update style. ### `client.styles.list()` #### Description List styles. ### `client.styles.delete()` #### Description Delete style. ### `client.styles.analyze()` #### Description Analyze writing style. ### `client.styles.compare()` #### Description Compare two styles. ### `client.styles.get_performance()` #### Description Get style metrics. ``` -------------------------------- ### Top Up Credit Balance Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Top up the credit balance. This method requires parameters to specify the top-up amount and details. ```python client.credits.topup_balance(**params) -> CreditTopupBalanceResponse ``` -------------------------------- ### Handle API Connection Errors Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/ERRORS.md Catch APIConnectionError to gracefully handle network issues or DNS failures. This example prints a user-friendly message and the underlying cause of the connection error. ```python try: client.x.tweets.search(q="query") except x_twitter_scraper.APIConnectionError as e: print("Network error. Check your internet connection.") print(f"Underlying cause: {e.__cause__}") ``` -------------------------------- ### Initialize XTwitterScraper using Context Manager Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Initialize the synchronous client using a context manager to ensure connections are automatically closed. This is the recommended approach for managing client lifecycle. ```python with XTwitterScraper(api_key="your-api-key") as client: tweets = client.x.tweets.search(q="python", limit=10) ``` -------------------------------- ### Initialize AsyncXTwitterScraper with API Key Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Instantiate the asynchronous client using an API key, which can be loaded from environment variables or provided directly. The client can be used with a context manager for proper resource handling. ```python import os import asyncio from x_twitter_scraper import AsyncXTwitterScraper async def main(): client = AsyncXTwitterScraper( api_key=os.environ.get("X_TWITTER_SCRAPER_API_KEY") ) # Use context manager for async operations async with AsyncXTwitterScraper(api_key="your-api-key") as client: tweets = await client.x.tweets.search(q="python", limit=10) print(tweets.has_next_page) asyncio.run(main()) ``` -------------------------------- ### Get User Information and Followers Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Retrieve a user's profile information using their username and then fetch their followers. Requires the user's ID obtained from the initial retrieval. ```python user = client.x.users.retrieve("@username") followers = client.x.users.retrieve_followers(user.id) ``` -------------------------------- ### Initialize Client with API Key Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Initialize the XTwitterScraper client using an API key. This is the recommended method for authentication. ```python # API Key (recommended) client = XTwitterScraper(api_key="your-key") ``` -------------------------------- ### Access Raw Response Data (Headers) Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/README.md Prefix HTTP methods with `.with_raw_response.` to access the raw `APIResponse` object, including headers. Use `.parse()` to get the deserialized data. ```python from x_twitter_scraper import XTwitterScraper client = XTwitterScraper() response = client.x.tweets.with_raw_response.search( q="from:elonmusk", limit=10, ) print(response.headers.get('X-My-Header')) tweet = response.parse() # get the object that `x.tweets.search()` would have returned print(tweet.has_next_page) ``` -------------------------------- ### Import Bookmark Types Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Imports necessary types for handling bookmarks, specifically the response for retrieving bookmark folders. ```python from x_twitter_scraper.types.x import BookmarkRetrieveFoldersResponse ``` -------------------------------- ### List Webhooks Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieve a list of all configured webhooks. ```python client.webhooks.list() -> WebhookListResponse ``` -------------------------------- ### Handle APIResponseValidationError with Strict Validation Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/ERRORS.md Catch errors related to unexpected API response schemas when strict validation is enabled. This example shows how to access the status code and the response body details. ```python try: client = XTwitterScraper(api_key="key", _strict_response_validation=True) tweets = client.x.tweets.search(q="query") except x_twitter_scraper.APIResponseValidationError as e: print(f"Invalid response schema: {e.status_code}") print(f"Details: {e.body}") ``` -------------------------------- ### Initialize XTwitterScraper Client with Options Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Instantiate the XTwitterScraper client using constructor parameters for authentication, connection settings, and request defaults. Ensure one authentication method (api_key or bearer_token) is provided. ```python from x_twitter_scraper import XTwitterScraper client = XTwitterScraper( # Authentication (required one) api_key="your-api-key", bearer_token="your-bearer-token", # Connection settings base_url="https://xquik.com/api/v1", timeout=60.0, max_retries=2, # HTTP client http_client=None, # Request defaults default_headers={"X-Custom": "value"}, default_query={"format": "json"}, # Advanced _strict_response_validation=False, ) ``` -------------------------------- ### Bulk Data Extraction Jobs Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Manage bulk data extraction jobs, including starting jobs, retrieving status and results, listing jobs, estimating costs, and exporting results in CSV/JSON format. Supports extraction of tweets, users, lists, and more. ```APIDOC ## Bulk Data Extraction Jobs ### `client.extractions.run()` #### Description Start extraction job (20+ tool types). ### `client.extractions.retrieve()` #### Description Get job status and results. ### `client.extractions.list()` #### Description List extraction jobs. ### `client.extractions.estimate_cost()` #### Description Estimate credit cost. ### `client.extractions.export_results()` #### Description Download results as CSV/JSON. ``` -------------------------------- ### List and Retrieve Events from a Monitor Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/monitors_resource.md Shows how to list all events associated with a specific monitor ID and how to retrieve the details of a single event using its ID. This integration helps in accessing detailed event information. ```python # List events from a monitor events = client.events.list(monitor_id="monitor_id") # Get specific event event = client.events.retrieve("event_id") print(f"Event type: {event.type}") print(f"Data: {event.data}") ``` -------------------------------- ### Monitor Configuration Data Model Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/TYPES.md Defines the structure for configuring a real-time account monitor. This includes essential details like the monitor's ID, the target account, its active status, creation timestamp, and an optional webhook URL for notifications. It also specifies the types of events to monitor. ```python class Monitor(BaseModel): id: str account: str is_active: bool created_at: str webhook_url: str | None event_types: list[str] ``` -------------------------------- ### Development Client Configuration Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Configure the scraper for a development environment with a specific API key and staging base URL. Sets a timeout and maximum retries. ```python from x_twitter_scraper import XTwitterScraper dev_client = XTwitterScraper( api_key="dev-key", base_url="https://staging-api.xquik.com/v1", timeout=30.0, max_retries=1 ) ``` -------------------------------- ### Set Account X Username Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Sets the X username for the account. Requires parameters defining the new username. ```python client.account.set_x_username(**params) ``` -------------------------------- ### Upload Media and Tweet Asynchronously Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/media_resource.md Demonstrates how to upload an image file and then create a tweet with the uploaded media using the asynchronous client. Ensure you have the 'asyncio' library and 'AsyncXTwitterScraper' imported. ```python import asyncio from x_twitter_scraper import AsyncXTwitterScraper from pathlib import Path async def upload_and_tweet(): async with AsyncXTwitterScraper(api_key="key") as client: response = await client.x.media.upload( account="@myaccount", file=Path("/path/to/image.jpg") ) tweet = await client.x.tweets.create( account="@myaccount", text="Posted from async!", media_ids=[response.media_id] ) return tweet asyncio.run(upload_and_tweet()) ``` -------------------------------- ### Testing Client Configuration Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CONFIGURATION.md Configure the scraper for testing with a specific API key and a custom httpx client for a short timeout. Sets maximum retries to 0 for fast failure. ```python from x_twitter_scraper import XTwitterScraper import httpx test_client = XTwitterScraper( api_key="test-key", http_client=httpx.Client(timeout=5.0), max_retries=0 # Fail fast in tests ) ``` -------------------------------- ### Use Client as a Context Manager (Synchronous) Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Utilize the `with` statement for automatic resource cleanup in synchronous operations. The client is automatically closed upon exiting the `with` block. ```python # Synchronous with XTwitterScraper(api_key="key") as client: tweets = client.x.tweets.search(q="python") ``` -------------------------------- ### Initialize Client using Environment Variable Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Initialize the XTwitterScraper client without arguments. It will automatically read the API key from the X_TWITTER_SCRAPER_API_KEY environment variable. ```python # Environment variable client = XTwitterScraper() # Reads X_TWITTER_SCRAPER_API_KEY ``` -------------------------------- ### Retrieve Bookmark Folders Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Retrieves all available folders for bookmarks. This method does not require any parameters. ```python client.x.bookmarks.retrieve_folders() ``` -------------------------------- ### Create API Key Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Creates a new API key for the account. Requires parameters for the key creation. ```python client.api_keys.create(**params) ``` -------------------------------- ### Upload Media using File Path Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/api-reference/media_resource.md Uploads a single media file specified by its file path. Ensure the file exists and is in a supported format (JPG, PNG, GIF, WebP for images; MP4, MOV for videos). ```python from pathlib import Path response = client.x.media.upload( account="@myaccount", file=Path("/path/to/image.jpg") ) print(f"Media ID: {response.media_id}") ``` -------------------------------- ### Create Support Ticket Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Create a new support ticket. This method requires parameters to define the ticket details. ```python client.support.tickets.create(**params) -> TicketCreateResponse ``` -------------------------------- ### Import Monitor Types Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/api.md Imports necessary types for working with Monitors. ```python from x_twitter_scraper.types import ( Monitor, MonitorCreateResponse, MonitorListResponse, MonitorDeactivateResponse, ) ``` -------------------------------- ### Import AsyncXTwitterScraper Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/CLIENT_INITIALIZATION.md Import the necessary asynchronous client class from the library. ```python from x_twitter_scraper import AsyncXTwitterScraper ``` -------------------------------- ### Paginate Through Search Results Source: https://github.com/xquik-dev/x-twitter-scraper-python/blob/main/_autodocs/INDEX.md Demonstrates how to paginate through search results using the `has_next_page` attribute and `next_cursor` for subsequent requests. ```python response = client.x.tweets.search(q="query", limit=50) while response.has_next_page: response = client.x.tweets.search(q="query", cursor=response.next_cursor) # Process response.tweets ```