Skip to content

Commit

Permalink
Added ability of report incorrect captchas
Browse files Browse the repository at this point in the history
  • Loading branch information
alperensert committed Jul 31, 2023
1 parent 13f4c3b commit 9d21153
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 11 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@
**/public
**/.cache
**/node_modules
**/.DS_Store
**/.DS_Store
**/.venv
6 changes: 6 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"[python]": {
"editor.defaultFormatter": "ms-python.autopep8"
},
"python.formatting.provider": "none"
}
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,24 @@ print(result.get("gRecaptchaResponse"))
```python
from capmonster_python import GeeTestTask

capmonster_python = GeeTestTask("API_KEY")
task_id = capmonster_python.create_task("website_url", "gt", "challenge")
result= capmonster_python.join_task_result(task_id)
capmonster = GeeTestTask("API_KEY")
task_id = capmonster.create_task("website_url", "gt", "challenge")
result= capmonster.join_task_result(task_id)
print(result.get("challenge"))
print(result.get("seccode"))
print(result.get("validate"))
```

#### Report incorrect captchas

```python
from capmonster_python import RecaptchaV2Task

capmonster = RecaptchaV2Task("API_KEY")
task_id = capmonster.create_task("website_url", "website_key")
result = capmonster.join_task_result(task_id)
report_result = capmonster.report_incorrect_captcha("token", task_id)
print(report_result)
```

For other examples and api documentation please visit [wiki](https://alperensert.github.io/capmonster_python)
1 change: 1 addition & 0 deletions capmonster_python/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
from .image_to_text import ImageToTextTask
from .geetest import GeeTestTask
from .utils import CapmonsterException
from .compleximage import ComplexImageTask
41 changes: 37 additions & 4 deletions capmonster_python/capmonster.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ class Capmonster:
_CREATE_TASK_URL = "/createTask"
_TASK_RESULT_URL = "/getTaskResult"
_BALANCE_URL = "/getBalance"
_INCORRECT_IMAGE_CAPTCHA_URL = "/reportIncorrectImageCaptcha"
_INCORRECT_TOKEN_CAPTCHA_URL = "/reportIncorrectTokenCaptcha"

def __init__(self, client_key):
self._client_key = client_key
Expand Down Expand Up @@ -38,7 +40,8 @@ def join_task_result(self, task_id: int, maximum_time: int = 120):
elif result is False:
i += 1
sleep(2)
raise CapmonsterException(61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")
raise CapmonsterException(
61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")

async def join_task_result_async(self, task_id: int, maximum_time: int = 120):
for i in range(0, maximum_time + 1, 2):
Expand All @@ -48,7 +51,31 @@ async def join_task_result_async(self, task_id: int, maximum_time: int = 120):
elif result is False:
i += 1
await asyncio.sleep(2)
raise CapmonsterException(61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")
raise CapmonsterException(
61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")

def report_incorrect_captcha(self, captcha_type: str, task_id: int) -> bool:
if captcha_type is not "image" or "token":
raise CapmonsterException(
1, "ERROR_INCORRECT_CAPTCHA_TYPE", "Valid captcha_type parameters are only 'image' or 'token'.")
try:
self._report_incorrect_captcha(
captcha_type=captcha_type, task_id=task_id)
return True
except:
return False

@check_response()
def _report_incorrect_captcha(self, captcha_type: str, task_id: int):
data = {
"clientKey": self._client_key,
"taskId": task_id
}
if captcha_type is "image":
response = self._make_request("reportIncorrectImageCaptcha", data)
else:
response = self._make_request("reportIncorrectTokenCaptcha", data)
return response

@staticmethod
def _is_ready(response: dict):
Expand All @@ -68,8 +95,13 @@ def _make_request(self, method: str, data: dict):
elif method == "createTask":
_method = self._CREATE_TASK_URL
data["softId"] = self.__SOFT_ID
elif method == "reportIncorrectImageCaptcha":
_method = self._INCORRECT_IMAGE_CAPTCHA_URL
elif method == "reportIncorrectTokenCaptcha":
_method = self._INCORRECT_TOKEN_CAPTCHA_URL
try:
response = requests.post("{}{}".format(self._HOST_URL, _method), json=data).json()
response = requests.post("{}{}".format(
self._HOST_URL, _method), json=data).json()
except Exception as err:
raise CapmonsterException(-1, type(err).__name__, str(err))
return response
Expand All @@ -88,7 +120,8 @@ def _add_cookies(cookies, data):
elif type(cookies) == list:
for i in cookies:
if not len(cookies) % 2 == 0:
raise AttributeError("List cookies length must be even numbers")
raise AttributeError(
"List cookies length must be even numbers")
if cookies.index(i) % 2 == 0:
str_cookies += "{}=".format(i)
elif cookies[cookies.index(i)] == cookies[-1]:
Expand Down
48 changes: 48 additions & 0 deletions capmonster_python/compleximage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
from .capmonster import UserAgent

class ComplexImageTask(UserAgent):
def __init__(self, client_key):
super(ComplexImageTask, self).__init__(client_key)

def create_task(self, _class: str, grid: str = None,
task_definition: str = None,
image_urls: list = None,
images_base64: list = None,
task: str = None,
websiteUrl: str = None):
if _class is not "recaptcha" or _class is not "hcaptcha":
raise ValueError("Currently only recaptcha or hcaptcha is supported as _class value.")
data = {
"clientKey": self._client_key,
"task": {
"type": "ComplexImageTask",
"class": _class,
"metadata": {}
}
}
if image_urls is not None:
data["task"]["imageUrls"] = image_urls
elif images_base64 is not None:
data["task"]["imagesBase64"] = images_base64
else:
raise ValueError("image_urls or images_base64 must be sent")
if _class is "recaptcha":
if grid is None:
raise ValueError("Grid parameter must sent with recaptcha")
else:
data["task"]["metadata"]["Grid"] = grid
if task is not None:
data["task"]["metadata"]["Task"] = task
elif task_definition is not None:
data["task"]["metadata"]["TaskDefinition"] = task_definition
else:
raise ValueError("task_definition or task parameter must be sent")
elif _class is "hcaptcha":
if task is not None:
data["task"]["metadata"]["Task"] = task
else:
raise ValueError("task parameter must be sent with hcaptcha")
if websiteUrl is not None:
data["task"]["websiteUrl"] = websiteUrl
data, is_user_agent = self._add_user_agent(data)
return self._make_request("createTask", data).get("taskId")
8 changes: 5 additions & 3 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,14 @@

setup(
name="capmonster_python",
version="2.3",
version="2.4.1",
packages=["capmonster_python"],
url="https://github.com/alperensert/capmonster_python",
long_description=long_description,
long_description_content_type="text/markdown",
license="MIT",
author="Alperen Sert",
author_email="mail@alperenn.com",
author_email="business@alperen.io",
description="capmonster.cloud library for Python",
requires=["requests"],
classifiers=[
Expand All @@ -27,6 +27,8 @@
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
],
use_scm_version=True,
setup_requires=["setuptools_scm", "wheel"],
Expand All @@ -37,4 +39,4 @@
"Source": 'https://github.com/alperensert/capmonster_python/',
"Tracker": 'https://github.com/alperensert/capmonster_python/issues',
},
)
)

0 comments on commit 9d21153

Please sign in to comment.