AutoIt captcha solver: an API client with WinHTTP
An AutoIt captcha solver is a script that posts a challenge to a solver API from a Windows automation, without any external library: the request goes through the WinHTTP component of Windows, and the image is encoded by a system function. With ilovecaptcha it makes two HTTPS calls, createTask then getTaskResult. This page explains each part and gives the complete script.
Preview: the API described here is in public beta. Endpoint names, fields and codes can still change until the end of the beta, and no API key is distributed yet.
How do you call a captcha solver API from AutoIt?
With the COM object WinHttp.WinHttpRequest.5.1, created by ObjCreate. The function _Post assembles the JSON body as a string that starts with clientKey, calls SetTimeouts with 30 seconds for each phase, opens a synchronous POST request, sets the header Content-Type:, sends the body and returns ResponseText. Windows handles HTTPS: nothing is added to the script.
| Item | Value |
|---|---|
| Runs on | AutoIt 3.3.14 or newer, on Windows |
| Libraries to add | None: two standard includes |
| File | solve.au3 |
| Command | AutoIt3.exe solve.au3 |
| HTTP client | WinHttp.WinHttpRequest.5.1 |
How do you send the captcha image and wait for the answer in AutoIt?
FileOpen in binary mode and FileRead load the image, and _Base64Encode converts it by calling CryptBinaryToStringA in Crypt32.dll twice: once for the length, once for the text, without line breaks. _Solve posts the task to createTask, then loops on getTaskResult.
POLL_MSis 1500, passed toSleep.TIMEOUT_MSis 120000, measured withTimerInitandTimerDiff._Fieldreads one value of the reply withStringRegExp._Objectreturns thesolutionobject by counting braces.
How do you handle the API key and errors in AutoIt?
Read the key with EnvGet from a variable such as ILOVECAPTCHA_KEY instead of the constant API_KEY: a compiled script can be decompiled, and the key with it. The example reports errors on the error stream with ConsoleWriteError and stops: exit code 1 when errorId is not 0, with errorCode and errorDescription, exit code 2 when the task is not ready in time. A failed request raises a COM error: register a handler with ObjEvent to catch it.
What does a complete AutoIt captcha solver client look like?
The script below is the whole client, in 80 lines. It defines _Post, _Field, _Object, _Solve, _GetBalance and _Base64Encode, then reads captcha.png, submits it as an aws-waf task and writes the solution to the console. Replace YOUR_API_KEY and YOUR_API_URL with your own values and adapt the JSON of the task to your captcha before you run it.
solve.au3 · Complete AutoIt client: one createTask call, then getTaskResult until the task is ready (preview format).#include <FileConstants.au3>
#include <StringConstants.au3>
Global Const $API_KEY = "YOUR_API_KEY"
Global Const $BASE_URL = "YOUR_API_URL"
Global Const $POLL_MS = 1500
Global Const $TIMEOUT_MS = 120000
Func _Post($sRoute, $sFields)
Local $sBody = '{"clientKey":"' & $API_KEY & '"' & (($sFields = "") ? "" : "," & $sFields) & '}'
Local $oHttp = ObjCreate("WinHttp.WinHttpRequest.5.1")
$oHttp.SetTimeouts(30000, 30000, 30000, 30000)
$oHttp.Open("POST", $BASE_URL & $sRoute, False)
$oHttp.SetRequestHeader("Content-Type", "application/json")
$oHttp.Send($sBody)
Local $sResult = $oHttp.ResponseText
Local $sErrorId = _Field($sResult, "errorId")
If $sErrorId <> "" And $sErrorId <> "0" Then
ConsoleWriteError(_Field($sResult, "errorCode") & ": " & _Field($sResult, "errorDescription") & @CRLF)
Exit 1
EndIf
Return $sResult
EndFunc
Func _Field($sJson, $sName)
Local $aMatch = StringRegExp($sJson, '"' & $sName & '"\s*:\s*(?:"((?:[^"\\]|\\.)*)"|([^,}\s]+))', $STR_REGEXPARRAYMATCH)
If @error Then Return ""
Return ($aMatch[0] <> "") ? $aMatch[0] : $aMatch[1]
EndFunc
Func _Object($sJson, $sName)
Local $iStart = StringInStr($sJson, '"' & $sName & '"')
If $iStart = 0 Then Return ""
$iStart = StringInStr($sJson, "{", $STR_NOCASESENSE, 1, $iStart)
Local $iDepth = 0
For $i = $iStart To StringLen($sJson)
Local $sChar = StringMid($sJson, $i, 1)
If $sChar = "{" Then $iDepth += 1
If $sChar = "}" Then
$iDepth -= 1
If $iDepth = 0 Then Return StringMid($sJson, $iStart, $i - $iStart + 1)
EndIf
Next
Return ""
EndFunc
Func _Solve($sTaskJson)
Local $sResult = _Post("/createTask", '"task":' & $sTaskJson)
If _Field($sResult, "status") = "ready" Then Return _Object($sResult, "solution")
Local $sTaskId = _Field($sResult, "taskId")
Local $hTimer = TimerInit()
While TimerDiff($hTimer) < $TIMEOUT_MS
Sleep($POLL_MS)
$sResult = _Post("/getTaskResult", '"taskId":' & $sTaskId)
If _Field($sResult, "status") = "ready" Then Return _Object($sResult, "solution")
WEnd
ConsoleWriteError("task " & $sTaskId & " not ready after " & ($TIMEOUT_MS / 1000) & " s" & @CRLF)
Exit 2
EndFunc
Func _GetBalance()
Return _Field(_Post("/getBalance", ""), "balance")
EndFunc
Func _Base64Encode($bData)
Local $tData = DllStructCreate("byte[" & BinaryLen($bData) & "]")
DllStructSetData($tData, 1, $bData)
Local $aCall = DllCall("Crypt32.dll", "bool", "CryptBinaryToStringA", "struct*", $tData, "dword", DllStructGetSize($tData), "dword", 0x40000001, "ptr", 0, "dword*", 0)
If @error Or Not $aCall[0] Then Return SetError(1, 0, "")
Local $tOut = DllStructCreate("char[" & $aCall[5] & "]")
$aCall = DllCall("Crypt32.dll", "bool", "CryptBinaryToStringA", "struct*", $tData, "dword", DllStructGetSize($tData), "dword", 0x40000001, "struct*", $tOut, "dword*", $aCall[5])
If @error Or Not $aCall[0] Then Return SetError(2, 0, "")
Return DllStructGetData($tOut, 1)
EndFunc
Local $hFile = FileOpen("captcha.png", $FO_BINARY)
Local $sImage = _Base64Encode(FileRead($hFile))
FileClose($hFile)
ConsoleWrite(_Solve('{"type":"aws-waf","image":"' & $sImage & '"}') & @CRLF)
ConsoleWrite(_GetBalance() & @CRLF)
AutoIt captcha solver: frequently asked questions
Do I need a UDF library or an SDK to solve captchas in AutoIt?
No. The script includes only FileConstants.au3 and StringConstants.au3, which are installed with AutoIt. The HTTPS request is made by a COM object that Windows provides, the base64 encoding by a function of Crypt32.dll, and the JSON is written and read as text. The file on this page is the complete client: include it in your own script with the include directive and call the function _Solve.
Can an AutoIt script click the answer itself?
Yes, and it is where AutoIt is at ease. For an image challenge, capture the region of the captcha with _ScreenCapture_Capture, send the file to _Solve, then replay the answer with MouseClick for points or MouseClickDrag for a slider distance, adding the screen position of the captured region to each coordinate. The returned values are in pixels of the image you sent, so capture at the size displayed.
What does _Solve return in AutoIt, and how do you read it?
A string that holds the solution object as JSON text, since AutoIt has no JSON type. Read a single value with the function _Field of the example and the name you expect: token for a token widget, offset for a slider, text for characters to type. For points, extract the numbers with StringRegExp in global mode, two per point, in pixels of the image you submitted.
Sources
The facts and figures quoted on this page come from these sources.
- AutoIt Consulting, Function ObjCreate, AutoIt documentation (creating a COM object).
- Microsoft, WinHttpRequest object and CryptBinaryToStringA function, Windows documentation.