### Install 2captcha-python Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/README.md Install the library using pip. Ensure you have Python 3.8+ and the required dependencies. ```bash pip install 2captcha-python ``` -------------------------------- ### Common Parameter Patterns Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Examples of common parameter patterns, including file input and image captcha options. ```APIDOC ## Common Parameter Patterns ### File Input #### File Path ```python result = solver.normal('/path/to/image.png') ``` #### URL ```python result = solver.normal('https://example.com/captcha.png') ``` #### Base64-Encoded ```python import base64 with open('image.png', 'rb') as f: b64 = base64.b64encode(f.read()).decode() result = solver.normal(b64) ``` ### Image Captcha Options ```python solver.normal( 'image.png', phrase=1, # Multiple words numeric=1, # Numbers only: 1=nums, 2=letters, 3=either, 4=both minLen=5, # Minimum length maxLen=10, # Maximum length caseSensitive=1, # Case matters calc=1, # Requires math lang='en', # Language hintText='text', # Worker instruction hintImg='img.png' # Instruction image ) ``` ``` -------------------------------- ### Basic Synchronous Initialization Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/configuration.md Instantiate the `TwoCaptcha` solver with only the required API key. This is the simplest way to start using the library for synchronous captcha solving. ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') ``` -------------------------------- ### AsyncTwoCaptcha Constructor with Options Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/configuration.md Initialize the asynchronous AsyncTwoCaptcha solver with identical constructor options to the synchronous version. This example demonstrates setting custom timeouts and polling intervals. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def main(): solver = AsyncTwoCaptcha( apiKey, softId=4580, callback=None, defaultTimeout=120, recaptchaTimeout=600, pollingInterval=10, server='2captcha.com', extendedResponse=None ) asyncio.run(main()) ``` -------------------------------- ### Check Account Balance Asynchronously Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Example of using the asynchronous balance method to check the account balance. Requires an API key. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def check_balance(): solver = AsyncTwoCaptcha('YOUR_API_KEY') balance = await solver.balance() print(f"Balance: ${balance:.2f}") asyncio.run(check_balance()) ``` -------------------------------- ### Send Captcha Asynchronously and Get Result Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Example of asynchronously sending a captcha using the send method, waiting for the result, and then retrieving it using get_result. Requires an API key. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def solve(): solver = AsyncTwoCaptcha('YOUR_API_KEY') captcha_id = await solver.send(file='captcha.png', method='post') await asyncio.sleep(30) result = await solver.get_result(captcha_id) print(f"Solution: {result}") asyncio.run(solve()) ``` -------------------------------- ### Solve and Report Captcha Asynchronously Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Example of solving a captcha using the normal method and then reporting it as correct using the asynchronous report method. Requires an API key. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def solve_and_report(): solver = AsyncTwoCaptcha('YOUR_API_KEY') result = await solver.normal('captcha.png') captcha_id = result['captchaId'] # Report as good await solver.report(captcha_id, True) asyncio.run(solve_and_report()) ``` -------------------------------- ### Retrieve Captcha Results and Balance with AsyncApiClient Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Illustrates how to use the `res` method to fetch captcha results by ID, retrieve account balance, and get results in JSON format. ```python from twocaptcha.async_api import AsyncApiClient import asyncio async def main(): client = AsyncApiClient() # Get captcha result result = await client.res( key='YOUR_API_KEY', action='get', id='123456789' ) # Get account balance balance = await client.res( key='YOUR_API_KEY', action='getbalance' ) # Get result in JSON format result_json = await client.res( key='YOUR_API_KEY', action='get', id='123456789', json=1 ) print(f"Result: {result}") print(f"Balance: {balance}") asyncio.run(main()) ``` -------------------------------- ### Get 2Captcha Python Library Version Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Check the installed version of the 2Captcha Python library. ```python import twocaptcha print(twocaptcha.__version__) # '2.0.7' ``` -------------------------------- ### Instantiate AsyncApiClient Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Demonstrates how to create an instance of AsyncApiClient, showing both the default server and an alternative server configuration. ```python from twocaptcha.async_api import AsyncApiClient import asyncio async def main(): # Default server client = AsyncApiClient() # Alternative server (RuCaptcha) client = AsyncApiClient(post_url='rucaptcha.com') asyncio.run(main()) ``` -------------------------------- ### Async Initialization with Custom Options and Balance Check Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/configuration.md Initialize the `AsyncTwoCaptcha` solver with custom parameters like `softId`, `callback`, `defaultTimeout`, `recaptchaTimeout`, and `pollingInterval`. It then demonstrates fetching the account balance asynchronously. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def main(): solver = AsyncTwoCaptcha( 'YOUR_API_KEY', softId=12345, callback='https://example.com/captcha-callback', defaultTimeout=180, recaptchaTimeout=900, pollingInterval=5 ) # Use solver here balance = await solver.balance() print(f"Balance: {balance}") asyncio.run(main()) ``` -------------------------------- ### GET /res.php Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Retrieves the results of an asynchronously submitted captcha job. This endpoint polls the API for the solution. ```APIDOC ## GET /res.php ### Description Used for retrieving results asynchronously. ### Method GET ### Endpoint `https://{post_url}/res.php?{query_params}` ### Parameters #### Query Parameters - **key** (str) - Required - Your API key. - **action** (str) - Required - The action to perform, typically 'get'. - **id** (str) - Required - The ID of the captcha job to retrieve results for. ### Request Example ```json { "example": "GET /res.php?key=YOUR_API_KEY&action=get&id=CAPTCHA_ID" } ``` ### Response #### Success Response (200) - **response** (str) - The captcha solution or an error message. #### Response Example ```json { "example": "OK|CAPTCHA_SOLUTIONS" or "ERROR: error message" } ``` ``` -------------------------------- ### Configure Proxy for Solver Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Set up proxy details for the solver instance. Supported types include HTTPS, SOCKS5, SOCKS4, and HTTP. ```python proxy = { 'type': 'HTTPS', # or 'SOCKS5', 'SOCKS4', 'HTTP' 'uri': 'login:password@ip.address:port' } result = solver.recaptcha( sitekey, url, proxy=proxy ) ``` -------------------------------- ### Instantiate ApiClient Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Instantiate the ApiClient with the default or an alternative API server hostname. ```python from twocaptcha.api import ApiClient # Default server client = ApiClient() # Alternative server (RuCaptcha) client = ApiClient(post_url='rucaptcha.com') ``` -------------------------------- ### Send Captcha and Get Result Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Send a captcha image for solving and then poll for the result. Includes a delay before polling. ```python from twocaptcha import TwoCaptcha import time solver = TwoCaptcha('YOUR_API_KEY') # Send captcha captcha_id = solver.send(method='post', file='captcha.png') # Poll manually time.sleep(30) result = solver.get_result(captcha_id) ``` -------------------------------- ### Initialize AsyncTwoCaptcha Solver Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Instantiate the AsyncTwoCaptcha class with your API key. This is the first step before calling any solving methods. Ensure you have the 'asyncio' library imported. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def main(): solver = AsyncTwoCaptcha('YOUR_API_KEY') # Use solver here balance = await solver.balance() print(f"Balance: {balance}") asyncio.run(main()) ``` -------------------------------- ### Configure Solver with Environment Variables Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Initialize the 2Captcha solver using an API key retrieved from environment variables. Recommended variables include `TWOCAPTCHA_API_KEY` and `TWOCAPTCHA_SOFT_ID`. ```python import os api_key = os.getenv('TWOCAPTCHA_API_KEY', 'default_key') solver = TwoCaptcha(api_key) ``` -------------------------------- ### Get Account Balance Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Retrieves the current account balance from the 2Captcha service. Formats the balance to two decimal places. ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') balance = solver.balance() print(f"Balance: ${balance:.2f}") ``` -------------------------------- ### Get Account Balance Source: https://github.com/2captcha/2captcha-python/blob/master/README.md Retrieve the current account balance using the balance method. Refer to API documentation for details. ```python balance = solver.balance() ``` -------------------------------- ### Enable Extended Response Mode Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Initialize the solver with `extendedResponse=True` to receive additional details in the response, such as status, user agent, and cookies. ```python solver = TwoCaptcha('API_KEY', extendedResponse=True) result = solver.recaptcha(sitekey, url) # result = { # 'captchaId': '123456789', # 'code': 'token_here', # 'status': 1, # 'user_agent': 'Mozilla/5.0...', # 'cookies': 'session=...', # ... # } ``` -------------------------------- ### Get Account Balance Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Retrieve the current account balance by calling the 'res' method with the 'getbalance' action and your API key. ```python from twocaptcha.api import ApiClient client = ApiClient() # Get account balance balance = client.res( key='YOUR_API_KEY', action='getbalance' ) ``` -------------------------------- ### Solve Coordinates Captcha Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Solves click-based captchas by returning point coordinates. Use hintText or hintImg to guide the worker. ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') result = solver.coordinates('image.png', hintText='Click on ghosts') ``` -------------------------------- ### Retrieve Captcha Result Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Retrieve the result of a submitted captcha using its ID and API key with the 'res' method and 'get' action. ```python from twocaptcha.api import ApiClient client = ApiClient() # Get captcha result result = client.res( key='YOUR_API_KEY', action='get', id='123456789' ) ``` -------------------------------- ### TwoCaptcha Constructor with Options Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/configuration.md Initialize the synchronous TwoCaptcha solver with various configuration options. This includes API key, software ID, callback URL, timeouts, polling interval, server hostname, and extended response mode. ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha( apiKey, softId=4580, callback=None, defaultTimeout=120, recaptchaTimeout=600, pollingInterval=10, server='2captcha.com', extendedResponse=None ) ``` -------------------------------- ### Configuring AsyncApiClient with post_url Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Illustrates how to initialize AsyncApiClient with a custom post_url attribute to specify the API server hostname. ```python from twocaptcha.async_api import AsyncApiClient import asyncio async def main(): client = AsyncApiClient(post_url='rucaptcha.com') print(client.post_url) # Output: rucaptcha.com asyncio.run(main()) ``` -------------------------------- ### GET /res.php Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Retrieves the results of a submitted captcha or performs other actions on the API. Supports JSON response format when the `json=1` parameter is used. ```APIDOC ## GET /res.php ### Description Used for retrieving results and performing other actions. ### Method GET ### Endpoint `https://{post_url}/res.php` ### Parameters #### Query Parameters - **key** (string) - Required - Your 2Captcha API key. - **action** (string) - Required - The action to perform, e.g., 'get' for results. - **id** (string) - Required (if action is 'get') - The ID of the captcha to retrieve results for. - **json** (integer) - Optional - Set to 1 to receive the response in JSON format. ### Request Example ```python from twocaptcha.api import ApiClient client = ApiClient() # Get captcha result in plain text response = client.res( action='get', id='YOUR_CAPTCHA_ID', key='YOUR_API_KEY' ) # Get captcha result in JSON format response_json = client.res( action='get', id='YOUR_CAPTCHA_ID', key='YOUR_API_KEY', json=1 ) ``` ### Response #### Success Response (200) - **text** (string) - The solved captcha text (plain text response). - **json_response** (object) - The response in JSON format if `json=1` was used. #### Response Example (Plain Text) ```text OK|SOLVED_CAPTCHA_TEXT ``` #### Response Example (JSON) ```json { "captchaId": "YOUR_CAPTCHA_ID", "code": "SOLVED_CAPTCHA_TEXT" } ``` #### Error Response - **text** (string) - An error message indicating the problem. #### Error Response Example ```text ERROR_CAPTCHA_UNSOLVABLE ``` ``` -------------------------------- ### Handle ApiException in Usage Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/errors.md Demonstrates how to catch ApiException and check for specific error messages like 'ERROR_ZERO_BALANCE' or 'ERROR_IP_BANNED' to provide user-friendly feedback. ```python from twocaptcha import TwoCaptcha, ApiException solver = TwoCaptcha('YOUR_API_KEY') try: result = solver.recaptcha(sitekey, url) except ApiException as e: if 'ERROR_ZERO_BALANCE' in str(e): print("Insufficient balance") elif 'ERROR_IP_BANNED' in str(e): print("IP is banned") else: print(f"API error: {e}") ``` -------------------------------- ### res() Method Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Asynchronously sends a GET request to the /res.php endpoint to retrieve captcha solving results, account balance, or perform other actions. ```APIDOC ## res() ### Description Asynchronously sends a GET request to the 2captcha `/res.php` endpoint to retrieve captcha results, balance, or perform other actions. ### Method GET ### Endpoint `/res.php` ### Parameters #### Path Parameters None #### Query Parameters - **kwargs** (dict) - Optional - Query parameters for the API endpoint. ### Returns Coroutine that returns API response string ### Raises - `NetworkException` - Network request failed or HTTP status != 200 - `ApiException` - API returned error response ### Example ```python from twocaptcha.async_api import AsyncApiClient import asyncio async def main(): client = AsyncApiClient() # Get captcha result result = await client.res( key='YOUR_API_KEY', action='get', id='123456789' ) # Get account balance balance = await client.res( key='YOUR_API_KEY', action='getbalance' ) # Get result in JSON format result_json = await client.res( key='YOUR_API_KEY', action='get', id='123456789', json=1 ) print(f"Result: {result}") print(f"Balance: {balance}") asyncio.run(main()) ``` ``` -------------------------------- ### Solve Captcha Asynchronously Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Example of using the asynchronous solve method to solve a user-defined captcha. Requires an API key and captcha details. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def solve(): solver = AsyncTwoCaptcha('YOUR_API_KEY') result = await solver.solve( method='userrecaptcha', googlekey='6Le...', pageurl='https://example.com' ) print(f"Token: {result['code']}") asyncio.run(solve()) ``` -------------------------------- ### Project File Structure Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/INDEX.md Illustrates the organization of the 2captcha-python library's documentation and source files. ```text output/ ├── INDEX.md # This file ├── README.md # Start here ├── QUICK_REFERENCE.md # Fast lookup ├── configuration.md # Configuration options ├── errors.md # Exception reference └── api-reference/ ├── TwoCaptcha.md # Sync solver (1368 lines) ├── AsyncTwoCaptcha.md # Async solver (937 lines) ├── ApiClient.md # Low-level sync (349 lines) └── AsyncApiClient.md # Low-level async (411 lines) ``` -------------------------------- ### Get Captcha Result with Error Handling Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Retrieves the result of a previously submitted captcha. Includes basic error handling for when the captcha is not yet ready. ```python from twocaptcha import TwoCaptcha import time solver = TwoCaptcha('YOUR_API_KEY') captcha_id = solver.send(file='captcha.png', method='post') time.sleep(20) try: result = solver.get_result(captcha_id) print(f"Solution: {result}") except Exception as e: print(f"Not ready: {e}") ``` -------------------------------- ### AsyncTwoCaptcha Constructor Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Initializes the AsyncTwoCaptcha solver with API key and optional configuration parameters. All methods are coroutines and must be awaited. ```APIDOC ## AsyncTwoCaptcha Constructor ### Description Initializes the AsyncTwoCaptcha solver with API key and optional configuration parameters. All methods are coroutines and must be awaited. ### Parameters - **apiKey** (str) - Required - Your 2captcha API key. - **softId** (int) - Optional - Your software ID. Defaults to 4580. - **callback** (str) - Optional - URL for the callback notification. - **defaultTimeout** (int) - Optional - Default timeout for CAPTCHA solving in seconds. Defaults to 120. - **recaptchaTimeout** (int) - Optional - Timeout for reCAPTCHA solving in seconds. Defaults to 600. - **pollingInterval** (int) - Optional - Interval for polling for results in seconds. Defaults to 10. - **server** (str) - Optional - The 2captcha API server to use. Defaults to '2captcha.com'. - **extendedResponse** (bool) - Optional - Whether to request an extended response from the API. ### Returns - AsyncTwoCaptcha instance ### Example ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def main(): solver = AsyncTwoCaptcha('YOUR_API_KEY') balance = await solver.balance() print(f"Balance: {balance}") asyncio.run(main()) ``` ``` -------------------------------- ### Submit and Get Result for Normal Captcha Source: https://github.com/2captcha/2captcha-python/blob/master/README.md Manually submit a normal captcha image and poll for the result. Requires a 20-second delay between submission and polling. ```python import time id = solver.send(file='path/to/captcha.jpg') time.sleep(20) code = solver.get_result(id) ``` -------------------------------- ### Using httpx.AsyncClient for Persistent Connections Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Shows how to manage a persistent httpx.AsyncClient for high-volume asynchronous requests, enabling connection pooling and efficient resource usage. ```python from twocaptcha.async_api import AsyncApiClient import asyncio import httpx async def main(): # For many concurrent requests, consider creating a persistent client async with httpx.AsyncClient() as http_client: # Manual requests using the same client response = await http_client.post('https://2captcha.com/in.php', data={...}) asyncio.run(main()) ``` -------------------------------- ### Get Captcha Result in JSON Format Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Retrieve captcha results in JSON format by setting the 'json' parameter to 1 when calling the 'res' method. ```python from twocaptcha.api import ApiClient client = ApiClient() # Get result in JSON format result_json = client.res( key='YOUR_API_KEY', action='get', id='123456789', json=1 ) ``` -------------------------------- ### Using TwoCaptcha Wrapper Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Shows the typical usage pattern where the high-level TwoCaptcha class is used, which internally creates and manages an ApiClient instance. This is the recommended approach for most users. ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') # Creates ApiClient internally result = solver.normal('captcha.png') ``` -------------------------------- ### Asynchronous File Handling with AsyncApiClient Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Demonstrates various ways to submit files asynchronously using AsyncApiClient, including multiple files, a single file, and base64 encoded content. ```python from twocaptcha.async_api import AsyncApiClient import asyncio async def main(): client = AsyncApiClient() # Multiple files (async) response = await client.in_( files={ 'file_1': 'path/to/image1.png', 'file_2': 'path/to/image2.png', }, method='post' ) # Single file (async) response = await client.in_( file='path/to/image.png', method='post' ) # Base64 content (no file I/O) response = await client.in_( method='base64', body='iVBORw0KGgoAAAANSUhEUgAAAAUA...' ) print(response) asyncio.run(main()) ``` -------------------------------- ### Configuring ApiClient with post_url Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Shows how to instantiate ApiClient with a custom post_url attribute to specify a different API server hostname. The updated attribute can be accessed directly. ```python from twocaptcha.api import ApiClient client = ApiClient(post_url='rucaptcha.com') print(client.post_url) # Output: rucaptcha.com ``` -------------------------------- ### Initialize Async Captcha Solver Source: https://github.com/2captcha/2captcha-python/blob/master/README.md Initialize the asynchronous solver using AsyncTwoCaptcha. All methods are awaitable and exceptions are handled similarly to the synchronous version. ```python import asyncio from twocaptcha import AsyncTwoCaptcha async def solve_captcha(): solver = AsyncTwoCaptcha('YOUR_API_KEY') try: recaptcha_result = await solver.recaptcha(...) return recaptcha_result except Exception as e: print(e) return None if __name__ == '__main__': result = asyncio.run(solve_captcha()) ``` -------------------------------- ### Handling Network Errors with NetworkException Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/errors.md Catch NetworkException to manage issues related to network communication failures with the 2captcha API. This example includes a simple retry mechanism with a delay. ```python from twocaptcha import TwoCaptcha, NetworkException import time solver = TwoCaptcha('YOUR_API_KEY') try: result = solver.recaptcha(sitekey, url) except NetworkException as e: print(f"Network error, retrying: {e}") time.sleep(5) ``` -------------------------------- ### Using Alternative Server (RuCaptcha) Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/configuration.md Configure the `TwoCaptcha` solver to use an alternative API server, specifically `rucaptcha.com`. This is useful if your account is registered on that domain. ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha( 'YOUR_API_KEY', server='rucaptcha.com' ) ``` -------------------------------- ### Basic Sequential Async Usage Pattern Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Demonstrates solving multiple captchas sequentially using asynchronous calls. Each captcha is solved one after another. ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def main(): solver = AsyncTwoCaptcha('YOUR_API_KEY') result1 = await solver.normal('captcha1.png') result2 = await solver.normal('captcha2.png') print(f"Results: {result1['code']}, {result2['code']}") asyncio.run(main()) ``` -------------------------------- ### Handling Invalid Input with ValidationException Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/errors.md Catch ValidationException to handle specific cases where input parameters provided to the solver are incorrect or incomplete. This example shows handling a non-existent image file. ```python from twocaptcha import TwoCaptcha, ValidationException solver = TwoCaptcha('YOUR_API_KEY') try: result = solver.normal('/nonexistent/image.png') except ValidationException as e: print(f"Invalid input: {e}") ``` -------------------------------- ### Configure Default and Request Timeouts Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Set default timeouts for the solver instance or override them for individual requests. Also demonstrates setting a custom polling interval. ```python # Instance defaults solver = TwoCaptcha('KEY', defaultTimeout=180, recaptchaTimeout=900) # Override per request result = solver.normal('image.png', timeout=300) result = solver.recaptcha(sitekey, url, timeout=600) # Override polling interval result = solver.normal('image.png', polling_interval=5) ``` -------------------------------- ### Initialize Solver with Environment Variable Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/README.md Initialize the TwoCaptcha solver using an API key stored in an environment variable for better security. This is the recommended approach for managing sensitive credentials. ```python import os api_key = os.getenv('TWOCAPTCHA_API_KEY') solver = TwoCaptcha(api_key) ``` -------------------------------- ### audio() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronously solves audio CAPTCHAs by uploading an audio file. This method is a coroutine and must be awaited. ```APIDOC ## audio() ### Description Asynchronously solves audio CAPTCHAs by uploading an audio file. This method is a coroutine and must be awaited. ### Method `async def audio(file: str, lang: str, **kwargs) -> dict` ### Parameters - **file** (str) - Required - Path to the audio file containing the CAPTCHA. - **lang** (str) - Required - The language of the audio CAPTCHA (e.g., 'en'). - **kwargs** - Optional - Additional parameters accepted by the 2captcha API for audio CAPTCHAs. ### Returns - dict - A dictionary containing the CAPTCHA solution, typically with a 'code' field. ### Example ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def solve(): solver = AsyncTwoCaptcha('YOUR_API_KEY') result = await solver.audio('audio.mp3', 'en') print(f"Answer: {result['code']}") asyncio.run(solve()) ``` ``` -------------------------------- ### Handling ApiException Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Demonstrates how to catch and handle ApiException, which is raised when the API returns an error. Ensure you import the necessary exception class. ```python from twocaptcha.api import ApiClient from twocaptcha.exceptions.api import ApiException client = ApiClient() try: response = client.in_(method='post', file='captcha.png', key='INVALID_KEY') except ApiException as e: print(f"API error: {e}") ``` -------------------------------- ### funcaptcha() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Solves FunCaptcha (Arkose Labs) challenges. Requires sitekey and URL of the page. Supports optional surl, userAgent, custom data parameters, software ID, callback URL, and proxy. ```APIDOC ## funcaptcha() ### Description Solves FunCaptcha (Arkose Labs) challenges. Requires sitekey and URL of the page. Supports optional surl, userAgent, custom data parameters, software ID, callback URL, and proxy. ### Method POST ### Endpoint /solve ### Parameters #### Query Parameters - **key** (str) - Required - Your API key - **method** (str) - Required - `funcaptcha` - **sitekey** (str) - Required - pk or data-pkey parameter - **url** (str) - Required - Full URL of page - **surl** (str) - Optional - surl parameter from page - **userAgent** (str) - Optional - User-Agent string - **data[key]** (str) - Optional - Custom data parameters - **softId** (int) - Optional - Software developer ID - **callback** (str) - Optional - Pingback URL - **proxy** (dict) - Optional - Proxy config ### Response #### Success Response (200) - **captchaId** (str) - ID of submitted captcha - **code** (str) - FunCaptcha token ### Request Example ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') result = solver.funcaptcha('69A21a01-cc95-4bd8-...', 'https://example.com') ``` ``` -------------------------------- ### ApiClient Constructor Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Initializes the ApiClient with a specified API server hostname. This client is typically managed internally by the TwoCaptcha class. ```APIDOC ## ApiClient Constructor ### Description Initializes the ApiClient with a specified API server hostname. This client is typically managed internally by the TwoCaptcha class. ### Parameters #### Path Parameters - **post_url** (str) - Optional - API server hostname (without https:// prefix). Defaults to '2captcha.com'. ### Returns ApiClient instance ### Example ```python from twocaptcha.api import ApiClient # Default server client = ApiClient() # Alternative server (RuCaptcha) client = ApiClient(post_url='rucaptcha.com') ``` ``` -------------------------------- ### Proxy Support for Captcha Solving Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/README.md Shows how to configure proxy settings for solving captchas. This is useful when the captcha solving service requires requests to originate from a specific IP address or network. ```python result = solver.recaptcha( sitekey='6Le...', url='https://example.com', proxy={ 'type': 'HTTPS', 'uri': 'user:password@proxy.example.com:8080' } ) ``` -------------------------------- ### funcaptcha() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronously solves FunCaptcha by providing the sitekey and URL. This method is a coroutine and must be awaited. ```APIDOC ## funcaptcha() ### Description Asynchronously solves FunCaptcha by providing the sitekey and URL. This method is a coroutine and must be awaited. ### Method `async def funcaptcha(sitekey: str, url: str, **kwargs) -> dict` ### Parameters - **sitekey** (str) - Required - The sitekey of the FunCaptcha widget. - **url** (str) - Required - The URL of the page where the FunCaptcha is located. - **kwargs** - Optional - Additional parameters accepted by the 2captcha API for FunCaptcha. ### Returns - dict - A dictionary containing the FunCaptcha solution, typically with a 'code' field. ``` -------------------------------- ### Binance Source: https://github.com/2captcha/2captcha-python/blob/master/README.md Solves Binance Captcha. Returns a token. ```APIDOC ## Binance ### Description Solves Binance Captcha. Returns a token. ### Method `solver.binance` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **sitekey** (string) - Required - The sitekey for Binance captcha. * **pageurl** (string) - Required - The URL of the page where the captcha appears. * **validate_id** (string) - Required - The validation ID for Binance captcha. ### Request Example ```python result = solver.binance(sitekey='register', pageurl='https://mysite.com/page/with/binance', validate_id='e20c622fa9384952832fc1c2a6b75c0a',) ``` ### Response #### Success Response (200) * **result** (object) - The captcha solving result. ``` -------------------------------- ### Importing Libraries Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Import necessary classes for synchronous, asynchronous, and exception handling in the 2captcha-python library. ```python from twocaptcha import TwoCaptcha from twocaptcha import AsyncTwoCaptcha from twocaptcha import ( SolverExceptions, ValidationException, NetworkException, ApiException, TimeoutException ) ``` -------------------------------- ### Initialize Solver with API Key Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/README.md Initialize the TwoCaptcha solver with your API key. Ensure the API key is kept secret and not hardcoded. ```python solver = TwoCaptcha('YOUR_API_KEY') ``` -------------------------------- ### amazon_waf() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronous version of solving Amazon WAF. Requires sitekey, iv, context, and the URL of the page. ```APIDOC ## amazon_waf() ### Description Asynchronous version of solving Amazon WAF. Requires sitekey, iv, context, and URL. ### Method Asynchronous function call ### Parameters - **sitekey** (str) - Required - The sitekey for Amazon WAF. - **iv** (str) - Required - The initialization vector (IV) for Amazon WAF. - **context** (str) - Required - The context for Amazon WAF. - **url** (str) - Required - The URL of the page with the Amazon WAF captcha. - **kwargs** - Optional - Additional parameters for the captcha solving process. ### Returns - **dict** - The result of the captcha solving process. ``` -------------------------------- ### TwoCaptcha Constructor Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Initializes the TwoCaptcha solver with your API key and optional configuration parameters. ```APIDOC ## TwoCaptcha Constructor ### Description Initializes the TwoCaptcha solver with your API key and optional configuration parameters. ### Parameters - **apiKey** (str) - Required - Your 2captcha API key - **softId** (int) - Optional - Software ID for reward tracking (Default: 4580) - **callback** (str) - Optional - Pingback URL for callback responses - **defaultTimeout** (int) - Optional - Timeout for normal captchas in seconds (Default: 120) - **recaptchaTimeout** (int) - Optional - Timeout for reCAPTCHA in seconds (Default: 600) - **pollingInterval** (int) - Optional - Polling interval in seconds (Default: 10) - **server** (str) - Optional - API server hostname (Default: 2captcha.com) - **extendedResponse** (bool) - Optional - Enable extended response format ### Example ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') ``` ``` -------------------------------- ### Asynchronous Solver Usage Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md Utilize the `AsyncTwoCaptcha` class for non-blocking operations with `asyncio`. Demonstrates sequential and concurrent solving, as well as checking balance asynchronously. ```python import asyncio async def main(): solver = AsyncTwoCaptcha('API_KEY') # Sequential result = await solver.normal('image.png') # Concurrent results = await asyncio.gather( solver.normal('image1.png'), solver.normal('image2.png'), solver.recaptcha(sitekey, url), ) # Check balance balance = await solver.balance() asyncio.run(main()) ``` -------------------------------- ### Submitting Multiple Files Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/ApiClient.md Illustrates how to submit multiple files for captcha solving using the 'files' parameter in the in_() method. Each file is specified with a unique key. ```python from twocaptcha.api import ApiClient client = ApiClient() # Multiple files response = client.in_( files={ 'file_1': 'path/to/image1.png', 'file_2': 'path/to/image2.png', }, method='post' ) ``` -------------------------------- ### FunCaptcha Source: https://github.com/2captcha/2captcha-python/blob/master/README.md Solves FunCaptcha (Arkoselabs) and returns a token. ```APIDOC ## FunCaptcha ### Description Solves FunCaptcha (Arkoselabs) and returns a token. ### Method Signature ```python solver.funcaptcha(sitekey: str, url: str, param1: any, ...) ``` ### Parameters * **sitekey** (string) - Required - The sitekey of the FunCaptcha widget. * **url** (string) - Required - The URL of the page where the FunCaptcha is located. * **param1** (any) - Required - Additional parameters for the solver. ``` -------------------------------- ### mtcaptcha() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronous version of solving MTcaptcha. Requires sitekey and URL. ```APIDOC ## mtcaptcha() ### Description Asynchronous version of solving MTcaptcha. Requires sitekey and URL. ### Method Asynchronous function call ### Parameters - **sitekey** (str) - Required - The sitekey for MTcaptcha. - **url** (str) - Required - The URL of the page with the MTcaptcha. - **kwargs** - Optional - Additional parameters for the captcha solving process. ### Returns - **dict** - The result of the captcha solving process. ``` -------------------------------- ### balance() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronously retrieves the current account balance. This is a simple call that returns the balance as a floating-point number. ```APIDOC ## balance() ### Description Asynchronous version of retrieving the account balance. This method makes a request to the 2Captcha service to fetch the current balance associated with the API key. ### Method Asynchronous function call ### Returns * **float** - The account balance as a floating-point number. ### Raises * **NetworkException** - Raised in case of a network error during the request. * **ApiException** - Raised if the API returns an error response. ### Example ```python from twocaptcha import AsyncTwoCaptcha import asyncio async def check_balance(): solver = AsyncTwoCaptcha('YOUR_API_KEY') balance = await solver.balance() print(f"Balance: ${balance:.2f}") asyncio.run(check_balance()) ``` ``` -------------------------------- ### Flexible Configuration Options Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/README.md Configure the TwoCaptcha solver with custom options such as software ID, callback URL, timeouts, polling interval, server selection, and extended response format. ```python solver = TwoCaptcha( 'YOUR_API_KEY', softId=12345, # Your software ID callback='https://example.com/callback', # Async callback defaultTimeout=180, # Custom normal captcha timeout recaptchaTimeout=900, # Custom reCAPTCHA timeout pollingInterval=5, # Check every 5 seconds server='rucaptcha.com', # Alternative server extendedResponse=True # Detailed response data ) ``` -------------------------------- ### keycaptcha() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Solves KeyCaptcha by providing specific parameters from the page and the URL. ```APIDOC ## keycaptcha() ### Description Solves KeyCaptcha by providing specific parameters from the page and the URL. ### Method POST ### Endpoint /in.php ### Parameters #### Query Parameters - **key** (str) - Required - Your 2Captcha API key. - **method** (str) - Required - Set to "keycaptcha". - **s_s_c_user_id** (str) - Required - Parameter from page. - **s_s_c_session_id** (str) - Required - Parameter from page. - **s_s_c_web_server_sign** (str) - Required - Parameter from page. - **s_s_c_web_server_sign2** (str) - Required - Parameter from page. - **url** (str) - Required - Full URL of page. - **softId** (int) - Optional - Software developer ID. - **callback** (str) - Optional - Pingback URL. - **proxy** (dict) - Optional - Proxy config. ### Request Example ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') result = solver.keycaptcha('123', 'abc', 'def', 'ghi', 'https://example.com') ``` ### Response #### Success Response (200) - **captchaId** (str) - The ID of the submitted captcha. - **code** (str) - KeyCaptcha token. ``` -------------------------------- ### cutcaptcha() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronous version of solving CutCaptcha. Requires misery key, API key, and URL. ```APIDOC ## cutcaptcha() ### Description Asynchronous version of solving CutCaptcha. Requires misery key, API key, and URL. ### Method Asynchronous function call ### Parameters - **misery_key** (str) - Required - The misery key for CutCaptcha. - **apikey** (str) - Required - The API key for CutCaptcha. - **url** (str) - Required - The URL of the page with the CutCaptcha. - **kwargs** - Optional - Additional parameters for the captcha solving process. ### Returns - **dict** - The result of the captcha solving process. ``` -------------------------------- ### binance() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Solves Binance captcha. Requires pageurl, sitekey, and validate_id. ```APIDOC ## binance() ### Description Solves Binance captcha. ### Parameters #### Path Parameters - **pageurl** (str) - Required - Full URL of page. - **sitekey** (str) - Required - bizId, bizType, or bizCode. - **validate_id** (str) - Required - validateId or securityId. #### Query Parameters - **useragent** (str) - Optional - Browser User-Agent. #### Keyword Arguments - **proxy** (dict) - Optional - Proxy config. - **kwargs** (dict) - Optional - Additional parameters for the solver. ``` -------------------------------- ### vkimage() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Solves VK image captcha. Requires files and steps. ```APIDOC ## vkimage() ### Description Solves VK image captcha. ### Parameters #### Path Parameters - **files** (str | dict) - Required - Path to the image file or a dictionary of image files. - **steps** (str) - Required - The steps for solving the VK image captcha. #### Keyword Arguments - **kwargs** (dict) - Optional - Additional parameters for the solver. ``` -------------------------------- ### Using camelCase Parameters Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/README.md Illustrates the recommended way of passing parameters to captcha solving methods using camelCase. This format is directly used in method parameters for clarity and consistency. ```python solver.normal( 'image.png', minLen=5, maxLen=10, caseSensitive=1, hintText='type numbers only' ) ``` -------------------------------- ### Handling API Exceptions with AsyncApiClient Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncApiClient.md Shows how to catch and handle ApiException, which is raised when the API returns an error, such as with an invalid API key. ```python from twocaptcha.async_api import AsyncApiClient from twocaptcha.exceptions.api import ApiException import asyncio async def main(): client = AsyncApiClient() try: response = await client.in_(method='post', file='captcha.png', key='INVALID_KEY') except ApiException as e: print(f"API error: {e}") asyncio.run(main()) ``` -------------------------------- ### Granular Exception Handling for All Common Errors Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/errors.md Illustrates catching specific exceptions like ValidationException, NetworkException, ApiException, and TimeoutException individually. This allows for tailored responses to different error scenarios. ```python from twocaptcha import ( TwoCaptcha, ValidationException, NetworkException, ApiException, TimeoutException ) solver = TwoCaptcha('YOUR_API_KEY') try: result = solver.recaptcha(sitekey, url) except ValidationException as e: print(f"Invalid parameters: {e}") # Handle invalid input except NetworkException as e: print(f"Network error: {e}") # Implement retry logic except ApiException as e: print(f"API error: {e}") # Handle API-specific errors except TimeoutException as e: print(f"Solving timed out: {e}") # Handle timeout ``` -------------------------------- ### balance() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/TwoCaptcha.md Retrieves the current account balance. Returns the balance as a floating-point number. ```APIDOC ## balance() ### Description Retrieve the current account balance. ### Method GET (implied by typical API interactions, though not explicitly stated as HTTP) ### Endpoint Not explicitly defined, assumed to be part of the 2Captcha API service. ### Returns - Account balance as a float. ### Raises - `NetworkException` - A network error occurred. - `ApiException` - An API error occurred. ### Example ```python from twocaptcha import TwoCaptcha solver = TwoCaptcha('YOUR_API_KEY') balance = solver.balance() print(f"Balance: ${balance:.2f}") ``` ``` -------------------------------- ### File Input Methods Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/QUICK_REFERENCE.md The library supports multiple ways to provide image input for captcha solving: using a local file path, a direct URL to an image, or a base64-encoded string of the image data. ```python # File path result = solver.normal('/path/to/image.png') # URL result = solver.normal('https://example.com/captcha.png') # Base64-encoded import base64 with open('image.png', 'rb') as f: b64 = base64.b64encode(f.read()).decode() result = solver.normal(b64) ``` -------------------------------- ### Configure TwoCaptcha Solver Options Source: https://github.com/2captcha/2captcha-python/blob/master/README.md Configure the TwoCaptcha solver with various options such as server address, API key, soft ID, callback URL, timeouts, and polling interval. This allows for fine-tuning the solver's behavior. ```python config = { 'server': '2captcha.com', 'apiKey': 'YOUR_API_KEY', 'softId': 123, 'callback': 'https://your.site/result-receiver', 'defaultTimeout': 120, 'recaptchaTimeout': 600, 'pollingInterval': 10, 'extendedResponse': False } solver = TwoCaptcha(**config) ``` -------------------------------- ### turnstile() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronous version of solving Cloudflare Turnstile. It requires a sitekey and the URL of the page. ```APIDOC ## turnstile() ### Description Asynchronous version of solving Cloudflare Turnstile. Requires sitekey and URL. ### Method Asynchronous function call ### Parameters - **sitekey** (str) - Required - The sitekey for Cloudflare Turnstile. - **url** (str) - Required - The URL of the page with the Turnstile captcha. - **kwargs** - Optional - Additional parameters for the captcha solving process. ### Returns - **dict** - The result of the captcha solving process. ``` -------------------------------- ### prosopo() Source: https://github.com/2captcha/2captcha-python/blob/master/_autodocs/api-reference/AsyncTwoCaptcha.md Asynchronous version of solving Prosopo Captcha. Requires sitekey and page URL. ```APIDOC ## prosopo() ### Description Asynchronous version of solving Prosopo Captcha. Requires sitekey and page URL. ### Method Asynchronous function call ### Parameters - **sitekey** (str) - Required - The sitekey for Prosopo Captcha. - **pageurl** (str) - Required - The URL of the page with the Prosopo Captcha. - **kwargs** - Optional - Additional parameters for the captcha solving process. ### Returns - **dict** - The result of the captcha solving process. ```