capmonster-python 3.2.0__tar.gz → 4.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. capmonster_python-4.0.0/PKG-INFO +150 -0
  2. capmonster_python-4.0.0/README.md +128 -0
  3. capmonster_python-4.0.0/pyproject.toml +36 -0
  4. capmonster_python-4.0.0/setup.cfg +4 -0
  5. capmonster_python-4.0.0/src/capmonster_python/__init__.py +33 -0
  6. capmonster_python-4.0.0/src/capmonster_python/client.py +245 -0
  7. capmonster_python-4.0.0/src/capmonster_python/exceptions.py +60 -0
  8. capmonster_python-4.0.0/src/capmonster_python/methods.py +32 -0
  9. capmonster_python-4.0.0/src/capmonster_python/tasks/__init__.py +42 -0
  10. capmonster_python-4.0.0/src/capmonster_python/tasks/basilisk.py +24 -0
  11. capmonster_python-4.0.0/src/capmonster_python/tasks/binance.py +31 -0
  12. capmonster_python-4.0.0/src/capmonster_python/tasks/complex_image_recaptcha.py +73 -0
  13. capmonster_python-4.0.0/src/capmonster_python/tasks/complex_image_recognition.py +33 -0
  14. capmonster_python-4.0.0/src/capmonster_python/tasks/datadome.py +62 -0
  15. capmonster_python-4.0.0/src/capmonster_python/tasks/geetest.py +86 -0
  16. capmonster_python-4.0.0/src/capmonster_python/tasks/image_to_text.py +37 -0
  17. capmonster_python-4.0.0/src/capmonster_python/tasks/imperva.py +50 -0
  18. capmonster_python-4.0.0/src/capmonster_python/tasks/prosopo.py +27 -0
  19. capmonster_python-4.0.0/src/capmonster_python/tasks/recaptcha_v2.py +40 -0
  20. capmonster_python-4.0.0/src/capmonster_python/tasks/recaptcha_v2_enterprise.py +40 -0
  21. capmonster_python-4.0.0/src/capmonster_python/tasks/recaptcha_v3.py +30 -0
  22. capmonster_python-4.0.0/src/capmonster_python/tasks/task.py +146 -0
  23. capmonster_python-4.0.0/src/capmonster_python/tasks/temu.py +32 -0
  24. capmonster_python-4.0.0/src/capmonster_python/tasks/tendi.py +30 -0
  25. capmonster_python-4.0.0/src/capmonster_python/tasks/turnstile.py +82 -0
  26. capmonster_python-4.0.0/src/capmonster_python.egg-info/PKG-INFO +150 -0
  27. capmonster_python-4.0.0/src/capmonster_python.egg-info/SOURCES.txt +29 -0
  28. capmonster_python-4.0.0/src/capmonster_python.egg-info/requires.txt +2 -0
  29. capmonster_python-3.2.0/PKG-INFO +0 -120
  30. capmonster_python-3.2.0/README.md +0 -91
  31. capmonster_python-3.2.0/capmonster_python/__init__.py +0 -13
  32. capmonster_python-3.2.0/capmonster_python/aws_waf.py +0 -22
  33. capmonster_python-3.2.0/capmonster_python/capmonster.py +0 -253
  34. capmonster_python-3.2.0/capmonster_python/compleximage.py +0 -51
  35. capmonster_python-3.2.0/capmonster_python/datadome.py +0 -19
  36. capmonster_python-3.2.0/capmonster_python/fun_captcha.py +0 -30
  37. capmonster_python-3.2.0/capmonster_python/geetest.py +0 -26
  38. capmonster_python-3.2.0/capmonster_python/hcaptcha.py +0 -36
  39. capmonster_python-3.2.0/capmonster_python/image_to_text.py +0 -43
  40. capmonster_python-3.2.0/capmonster_python/recaptcha_v2.py +0 -27
  41. capmonster_python-3.2.0/capmonster_python/recaptcha_v2_enterprise.py +0 -30
  42. capmonster_python-3.2.0/capmonster_python/recaptcha_v3.py +0 -24
  43. capmonster_python-3.2.0/capmonster_python/tendi.py +0 -19
  44. capmonster_python-3.2.0/capmonster_python/turnstile.py +0 -23
  45. capmonster_python-3.2.0/capmonster_python/utils.py +0 -35
  46. capmonster_python-3.2.0/capmonster_python.egg-info/PKG-INFO +0 -120
  47. capmonster_python-3.2.0/capmonster_python.egg-info/SOURCES.txt +0 -24
  48. capmonster_python-3.2.0/capmonster_python.egg-info/requires.txt +0 -2
  49. capmonster_python-3.2.0/setup.cfg +0 -7
  50. capmonster_python-3.2.0/setup.py +0 -42
  51. {capmonster_python-3.2.0 → capmonster_python-4.0.0}/LICENSE +0 -0
  52. {capmonster_python-3.2.0 → capmonster_python-4.0.0/src}/capmonster_python.egg-info/dependency_links.txt +0 -0
  53. {capmonster_python-3.2.0 → capmonster_python-4.0.0/src}/capmonster_python.egg-info/top_level.txt +0 -0
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: capmonster_python
3
+ Version: 4.0.0
4
+ Summary: capmonster.cloud library/package for Python
5
+ Author-email: Alperen Sert <business@alperen.io>
6
+ License: MIT
7
+ Project-URL: Documentation, https://alperensert.github.io/capmonster_python/
8
+ Project-URL: Source, https://github.com/alperensert/capmonster_python/
9
+ Project-URL: Tracker, https://github.com/alperensert/capmonster_python/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.9
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: httpx>=0.27.0
20
+ Requires-Dist: pydantic>=2.0
21
+ Dynamic: license-file
22
+
23
+ # 🤖 Capmonster Python
24
+
25
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/capmonster-python?style=for-the-badge)
26
+ ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/alperensert/capmonster_python?style=for-the-badge)
27
+ ![GitHub last commit](https://img.shields.io/github/last-commit/alperensert/capmonster_python?style=for-the-badge)
28
+ ![GitHub Release](https://img.shields.io/github/v/release/alperensert/capmonster_python?style=for-the-badge)
29
+ ![GitHub Repo stars](https://img.shields.io/github/stars/alperensert/capmonster_python?style=for-the-badge&color=rgb(255%2C%20255%2C%20143)&cacheSeconds=3600)
30
+
31
+ A modern, strongly typed, async-friendly Python SDK for solving CAPTCHA challenges
32
+ using [Capmonster.Cloud](https://capmonster.cloud/).
33
+
34
+ Supports reCAPTCHA v2 & v3, Cloudflare Turnstile, GeeTest (v3 & v4) and [much more](#-supported-captcha-types).
35
+
36
+ ---
37
+
38
+ ## ✨ Features
39
+
40
+ - ✅ Fully typed Pydantic v2 models
41
+ - 🔁 Both sync and async API support
42
+ - 🔐 Proxy and User-Agent configuration
43
+ - 📦 Supports the most common CAPTCHA types
44
+ - 📚 Intuitive API with powerful task building
45
+
46
+ ---
47
+
48
+ ## 🔧 Installation
49
+
50
+ ```bash
51
+ pip install capmonster_python
52
+ ```
53
+
54
+ > [!IMPORTANT]
55
+ > You're viewing the documentation for **Capmonster Python v4**, which includes breaking changes. If you prefer the
56
+ > old syntax used in versions prior to 4.x, you can continue using it by installing the legacy version:
57
+ > ```pip install capmonster_python==3.2```
58
+
59
+ ## 🚀 Quick Start
60
+
61
+ ### Async Example
62
+
63
+ ```python
64
+ import asyncio
65
+ from capmonster_python import CapmonsterClient, RecaptchaV3Task
66
+
67
+
68
+ async def main():
69
+ client = CapmonsterClient(api_key="YOUR_API_KEY")
70
+
71
+ task = RecaptchaV3Task(
72
+ websiteURL="https://example.com",
73
+ websiteKey="SITE_KEY_HERE",
74
+ minScore=0.5,
75
+ pageAction="verify"
76
+ )
77
+
78
+ task_id = await client.create_task_async(task)
79
+ result = await client.join_task_result_async(task_id)
80
+ print(result)
81
+
82
+
83
+ asyncio.run(main())
84
+
85
+ ```
86
+
87
+ ### Sync Example
88
+
89
+ ```python
90
+ from capmonster_python import CapmonsterClient, RecaptchaV2Task
91
+
92
+ client = CapmonsterClient(api_key="<YOUR_API_KEY>")
93
+
94
+ task = RecaptchaV2Task(
95
+ websiteURL="https://example.com",
96
+ websiteKey="SITE_KEY_HERE"
97
+ )
98
+
99
+ task_id = client.create_task(task)
100
+ result = client.join_task_result(task_id)
101
+ print(result)
102
+ ```
103
+
104
+ ---
105
+
106
+ ## 🧠 Supported CAPTCHA Types
107
+
108
+ Capmonster Python v4 supports a wide range of CAPTCHA formats — from mainstream challenges like reCAPTCHA and Turnstile
109
+ to enterprise-grade shields like Imperva and DataDome. Each task supports full Pydantic validation ✅ and both sync and
110
+ async clients 🔄 unless noted.
111
+
112
+ | 🔖 Category | CAPTCHA Type | Class Name | Proxy Required | Notes |
113
+ |---------------------------|--------------------------------|-------------------------------|----------------|----------------------------------------|
114
+ | 🧩 reCAPTCHA | reCAPTCHA v2 | `RecaptchaV2Task` | Optional | Visible / Invisible supported ✅ 🔄 |
115
+ | | reCAPTCHA v2 Enterprise | `RecaptchaV2EnterpriseTask` | Optional | `enterprisePayload` & `apiDomain` ✅ 🔄 |
116
+ | | reCAPTCHA v3 | `RecaptchaV3Task` | ❌ No | Score-based, proxyless ✅ 🔄 |
117
+ | 🛡️ Cloudflare | Turnstile (token) | `TurnstileTask` | ❌ No | Lightweight, async-ready ✅ 🔄 |
118
+ | | Turnstile (cf_clearance) | `TurnstileCloudFlareTask` | ✅ Yes | Full HTML + proxy required ✅ 🔄 |
119
+ | 📸 Image-based | Image-to-Text OCR | `ImageToTextTask` | ❌ No | Base64 image + module control ✅ 🔄 |
120
+ | | Complex Image (Recaptcha-like) | `ComplexImageRecaptchaTask` | ❌ No | Grid-based, metadata aware ✅ 🔄 |
121
+ | | Complex Image Recognition (AI) | `ComplexImageRecognitionTask` | ❌ No | Supports tasks like Shein, OOCL ✅ 🔄 |
122
+ | 🧠 Human Behavior | GeeTest v3 | `GeeTestV3Task` | Optional | Challenge + `gt` key + freshness ✅ 🔄 |
123
+ | | GeeTest v4 | `GeeTestV4Task` | Optional | `initParameters` supported ✅ 🔄 |
124
+ | 🛡️ Enterprise Protection | DataDome | `DataDomeTask` | ✅ Recommended | Cookie & page context needed ✅ 🔄 |
125
+ | | Imperva | `ImpervaTask` | ✅ Recommended | Incapsula + Reese84 logic ✅ 🔄 |
126
+ | 🏦 Platform-Specific | Binance Login | `BinanceTask` | ✅ Yes | `validateId` for login flow ✅ 🔄 |
127
+ | | Temu | `TemuTask` | ❌ No | Cookie-injected behavioral solver ✅ 🔄 |
128
+ | | TenDI | `TenDITask` | ✅ Yes | Custom captchaAppId field ✅ 🔄 |
129
+ | 🧪 Miscellaneous | Prosopo | `ProsopoTask` | Optional | Used in zk or crypto UIs ✅ 🔄 |
130
+ | | Basilisk | `BasiliskTask` | ❌ No | Minimalist site-key puzzle ✅ 🔄 |
131
+
132
+ ## 🧩 Advanced Usage
133
+
134
+ - Callback URLs are supported during task creation.
135
+ - Includes auto-retry loop for polling results (up to 120s)
136
+
137
+ ## 💬 Community & Support
138
+
139
+ Need help or have a question?
140
+
141
+ - 📧 Contact: business@alperen.io
142
+ - 🐛 Found a bug? [Open an issue](https://github.com/alperensert/capmonster_python/issues)
143
+
144
+ > [!NOTE]
145
+ > Community support is intended only for questions and issues related to this project. Custom usage scenarios,
146
+ > integrations, or application-specific logic are outside the scope of support.
147
+
148
+ ## 📄 License
149
+
150
+ This project is licensed under the [MIT License](/LICENSE).
@@ -0,0 +1,128 @@
1
+ # 🤖 Capmonster Python
2
+
3
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/capmonster-python?style=for-the-badge)
4
+ ![GitHub code size in bytes](https://img.shields.io/github/languages/code-size/alperensert/capmonster_python?style=for-the-badge)
5
+ ![GitHub last commit](https://img.shields.io/github/last-commit/alperensert/capmonster_python?style=for-the-badge)
6
+ ![GitHub Release](https://img.shields.io/github/v/release/alperensert/capmonster_python?style=for-the-badge)
7
+ ![GitHub Repo stars](https://img.shields.io/github/stars/alperensert/capmonster_python?style=for-the-badge&color=rgb(255%2C%20255%2C%20143)&cacheSeconds=3600)
8
+
9
+ A modern, strongly typed, async-friendly Python SDK for solving CAPTCHA challenges
10
+ using [Capmonster.Cloud](https://capmonster.cloud/).
11
+
12
+ Supports reCAPTCHA v2 & v3, Cloudflare Turnstile, GeeTest (v3 & v4) and [much more](#-supported-captcha-types).
13
+
14
+ ---
15
+
16
+ ## ✨ Features
17
+
18
+ - ✅ Fully typed Pydantic v2 models
19
+ - 🔁 Both sync and async API support
20
+ - 🔐 Proxy and User-Agent configuration
21
+ - 📦 Supports the most common CAPTCHA types
22
+ - 📚 Intuitive API with powerful task building
23
+
24
+ ---
25
+
26
+ ## 🔧 Installation
27
+
28
+ ```bash
29
+ pip install capmonster_python
30
+ ```
31
+
32
+ > [!IMPORTANT]
33
+ > You're viewing the documentation for **Capmonster Python v4**, which includes breaking changes. If you prefer the
34
+ > old syntax used in versions prior to 4.x, you can continue using it by installing the legacy version:
35
+ > ```pip install capmonster_python==3.2```
36
+
37
+ ## 🚀 Quick Start
38
+
39
+ ### Async Example
40
+
41
+ ```python
42
+ import asyncio
43
+ from capmonster_python import CapmonsterClient, RecaptchaV3Task
44
+
45
+
46
+ async def main():
47
+ client = CapmonsterClient(api_key="YOUR_API_KEY")
48
+
49
+ task = RecaptchaV3Task(
50
+ websiteURL="https://example.com",
51
+ websiteKey="SITE_KEY_HERE",
52
+ minScore=0.5,
53
+ pageAction="verify"
54
+ )
55
+
56
+ task_id = await client.create_task_async(task)
57
+ result = await client.join_task_result_async(task_id)
58
+ print(result)
59
+
60
+
61
+ asyncio.run(main())
62
+
63
+ ```
64
+
65
+ ### Sync Example
66
+
67
+ ```python
68
+ from capmonster_python import CapmonsterClient, RecaptchaV2Task
69
+
70
+ client = CapmonsterClient(api_key="<YOUR_API_KEY>")
71
+
72
+ task = RecaptchaV2Task(
73
+ websiteURL="https://example.com",
74
+ websiteKey="SITE_KEY_HERE"
75
+ )
76
+
77
+ task_id = client.create_task(task)
78
+ result = client.join_task_result(task_id)
79
+ print(result)
80
+ ```
81
+
82
+ ---
83
+
84
+ ## 🧠 Supported CAPTCHA Types
85
+
86
+ Capmonster Python v4 supports a wide range of CAPTCHA formats — from mainstream challenges like reCAPTCHA and Turnstile
87
+ to enterprise-grade shields like Imperva and DataDome. Each task supports full Pydantic validation ✅ and both sync and
88
+ async clients 🔄 unless noted.
89
+
90
+ | 🔖 Category | CAPTCHA Type | Class Name | Proxy Required | Notes |
91
+ |---------------------------|--------------------------------|-------------------------------|----------------|----------------------------------------|
92
+ | 🧩 reCAPTCHA | reCAPTCHA v2 | `RecaptchaV2Task` | Optional | Visible / Invisible supported ✅ 🔄 |
93
+ | | reCAPTCHA v2 Enterprise | `RecaptchaV2EnterpriseTask` | Optional | `enterprisePayload` & `apiDomain` ✅ 🔄 |
94
+ | | reCAPTCHA v3 | `RecaptchaV3Task` | ❌ No | Score-based, proxyless ✅ 🔄 |
95
+ | 🛡️ Cloudflare | Turnstile (token) | `TurnstileTask` | ❌ No | Lightweight, async-ready ✅ 🔄 |
96
+ | | Turnstile (cf_clearance) | `TurnstileCloudFlareTask` | ✅ Yes | Full HTML + proxy required ✅ 🔄 |
97
+ | 📸 Image-based | Image-to-Text OCR | `ImageToTextTask` | ❌ No | Base64 image + module control ✅ 🔄 |
98
+ | | Complex Image (Recaptcha-like) | `ComplexImageRecaptchaTask` | ❌ No | Grid-based, metadata aware ✅ 🔄 |
99
+ | | Complex Image Recognition (AI) | `ComplexImageRecognitionTask` | ❌ No | Supports tasks like Shein, OOCL ✅ 🔄 |
100
+ | 🧠 Human Behavior | GeeTest v3 | `GeeTestV3Task` | Optional | Challenge + `gt` key + freshness ✅ 🔄 |
101
+ | | GeeTest v4 | `GeeTestV4Task` | Optional | `initParameters` supported ✅ 🔄 |
102
+ | 🛡️ Enterprise Protection | DataDome | `DataDomeTask` | ✅ Recommended | Cookie & page context needed ✅ 🔄 |
103
+ | | Imperva | `ImpervaTask` | ✅ Recommended | Incapsula + Reese84 logic ✅ 🔄 |
104
+ | 🏦 Platform-Specific | Binance Login | `BinanceTask` | ✅ Yes | `validateId` for login flow ✅ 🔄 |
105
+ | | Temu | `TemuTask` | ❌ No | Cookie-injected behavioral solver ✅ 🔄 |
106
+ | | TenDI | `TenDITask` | ✅ Yes | Custom captchaAppId field ✅ 🔄 |
107
+ | 🧪 Miscellaneous | Prosopo | `ProsopoTask` | Optional | Used in zk or crypto UIs ✅ 🔄 |
108
+ | | Basilisk | `BasiliskTask` | ❌ No | Minimalist site-key puzzle ✅ 🔄 |
109
+
110
+ ## 🧩 Advanced Usage
111
+
112
+ - Callback URLs are supported during task creation.
113
+ - Includes auto-retry loop for polling results (up to 120s)
114
+
115
+ ## 💬 Community & Support
116
+
117
+ Need help or have a question?
118
+
119
+ - 📧 Contact: business@alperen.io
120
+ - 🐛 Found a bug? [Open an issue](https://github.com/alperensert/capmonster_python/issues)
121
+
122
+ > [!NOTE]
123
+ > Community support is intended only for questions and issues related to this project. Custom usage scenarios,
124
+ > integrations, or application-specific logic are outside the scope of support.
125
+
126
+ ## 📄 License
127
+
128
+ This project is licensed under the [MIT License](/LICENSE).
@@ -0,0 +1,36 @@
1
+ [project]
2
+ name = "capmonster_python"
3
+ version = "4.0.0"
4
+ description = "capmonster.cloud library/package for Python"
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = { text = "MIT" }
8
+ authors = [{ name = "Alperen Sert", email = "business@alperen.io" }]
9
+ dependencies = [
10
+ "httpx>=0.27.0",
11
+ "pydantic>=2.0"
12
+ ]
13
+
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.9",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11"
21
+ ]
22
+
23
+ [project.urls]
24
+ Documentation = "https://alperensert.github.io/capmonster_python/"
25
+ Source = "https://github.com/alperensert/capmonster_python/"
26
+ Tracker = "https://github.com/alperensert/capmonster_python/issues"
27
+
28
+ [build-system]
29
+ requires = ["setuptools>=61", "wheel"]
30
+ build-backend = "setuptools.build_meta"
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.setuptools.package-dir]
36
+ "" = "src"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,33 @@
1
+ from .client import CapmonsterClient
2
+ from .exceptions import *
3
+ from .tasks import *
4
+
5
+ __all__ = [
6
+ "CapmonsterClient",
7
+ "VanillaTaskPayload",
8
+ "ProxyPayload",
9
+ "UserAgentPayload",
10
+ "BasiliskTask",
11
+ "BinanceTask",
12
+ "ComplexImageRecaptchaTask",
13
+ "ComplexImageRecaptchaMetadata",
14
+ "ComplexImageRecognitionTask",
15
+ "DataDomeTask",
16
+ "DataDomeMetadata",
17
+ "GeeTestV3Task",
18
+ "GeeTestV4Task",
19
+ "ImageToTextTask",
20
+ "ImpervaTask",
21
+ "ImpervaTaskMetadata",
22
+ "ProsopoTask",
23
+ "RecaptchaV2Task",
24
+ "RecaptchaV2EnterpriseTask",
25
+ "RecaptchaV3Task",
26
+ "TemuTask",
27
+ "TenDITask",
28
+ "TurnstileTask",
29
+ "TurnstileCloudFlareTask",
30
+ "CapmonsterException",
31
+ "CapmonsterAPIException",
32
+ "CapmonsterValidationException"
33
+ ]
@@ -0,0 +1,245 @@
1
+ import asyncio
2
+ from time import sleep
3
+ from typing import Optional
4
+
5
+ from httpx import Response, AsyncClient, Client
6
+
7
+ from .exceptions import CapmonsterAPIException, CapmonsterException
8
+ from .methods import GetBalancePayload, GetTaskResultPayload, CreateTaskPayload
9
+ from .tasks.task import TaskPayload
10
+
11
+
12
+ class CapmonsterClient:
13
+ __BASE_URL = "https://api.capmonster.cloud"
14
+ __BALANCE_URL = "/getBalance"
15
+ __TASK_RESULT_URL = "/getTaskResult"
16
+ __CREATE_TASK_URL = "/createTask"
17
+ __MAX_RETRY = 120
18
+ __PER_RETRY_DELAY = 1
19
+
20
+ def __init__(self, api_key: str, timeout: Optional[float] = 30.0) -> None:
21
+ self.api_key = api_key
22
+ self.__async_client = AsyncClient(timeout=timeout, base_url=self.__BASE_URL)
23
+ self.__sync_client = Client(timeout=timeout, base_url=self.__BASE_URL)
24
+
25
+ def get_balance(self) -> float:
26
+ """
27
+ Fetches the current balance using the provided API key.
28
+
29
+ Raises:
30
+ This method may raise exceptions if the HTTP request fails or the JSON response
31
+ format is unexpected. These exceptions are not handled within the method.
32
+
33
+ Returns:
34
+ float: The balance fetched from the external service. Defaults to 0.0 if the balance
35
+ key is not found in the response.
36
+ """
37
+ payload = GetBalancePayload(clientKey=self.api_key).model_dump()
38
+ response = self.__make_sync_request(self.__BALANCE_URL, payload).json()
39
+ return response.get("balance", 0.0)
40
+
41
+ async def get_balance_async(self) -> float:
42
+ """
43
+ Asynchronously fetches the current balance using the provided API key.
44
+
45
+ Raises:
46
+ This method may raise exceptions if the HTTP request fails or the JSON response
47
+ format is unexpected. These exceptions are not handled within the method.
48
+
49
+ Returns:
50
+ float: The balance fetched from the external service. Defaults to 0.0 if the balance
51
+ key is not found in the response.
52
+ """
53
+ payload = GetBalancePayload(clientKey=self.api_key).model_dump()
54
+ response = await self.__make_async_request(self.__BALANCE_URL, payload)
55
+ return response.json().get("balance", 0.0)
56
+
57
+ def create_task(self, task: TaskPayload, callback_url: Optional[str] = None) -> int:
58
+ """
59
+ Creates a task based on the provided payload and returns the task ID.
60
+
61
+ This method is responsible for initiating a task by preparing the request with the
62
+ provided task details and optional callback URL, sending a synchronous request to the
63
+ task creation endpoint, and parsing the response to retrieve the task ID.
64
+
65
+ Args:
66
+ task: The task configuration payload that defines the specifics of the task to be
67
+ created.
68
+ callback_url: An optional URL to be called back upon task completion or update.
69
+
70
+ Returns:
71
+ The unique identifier of the created task.
72
+
73
+ Raises:
74
+ CapmonsterException: If the task creation request fails or the response is not contains valid task id.
75
+ """
76
+ payload = CreateTaskPayload(clientKey=self.api_key, task=task, callbackUrl=callback_url).model_dump(
77
+ exclude_none=True)
78
+ payload["softId"] = 30
79
+ response = self.__make_sync_request(self.__CREATE_TASK_URL, payload).json()
80
+ return response.get("taskId", 0)
81
+
82
+ async def create_task_async(self, task: TaskPayload, callback_url: Optional[str] = None) -> int:
83
+ """
84
+ Asynchronously creates a task based on the provided payload and returns the task ID.
85
+
86
+ This method is responsible for initiating a task by preparing the request with the
87
+ provided task details and optional callback URL, sending a synchronous request to the
88
+ task creation endpoint, and parsing the response to retrieve the task ID.
89
+
90
+ Args:
91
+ task: The task configuration payload that defines the specifics of the task to be
92
+ created.
93
+ callback_url: An optional URL to be called back upon task completion or update.
94
+
95
+ Returns:
96
+ The unique identifier of the created task.
97
+
98
+ Raises:
99
+ CapmonsterException: If the task creation request fails or the response is not contains valid task id.
100
+ """
101
+ payload = CreateTaskPayload(clientKey=self.api_key, task=task, callbackUrl=callback_url).model_dump(
102
+ exclude_none=True)
103
+ payload["softId"] = 30
104
+ request = await self.__make_async_request(self.__CREATE_TASK_URL, payload)
105
+ response = request.json()
106
+ return response.get("taskId", 0)
107
+
108
+ def get_task_result(self, task_id: int) -> dict:
109
+ """
110
+ Fetches the result of a specific task by its identifier.
111
+
112
+ This function interacts with API to retrieve the results of a
113
+ previously submitted task. The function uses the provided task ID and
114
+ sends a request to the API endpoint to get the result. It returns the
115
+ solution data extracted from the API response or an empty dictionary if
116
+ no solution data is found.
117
+
118
+ Args:
119
+ task_id (int): An integer representing the unique identifier of the task.
120
+
121
+ Returns:
122
+ dict: A dictionary containing the solution data retrieved from the task
123
+ result API endpoint. If the solution is not found in the response, an empty
124
+ dictionary is returned.
125
+ """
126
+ payload = GetTaskResultPayload(clientKey=self.api_key, taskId=task_id).model_dump()
127
+ response = self.__make_sync_request(self.__TASK_RESULT_URL, payload).json()
128
+ return response.get("solution", {})
129
+
130
+ async def get_task_result_async(self, task_id: int) -> dict:
131
+ """
132
+ Asynchronously fetches the result of a specific task by its identifier.
133
+
134
+ This function interacts with API to retrieve the results of a
135
+ previously submitted task. The function uses the provided task ID and
136
+ sends a request to the API endpoint to get the result. It returns the
137
+ solution data extracted from the API response or an empty dictionary if
138
+ no solution data is found.
139
+
140
+ Args:
141
+ task_id (int): An integer representing the unique identifier of the task.
142
+
143
+ Returns:
144
+ dict: A dictionary containing the solution data retrieved from the task
145
+ result API endpoint. If the solution is not found in the response, an empty
146
+ dictionary is returned.
147
+ """
148
+ payload = GetTaskResultPayload(clientKey=self.api_key, taskId=task_id).model_dump()
149
+ request = await self.__make_async_request(self.__TASK_RESULT_URL, payload)
150
+ response = request.json()
151
+ return response.get("solution", {})
152
+
153
+ def join_task_result(self, task_id: int) -> dict:
154
+ """
155
+ Joins and retrieves the result of a task given its ID, retrying a specified number
156
+ of times if the result is not immediately available.
157
+
158
+ Args:
159
+ task_id: The identifier of the task for which the result needs to be retrieved.
160
+
161
+ Returns:
162
+ dict:
163
+ The result of the task if successfully retrieved within the maximum retries.
164
+
165
+ Raises:
166
+ CapmonsterException:
167
+ If the maximum retry limit is exceeded without obtaining the task result.
168
+ """
169
+ for _ in range(0, self.__MAX_RETRY + 1):
170
+ result = self.get_task_result(task_id)
171
+ if result:
172
+ return result
173
+ elif not result:
174
+ sleep(self.__PER_RETRY_DELAY)
175
+ raise CapmonsterAPIException(
176
+ 61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")
177
+
178
+ async def join_task_result_async(self, task_id: int):
179
+ """
180
+ Asynchronously joins and retrieves the result of a task given its ID, retrying a specified number
181
+ of times if the result is not immediately available.
182
+
183
+ Args:
184
+ task_id: The identifier of the task for which the result needs to be retrieved.
185
+
186
+ Returns:
187
+ dict:
188
+ The result of the task if successfully retrieved within the maximum retries.
189
+
190
+ Raises:
191
+ CapmonsterException:
192
+ If the maximum retry limit is exceeded without obtaining the task result.
193
+ """
194
+ for _ in range(0, self.__MAX_RETRY + 1):
195
+ result = await self.get_task_result_async(task_id)
196
+ if result:
197
+ return result
198
+ elif not result:
199
+ await asyncio.sleep(self.__PER_RETRY_DELAY)
200
+ raise CapmonsterAPIException(
201
+ 61, "ERROR_MAXIMUM_TIME_EXCEED", "Maximum time is exceed.")
202
+
203
+ def __make_sync_request(self, url: str, payload: dict) -> Response:
204
+ try:
205
+ response = self.__sync_client.post(url, json=payload)
206
+ return self.__check_response(response)
207
+ except Exception as e:
208
+ raise CapmonsterException(-1, type(e).__name__, str(e))
209
+
210
+ async def __make_async_request(self, url: str, payload: dict) -> Response:
211
+ try:
212
+ post = await self.__async_client.post(url, json=payload)
213
+ return self.__check_response(post)
214
+ except Exception as e:
215
+ raise CapmonsterException(-1, type(e).__name__, str(e))
216
+
217
+ @staticmethod
218
+ def __is_ready(response: dict):
219
+ status = response.get("status")
220
+ if status == "processing":
221
+ return False
222
+ elif status == "ready":
223
+ return True
224
+ else:
225
+ raise CapmonsterAPIException(error_id=-1,
226
+ error_code="CAPMONSTER_API_ERROR",
227
+ error_description="Sometimes can be happen if Capmonster "
228
+ "servers there is too much intensity")
229
+
230
+ @staticmethod
231
+ def __check_response(data: Response) -> Response:
232
+ response = data.json()
233
+ if type(response) is dict:
234
+ if response.get("errorId", 0) != 0:
235
+ raise CapmonsterAPIException(
236
+ response.get("errorId"),
237
+ response.get("errorCode", response.get("errorCode", "UNKNOWN_ERROR")),
238
+ response.get("errorDescription", response.get("errorDescription", "Unknown error"))
239
+ )
240
+ return data
241
+ else:
242
+ raise CapmonsterAPIException(error_id=-1,
243
+ error_code="CAPMONSTER_API_ERROR",
244
+ error_description="Sometimes can be happen if Capmonster "
245
+ "servers there is too much intensity")
@@ -0,0 +1,60 @@
1
+ class CapmonsterException(Exception):
2
+ """
3
+ Generic exception class for all errors.
4
+
5
+ Notes:
6
+ This will be raised for errors that are not caught elsewhere.
7
+ These errors can be related HTTP requests, API responses, or other issues.
8
+ """
9
+ pass
10
+
11
+
12
+ class CapmonsterAPIException(CapmonsterException):
13
+ """
14
+ Raised when the Capmonster API returns an error.
15
+
16
+ Attributes:
17
+ error_id: The error ID returned by the API.
18
+ error_code: The error code returned by the API.
19
+ error_description: The error description returned by the API.
20
+
21
+ Notes:
22
+ - Error codes are defined in the API documentation.
23
+ """
24
+
25
+ def __init__(self, error_id, error_code, error_description, *args, **kwargs):
26
+ super(CapmonsterAPIException, self).__init__("[{}:{}]{}".format(error_code, error_id, error_description))
27
+ self.error_description = error_description
28
+ self.error_id = error_id
29
+ self.error_code = error_code
30
+
31
+ def __str__(self):
32
+ return "[{}] {}".format(self.error_code, self.error_description)
33
+
34
+
35
+ class CapmonsterValidationException(CapmonsterException):
36
+ """
37
+ Raised when a Capmonster task configuration is invalid.
38
+
39
+ Attributes:
40
+ message: The error message describing the invalid configuration.
41
+ field: The field in the configuration that caused the error, if applicable.
42
+ task: The task type that caused the error, if applicable.
43
+
44
+ Notes:
45
+ - This error only raises when the validation fails within the SDK task creation.
46
+ """
47
+
48
+ def __init__(self, message: str, *, field: str = None, task: str = None):
49
+ self.message = message
50
+ self.field = field
51
+ self.task = task
52
+ super().__init__(self._format_message())
53
+
54
+ def _format_message(self) -> str:
55
+ base = f"[CapmonsterValidationError] {self.message}"
56
+ if self.field:
57
+ base += f" (field: {self.field})"
58
+ if self.task:
59
+ base += f" [task: {self.task}]"
60
+ return base