Skip to content

Commit 6686eb1

Browse files
author
Andrei
authored
Merge pull request #57 from AndreiDrang/upd_methods
Upd methods and tests
2 parents 4b3bf0a + 03c40c0 commit 6686eb1

16 files changed

+327
-313
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,6 @@ For tests:
203203
1. Clon repo;
204204
2. ```bash
205205
export anticaptcha_key=SERVICE_KEY
206-
pip install pytest pytest-asyncio
206+
pip install pytest pytest-asyncio requests_mock
207207
pytest tests
208208
```

python3_anticaptcha/AntiCaptchaControl.py

Lines changed: 157 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,39 @@
11
import aiohttp
22
import requests
33

4-
from python3_anticaptcha import (
5-
get_balance_url,
6-
get_app_stats_url,
7-
get_queue_status_url,
8-
incorrect_recaptcha_url,
9-
incorrect_imagecaptcha_url,
10-
)
4+
# Адрес для получения баланса
5+
get_balance_url = "https://api.anti-captcha.com/getBalance"
6+
# Адрес для отправки жалобы на неверное решение капчи-изображения
7+
incorrect_imagecaptcha_url = "https://api.anti-captcha.com/reportIncorrectImageCaptcha"
8+
# Адрес для отправки жалобы на неверное решение ReCaptcha
9+
incorrect_recaptcha_url = "https://api.anti-captcha.com/reportIncorrectRecaptcha"
10+
# Адрес для получения информации о очереди
11+
get_queue_status_url = "https://api.anti-captcha.com/getQueueStats"
12+
# С помощью этого метода можно получить статистику трат за последние 24 часа.
13+
get_spend_stats_url = "https://api.anti-captcha.com/getSpendingStats"
14+
# Адрес для получения информации о приложении
15+
get_app_stats_url = "https://api.anti-captcha.com/getAppStats"
16+
# С помощью этого метода можно получить статистику трат за последние 24 часа.
17+
send_funds_url = "https://api.anti-captcha.com/sendFunds"
1118

1219
# available app stats mods
1320
mods = ("errors", "views", "downloads", "users", "money")
1421
# available complaint captcha types
1522
complaint_types = ("image", "recaptcha")
1623
# availalbe queue ID's
17-
queue_ids = (1, 2, 5, 6, 7, 10)
24+
queue_ids = (1, 2, 5, 6, 7, 10, 11, 12, 13, 18, 19, 20)
25+
26+
queues_names = (
27+
"English ImageToText",
28+
"Russian ImageToText",
29+
"Recaptcha Proxy-on",
30+
"Recaptcha Proxyless",
31+
"FunCaptcha",
32+
"Funcaptcha Proxyless",
33+
"Square Net Task",
34+
"GeeTest Proxy-on",
35+
"GeeTest Proxyless",
36+
)
1837

1938

2039
class AntiCaptchaControl:
@@ -44,6 +63,56 @@ def get_balance(self) -> dict:
4463

4564
return answer.json()
4665

66+
def send_funds(
67+
self, accountLogin: str = None, accountEmail: str = None, amount: float = None
68+
) -> dict:
69+
"""
70+
Отправить средства другому пользователю
71+
В вашем аккаунте должна быть включена опция отправки средств через API.
72+
Включается через службу поддержки, нужно указать причину зачем вам это требуется.
73+
74+
:param accountLogin: Логин целевого аккаунта
75+
:param accountEmail: Адрес почты целевого аккаунта
76+
:param amount: Сумма
77+
"""
78+
payload = {
79+
"clientKey": self.ANTICAPTCHA_KEY,
80+
"accountLogin": accountLogin,
81+
"accountEmail": accountEmail,
82+
"amount": amount,
83+
}
84+
# get response
85+
answer = requests.post(send_funds_url, json=payload, verify=False)
86+
return answer.json()
87+
88+
def get_spend_stats(
89+
self, date: int = None, queue: str = None, softId: int = None, ip: str = None
90+
) -> dict:
91+
f"""
92+
С помощью этого метода можно получить статистику трат за последние 24 часа.
93+
:param date: Unix timestamp начала периода 24-х часового отчета
94+
:param queue: Имя очереди, может быть найдено в статистике Антикапчи.
95+
Если не указано, то возвращается суммированная статистика по всем очередям.
96+
:param softId: ID приложения из Developers Center
97+
:param ip: IP с которого шли запросы к API
98+
:return: Возвращает словарь с данными трат
99+
"""
100+
if queue and queue not in queues_names:
101+
raise ValueError(
102+
f"\nWrong `queue` parameter. Valid params: {queues_names}."
103+
f"\n\tYour param - `{queue}`"
104+
)
105+
payload = {
106+
"clientKey": self.ANTICAPTCHA_KEY,
107+
"date": date,
108+
"queue": queue,
109+
"softId": softId,
110+
"ip": ip,
111+
}
112+
# get response
113+
answer = requests.post(get_spend_stats_url, json=payload, verify=False)
114+
return answer.json()
115+
47116
def get_app_stats(self, softId: int, mode: str = "errors") -> dict:
48117
"""
49118
Получение статистики приложения
@@ -98,6 +167,12 @@ def get_queue_status(queue_id: int) -> dict:
98167
6 - Recaptcha Proxyless
99168
7 - Funcaptcha
100169
10 - Funcaptcha Proxyless
170+
11 - Square Net Task
171+
12 - GeeTest Proxy-On
172+
13 - GeeTest Proxyless
173+
18 - Recaptcha V3 s0.3
174+
19 - Recaptcha V3 s0.7
175+
20 - Recaptcha V3 s0.9
101176
102177
Пример выдачи ответа:
103178
{
@@ -148,7 +223,68 @@ async def get_balance(self) -> dict:
148223
async with session.post(
149224
get_balance_url, json={"clientKey": self.ANTICAPTCHA_KEY}
150225
) as resp:
151-
return await resp.json()
226+
if await resp.text():
227+
return await resp.json()
228+
else:
229+
return {"errorId": 1}
230+
231+
async def send_funds(
232+
self, accountLogin: str = None, accountEmail: str = None, amount: float = None
233+
) -> dict:
234+
"""
235+
Отправить средства другому пользователю
236+
В вашем аккаунте должна быть включена опция отправки средств через API.
237+
Включается через службу поддержки, нужно указать причину зачем вам это требуется.
238+
239+
:param accountLogin: Логин целевого аккаунта
240+
:param accountEmail: Адрес почты целевого аккаунта
241+
:param amount: Сумма
242+
"""
243+
payload = {
244+
"clientKey": self.ANTICAPTCHA_KEY,
245+
"accountLogin": accountLogin,
246+
"accountEmail": accountEmail,
247+
"amount": amount,
248+
}
249+
# get response
250+
async with aiohttp.ClientSession() as session:
251+
async with session.post(send_funds_url, json=payload) as resp:
252+
if await resp.text():
253+
return await resp.json()
254+
else:
255+
return {"errorId": 1}
256+
257+
async def get_spend_stats(
258+
self, date: int = None, queue: str = None, softId: int = None, ip: str = None
259+
) -> dict:
260+
f"""
261+
С помощью этого метода можно получить статистику трат за последние 24 часа.
262+
:param date: Unix timestamp начала периода 24-х часового отчета
263+
:param queue: Имя очереди, может быть найдено в статистике Антикапчи.
264+
Если не указано, то возвращается суммированная статистика по всем очередям.
265+
:param softId: ID приложения из Developers Center
266+
:param ip: IP с которого шли запросы к API
267+
:return: Возвращает словарь с данными трат
268+
"""
269+
if queue and queue not in queues_names:
270+
raise ValueError(
271+
f"\nWrong `queue` parameter. Valid params: {queues_names}."
272+
f"\n\tYour param - `{queue}`"
273+
)
274+
payload = {
275+
"clientKey": self.ANTICAPTCHA_KEY,
276+
"date": date,
277+
"queue": queue,
278+
"softId": softId,
279+
"ip": ip,
280+
}
281+
# get response
282+
async with aiohttp.ClientSession() as session:
283+
async with session.post(get_spend_stats_url, json=payload) as resp:
284+
if await resp.text():
285+
return await resp.json()
286+
else:
287+
return {"errorId": 1}
152288

153289
async def get_app_stats(self, softId: int, mode: str = "errors") -> dict:
154290
"""
@@ -185,12 +321,18 @@ async def complaint_on_result(self, reported_id: int, captcha_type: str = "image
185321
if captcha_type == "image":
186322
async with aiohttp.ClientSession() as session:
187323
async with session.post(incorrect_imagecaptcha_url, json=payload) as resp:
188-
return await resp.json()
324+
if await resp.text():
325+
return await resp.json()
326+
else:
327+
return {"errorId": 1}
189328
# complaint on re-captcha
190329
elif captcha_type == "recaptcha":
191330
async with aiohttp.ClientSession() as session:
192331
async with session.post(incorrect_recaptcha_url, json=payload) as resp:
193-
return await resp.json()
332+
if await resp.text():
333+
return await resp.json()
334+
else:
335+
return {"errorId": 1}
194336

195337
@staticmethod
196338
async def get_queue_status(queue_id: int) -> dict:
@@ -228,4 +370,7 @@ async def get_queue_status(queue_id: int) -> dict:
228370

229371
async with aiohttp.ClientSession() as session:
230372
async with session.post(get_queue_status_url, json=payload) as resp:
231-
return await resp.json()
373+
if await resp.text():
374+
return await resp.json()
375+
else:
376+
return {"errorId": 1}

python3_anticaptcha/CallbackClient.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
import json
22
import time
33

4+
import pika
45
import requests
56

6-
import pika
77
from python3_anticaptcha import (
88
HOST,
99
PORT,

python3_anticaptcha/FunCaptchaTaskProxyless.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,16 @@ def __exit__(self, exc_type, exc_value, traceback):
4242
return True
4343

4444
# Работа с капчёй
45-
def captcha_handler(self, websiteURL: str, websitePublicKey: str, **kwargs) -> dict:
45+
def captcha_handler(self, websiteURL: str, data: str, websitePublicKey: str, **kwargs) -> dict:
4646
"""
4747
Метод получает ссылку на страницу на которпой расположена капча и ключ капчи
4848
:param websiteURL: Ссылка на страницу с капчёй
49+
:param data: Дополнительный параметр, который может требоваться для некоторых решений фанкапчи.
4950
:param websitePublicKey: Ключ капчи(как его получить - описано в документаии на сайте антикапчи)
5051
:return: Возвращает ответ сервера в виде JSON(ответ так же можно глянуть в документации антикапчи)
5152
"""
5253
self.task_payload["task"].update(
53-
{"websiteURL": websiteURL, "websitePublicKey": websitePublicKey}
54+
{"websiteURL": websiteURL, "data": data, "websitePublicKey": websitePublicKey}
5455
)
5556
# Отправляем на антикапча параметры фанкапич,
5657
# в результате получаем JSON ответ содержащий номер решаемой капчи
@@ -102,15 +103,16 @@ def __init__(self, anticaptcha_key: str, sleep_time: int = 5, callbackUrl: str =
102103
self.result_payload = {"clientKey": anticaptcha_key}
103104

104105
# Работа с капчёй
105-
async def captcha_handler(self, websiteURL: str, websitePublicKey: str) -> dict:
106+
async def captcha_handler(self, websiteURL: str, data: str, websitePublicKey: str) -> dict:
106107
"""
107108
Метод получает ссылку на страницу на которпой расположена капча и ключ капчи
108109
:param websiteURL: Ссылка на страницу с капчёй
110+
:param data: Дополнительный параметр, который может требоваться для некоторых решений фанкапчи.
109111
:param websitePublicKey: Ключ капчи(как его получить - описано в документаии на сайте антикапчи)
110112
:return: Возвращает ответ сервера в виде JSON(ответ так же можно глянуть в документации антикапчи)
111113
"""
112114
self.task_payload["task"].update(
113-
{"websiteURL": websiteURL, "websitePublicKey": websitePublicKey}
115+
{"websiteURL": websiteURL, "data": data, "websitePublicKey": websitePublicKey}
114116
)
115117
# Отправляем на антикапча параметры фанкапич,
116118
# в результате получаем JSON ответ содержащий номер решаемой капчи

python3_anticaptcha/ReCaptchaV3TaskProxyless.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def __exit__(self, exc_type, exc_value, traceback):
5252

5353
# Работа с капчёй
5454
def captcha_handler(
55-
self, websiteURL: str, websiteKey: str, minScore: float, pageAction: str, **kwargs
55+
self, websiteURL: str, websiteKey: str, minScore: float, pageAction: str = None, **kwargs
5656
) -> dict:
5757
"""
5858
Метод решения ReCaptcha V3
@@ -144,7 +144,7 @@ def __exit__(self, exc_type, exc_value, traceback):
144144

145145
# Работа с капчёй
146146
async def captcha_handler(
147-
self, websiteURL: str, websiteKey: str, minScore: float, pageAction: str
147+
self, websiteURL: str, websiteKey: str, minScore: float, pageAction: str = None
148148
) -> dict:
149149
"""
150150
Метод решения ReCaptcha V3

python3_anticaptcha/__init__.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,6 @@
99
app_key,
1010
get_result_url,
1111
create_task_url,
12-
get_balance_url,
13-
get_app_stats_url,
14-
get_queue_status_url,
15-
incorrect_recaptcha_url,
16-
incorrect_imagecaptcha_url,
1712
)
1813
from .errors import ReadError, IdGetError, ParamError
1914
from .get_answer import get_sync_result, get_async_result

python3_anticaptcha/config.py

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,16 +6,6 @@
66
create_task_url = "https://api.anti-captcha.com/createTask"
77
# Адрес для получения ответа
88
get_result_url = "https://api.anti-captcha.com/getTaskResult"
9-
# Адрес для получения баланса
10-
get_balance_url = "https://api.anti-captcha.com/getBalance"
11-
# Адрес для отправки жалобы на неверное решение капчи-изображения
12-
incorrect_imagecaptcha_url = "https://api.anti-captcha.com/reportIncorrectImageCaptcha"
13-
# Адрес для отправки жалобы на неверное решение ReCaptcha
14-
incorrect_recaptcha_url = "https://api.anti-captcha.com/reportIncorrectRecaptcha"
15-
# Адрес для получения информации о очереди
16-
get_queue_status_url = "https://api.anti-captcha.com/getQueueStats"
17-
# Адрес для получения информации о приложении
18-
get_app_stats_url = "https://api.anti-captcha.com/getAppStats"
199
# ключ приложения
2010
app_key = "867"
2111

setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
1313
AUTHOR = "AndreiDrang, redV0ID"
1414
REQUIRES_PYTHON = ">=3.6.0"
15-
VERSION = "1.5.6"
15+
VERSION = "1.6"
1616
REQUIRED = ["requests==2.23.0", "aiohttp==3.6.2", "pika==1.1.0"]
1717

1818
here = os.path.abspath(os.path.dirname(__file__))

0 commit comments

Comments
 (0)