ballagb19 commited on
Commit
dad3f62
·
verified ·
1 Parent(s): 4ad7943

Upload scripts/hcaptcha_bot.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/hcaptcha_bot.py +379 -0
scripts/hcaptcha_bot.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """hCaptcha Playwright automation wrapper.
2
+
3
+ Runs on your local machine. Detects hCaptcha on faucet pages,
4
+ screenshots tiles, calls the vision model API to classify them,
5
+ and clicks matching tiles with human-like delays.
6
+
7
+ Usage:
8
+ python scripts/hcaptcha_bot.py https://faucet-wave.online/tron-faucet/
9
+
10
+ Or import and use in your existing claimer scripts:
11
+ from scripts.hcaptcha_bot import solve_hcaptcha
12
+ await solve_hcaptcha(page, "https://faucet-wave.online/tron-faucet/")
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import asyncio
18
+ import base64
19
+ import io
20
+ import os
21
+ import random
22
+ import sys
23
+ import time
24
+ from typing import Optional
25
+
26
+ import httpx
27
+
28
+ try:
29
+ from playwright.async_api import async_playwright, Page, ElementHandle
30
+ except ImportError:
31
+ print("ERROR: playwright not installed. Run: pip install playwright && playwright install chromium")
32
+ sys.exit(1)
33
+
34
+
35
+ # Config
36
+ API_URL = os.environ.get("CAPTCHA_SOLVER_URL", "http://localhost:8765")
37
+ HF_SPACE_URL = os.environ.get("HF_SPACE_URL", "") # Set this for HF Spaces deployment
38
+ SOLVER_URL = HF_SPACE_URL or API_URL
39
+ TILE_DELAY_MIN = 0.8 # Min seconds between tile clicks
40
+ TILE_DELAY_MAX = 2.5 # Max seconds between tile clicks
41
+ CLICK_DELAY_MIN = 0.3
42
+ CLICK_DELAY_MAX = 0.8
43
+
44
+
45
+ async def _call_classify_api(
46
+ image_bytes: bytes,
47
+ instruction: str,
48
+ client: httpx.AsyncClient,
49
+ ) -> dict:
50
+ """Call POST /classify with a tile image."""
51
+ b64 = base64.b64encode(image_bytes).decode("ascii")
52
+ payload = {
53
+ "image_base64": b64,
54
+ "instruction": instruction,
55
+ }
56
+ try:
57
+ r = await client.post(f"{SOLVER_URL}/classify", json=payload, timeout=30)
58
+ r.raise_for_status()
59
+ return r.json()
60
+ except Exception as exc:
61
+ return {"match": False, "confidence": 0.0, "caption": "", "error": str(exc)}
62
+
63
+
64
+ def _extract_instruction(modal_content: str) -> str:
65
+ """Extract hCaptcha instruction text from the challenge header."""
66
+ # Common hCaptcha patterns
67
+ patterns = [
68
+ r"(?:click|find|select|choose)\s+all\s+[^.]+",
69
+ r"(?:click|find|select|choose)\s+the\s+[^.]+",
70
+ r"(?:which|what)\s+[^?]+\?",
71
+ ]
72
+ text_lower = modal_content.lower()
73
+ for pattern in patterns:
74
+ import re
75
+ match = re.search(pattern, text_lower, re.IGNORECASE)
76
+ if match:
77
+ return match.group(0).strip()
78
+ return modal_content.strip()
79
+
80
+
81
+ async def _human_like_mouse_move(page: Page, x: float, y: float) -> None:
82
+ """Move mouse to (x, y) with human-like curve."""
83
+ await page.mouse.move(x, y, steps=random.randint(10, 25))
84
+ await asyncio.sleep(random.uniform(CLICK_DELAY_MIN, CLICK_DELAY_MAX))
85
+
86
+
87
+ async def _click_with_human_delay(page: Page, selector: str) -> None:
88
+ """Click an element with random human-like delay."""
89
+ await asyncio.sleep(random.uniform(TILE_DELAY_MIN, TILE_DELAY_MAX))
90
+ element = await page.query_selector(selector)
91
+ if element:
92
+ box = await element.bounding_box()
93
+ if box:
94
+ # Click slightly off-center for realism
95
+ x = box["x"] + box["width"] * random.uniform(0.3, 0.7)
96
+ y = box["y"] + box["height"] * random.uniform(0.3, 0.7)
97
+ await _human_like_mouse_move(page, x, y)
98
+ await asyncio.sleep(random.uniform(0.1, 0.3))
99
+ await page.mouse.click(x, y)
100
+
101
+
102
+ async def _screenshot_tile(page: Page, tile_index: int, grid_selector: str = ".task-image") -> Optional[bytes]:
103
+ """Screenshot a specific tile from the hCaptcha grid."""
104
+ tiles = await page.query_selector_all(grid_selector)
105
+ if tile_index >= len(tiles):
106
+ return None
107
+ tile = tiles[tile_index]
108
+ screenshot = await tile.screenshot()
109
+ return screenshot
110
+
111
+
112
+ async def solve_hcaptcha(
113
+ page: Page,
114
+ max_retries: int = 3,
115
+ verbose: bool = True,
116
+ ) -> bool:
117
+ """Solve hCaptcha on the current page.
118
+
119
+ Args:
120
+ page: Playwright page with hCaptcha loaded.
121
+ max_retries: Number of attempts before giving up.
122
+ verbose: Print progress info.
123
+
124
+ Returns:
125
+ True if captcha was solved successfully, False otherwise.
126
+ """
127
+ for attempt in range(max_retries):
128
+ if verbose:
129
+ print(f"[hCaptcha] Attempt {attempt + 1}/{max_retries}")
130
+
131
+ try:
132
+ # Wait for hCaptcha iframe to appear
133
+ hcaptcha_frame = None
134
+ for frame in page.frames:
135
+ if "hcaptcha" in frame.url.lower():
136
+ hcaptcha_frame = frame
137
+ break
138
+
139
+ if not hcaptcha_frame:
140
+ # Try clicking the checkbox first
141
+ checkbox = await page.query_selector(".h-captcha iframe, iframe[src*='hcaptcha']")
142
+ if checkbox:
143
+ await checkbox.click()
144
+ await asyncio.sleep(2)
145
+ # Re-check frames
146
+ for frame in page.frames:
147
+ if "hcaptcha" in frame.url.lower():
148
+ hcaptcha_frame = frame
149
+ break
150
+
151
+ if not hcaptcha_frame:
152
+ if verbose:
153
+ print("[hCaptcha] No hCaptcha iframe found")
154
+ return False
155
+
156
+ # Wait for challenge to load (if checkbox was already solved)
157
+ await asyncio.sleep(1)
158
+
159
+ # Check if already solved (checkbox is green)
160
+ checkbox_frame = None
161
+ for frame in page.frames:
162
+ if "hcaptcha" in frame.url.lower() and "checkbox" in frame.url.lower():
163
+ checkbox_frame = frame
164
+ break
165
+
166
+ if checkbox_frame:
167
+ is_checked = await checkbox_frame.query_selector(".check")
168
+ if is_checked:
169
+ if verbose:
170
+ print("[hCaptcha] Already solved!")
171
+ return True
172
+
173
+ # Look for the challenge iframe (separate from checkbox iframe)
174
+ challenge_frame = None
175
+ for frame in page.frames:
176
+ if "hcaptcha" in frame.url.lower() and "challenge" in frame.url.lower():
177
+ challenge_frame = frame
178
+ break
179
+
180
+ if not challenge_frame:
181
+ # Challenge might be in the main frame's modal
182
+ challenge_frame = page
183
+
184
+ # Extract instruction text
185
+ instruction = ""
186
+ try:
187
+ header = await challenge_frame.query_selector(".challenge-header, .prompt-text, [class*='header']")
188
+ if header:
189
+ instruction = await header.inner_text()
190
+ else:
191
+ # Try getting all visible text in the challenge
192
+ body = await challenge_frame.query_selector("body")
193
+ if body:
194
+ all_text = await body.inner_text()
195
+ instruction = _extract_instruction(all_text)
196
+ except Exception:
197
+ pass
198
+
199
+ if not instruction:
200
+ if verbose:
201
+ print("[hCaptcha] Could not extract instruction")
202
+ continue
203
+
204
+ if verbose:
205
+ print(f"[hCaptcha] Instruction: {instruction}")
206
+
207
+ # Screenshot all tiles
208
+ tiles = await challenge_frame.query_selector_all(".task-image, [class*='tile'], [class*='image']")
209
+ if not tiles:
210
+ if verbose:
211
+ print("[hCaptcha] No tiles found in challenge")
212
+ continue
213
+
214
+ if verbose:
215
+ print(f"[hCaptcha] Found {len(tiles)} tiles")
216
+
217
+ # Classify each tile via API
218
+ matches = []
219
+ async with httpx.AsyncClient() as client:
220
+ for i, tile in enumerate(tiles):
221
+ try:
222
+ tile_screenshot = await tile.screenshot()
223
+ result = await _call_classify_api(tile_screenshot, instruction, client)
224
+ if result.get("match"):
225
+ matches.append(i)
226
+ if verbose:
227
+ status = "MATCH" if result.get("match") else "skip"
228
+ caption = result.get("caption", "")
229
+ conf = result.get("confidence", 0)
230
+ print(f" Tile {i + 1}: {status} (conf={conf:.2f}) caption={caption}")
231
+ except Exception as exc:
232
+ if verbose:
233
+ print(f" Tile {i + 1}: error - {exc}")
234
+
235
+ if not matches:
236
+ if verbose:
237
+ print("[hCaptcha] No matches found, skipping")
238
+ # Click "Get a new challenge" button
239
+ try:
240
+ refresh_btn = await challenge_frame.query_selector(
241
+ ".refresh-button, [class*='refresh'], button[aria-label*='refresh']"
242
+ )
243
+ if refresh_btn:
244
+ await refresh_btn.click()
245
+ await asyncio.sleep(2)
246
+ continue
247
+ except Exception:
248
+ pass
249
+ continue
250
+
251
+ if verbose:
252
+ print(f"[hCaptcha] Clicking tiles: {[m + 1 for m in matches]}")
253
+
254
+ # Click matching tiles with human-like delays
255
+ for idx in matches:
256
+ tile = tiles[idx]
257
+ try:
258
+ box = await tile.bounding_box()
259
+ if box:
260
+ x = box["x"] + box["width"] * random.uniform(0.3, 0.7)
261
+ y = box["y"] + box["height"] * random.uniform(0.3, 0.7)
262
+ await _human_like_mouse_move(page, x, y)
263
+ await asyncio.sleep(random.uniform(0.1, 0.3))
264
+ await page.mouse.click(x, y)
265
+ await asyncio.sleep(random.uniform(TILE_DELAY_MIN, TILE_DELAY_MAX))
266
+ except Exception as exc:
267
+ if verbose:
268
+ print(f" Failed to click tile {idx + 1}: {exc}")
269
+
270
+ # Click Verify button
271
+ await asyncio.sleep(random.uniform(1.0, 2.0))
272
+ try:
273
+ verify_btn = await challenge_frame.query_selector(
274
+ ".verify-button, button[type='submit'], [class*='verify']"
275
+ )
276
+ if verify_btn:
277
+ await verify_btn.click()
278
+ await asyncio.sleep(3)
279
+
280
+ # Check if solved
281
+ for frame in page.frames:
282
+ if "hcaptcha" in frame.url.lower() and "checkbox" in frame.url.lower():
283
+ is_checked = await frame.query_selector(".check")
284
+ if is_checked:
285
+ if verbose:
286
+ print("[hCaptcha] Solved successfully!")
287
+ return True
288
+
289
+ # If we get here, might need another attempt
290
+ if verbose:
291
+ print("[hCaptcha] Verification pending, checking...")
292
+
293
+ except Exception as exc:
294
+ if verbose:
295
+ print(f"[hCaptcha] Verify click failed: {exc}")
296
+
297
+ except Exception as exc:
298
+ if verbose:
299
+ print(f"[hCaptcha] Attempt {attempt + 1} error: {exc}")
300
+
301
+ # Wait before retry
302
+ await asyncio.sleep(random.uniform(2.0, 4.0))
303
+
304
+ if verbose:
305
+ print(f"[hCaptcha] Failed after {max_retries} attempts")
306
+ return False
307
+
308
+
309
+ async def main():
310
+ """CLI entry point: solve hCaptcha on a given URL."""
311
+ import argparse
312
+ parser = argparse.ArgumentParser(description="Solve hCaptcha on a faucet page")
313
+ parser.add_argument("url", help="URL of the page with hCaptcha")
314
+ parser.add_argument("--address", help="FaucetPay address to fill in")
315
+ parser.add_argument("--api", default=SOLVER_URL, help="Captcha solver API URL")
316
+ parser.add_argument("--headless", action="store_true", help="Run headless (no browser window)")
317
+ args = parser.parse_args()
318
+
319
+ global SOLVER_URL
320
+ SOLVER_URL = args.api
321
+
322
+ async with async_playwright() as p:
323
+ browser = await p.chromium.launch(
324
+ headless=args.headless,
325
+ args=[
326
+ "--disable-blink-features=AutomationControlled",
327
+ "--no-sandbox",
328
+ ],
329
+ )
330
+ context = await browser.new_context(
331
+ viewport={"width": 1280, "height": 800},
332
+ user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
333
+ )
334
+ page = await context.new_page()
335
+
336
+ print(f"[bot] Navigating to {args.url}")
337
+ await page.goto(args.url, wait_until="networkidle")
338
+ await asyncio.sleep(2)
339
+
340
+ # Fill in address if provided
341
+ if args.address:
342
+ addr_input = await page.query_selector("#fp-address, input[name='address']")
343
+ if addr_input:
344
+ await addr_input.fill(args.address)
345
+ print(f"[bot] Address filled: {args.address}")
346
+
347
+ # Click Claim button to open modal
348
+ claim_btn = await page.query_selector("#faucet-claim-btn, .faucet-btn")
349
+ if claim_btn:
350
+ await claim_btn.click()
351
+ print("[bot] Claim button clicked, modal opened")
352
+ await asyncio.sleep(2)
353
+
354
+ # Solve hCaptcha
355
+ solved = await solve_hcaptcha(page, max_retries=3, verbose=True)
356
+
357
+ if solved:
358
+ # Click Submit
359
+ submit_btn = await page.query_selector("#faucet-submit-btn, button.faucet-btn")
360
+ if submit_btn:
361
+ await submit_btn.click()
362
+ print("[bot] Submit clicked!")
363
+ await asyncio.sleep(5)
364
+
365
+ # Check for success message
366
+ success = await page.query_selector(".faucet-success, [class*='success']")
367
+ if success:
368
+ msg = await success.inner_text()
369
+ print(f"[bot] SUCCESS: {msg}")
370
+ else:
371
+ print("[bot] Claim submitted, check results")
372
+ else:
373
+ print("[bot] Failed to solve hCaptcha")
374
+
375
+ await browser.close()
376
+
377
+
378
+ if __name__ == "__main__":
379
+ asyncio.run(main())