Metadata-Version: 2.4
Name: captchasonline
Version: 1.0.1
Summary: A python package for solving captchas using the captchas.online API web service.
Home-page: https://captchas.online
Author: Captchas.Online
Author-email: Captchas Online <support@captchas.online>
License-Expression: MIT
Project-URL: Homepage, https://captchas.online
Project-URL: Issues, https://captchasolutions.raiseaticket.com/support/#/newticket
Classifier: Programming Language :: Python :: 3
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

See: https://captchas.online/ for a fast and cheap unlimited captcha solving...

## Installation

This package can be installed with Pip:

```bash
pip3 install captchasonline
```


## Configuration

CaptchasOnline instance can be created like this:

```python 
from captchasonline import CaptchasOnline

solver = CaptchasOnline('YOUR_API_KEY')
```

<details>
<summary>Async</summary>

```python 
from captchasonline import AsyncCaptchasOnline

solver = AsyncCaptchasOnline('YOUR_API_KEY')
```

</details>

Also, there are a few options that can be configured:

```python 
config = {
            'server':           'captchas.online',
            'apiKey':           'YOUR_API_KEY',
            'softId':            123,
            'callback':         'https://your.site/result-receiver',
            'defaultTimeout':    120,
            'recaptchaTimeout':  600,
            'pollingInterval':   10,
            'extendedResponse':  False
        }
solver = CaptchasOnline(**config)
```

### CaptchasOnline instance options

| Option           | Default value  | Description                                                                                                                                            |
| ---------------- | -------------- |--------------------------------------------------------------------------------------------------------------------------------------------------------|
| server           | `captchasonline` | API server. You can set it to `rucaptcha.com` if your account is registered there                                                                      |
| softId           | 4580           | your software ID obtained after publishing in [2captcha software catalog]                                                                              |
| callback         | -              | URL of your web server that receives the captcha recognition result. The URL should be first registered in [pingback settings] of your account         |
| defaultTimeout   | 120            | Polling timeout in seconds for all captcha types except reCAPTCHA. Defines how long the module tries to get the answer from the `res.php` API endpoint |
| recaptchaTimeout | 600            | Polling timeout for reCAPTCHA in seconds. Defines how long the module tries to get the answer from the `res.php` API endpoint                          |
| pollingInterval  | 10             | Interval in seconds between requests to the `res.php` API endpoint. Setting values less than 5 seconds is not recommended                              |
| extendedResponse | None           | Set to `True` to get the response with additional fields or in more practical format (enables `JSON` response from `res.php` API endpoint). Suitable for [ClickCaptcha](#clickcaptcha), [Canvas](#canvas) |


> [!IMPORTANT]
> Once `callback` is defined for the `CaptchasOnline` instance, all methods return only the captcha ID and DO NOT poll the API to get the result. The result will be sent to the callback URL.

To get the answer manually use [get_result method](#send--get_result)

## Solve captcha
When you submit any image-based CAPTCHA, you can provide additional options to help 2captcha workers solve it properly.

### Captcha options
| Option        | Default Value | Description                                                                                        |
| ------------- | ------------- | -------------------------------------------------------------------------------------------------- |
| numeric       | 0             | Defines if the captcha contains numeric or other symbols [see more info in the API docs][post options] |
| minLen        | 0             | minimal answer length                                                                              |
| maxLen        | 0             | maximum answer length                                                                              |
| phrase        | 0             | defines if the answer contains multiple words or not                                               |
| caseSensitive | 0             | defines if the answer is case sensitive                                                            |
| calc          | 0             | defines captcha requires calculation                                                               |
| lang          | -             | defines the captcha language; see the [list of supported languages]                                |
| hintImg       | -             | an image with a hint shown to workers with the captcha                                               |
| hintText      | -             | hint or task text shown to workers with the captcha                                                |

Below, you can find basic examples for every captcha type. Check out [examples directory] for more examples with all available options.

### Normal Captcha
 
To bypass a normal captcha (distorted text on an image) use the following method. This method can also be used to recognize any text in an image.

```python 
result = solver.normal('path/to/captcha.jpg', param1=..., ...)
# OR
result = solver.normal('https://site-with-captcha.com/path/to/captcha.jpg', param1=..., ...)
```
 
### reCAPTCHA v2
 
Use the following method to solve reCAPTCHA V2 and obtain a token to bypass the protection.

```python 
result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                          url='https://mysite.com/page/with/recaptcha',
                          param1=..., ...)
```

### reCAPTCHA v3
 
This method provides a reCAPTCHA V3 solver and returns a token.
```python
result = solver.recaptcha(sitekey='6Le-wvkSVVABCPBMRTvw0Q4Muexq1bi0DJwx_mJ-',
                            url='https://mysite.com/page/with/recaptcha',
                            version='v3',
                            param1=..., ...)
```
 
### GeeTest
 
Method to solve GeeTest puzzle captcha. Returns a set of tokens as JSON.
```python
result = solver.geetest(gt='f1ab2cdefa3456789012345b6c78d90e',
                        challenge='12345678abc90123d45678ef90123a456b',
                        url='https://www.site.com/page/',
                        param1=..., ...)

```
 
### Lemin Cropped Captcha
 
Use this method to solve the Lemin captcha. Returns JSON with an answer containing the following values: answer, challenge_id.
```python
result = solver.lemin(captcha_id='CROPPED_1abcd2f_a1234b567c890d12ef3a456bc78d901d',
                            div_id='lemin-cropped-captcha', 
                            url='https://www.site.com/page/',
                            param1=..., ...)

```
 
### Cloudflare Turnstile
 
Use this method to solve Cloudflare Turnstile. Returns JSON with the token.
```python
result = solver.turnstile(sitekey='0x1AAAAAAAAkg0s2VIOD34y5',
                            url='http://mysite.com/', 
                            data='foo',
                            pagedata='bar',
                            action='challenge',
                            useragent='Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36')
```
 
### CaptchaFox
 
This method can be used to solve CaptchaFox using a token. Returns a token.

```python
result = solver.captchafox(sitekey='sk_ILKWNruBBVKDOM7dZs59KHnDLEWiH',
                           pageurl='https://mysite.com/page/with/captchafox',
                           userAgent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
                           proxy={'type': 'HTTPS',
                                  'uri': 'login:password@IP_address:PORT'})
```  

## Other methods

### send / get_result
These methods can be used for manual captcha submission and answer polling. The `send()` method supports sending any captcha 
type, to specify the captcha type you must send value `method` manually, for example `method='recaptcha'` for solving reCaptcha. 

Example for solving Normal captcha manually:
```python
import time
. . . . . 


id = solver.send(file='path/to/captcha.jpg')
time.sleep(20)

code = solver.get_result(id)
```

### balance
 
Use this method to get your account's balance
```python
balance = solver.balance()
``` 

## Error handling
In case of an error, the captcha solver throws an exception. It's important to properly handle these cases. We recommend using `try except` to handle exceptions. 
```python
try:
    result = solver.text('If tomorrow is Saturday, what day is today?')
except ValidationException as e:
    # invalid parameters passed
	print(e)
except NetworkException as e:
	# network error occurred
	print(e)
except ApiException as e:
    # api respond with error
	print(e)
except TimeoutException as e:
    # captcha is not solved so far
	print(e)
```
 

```python
proxy={
    'type': 'HTTPS',
    'uri': 'login:password@IP_address:PORT'
}
```

## Async calls

To use the async version, just replace `CaptchasOnline` with `AsyncCaptchasOnline`:

```python
import asyncio
from captchasonline import AsyncCaptchasOnline

async def solve_captcha():
    solver = AsyncCaptchasOnline('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())
```

The `AsyncCaptchasOnline` class supports all the same methods and parameters as the synchronous `CaptchasOnline` class but operates asynchronously. Configuration is identical.

### Solving Multiple Captchas in Parallel

One of the main advantages of using async support is the ability to solve multiple captchas concurrently:

```python
async def solve_multiple_captchas():
    solver = AsyncCaptchasOnline('YOUR_API_KEY')
    
    # Start all tasks simultaneously
    task1 = asyncio.create_task(solver.text('What color is the sky on a clear day?'))
    task2 = asyncio.create_task(solver.text('What is 2+2?'))
    task3 = asyncio.create_task(solver.text('Name of the planet we live on?'))
    
    # Wait for all tasks to complete
    results = await asyncio.gather(task1, task2, task3, return_exceptions=True)
    return results

# This completes much faster than solving captchas sequentially
results = asyncio.run(solve_multiple_captchas())
```

Examples of solving all supported captcha types asynchronously are located in the [examples/async directory] directory.

### Legacy Async Method

For backward compatibility, you can also use the traditional executor-based approach with the synchronous client:

```python
import asyncio
import concurrent.futures
from captchasonline import CaptchasOnline

API_KEY = "YOUR_API_KEY"
image = "data:image/png;base64,iVBORw0KGgoA..."

async def captchaSolver(image):
    loop = asyncio.get_running_loop()
    with concurrent.futures.ThreadPoolExecutor() as pool:
        result = await loop.run_in_executor(pool, lambda: CaptchasOnline(API_KEY).normal(image))
        return result

captcha_result = asyncio.run(captchaSolver(image))
```
 
## Get in touch

<a href="mailto:support@captchas.online"><img src="https://github.com/user-attachments/assets/539df209-7c85-4fa5-84b4-fc22ab93fac7" width="80" height="30"></a>
<a href="https://captchasolutions.raiseaticket.com/support/#/newticket"><img src="https://github.com/user-attachments/assets/be044db5-2e67-46c6-8c81-04b78bd99650" width="81" height="30"></a>
 
## License

The code in this repository is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more details.

### Graphics and Trademarks

The graphics and trademarks included in this repository are not covered by the MIT License. Please contact <a href="mailto:support@captchas.online">support</a> for permissions regarding the use of these materials.


<!-- Shared links for README.md -->
[Captchas Online]: https://captchas.online/ 
