
Security News
Deno 2.6 + Socket: Supply Chain Defense In Your CLI
Deno 2.6 introduces deno audit with a new --socket flag that plugs directly into Socket to bring supply chain security checks into the Deno CLI.
async-2captcha
Advanced tools
async-2captcha is an asynchronous Python client for the 2Captcha API. It provides helper classes for creating and managing captcha-solving tasks, including specialized solvers for Cloudflare Turnstile and image-based captchas (with selectable coordinates). This library is designed to handle common errors gracefully, raising both HTTP exceptions and 2Captcha-specific exceptions when appropriate.
async/await, allowing concurrent operations.4xx / 5xx) if the server’s status code is >= 400.ERROR_NO_SLOT_AVAILABLE, ERROR_ZERO_BALANCE, etc.) with clear messages.httpx[http2] and passing http2=True when creating the Async2Captcha client.get_balance().Requires Python 3.8+.
pip install async-2captcha
If you want HTTP/2 support (optional), install:
pip install httpx[http2]
import asyncio
from async_2captcha.client import Async2Captcha
async def main():
api_key = "YOUR_2CAPTCHA_API_KEY"
# Pass http2=True if you installed httpx[http2] and want to enable HTTP/2
captcha_client = Async2Captcha(api_key, http2=True)
balance = await captcha_client.get_balance()
print(f"Your 2Captcha balance is: ${balance:.2f}")
asyncio.run(main())
Turnstile is Cloudflare’s captcha alternative. To solve a Turnstile captcha:
import asyncio
from async_2captcha.client import Async2Captcha
async def solve_turnstile():
api_key = "YOUR_2CAPTCHA_API_KEY"
client = Async2Captcha(api_key)
# For a normal Turnstile widget (proxyless):
task_result = await client.turnstile.create_task(
website_url="https://example.com/login",
website_key="0x4AAAAAAAA...",
)
# If the task succeeded, you'll receive a TurnstileTask object with a solution field:
if task_result.solution:
print("Turnstile token:", task_result.solution.token)
print("User agent used:", task_result.solution.user_agent)
else:
print("No solution found or an error occurred.")
asyncio.run(solve_turnstile())
proxy_url such as "http://user:pass@1.2.3.4:8080" or "socks5://..." to create_task(). The solver will automatically switch to a proxy-based task.Some captchas require clicking specific regions of an image. Use the CoordinatesSolver:
import asyncio
import base64
from async_2captcha.client import Async2Captcha
async def solve_coordinates():
api_key = "YOUR_2CAPTCHA_API_KEY"
client = Async2Captcha(api_key)
# Prepare the image as a base64 string
with open("captcha.jpg", "rb") as f:
image_data = base64.b64encode(f.read()).decode("utf-8")
# Create and wait for the coordinates task
task_result = await client.coordinates.create_task(
body=image_data,
comment="Click all the apples in the image."
)
# On success, you'll have a list of (x, y) coordinates
if task_result.solution:
print("Coordinates:", task_result.solution.coordinates)
else:
print("No solution found or an error occurred.")
asyncio.run(solve_coordinates())
While the included solver classes (TurnstileSolver, CoordinatesSolver, etc.) automate task creation and waiting, you can also manage tasks directly:
import asyncio
from async_2captcha.client import Async2Captcha
from async_2captcha.enums import TaskType
async def create_and_poll_task():
api_key = "YOUR_2CAPTCHA_API_KEY"
client = Async2Captcha(api_key)
# Create a task manually
running_task = await client.create_task(TaskType.TURNSTILE_PROXYLESS, payload={
"websiteURL": "https://example.com",
"websiteKey": "0x4AAAAAAA..."
})
# Poll or wait until completed
task_result = await running_task.wait_until_completed()
if task_result.is_ready():
print("Task is solved!", task_result.solution)
else:
print("Task is still processing...")
asyncio.run(create_and_poll_task())
import asyncio
from async_2captcha.client import Async2Captcha
async def check_balance():
client = Async2Captcha("YOUR_2CAPTCHA_API_KEY")
balance = await client.get_balance()
print(f"2Captcha balance: ${balance}")
asyncio.run(check_balance())
Located in async_2captcha/client.py, the core class:
api_key (str): 2Captcha API key.http2 (bool, optional): If True, enables HTTP/2 (requires pip install httpx[http2]).turnstile: A TurnstileSolver instance.coordinates: A CoordinatesSolver instance.create_task(type: TaskType, payload: Dict[str, Any]) -> RunningTask
get_task_result(task_id: int) -> Task
get_balance() -> float
async_2captcha/solvers/turnstile.py):
create_task(website_url, website_key, action=None, data=None, pagedata=None, proxy_url=None) -> TurnstileTaskTurnstileTask object with the solution containing the Turnstile token.async_2captcha/solvers/coordinates.py):
create_task(body, comment=None, img_instructions=None, min_clicks=None, max_clicks=None) -> CoordinatesTaskCoordinatesTask object, whose solution includes a list of clicked coordinates.The following captcha solvers are currently placeholders (NotImplementedSolver). They will raise a NotImplementedError if called. Contributions to implement them are welcome.
Complex captchas:
recaptcha_v2recaptcha_v3recaptcha_v2_enterpriserecaptcha_v3_enterprisearkose_labsgeetestcapy_puzzlekeycaptchaleminamazon_captchacybersiaramt_captchacutcaptchafriendly_captchadatadome_captchaatb_captchatencentprosopo_procaptchaSimple captchas:
normal_captchatext_captcharotategriddraw_aroundbounding_boxaudio_captchaThe project uses Pydantic models to structure data responses from the 2Captcha API. These models are defined across various files within the async_2captcha/models/ directory. Notable models include:
Task (models/task.py):
is_ready(): Returns True if the task is completed and ready.is_processing(): Returns True if the task is still being processed.TurnstileTask (solvers/turnstile.py):
Task model and includes Turnstile-specific solutions such as tokens and user agents.CoordinatesTask (solvers/coordinates.py):
Task model and includes the list of (x, y) coordinates selected in image-based captchas.Base Models:
CamelCaseModel (models/base.py): A base model used for converting fields between camelCase (used by 2Captcha) and snake_case (used internally).These models ensure consistency and validation of API responses. When creating new solvers, you can extend these base models to support specific types of captchas.
2Captcha always returns HTTP 200 for successful or failed tasks. Errors are indicated by a non-zero errorId in the JSON response, at which point a 2Captcha-specific exception is raised. Example codes include:
ERROR_NO_SLOT_AVAILABLE (errorId=2)ERROR_ZERO_BALANCE (errorId=10)ERROR_CAPTCHA_UNSOLVABLE (errorId=12)Additionally, HTTP errors (e.g., if 2Captcha.com is unreachable or returns 4xx/5xx) are raised as HTTPError subclasses. Here’s how to handle them:
import asyncio
from async_2captcha.client import Async2Captcha
from async_2captcha.errors.http_errors import HTTPError
from async_2captcha.errors.client_errors import TwoCaptchaError
async def example():
try:
client = Async2Captcha("API_KEY", http2=True)
balance = await client.get_balance()
print("Balance:", balance)
except HTTPError as http_err:
print(f"HTTP error occurred: {http_err}")
except TwoCaptchaError as captcha_err:
print(f"2Captcha-specific error: {captcha_err}")
asyncio.run(example())
Contributions are welcome! Feel free to open an issue or submit a pull request for:
git clone https://github.com/diprog/async-2captcha.git
cd async-2captcha
python -m venv venv
source venv/bin/activate
pip install -r requirements.txt
pip install -e .
Please follow PEP 8 style guidelines and ensure all tests pass before submitting a pull request.
This project is licensed under the MIT License.
© 2025 Dmitry. All rights reserved.
FAQs
An asynchronous Python client for the 2Captcha API.
We found that async-2captcha demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
Deno 2.6 introduces deno audit with a new --socket flag that plugs directly into Socket to bring supply chain security checks into the Deno CLI.

Security News
New DoS and source code exposure bugs in React Server Components and Next.js: what’s affected and how to update safely.

Security News
Socket CEO Feross Aboukhadijeh joins Software Engineering Daily to discuss modern software supply chain attacks and rising AI-driven security risks.