GithubHelp home page GithubHelp logo

2captcha / 2captcha-python Goto Github PK

View Code? Open in Web Editor NEW
496.0 496.0 93.0 382 KB

Python 3 package for easy integration with the API of 2captcha captcha solving service to bypass recaptcha, hcaptcha, funcaptcha, geetest and solve any other captchas.

Home Page: https://2captcha.com

License: MIT License

Python 100.00%
2captcha anti-captcha anticaptcha bypass-invisible-recaptcha bypass-recaptcha-v2 bypass-recaptcha-v3 bypasscaptcha captcha-breaking captcha-bypass captcha-recognition captcha-services-for-recaptcha-v2 captcha-solver captcha-solving deathbycaptcha google-recaptcha-solver hcaptcha-bypass hcaptcha-solver recaptcha-solver recaptcha-solver-python recaptcha-v2-captcha-solver

2captcha-python's People

Contributors

arthurauffray avatar asenatorrr avatar caffeinatedmike avatar dzmitry-duboyski avatar henry-swe avatar iamarkadiypolukhin avatar kratzky avatar nathanielobrown avatar poplers24 avatar slenderman00 avatar thicccat688 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

2captcha-python's Issues

ValueError: Failed to send message: 400 {'captcha_key': ['captcha-required']

Hey man! Could you guide me with this? What am I doing wrong?

async def send_message(self, message, api_key: str):
    headers = self.__get_headers()

    async with self.__session.post(
            f"{self.BASE_URL}{self.TYPE_ENDPOINT_START}{self.channel_id}{self.TYPE_ENDPOINT_END}", headers=headers,
    ) as response:
        if response.status == 204:
            pass
        else:
            raise ValueError(f"Failed to type: {response.status} {await response.json()}")

    async with self.__session.post(
            f"{self.BASE_URL}{self.SEND_ENDPOINT_START}{self.channel_id}{self.SEND_ENDPOINT_END}", headers=headers,
            json={"content": message, "flags": 0, "nonce": "f4yh5", "tts": False}
    ) as response:
        if response.status == 200:
            data = await response.json()
            self.__message_id = data["id"]
            return data["id"]
        else:
            data = await response.json()
            solver = TwoCaptcha(apiKey=api_key)
            result = await solver.hcaptcha(
                sitekey="a9b5fb07-92ff-493f-86fe-352a2803b3df",
                url='https://discord.com/',
                data=data['captcha_rqdata'],
                invisible=True,
                UserAgent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'discord/1.0.9016 Chrome/108.0.5359.215 Electron/22.3.12 Safari/537.36'
                )
            headers.update({"X-Captcha-Key": result["code"]})
            async with self.__session.post(
                    f"{self.BASE_URL}{self.SEND_ENDPOINT_START}{self.channel_id}{self.SEND_ENDPOINT_END}",
                    headers=headers,
                    json={"content": message, "flags": 0, "nonce": "nonce", "tts": False}
            ) as resp:
                if resp.status == 200:
                    data = await resp.json()
                    self.__message_id = data["id"]
                    return data["id"]
                else:
                    raise ValueError(f"Failed to send message: {resp.status} {await resp.json()}")

Case Sensitive does not work

When I run the script gives only lowercase

I use the example you have with options.

import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(file))))

from twocaptcha import TwoCaptcha

in this example we store the API key inside environment variables that can be set like:

export APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Linux or macOS

set APIKEY_2CAPTCHA=1abc234de56fab7c89012d34e56fa7b8 on Windows

you can just set the API key directly to it's value like:

api_key="1abc234de56fab7c89012d34e56fa7b8"

api_key = os.getenv('APIKEY_2CAPTCHA', 'YOUR_API_KEY')

solver = TwoCaptcha(api_key, defaultTimeout=30, pollingInterval=5)

try:
result = solver.normal(
'./images/normal_2.jpg',
numeric=4,
minLen=4,
maxLen=20,
phrase=0,
caseSensitive=0,
calc=0,
lang='en',
# hintImg='./images/normal_hint.jpg',
# hintText='Type red symbols only',
)

except Exception as e:
sys.exit(e)

else:
sys.exit('result: ' + str(result))

NameError: name 'b64encode' is not defined

Error NameError: name 'b64encode' is not defined occures when url of captcha iamge is provided solver.normal('http://site.loc/wr-780.jpg')
You need import base64 in solver.py and call function as base64.b64encode in line 442

Welp

So i did something but idk how to use it in selenium python3

twocaptcha.api.ApiException: ERROR_ZERO_BALANCE

Describe the bug
When I launch the Account Creator, here is the issue I get:

Starting account creation for: [email protected]
Traceback (most recent call last):
File "C:\Users\nicod\Desktop\RAIDTOOLBOX\discord-spam-bots-master\discord-spam-bots-master\bots\misc\account-creator\account_creator.py", line 81, in
create()
File "C:\Users\nicod\Desktop\RAIDTOOLBOX\discord-spam-bots-master\discord-spam-bots-master\bots\misc\account-creator\account_creator.py", line 44, in create
recaptcha_answer = solver.hcaptcha(sitekey=site_key,url=discordUrl)
File "C:\Python310\lib\site-packages\twocaptcha\solver.py", line 198, in hcaptcha
result = self.solve(sitekey=sitekey,
File "C:\Python310\lib\site-packages\twocaptcha\solver.py", line 403, in solve
id_ = self.send(**kwargs)
File "C:\Python310\lib\site-packages\twocaptcha\solver.py", line 457, in send
response = self.api_client.in_(files=files, **params)
File "C:\Python310\lib\site-packages\twocaptcha\api.py", line 76, in in_
raise ApiException(resp)
twocaptcha.api.ApiException: ERROR_ZERO_BALANCE

I'm on masterfork and windows 11

Support on AWS Lambda

Hello, I've tried to resolve captcha on AWS Lambda and it does not working. There is no message and it don't execute the sequence...

def resolve_captcha(self, image_url):
        result = None
        random_image_path = '/tmp/' + generate_random_string(length=10) + ".png"
        with urlopen(image_url) as url:
            with open(random_image_path, 'wb') as f:
                f.write(url.read())
        solver = TwoCaptcha('APIKEY_2CAPTCHA')
        try:
            result = solver.normal(random_image_path)
            os.remove(random_image_path)
        except ValidationException as e:
            # invalid parameters passed
            print(e)
            os.remove(random_image_path)
        except NetworkException as e:
            # network error occurred
            print(e)
            os.remove(random_image_path)
        except ApiException as e:
            # api respond with error
            print(e)
            os.remove(random_image_path)
        except TimeoutException as e:
            # captcha is not solved so far
            print(e)
            os.remove(random_image_path)
        return result

Do you have some tips for this issue (it work locally).
Thank's in advance.

Missing MIT LICENSE file

Missing MIT LICENSE file.

Can you add this file?
And can you precise in the README this project is under the MIT license?

Thanks,

How to submit if the form haven't submit button?

Hello, i try to use 2captcha-python to resolve the cloudflare's hcaptcha, but the scripts haven't submit button, once i force submit, it will prompt "wrong captcha", how to solve this problem?

nosubmit

Docker compose error

Hey,

I am having problems using this package with docker compose.

This is my requirements file:

2captcha-python==1.1.0
aniso8601==9.0.1
APScheduler==3.7.0
astroid==2.5.3
beautifulsoup4==4.9.3
cbpro==1.1.4
click==7.1.2
colorama==0.4.4
dnspython==2.1.0
email-validator==1.1.2
Flask==1.1.2
flask-mongoengine==1.0.0
Flask-RESTful==0.3.8
Flask-WTF==0.14.3
idna==3.1
isort==5.8.0
itsdangerous==1.1.0
Jinja2==2.11.3
lazy-object-proxy==1.6.0
MarkupSafe==1.1.1
mccabe==0.6.1
mongoengine==0.23.0
pylint==2.7.4
pymongo==3.5.1
pytz==2021.1
requests==2.13.0
selenium==3.141.0
six==1.10.0
sortedcontainers==2.3.0
soupsieve==2.2.1
toml==0.10.2
typed-ast==1.4.3
tzlocal==2.1
urllib3==1.26.4
websocket-client==0.40.0
Werkzeug==1.0.1
wrapt==1.12.1
WTForms==2.3.3

When doing docker-compose up I get the following error:

> [6/7] RUN pip3 install -r requirements.txt:
#10 1.578 Collecting requests==2.13.0
#10 1.730   Downloading https://files.pythonhosted.org/packages/7e/ac/a80ed043485a3764053f59ca92f809cc8a18344692817152b0e8bd3ca891/requests-2.13.0-py2.py3-none-any.whl (584kB)
#10 2.112 Collecting 2captcha-python==1.1.0
#10 2.139   Downloading https://files.pythonhosted.org/packages/39/ad/5939251435bf7f47293eded6341ef8d4299aff623270be8c71da7fe9e205/2captcha-python-1.1.0.tar.gz
#10 2.388     ERROR: Command errored out with exit status 1:
#10 2.388      command: /usr/local/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-sf9esfkc/2captcha-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-sf9esfkc/2captcha-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-sf9esfkc/2captcha-python/pip-egg-info
#10 2.388          cwd: /tmp/pip-install-sf9esfkc/2captcha-python/
#10 2.388     Complete output (9 lines):
#10 2.388     Traceback (most recent call last):
#10 2.388       File "<string>", line 1, in <module>
#10 2.388       File "/tmp/pip-install-sf9esfkc/2captcha-python/setup.py", line 4, in <module>
#10 2.388         from twocaptcha import __version__
#10 2.388       File "/tmp/pip-install-sf9esfkc/2captcha-python/twocaptcha/__init__.py", line 1, in <module>
#10 2.388         from .api import ApiClient
#10 2.388       File "/tmp/pip-install-sf9esfkc/2captcha-python/twocaptcha/api.py", line 3, in <module>
#10 2.388         import requests
#10 2.388     ModuleNotFoundError: No module named 'requests'
#10 2.388     ----------------------------------------
#10 2.393 ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
#10 2.582 WARNING: You are using pip version 19.3.1; however, version 21.1 is available.

It looks like the error is coming a 2captcha-python module.

Please could you investigate?

Move `__version__` out of the twocaptcha package

Move the __version__ variable definition outside of the twocaptcha package. When setup.py tries to import that value, it causes an import of the requests library (via the ApiClient import) in twocaptcha/__init__.py . This breaks builds because it necessitates that users install requests before twocaptcha rather than being able to install libraries all in one go (e.g. via pip install -r requirements.tx).

Suggestion: Move it to a __version__.txt file and have setup.py and twocaptcha/__init__.py read it in as a value.

[Feat. request] Return result from getting report

Code to implement locates at

self.api_client.res(key=self.API_KEY, action=rep, id=id_)

As in documentation:

List of GET request parameters for http://2captcha.com/res.php

json Integer
Default: 0 No 0 - server will send the response as plain text
1 - tells the server to send the response as JSON

Server will return OK_REPORT_RECORDED response to your request. Or an error code if something went wrong.

'TwoCaptcha' object has no attribute 'normal'

If i will try this:

my_api_key = "my_top_secret_key"
solver = TwoCaptcha(my_api_key)
try:
    result = solver.normal('./images/normal.jpg')

i will get this: 'TwoCaptcha' object has no attribute 'normal'

any suggestions what i am doing wrong?

Add RQData.

Impossible to solve discord requests if you don't have that anymore, thanks.

What should I put in data parameter inside the response with already solved hCaptcha?

When I'm requesting page with requests library I receive this respoce from a server:

{'captcha_key': ['You need to update your app to join this server.'], 'captcha_sitekey': 'a9b5fb07-92ff-493f-86fe-352a2803b3df', 'captcha_service': 'hcaptcha', 'captcha_rqdata': 'OccZocPS0udA/9MOyn4qvfLuti5qTqBYoyNljA7F5cT8JBJrhBWRhw0TEDEFDTOOHMnE6jvE2WzhbGjvDN4hk9fxZkcvQ7Bgjjd/QEJEXReGJWyyxhB0HFSjFjRjn6H23PJjdTyRWpDrTjhV6l/qDb4O14C9XiiXfKF2hQgh', 'captcha_rqtoken': 'IlZFamJXMkdPZ1BiMTJsYlJhQ2NMYlFOaHJTWWdtUjl0NjBhQ0cyZTFCWmhtd01xc0pYeCtMMHhENXNKcmpWRHJPN0FrM2c9PWk5Zk5NUmRRdTNjdFRTTDQi.Yn7Hbw.CNj-_pg2pNmt47a-9OG8PyevmHA'}

then I'm using twocaptcha for solving this captcha in that manner:
recaptcha_answer = solver.hcaptcha(sitekey="a9b5fb07-92ff-493f-86fe-352a2803b3df", url=f'https://discord.com/api/v9/invites/{my_invite}', defaultTimeout=600)

and this function return captchaId and code.

The question is where and what should I put in data parameter if captcha is invisible? Cause If I requesting this page again with just a code as captcha_key server response for solving captcha again. I think I just give the wrong payload.

Cloudflare Turnstile solver giving ERROR_BAD_PARAMETERS

Hello there,
I am trying to use this library to solve Cloudflare turnstile captcha for one of the sites. But I am getting ERROR BAD PARAMETERS as the error.
Here is the full log.

result = solver.turnstile(
   ...:         sitekey='0x4AAAAAAAAjq6WYeRDKmebM',
   ...:         url='https://recorder.maricopa.gov/recdocdata/'
   ...: )
---------------------------------------------------------------------------
ApiException                              Traceback (most recent call last)
Cell In[3], line 1
----> 1 result = solver.turnstile(
      2         sitekey='0x4AAAAAAAAjq6WYeRDKmebM',
      3         url='https://recorder.maricopa.gov/recdocdata/'
      4 )

File ~/.local/lib/python3.8/site-packages/twocaptcha/solver.py:443, in TwoCaptcha.turnstile(self, sitekey, url, **kwargs)
    429 def turnstile(self, sitekey, url, **kwargs):
    430     '''
    431     Wrapper for solving Cloudflare Turnstile
    432 
   (...)
    440 
    441     '''
--> 443     result = self.solve(sitekey=sitekey,
    444                         url=url,
    445                         method='turnstile',
    446                         **kwargs)
    447     return result

File ~/.local/lib/python3.8/site-packages/twocaptcha/solver.py:492, in TwoCaptcha.solve(self, timeout, polling_interval, **kwargs)
    475 def solve(self, timeout=0, polling_interval=0, **kwargs):
    476     '''
    477     sends captcha, receives result
    478 
   (...)
    489     result : string
    490     '''
--> 492     id_ = self.send(**kwargs)
    493     result = {'captchaId': id_}
    495     if self.callback is None:

File ~/.local/lib/python3.8/site-packages/twocaptcha/solver.py:546, in TwoCaptcha.send(self, **kwargs)
    542 params = self.rename_params(params)
    544 params, files = self.check_hint_img(params)
--> 546 response = self.api_client.in_(files=files, **params)
    548 if not response.startswith('OK|'):
    549     raise ApiException(f'cannot recognize response {response}')

File ~/.local/lib/python3.8/site-packages/twocaptcha/api.py:76, in ApiClient.in_(self, files, **kwargs)
     73 resp = resp.content.decode('utf-8')
     75 if 'ERROR' in resp:
---> 76     raise ApiException(resp)
     78 return resp

ApiException: ERROR_BAD_PARAMETERS

Any help will be appreciated.

Thank you

Geetest3 always returning ERROR_CAPTCHA_UNSOLVABLE

I am trying to solve a Geetest3 captcha using the 2captcha API. For each of my over 30 captchas I tried to solve I get a few 200 responses stating CAPCHA_NOT_READY for a few seconds, and then I get a 200 with ERROR_CAPTCHA_UNSOLVABLE.

All of these show up within my dashboard on the 2captcha website, where I can see all of my requests coming in, yet each one of them was apparently unsolvable. Is there currently a bug with the way Geecaptchas are processed?

Turn off ssl verification

Is there any way to turn SSL verification off?
we can do
requests.get("http://url", verify=False)
But not work for solver.

import error follow on document example

I follow the document using this line

from twocaptcha import TwoCaptcha

But it will throw an error ImportError: cannot import name 'TwoCaptcha' from 'twocaptcha' (unknown location

Shouldn't it be

from twocaptcha.solver import TwoCaptcha

in document?

I am using 1.2.1 version

AttributeError: 'TwoCaptcha' object has no attribute 'hcaptcha'

solver = TwoCaptcha('Hidden)

try:
    login_response = requests.post('https://discord.com/api/v9/auth/login', json=login_payload)

    captcha_key = solver.hcaptcha(
        sitekey='f5561ba9-8f1e-40ca-9b5b-Hidden',
        url='https://discord.com/api/v9/auth/login')

    login_response.raise_for_status()
except requests.exceptions.HTTPError as err:
    print(f"Login Failed with status code {err.response.status_code}: {err.response.text}")
    raise

Use Proxy

How can I use a proxy with the solver? I'd be interested in doing so in order to change IP.

Solving HCaptcha without submit button

How can solve HCaptcha without submit button. Is there any way to make something like that ___grecaptcha_cfg.clients[0].L.L.callback("TOKENCAPTCHA")?

AttributeError: 'TwoCaptcha' object has no attribute 'normal'

I have both installed: twocaptcha and 2captcha-python
the code:

from twocaptcha import TwoCaptcha

...

solver = TwoCaptcha(captchaKey)
try:
captcha = solver.normal("config/captcha_image.png")
logging.info(f"Resultado 2captcha: {captcha}")
return captcha
except Exception as e:
logging.error(f"Erro ao resolver o captcha automaticamente: {e}โ€)

iโ€™ve also tried like:
captcha = solver.normal(file="config/captcha_image.png")

Selenium?

So i wonder how it should works with selenium, beacouse i tried lot of ways and it still not completing the h-captcha,
take a look at it:

AttributeError: 'TwoCaptcha' object has no attribute 'recaptcha'

I update both TwoCaptcha and 2captcha-python to the latest version. Show my code below:
solver = TwoCaptcha(api_key)
try:
result = solver.recaptcha(sitekey=site_key, url=pageurl)
print("Recaptcha Answer:", result['code'])

except Exception as e:
print('Error:', e)

Thanks for your help.

Errors in module

  1. apiKey is ignored if passed inside the options
  2. if the callback is passed, captchaId should be returned, but it is polling the api to get an answer
    3. AttributeError: 'TwoCaptcha' object has no attribute 'getResult' when calling getResult method

CERTIFICATE_VERIFY_FAILED

Hi team,
what causing this error:
HTTPSConnectionPool(host='2captcha.com', port=443): Max retries exceeded with url: /in.php (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:997)')))
I could run the code in different computer and get result. But change to this new computer, using window subsystem on linux. I meet this
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.