python3-anticaptcha/python3_anticaptcha/AntiCaptchaControl.py

363 lines
16 KiB
Python
Raw Normal View History

import aiohttp
2020-02-14 13:51:36 +00:00
import requests
2020-03-11 13:22:12 +00:00
# Адрес для получения баланса
get_balance_url = "https://api.anti-captcha.com/getBalance"
# Адрес для отправки жалобы на неверное решение капчи-изображения
incorrect_imagecaptcha_url = "https://api.anti-captcha.com/reportIncorrectImageCaptcha"
# Адрес для отправки жалобы на неверное решение ReCaptcha
incorrect_recaptcha_url = "https://api.anti-captcha.com/reportIncorrectRecaptcha"
# Адрес для получения информации о очереди
get_queue_status_url = "https://api.anti-captcha.com/getQueueStats"
# С помощью этого метода можно получить статистику трат за последние 24 часа.
get_spend_stats_url = "https://api.anti-captcha.com/getSpendingStats"
# Адрес для получения информации о приложении
get_app_stats_url = "https://api.anti-captcha.com/getAppStats"
# С помощью этого метода можно получить статистику трат за последние 24 часа.
send_funds_url = "https://api.anti-captcha.com/sendFunds"
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, 11, 12, 13, 18, 19, 20, 21, 22)
2020-03-10 17:26:00 +00:00
queues_names = (
"English ImageToText",
"Russian ImageToText",
"Recaptcha Proxy-on",
"Recaptcha Proxyless",
"FunCaptcha",
"Funcaptcha Proxyless",
"Square Net Task",
"GeeTest Proxy-on",
"GeeTest Proxyless",
)
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
"""
answer = requests.post(get_balance_url, json={"clientKey": self.ANTICAPTCHA_KEY}, verify=False)
return answer.json()
def send_funds(self, accountLogin: str = None, accountEmail: str = None, amount: float = None) -> dict:
2020-03-10 17:26:00 +00:00
"""
Отправить средства другому пользователю
В вашем аккаунте должна быть включена опция отправки средств через API.
Включается через службу поддержки, нужно указать причину зачем вам это требуется.
:param accountLogin: Логин целевого аккаунта
:param accountEmail: Адрес почты целевого аккаунта
:param amount: Сумма
"""
payload = {
"clientKey": self.ANTICAPTCHA_KEY,
"accountLogin": accountLogin,
"accountEmail": accountEmail,
"amount": amount,
}
# get response
answer = requests.post(send_funds_url, json=payload, verify=False)
return answer.json()
def get_spend_stats(
self, date: int = None, queue: str = None, softId: int = None, ip: str = None
) -> dict:
f"""
С помощью этого метода можно получить статистику трат за последние 24 часа.
:param date: Unix timestamp начала периода 24-х часового отчета
:param queue: Имя очереди, может быть найдено в статистике Антикапчи.
Если не указано, то возвращается суммированная статистика по всем очередям.
:param softId: ID приложения из Developers Center
:param ip: IP с которого шли запросы к API
:return: Возвращает словарь с данными трат
"""
2020-03-10 17:54:42 +00:00
if queue and queue not in queues_names:
2020-03-10 17:26:00 +00:00
raise ValueError(
f"\nWrong `queue` parameter. Valid params: {queues_names}." f"\n\tYour param - `{queue}`"
2020-03-10 17:26:00 +00:00
)
payload = {
"clientKey": self.ANTICAPTCHA_KEY,
"date": date,
"queue": queue,
"softId": softId,
"ip": ip,
}
# get response
answer = requests.post(get_spend_stats_url, json=payload, verify=False)
return answer.json()
def get_app_stats(self, softId: int, mode: str = "errors") -> dict:
"""
Получение статистики приложения
:return: Возвращает актуальный баланс
"""
if mode not in mods:
raise ValueError(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
2020-03-10 17:26:00 +00:00
11 - Square Net Task
12 - GeeTest Proxy-On
13 - GeeTest Proxyless
18 - Recaptcha V3 s0.3
19 - Recaptcha V3 s0.7
20 - Recaptcha V3 s0.9
2019-03-15 17:09:12 +00:00
Пример выдачи ответа:
{
"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-09-03 21:54:10 +00:00
)
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:
async with session.post(get_balance_url, json={"clientKey": self.ANTICAPTCHA_KEY}) as resp:
2020-03-11 13:22:12 +00:00
if await resp.text():
return await resp.json()
else:
return {"errorId": 1}
2020-03-10 17:26:00 +00:00
async def send_funds(
self, accountLogin: str = None, accountEmail: str = None, amount: float = None
) -> dict:
"""
Отправить средства другому пользователю
В вашем аккаунте должна быть включена опция отправки средств через API.
Включается через службу поддержки, нужно указать причину зачем вам это требуется.
:param accountLogin: Логин целевого аккаунта
:param accountEmail: Адрес почты целевого аккаунта
:param amount: Сумма
"""
payload = {
"clientKey": self.ANTICAPTCHA_KEY,
"accountLogin": accountLogin,
"accountEmail": accountEmail,
"amount": amount,
}
# get response
async with aiohttp.ClientSession() as session:
2020-03-10 17:54:42 +00:00
async with session.post(send_funds_url, json=payload) as resp:
2020-03-11 13:22:12 +00:00
if await resp.text():
return await resp.json()
else:
return {"errorId": 1}
2020-03-10 17:26:00 +00:00
async def get_spend_stats(
self, date: int = None, queue: str = None, softId: int = None, ip: str = None
) -> dict:
f"""
С помощью этого метода можно получить статистику трат за последние 24 часа.
:param date: Unix timestamp начала периода 24-х часового отчета
:param queue: Имя очереди, может быть найдено в статистике Антикапчи.
Если не указано, то возвращается суммированная статистика по всем очередям.
:param softId: ID приложения из Developers Center
:param ip: IP с которого шли запросы к API
:return: Возвращает словарь с данными трат
"""
2020-03-10 17:54:42 +00:00
if queue and queue not in queues_names:
2020-03-10 17:26:00 +00:00
raise ValueError(
f"\nWrong `queue` parameter. Valid params: {queues_names}." f"\n\tYour param - `{queue}`"
2020-03-10 17:26:00 +00:00
)
payload = {
"clientKey": self.ANTICAPTCHA_KEY,
"date": date,
"queue": queue,
"softId": softId,
"ip": ip,
}
# get response
async with aiohttp.ClientSession() as session:
2020-03-10 17:54:42 +00:00
async with session.post(get_spend_stats_url, json=payload) as resp:
2020-03-11 13:22:12 +00:00
if await resp.text():
return await resp.json()
else:
return {"errorId": 1}
2020-03-10 17:26:00 +00:00
async def get_app_stats(self, softId: int, mode: str = "errors") -> dict:
"""
Получение баланса аккаунта
:return: Возвращает актуальный баланс
"""
if mode not in mods:
raise ValueError(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:
2020-03-11 13:22:12 +00:00
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:
2020-03-11 13:22:12 +00:00
if await resp.text():
return await resp.json()
else:
return {"errorId": 1}
2019-08-21 01:34:11 +00:00
# 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:
2020-03-11 13:22:12 +00:00
if await resp.text():
return await resp.json()
else:
return {"errorId": 1}
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-09-03 21:54:10 +00:00
)
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:
2020-03-11 13:22:12 +00:00
if await resp.text():
return await resp.json()
else:
return {"errorId": 1}