Logo of «2Captcha»To home page
Captcha bypass tutorials

Was this helpful?

How to bypass captcha using Ruby

Nick McBain
Nick McBain

Technical engineer

Introduction

When automating testing, parsing data, or developing bots in Ruby, developers often face the need to bypass captchas. Writing custom HTTP requests, implementing polling loops, and handling timeouts complicates the code and distracts from the core business logic.

In this guide, we will look at how to use the official ruby-2captcha library to integrate with the 2Captcha API. We will cover the installation process, client initialization, solving popular captcha types, and proper error handling.

Installation and setup

The library is compatible with Ruby version 2.5 and above, has no heavy external dependencies, and integrates easily into any project, from simple scripts to large Ruby on Rails applications.

You can install the package via Bundler by adding the following line to your Gemfile:

ruby Copy
gem 'ruby-2captcha'

Then run the command in your terminal:

bash Copy
bundle install

Or install the library directly via RubyGems:

bash Copy
gem install ruby-2captcha

After installation, include it in your code:

ruby Copy
require 'api_2captcha'

Client initialization

To get started, you need to create a client instance and pass your API key to it. For security reasons, it is recommended to store the key in environment variables rather than in the source code.

ruby Copy
api_key = ENV.fetch('CAPTCHA_API_KEY')
client = Api2Captcha.new(api_key)

Solving different types of captchas

The library interface is designed so that each captcha type has its own dedicated method. The method automatically sends the task to the server, waits for it to be solved, and returns the final result (text or token).

1. Text or image captcha (Normal)

To solve standard image captchas, the normal method is used. The image can be passed as a file path or a byte array.

ruby Copy
result = client.normal({
  image: File.read('/path/to/captcha.png')
})
puts "Recognized text: #{result}"

2. reCAPTCHA v2 and Invisible

To bypass reCAPTCHA, you need to pass the sitekey (the googlekey parameter) and the page URL (pageurl). If the invisible version of the captcha is used, add the invisible: true parameter.

ruby Copy
token = client.recaptcha_v2({
  googlekey: '6LeTxvsqAAAAAK...',
  pageurl: 'https://example.com/login',
  invisible: true
})
puts "g-recaptcha-response: #{token}"

3. Cloudflare Turnstile

Modern protection from Cloudflare requires passing the sitekey, page URL, and, to increase the chances of a successful pass, the current User-Agent.

ruby Copy
token = client.turnstile({
  sitekey: '0x4AAAAAA...',
  pageurl: 'https://example.com/protected',
  useragent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36'
})
puts "cf-turnstile-response: #{token}"

4. Audio captcha

If the website uses an audio captcha, the library allows you to send an audio file (usually in MP3 format) and get the recognized text.

ruby Copy
decoded_text = client.audio({
  audio: File.read('/path/to/challenge.mp3'),
  lang: 'ru' # Specify the language if it differs from English
})
puts "Answer: #{decoded_text}"

Additional settings

Working via proxy

If the target website strictly checks IP addresses and binds the captcha to a specific proxy, you can pass the proxy parameters directly to the solving method.

ruby Copy
token = client.recaptcha_v2({
  googlekey: '6LeTxvsqAAAAAK...',
  pageurl: 'https://example.com/login',
  proxytype: 'http',
  proxy: 'login:password@198.51.100.10:8080'
})

Timeout configuration

By default, the library waits for a captcha solution for 120 seconds. For complex tasks or when working on slow networks, these parameters can be overridden.

ruby Copy
client.default_timeout = 300      # Maximum waiting time (in seconds)
client.polling_interval = 15      # Interval between status requests (in seconds)

Asynchronous mode (Callback)

If your application should not be blocked while waiting for a response, you can set up a webhook. The method will instantly return the task_id, and the solution result will be sent via a POST request to the URL you specified.

ruby Copy
client.callback = 'https://your-app.com/captcha/webhook'

task_id = client.normal({ image: '/path/to/captcha.png' })
puts "Task sent, ID: #{task_id}"

Error handling

The library provides specialized exception classes, allowing you to clearly separate validation errors, network failures, and API responses.

ruby Copy
begin
  result = client.recaptcha_v2({
    googlekey: '6LeTxvsqAAAAAK...',
    pageurl: 'https://example.com/login'
  })
  puts "Captcha successfully solved: #{result}"
rescue Api2Captcha::ValidationException => e
  puts "Invalid request parameters: #{e.message}"
rescue Api2Captcha::NetworkException => e
  puts "API connection error: #{e.message}"
rescue Api2Captcha::TimeoutException => e
  puts "Solution waiting time exceeded"
rescue Api2Captcha::ApiException => e
  puts "Service-side error: #{e.message}"
end

Common error codes

When exceptions occur, the library translates API error codes into understandable messages. The main ones are presented in the table:

Error Code Description Recommendation
ERROR_WRONG_USER_KEY Invalid API key format or value Check the key correctness in environment variables
ERROR_ZERO_BALANCE Insufficient funds on balance Top up your account in the 2Captcha dashboard
ERROR_NO_SLOT_AVAILABLE No free workers available Retry after 10–15 seconds
ERROR_BAD_PARAMETERS Required parameters are missing Check parameter compliance with the documentation
ERROR_PROXY_CONNECT_REFUSED Failed to connect to the proxy Check proxy availability and string format
ERROR_CAPTCHA_UNSOLVABLE Captcha was not solved Funds are refunded, try refreshing the captcha

Solution accuracy reports

To maintain high recognition quality and refund funds for incorrect solutions, use the report submission methods.

ruby Copy
# If the website accepted the token and the form was successfully submitted
client.report_correct(task_id)

# If the website rejected the token with a validation error
client.report_incorrect(task_id)

Conclusion

The ruby-2captcha library takes over all the routine work of interacting with the 2Captcha API: it hides polling loops, validates input parameters, and returns ready-made tokens or recognized text. Thanks to its clean and idiomatic syntax, it easily integrates into both console utilities and Ruby on Rails web applications.

To get started, simply install the package, initialize the client with your API key, and call the required method. If necessary, you can easily add proxy support, configure timeouts, or implement asynchronous processing via callback URLs.