### Install XClientTransaction Source: https://github.com/isarabjitdhiman/xclienttransaction/blob/master/README.md Install the XClientTransaction library using pip. Ensure you are using the latest version. ```bash pip install XClientTransaction -U --no-cache-dir ``` -------------------------------- ### Initialize ClientTransaction and Generate IDs Source: https://context7.com/isarabjitdhiman/xclienttransaction/llms.txt Demonstrates the full workflow of fetching required assets from X.com and generating transaction IDs for specific API endpoints. ```python import bs4 import requests from urllib.parse import urlparse from x_client_transaction import ClientTransaction from x_client_transaction.utils import generate_headers, get_ondemand_file_url # Initialize session with required headers session = requests.Session() session.headers = generate_headers() # Fetch the X.com home page home_page = session.get(url="https://x.com") home_page_response = bs4.BeautifulSoup(home_page.content, 'html.parser') # Fetch the ondemand.s JavaScript file ondemand_file_url = get_ondemand_file_url(response=home_page_response) ondemand_file = session.get(url=ondemand_file_url) ondemand_file_response = ondemand_file.text # Initialize the ClientTransaction object ct = ClientTransaction( home_page_response=home_page_response, ondemand_file_response=ondemand_file_response ) # Generate transaction IDs for different endpoints # Example 1: POST request to client_event endpoint url = "https://x.com/i/api/1.1/jot/client_event.json" path = urlparse(url=url).path # /i/api/1.1/jot/client_event.json transaction_id = ct.generate_transaction_id(method="POST", path=path) print(f"Transaction ID: {transaction_id}") # Example 2: GET request to GraphQL UserByScreenName endpoint graphql_url = "https://x.com/i/api/graphql/1VOOyvKkiI3FMmkeDNxM9A/UserByScreenName" graphql_path = urlparse(url=graphql_url).path user_transaction_id = ct.generate_transaction_id(method="GET", path=graphql_path) print(f"User Lookup Transaction ID: {user_transaction_id}") # Use the transaction ID in API requests api_headers = { **session.headers, "X-Client-Transaction-Id": transaction_id } ``` -------------------------------- ### Integrate X Client Transaction with requests Source: https://context7.com/isarabjitdhiman/xclienttransaction/llms.txt Demonstrates creating a session, fetching required assets, and performing an authenticated API request with a generated transaction ID. ```python import bs4 import requests from urllib.parse import urlparse from x_client_transaction import ClientTransaction from x_client_transaction.utils import generate_headers, get_ondemand_file_url def create_x_api_session(): """Create a fully configured session for X API requests.""" session = requests.Session() session.headers = generate_headers() # Fetch required pages home_page = session.get(url="https://x.com") home_page_response = bs4.BeautifulSoup(home_page.content, 'html.parser') ondemand_url = get_ondemand_file_url(response=home_page_response) ondemand_file = session.get(url=ondemand_url) # Create transaction generator ct = ClientTransaction( home_page_response=home_page_response, ondemand_file_response=ondemand_file.text ) return session, ct def make_api_request(session, ct, url, method="GET", **kwargs): """Make an authenticated API request with transaction ID.""" path = urlparse(url=url).path transaction_id = ct.generate_transaction_id(method=method, path=path) headers = { **kwargs.pop("headers", {}), "X-Client-Transaction-Id": transaction_id } return session.request(method=method, url=url, headers=headers, **kwargs) # Usage session, ct = create_x_api_session() # Make API calls with automatic transaction ID generation response = make_api_request( session, ct, url="https://x.com/i/api/graphql/ABC123/UserByScreenName", method="GET", params={"variables": '{"screen_name":"twitter"}'} ) print(f"Status: {response.status_code}") ``` -------------------------------- ### Generate Standard Browser Headers Source: https://context7.com/isarabjitdhiman/xclienttransaction/llms.txt Creates headers to mimic browser requests, compatible with both requests and httpx libraries. ```python from x_client_transaction.utils import generate_headers # Generate standard browser headers headers = generate_headers() print(headers) # Output: # { # "Authority": "x.com", # "Accept-Language": "en-US,en;q=0.9", # "Cache-Control": "no-cache", # "Referer": "https://x.com", # "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ...", # "X-Twitter-Active-User": "yes", # "X-Twitter-Client-Language": "en" # } # Use with requests import requests session = requests.Session() session.headers = headers response = session.get("https://x.com") # Use with httpx import httpx client = httpx.Client(headers=headers) response = client.get("https://x.com") ``` -------------------------------- ### Handle Twitter to X.com Migration (Asynchronous) Source: https://context7.com/isarabjitdhiman/xclienttransaction/llms.txt Provides an asynchronous version of the migration handler for use with httpx.AsyncClient. Use this for non-blocking operations. It returns a BeautifulSoup object of the final home page. ```python import asyncio import httpx import bs4 from x_client_transaction import ClientTransaction from x_client_transaction.utils import ( generate_headers, handle_x_migration_async, get_ondemand_file_url ) async def generate_transaction_id_async(): # Initialize async client async with httpx.AsyncClient(headers=generate_headers()) as session: # Handle migration and get home page home_page_response = await handle_x_migration_async(session=session) # Alternative: Direct fetch for x.com (no migration needed) # home_page = await session.get(url="https://x.com") # home_page_response = bs4.BeautifulSoup(home_page.content, 'html.parser') # Fetch ondemand file ondemand_file_url = get_ondemand_file_url(response=home_page_response) ondemand_file = await session.get(url=ondemand_file_url) ondemand_file_response = ondemand_file.text # Generate transaction ID ct = ClientTransaction( home_page_response=home_page_response, ondemand_file_response=ondemand_file_response ) transaction_id = ct.generate_transaction_id( method="GET", path="/i/api/graphql/ABC123/UserByScreenName" ) return transaction_id # Run async function transaction_id = asyncio.run(generate_transaction_id_async()) print(f"Generated Transaction ID: {transaction_id}") ``` -------------------------------- ### Synchronous Twitter API Request with X-Client-Transaction-ID Source: https://github.com/isarabjitdhiman/xclienttransaction/blob/master/README.md Demonstrates how to initialize a session, generate headers, handle X migration for twitter.com, and fetch the ondemand.s file response using synchronous requests. This is required for generating the transaction ID. ```python import bs4 import requests from x_client_transaction.utils import generate_headers, handle_x_migration, get_ondemand_file_url # INITIALIZE SESSION session = requests.Session() session.headers = generate_headers() # GET HOME PAGE RESPONSE # required only when hitting twitter.com but not x.com # returns bs4.BeautifulSoup object home_page_response = handle_x_migration(session=session) # for x.com no migration is required, just simply do home_page = session.get(url="https://x.com") home_page_response = bs4.BeautifulSoup(home_page.content, 'html.parser') # GET ondemand.s FILE RESPONSE ondemand_file_url = get_ondemand_file_url(response=home_page_response) ondemand_file = session.get(url=ondemand_file_url) ondemand_file_response = bs4.BeautifulSoup(ondemand_file.content, 'html.parser') # Getting "Couldn't get KEY_BYTE indices" error? Try passing the original response or the response text # both should work # ondemand_file_response = ondemand_file ondemand_file_response = ondemand_file.text ``` -------------------------------- ### Handle Twitter to X.com Migration (Synchronous) Source: https://context7.com/isarabjitdhiman/xclienttransaction/llms.txt Automatically handles the Twitter to X.com domain migration process. Use this function when performing synchronous requests. It returns a BeautifulSoup object of the final home page. ```python import requests from x_client_transaction.utils import generate_headers, handle_x_migration, get_ondemand_file_url # Initialize session session = requests.Session() session.headers = generate_headers() # Handle migration automatically (works for both twitter.com and x.com) # Returns a BeautifulSoup object of the final home page home_page_response = handle_x_migration(session=session) # The response contains the verification key in meta tags verification_key = home_page_response.select_one( "meta[name='twitter-site-verification']" ) print(f"Verification key found: {verification_key is not None}") # Continue with ondemand file fetch ondemand_url = get_ondemand_file_url(response=home_page_response) print(f"Ondemand file URL: {ondemand_url}") ``` -------------------------------- ### Generate Transaction IDs with Custom Parameters Source: https://context7.com/isarabjitdhiman/xclienttransaction/llms.txt Shows how to generate transaction IDs using the ClientTransaction instance, including optional custom timestamps for testing. ```python from x_client_transaction import ClientTransaction # Assuming ct is an initialized ClientTransaction instance # Generate transaction ID with default parameters transaction_id = ct.generate_transaction_id( method="GET", path="/i/api/graphql/ABC123/TweetDetail" ) # Generate with custom timestamp (useful for testing) import math import time custom_time = math.floor((time.time() * 1000 - 1682924400 * 1000) / 1000) transaction_id_with_time = ct.generate_transaction_id( method="POST", path="/i/api/1.1/statuses/update.json", time_now=custom_time ) # The transaction ID can be used directly in request headers headers = { "X-Client-Transaction-Id": transaction_id, "Authorization": "Bearer YOUR_TOKEN", "Content-Type": "application/json" } ``` -------------------------------- ### Asynchronous Twitter API Request with X-Client-Transaction-ID Source: https://github.com/isarabjitdhiman/xclienttransaction/blob/master/README.md Shows how to perform asynchronous requests to the Twitter API, including session initialization with generated headers, handling X migration, and fetching the ondemand.s file. This is necessary for generating the transaction ID in an async environment. ```python import bs4 import httpx from x_client_transaction.utils import generate_headers, handle_x_migration_async, get_ondemand_file_url # INITIALIZE SESSION session = httpx.AsyncClient(headers=generate_headers()) # GET HOME PAGE RESPONSE # required only when hitting twitter.com but not x.com # returns bs4.BeautifulSoup object home_page_response = await handle_x_migration_async(session=session) # for x.com no migration is required, just simply do home_page = await session.get(url="https://x.com") home_page_response = bs4.BeautifulSoup(home_page.content, 'html.parser') # GET ondemand.s FILE RESPONSE ondemand_file_url = get_ondemand_file_url(response=home_page_response) ondemand_file = await session.get(url=ondemand_file_url) ondemand_file_response = bs4.BeautifulSoup(ondemand_file.content, 'html.parser') # Getting "Couldn't get KEY_BYTE indices" error? Try passing the original response or the response text # both should work # ondemand_file_response = ondemand_file ondemand_file_response = ondemand_file.text ``` -------------------------------- ### Generate X-Client-Transaction-Id Source: https://github.com/isarabjitdhiman/xclienttransaction/blob/master/README.md Generates the X-Client-Transaction-Id using the ClientTransaction class. Requires the home page and ondemand.s file responses obtained from previous steps. The method and path of the target API endpoint are needed for generation. ```python from urllib.parse import urlparse from x_client_transaction import ClientTransaction # Example 1 # replace the url and http method as per your use case url = "https://x.com/i/api/1.1/jot/client_event.json" method = "POST" path = urlparse(url=url).path # path will be /i/api/1.1/jot/client_event.json in this case # Example 2 user_by_screen_name_url = "https://x.com/i/api/graphql/1VOOyvKkiI3FMmkeDNxM9A/UserByScreenName" user_by_screen_name_http_method = "GET" user_by_screen_name_path = urlparse(url=url).path # path will be /i/api/graphql/1VOOyvKkiI3FMmkeDNxM9A/UserByScreenName in this case ct = ClientTransaction(home_page_response=home_page_response, ondemand_file_response=ondemand_file_response) transaction_id = ct.generate_transaction_id(method=method, path=path) transaction_id_for_user_by_screen_name_endpoint = ct.generate_transaction_id( method=user_by_screen_name_http_method, path=user_by_screen_name_path) print(transaction_id) print(transaction_id_for_user_by_screen_name_endpoint) ``` -------------------------------- ### Extract Ondemand File URL Source: https://context7.com/isarabjitdhiman/xclienttransaction/llms.txt Extracts the URL of the ondemand.s JavaScript file from the home page HTML. This file is crucial for transaction ID generation. The function requires a BeautifulSoup object of the home page. ```python import bs4 import requests from x_client_transaction.utils import generate_headers, get_ondemand_file_url # Fetch home page session = requests.Session() session.headers = generate_headers() home_page = session.get(url="https://x.com") home_page_response = bs4.BeautifulSoup(home_page.content, 'html.parser') # Extract ondemand file URL ondemand_url = get_ondemand_file_url(response=home_page_response) print(f"Ondemand URL: {ondemand_url}") # Output: https://abs.twimg.com/responsive-web/client-web/ondemand.s.a.js # Fetch the ondemand file ondemand_response = session.get(url=ondemand_url) # Can pass as text or BeautifulSoup object to ClientTransaction ondemand_text = ondemand_response.text # or ondemand_soup = bs4.BeautifulSoup(ondemand_response.content, 'html.parser') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.