Ruby captcha solver: an API client with Net::HTTP
A Ruby captcha solver is a script of a few dozen lines that posts a challenge to a solver API and parses the answer with the libraries that come with Ruby: net/http and json. With ilovecaptcha it makes two HTTPS calls, createTask then getTaskResult. This page explains the request, the base64 encoding, the polling loop and the errors, then gives the complete file.
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 Ruby?
With Net:, which takes a URI, a body and a hash of headers, and switches to HTTPS by itself when the address starts with https. The method post merges the key into the body under clientKey, serialises it with JSON.generate, sends it as application/ and parses the reply with JSON.parse. Two require lines are enough: json and net/.
| Item | Value |
|---|---|
| Runs on | Ruby 2.7 or newer |
| Gems to install | None: libraries shipped with Ruby |
| File | solve.rb |
| Command | ruby solve.rb |
| HTTP client | Net: |
How do you send the captcha image and wait for the answer in Ruby?
File.binread loads the image, and pack with the directive m0 encodes it in base64 on a single line, without loading the base64 library. solve posts the task to createTask, keeps taskId, then calls getTaskResult after each sleep until status is ready.
POLL_SECONDSis 1.5, passed tosleep.TIMEOUT_SECONDSis 120: past that,solveraises aRuntimeError.- The deadline uses
Process.clock_gettimewithCLOCK_MONOTONIC, which clock changes do not affect. - A reply already
readyatcreateTaskis returned at once.
How do you handle the API key and errors in Ruby?
Read the key with ENV.fetch from a variable such as ILOVECAPTCHA_KEY: it raises a KeyError when the variable is missing, so a forgotten key fails at start-up, not at the first call. When errorId is not 0, post raises with errorCode and errorDescription in the message. Network failures raise the exceptions of Net:, such as Net: or SocketError, to rescue around solve.
What does a complete Ruby captcha solver client look like?
The file below is the whole client, in 36 lines. It defines the methods post, solve and balance, then reads captcha.png, submits it as an aws-waf task and prints the solution with puts. Replace YOUR_API_KEY and YOUR_API_URL with your own values, adapt the task hash to your captcha, and run the script with ruby.
solve.rb · Complete Ruby client: one createTask call, then getTaskResult until the task is ready (preview format).require "json"
require "net/http"
API_KEY = "YOUR_API_KEY"
BASE_URL = "YOUR_API_URL"
POLL_SECONDS = 1.5
TIMEOUT_SECONDS = 120
def post(route, body)
payload = JSON.generate({ clientKey: API_KEY }.merge(body))
response = Net::HTTP.post(URI(BASE_URL + route), payload, "Content-Type" => "application/json")
result = JSON.parse(response.body)
raise "#{result["errorCode"]}: #{result["errorDescription"]}" if result.fetch("errorId", 0) != 0
result
end
def solve(task)
result = post("/createTask", { task: task })
return result["solution"] if result["status"] == "ready"
task_id = result["taskId"]
deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + TIMEOUT_SECONDS
while Process.clock_gettime(Process::CLOCK_MONOTONIC) < deadline
sleep POLL_SECONDS
result = post("/getTaskResult", { taskId: task_id })
return result["solution"] if result["status"] == "ready"
end
raise "task #{task_id} not ready after #{TIMEOUT_SECONDS} s"
end
def balance
post("/getBalance", {})["balance"]
end
image = [File.binread("captcha.png")].pack("m0")
puts solve({ type: "aws-waf", image: image })
puts balance
Ruby captcha solver: frequently asked questions
Do I need a gem or an SDK to solve captchas in Ruby?
No. net/http and json are delivered with Ruby, and the image is encoded by a method of Array, so the Gemfile of your project does not change. The file on this page is the complete client. In a Rails application, place post and solve in a small class under app/services or lib, and read the key from the credentials of the application instead of a constant.
Why does the Ruby example use pack instead of the base64 library?
Because pack is a method of Array, always available, while base64 is a separate library: since Ruby 3.4 it is no longer a default gem and must be added to the Gemfile. The directive m0 produces standard base64 without line breaks, which is what a JSON field needs; the directive m alone inserts a line break every 60 characters. Base64.strict_encode64 gives the same string, if you prefer the explicit name.
What does solve return in Ruby, and how do you read it?
A Hash with string keys, since JSON.parse is called without the symbolize_names option. Read the key your task type returns: token for a token widget, points for an image grid, offset for a slider, text for characters to type. Points is an Array of two-element Arrays, in pixels of the image you submitted, which each or map can walk. Use fetch to get an error when the key is absent.
Sources
The facts and figures quoted on this page come from these sources.
- Ruby core team, class Net::HTTP, Ruby documentation (Net::HTTP.post).
- Ruby core team, module JSON, Ruby documentation (JSON.generate, JSON.parse).