python3-anticaptcha/python3_anticaptcha/AntiCaptchaControl.py

232 lines
9.3 KiB
Python
Raw Normal View History

import aiohttp
2020-02-14 13:51:36 +00:00
import requests
2019-03-19 19:26:12 +00:00
from python3_anticaptcha import (
get_balance_url,
get_app_stats_url,
2019-03-19 19:26:12 +00:00
get_queue_status_url,
2020-02-14 13:51:36 +00:00
incorrect_recaptcha_url,
incorrect_imagecaptcha_url,
2019-03-19 19:26:12 +00:00
)
2019-08-21 01:34:11 +00:00
# available app stats mods
mods = ("errors", "views", "downloads", "users", "money")
2019-08-21 01:34:11 +00:00
# available complaint captcha types
complaint_types = ("image", "recaptcha")
2019-09-03 21:54:10 +00:00
# availalbe queue ID's
queue_ids = (1, 2, 5, 6, 7, 10)
class AntiCaptchaControl:
def __init__(self, anticaptcha_key: str):
"""
Синхронный метод работы с балансом и жалобами
:param anticaptcha_key: Ключ антикапчи
"""
self.ANTICAPTCHA_KEY = anticaptcha_key
2019-03-19 19:26:12 +00:00
2019-02-14 10:33:16 +00:00
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
return False
return True
def get_balance(self) -> dict:
2019-03-15 17:09:12 +00:00
"""
Получение баланса аккаунта
:return: Возвращает актуальный баланс
2019-03-15 17:09:12 +00:00
"""
2020-01-30 21:08:17 +00:00
answer = requests.post(
get_balance_url, json={"clientKey": self.ANTICAPTCHA_KEY}, verify=False
)
return answer.json()
def get_app_stats(self, softId: int, mode: str = "errors") -> dict:
"""
Получение статистики приложения
:return: Возвращает актуальный баланс
"""
if mode not in mods:
raise ValueError(
2019-11-25 17:08:18 +00:00
f"\nWrong `mode` parameter. Valid params: {mods}." f"\n\tYour param - `{mode}`"
)
payload = {"clientKey": self.ANTICAPTCHA_KEY, "softId": softId, "mode": mode}
2020-01-30 21:08:17 +00:00
answer = requests.post(get_app_stats_url, json=payload, verify=False)
2019-10-05 00:53:06 +00:00
if answer.text:
return answer.json()
else:
return {"errorId": 1}
2019-11-25 17:08:18 +00:00
def complaint_on_result(self, reported_id: int, captcha_type: str = "image") -> dict:
2019-08-21 01:34:11 +00:00
f"""
Позволяет отправить жалобу на неправильно решённую капчу.
:param reported_id: Отправляете ID капчи на которую нужно пожаловаться
2019-08-21 01:34:11 +00:00
:param captcha_type: Тип капчи на который идёт жалоба. Возможные варианты:
{complaint_types}
:return: Возвращает True/False, в зависимости от результата
2019-03-15 17:09:12 +00:00
"""
2019-08-21 01:34:11 +00:00
if captcha_type not in complaint_types:
raise ValueError(
f"\nWrong `captcha_type` parameter. Valid params: {complaint_types}."
f"\n\tYour param - `{captcha_type}`"
)
2019-03-19 19:26:12 +00:00
payload = {"clientKey": self.ANTICAPTCHA_KEY, "taskId": reported_id}
2019-08-21 01:34:11 +00:00
# complaint on image captcha
if captcha_type == "image":
2020-01-30 21:08:17 +00:00
answer = requests.post(incorrect_imagecaptcha_url, json=payload, verify=False)
2019-08-21 01:34:11 +00:00
# complaint on re-captcha
elif captcha_type == "recaptcha":
2020-01-30 21:08:17 +00:00
answer = requests.post(incorrect_recaptcha_url, json=payload, verify=False)
2019-03-15 17:09:12 +00:00
return answer.json()
2019-09-08 18:24:06 +00:00
@staticmethod
def get_queue_status(queue_id: int) -> dict:
2019-03-15 17:09:12 +00:00
"""
2019-03-15 21:26:48 +00:00
Получение информации о загрузке очереди, в зависимости от ID очереди.
2019-03-15 17:09:12 +00:00
2019-03-15 21:26:48 +00:00
Метод позволяет определить, насколько в данный момент целесообразно загружать новое задание в очередь.
Данные в выдаче кешируются на 10 секунд.
2019-03-15 17:09:12 +00:00
Список ID очередей:
1 - стандартная ImageToText, язык английский
2 - стандартная ImageToText, язык русский
5 - Recaptcha NoCaptcha
6 - Recaptcha Proxyless
7 - Funcaptcha
10 - Funcaptcha Proxyless
Пример выдачи ответа:
{
"waiting":242,
"load":60.33,
"bid":"0.0008600982",
"speed":10.77,
"total": 610
}
:param queue_id: Номер очереди
:return: JSON-объект
"""
2019-09-03 21:54:10 +00:00
if queue_id not in queue_ids:
raise ValueError(
f"\nWrong `mode` parameter. Valid params: {queue_ids}."
f"\n\tYour param - `{queue_id}`"
)
2019-03-19 19:26:12 +00:00
payload = {"queueId": queue_id}
2019-03-15 17:09:12 +00:00
2020-01-30 21:08:17 +00:00
answer = requests.post(get_queue_status_url, json=payload, verify=False)
return answer.json()
class aioAntiCaptchaControl:
def __init__(self, anticaptcha_key: str):
"""
Асинхронный метод работы с балансом и жалобами
:param anticaptcha_key: Ключ антикапчи
"""
self.ANTICAPTCHA_KEY = anticaptcha_key
2019-03-19 19:26:12 +00:00
2019-02-14 10:33:16 +00:00
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
return False
return True
async def get_balance(self) -> dict:
2019-03-15 17:09:12 +00:00
"""
Получение баланса аккаунта
:return: Возвращает актуальный баланс
2019-03-15 17:09:12 +00:00
"""
async with aiohttp.ClientSession() as session:
2019-03-19 19:26:12 +00:00
async with session.post(
get_balance_url, json={"clientKey": self.ANTICAPTCHA_KEY}
) as resp:
return await resp.json()
async def get_app_stats(self, softId: int, mode: str = "errors") -> dict:
"""
Получение баланса аккаунта
:return: Возвращает актуальный баланс
"""
if mode not in mods:
raise ValueError(
2019-11-25 17:08:18 +00:00
f"\nWrong `mode` parameter. Valid params: {mods}." f"\n\tYour param - `{mode}`"
)
payload = {"clientKey": self.ANTICAPTCHA_KEY, "softId": softId, "mode": mode}
async with aiohttp.ClientSession() as session:
async with session.post(get_app_stats_url, json=payload) as resp:
if await resp.text():
return await resp.json()
else:
return {"errorId": 1}
2019-11-25 17:08:18 +00:00
async def complaint_on_result(self, reported_id: int, captcha_type: str = "image") -> dict:
2019-08-21 01:34:11 +00:00
f"""
Позволяет отправить жалобу на неправильно решённую капчу.
:param reported_id: Отправляете ID капчи на которую нужно пожаловаться
2019-08-21 01:34:11 +00:00
:param captcha_type: Тип капчи на который идёт жалоба. Возможные варианты:
{complaint_types}
:return: Возвращает True/False, в зависимости от результата
2019-03-15 17:09:12 +00:00
"""
2019-08-21 01:34:11 +00:00
if captcha_type not in complaint_types:
raise ValueError(
f"\nWrong `captcha_type` parameter. Valid params: {complaint_types}."
f"\n\tYour param - `{captcha_type}`"
)
2019-03-19 19:26:12 +00:00
payload = {"clientKey": self.ANTICAPTCHA_KEY, "taskId": reported_id}
2019-08-21 01:34:11 +00:00
# complaint on image captcha
if captcha_type == "image":
async with aiohttp.ClientSession() as session:
2019-11-25 17:08:18 +00:00
async with session.post(incorrect_imagecaptcha_url, json=payload) as resp:
2019-08-21 01:34:11 +00:00
return await resp.json()
# complaint on re-captcha
elif captcha_type == "recaptcha":
async with aiohttp.ClientSession() as session:
async with session.post(incorrect_recaptcha_url, json=payload) as resp:
return await resp.json()
2019-03-15 17:09:12 +00:00
2019-09-08 18:24:06 +00:00
@staticmethod
async def get_queue_status(queue_id: int) -> dict:
2019-03-15 17:09:12 +00:00
"""
2019-03-15 21:26:48 +00:00
Получение информации о загрузке очереди, в зависимости от ID очереди.
2019-03-15 17:09:12 +00:00
2019-03-15 21:26:48 +00:00
Метод позволяет определить, насколько в данный момент целесообразно загружать новое задание в очередь.
Данные в выдаче кешируются на 10 секунд.
2019-03-15 17:09:12 +00:00
Список ID очередей:
1 - стандартная ImageToText, язык английский
2 - стандартная ImageToText, язык русский
5 - Recaptcha NoCaptcha
6 - Recaptcha Proxyless
7 - Funcaptcha
10 - Funcaptcha Proxyless
Пример выдачи ответа:
{
"waiting":242,
"load":60.33,
"bid":"0.0008600982",
"speed":10.77,
"total": 610
}
:param queue_id: Номер очереди
:return: JSON-объект
"""
2019-09-03 21:54:10 +00:00
if queue_id not in queue_ids:
raise ValueError(
f"\nWrong `mode` parameter. Valid params: {queue_ids}."
f"\n\tYour param - `{queue_id}`"
)
2019-03-19 19:26:12 +00:00
payload = {"queueId": queue_id}
2019-03-15 17:09:12 +00:00
async with aiohttp.ClientSession() as session:
async with session.post(get_queue_status_url, json=payload) as resp:
return await resp.json()