| 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 | |
| 18 | __REPORT_IMAGE_URL = "/reportIncorrectImageCaptcha" |
| 19 | __REPORT_TOKEN_URL = "/reportIncorrectTokenCaptcha" |
| 20 | __USER_AGENT_URL = "https://capmonster.cloud/api/useragent/actual" |
| 21 | |
| 22 | def __init__(self, api_key: str, timeout: Optional[float] = 30.0, |
| 23 | max_retries: int = 120, retry_delay: float = 2.0) -> None: |
| 24 | self.api_key = api_key |
| 25 | self.__max_retries = max_retries |
| 26 | self.__retry_delay = retry_delay |
| 27 | self.__async_client = AsyncClient(timeout=timeout, base_url=self.__BASE_URL) |
| 28 | self.__sync_client = Client(timeout=timeout, base_url=self.__BASE_URL) |
| 29 | |
| 30 | def __enter__(self) -> "CapmonsterClient": |
| 31 | return self |
| 32 | |
| 33 | def __exit__(self, *args) -> None: |
| 34 | self.__sync_client.close() |
| 35 | |
| 36 | async def __aenter__(self) -> "CapmonsterClient": |
| 37 | return self |
| 38 | |
| 39 | async def __aexit__(self, *args) -> None: |
| 40 | await self.__async_client.aclose() |
| 41 | |
| 42 | def get_balance(self) -> float: |
| 43 | """ |
| 44 | Fetches the current balance using the provided API key. |
| 45 | |
| 46 | Raises: |
| 47 | This method may raise exceptions if the HTTP request fails or the JSON response |
| 48 | format is unexpected. These exceptions are not handled within the method. |
| 49 | |
| 50 | Returns: |
| 51 | float: The balance fetched from the external service. Defaults to 0.0 if the balance |
| 52 | key is not found in the response. |
| 53 | """ |
| 54 | payload = GetBalancePayload(clientKey=self.api_key).model_dump() |
| 55 | response = self.__make_sync_request(self.__BALANCE_URL, payload).json() |
| 56 | return response.get("balance", 0.0) |
| 57 | |
| 58 | async def get_balance_async(self) -> float: |
| 59 | """ |
| 60 | Asynchronously fetches the current balance using the provided API key. |
| 61 | |
| 62 | Raises: |
| 63 | This method may raise exceptions if the HTTP request fails or the JSON response |
| 64 | format is unexpected. These exceptions are not handled within the method. |
| 65 | |
| 66 | Returns: |
| 67 | float: The balance fetched from the external service. Defaults to 0.0 if the balance |
| 68 | key is not found in the response. |
| 69 | """ |
no outgoing calls