From 0ca89e7ad0f60592801e41f8989599192cdd5ef1 Mon Sep 17 00:00:00 2001 From: capmonster-sdk-bot Date: Thu, 19 Nov 2026 09:23:30 +0000 Subject: [PATCH 1/2] Expose solution cost from getTaskResult via SolvedTask --- CHANGELOG.md | 8 +++++ Cargo.toml | 2 +- README.md | 22 ++++++------ examples/image_to_text.rs | 2 +- examples/recaptcha_v2.rs | 5 +-- src/client.rs | 28 +++++++++++---- src/lib.rs | 7 ++-- tests/client.rs | 75 +++++++++++++++++++++++++++++++++++++-- 8 files changed, 122 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e163bc1..0994460 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ All notable changes to this crate are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), versions follow [SemVer](https://semver.org/) (while the major version is 0, a breaking change bumps the **minor** number). +## [0.3.0] + +### Added +- `SolvedTask` (`solution` and optional `cost` in USD from `getTaskResult`). + +### Changed +- `TaskStatus::Ready` now carries a `SolvedTask`, and `solve_captcha` returns `SolvedTask` instead of the bare solution `Value`. + ## [0.2.0] ### Added diff --git a/Cargo.toml b/Cargo.toml index a67ec66..07557e4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "capmonstercloud-client" -version = "0.2.0" +version = "0.3.0" edition = "2021" rust-version = "1.88" description = "Async Rust client for the CapMonster Cloud captcha-solving API" diff --git a/README.md b/README.md index f93f721..87c6595 100644 --- a/README.md +++ b/README.md @@ -106,9 +106,11 @@ async fn main() -> capmonstercloud_client::Result<()> { "6Lcg7CMUAAAAANphynKgn9YAgA4tQ2KI_iqRyTwd", ); - // Send task and receive token (the `solution` object as serde_json::Value) - let solution = client.solve_captcha(&request).await?; - println!("reCAPTCHA Token: {}", solution["gRecaptchaResponse"]); + // Send task and receive token (`solved.solution` is the solution object as serde_json::Value) + let solved = client.solve_captcha(&request).await?; + println!("reCAPTCHA Token: {}", solved.solution["gRecaptchaResponse"]); + // Solution cost in USD (None if the API did not return it) + println!("Cost: {:?}", solved.cost); Ok(()) } ``` @@ -130,9 +132,9 @@ async fn main() -> capmonstercloud_client::Result<()> { TurnstileStandard::new().with_proxy(proxy), ); - let solution = client.solve_captcha(&request).await?; - // inject solution["token"] into the cf-turnstile-response field of your browser session and submit - println!("Turnstile token: {}", solution["token"]); + let solved = client.solve_captcha(&request).await?; + // inject solved.solution["token"] into the cf-turnstile-response field of your browser session and submit + println!("Turnstile token: {}", solved.solution["token"]); Ok(()) } ``` @@ -146,7 +148,7 @@ println!("balance: {}", client.get_balance().await?); let task_id = client.create_task(&request).await?; match client.get_task_result(task_id).await? { TaskStatus::Processing => println!("not ready yet"), - TaskStatus::Ready(solution) => println!("{solution}"), + TaskStatus::Ready(solved) => println!("{} (cost: {:?})", solved.solution, solved.cost), } ``` @@ -178,8 +180,8 @@ async fn main() -> capmonstercloud_client::Result<()> { "YOUR_SITE_KEY", ); - let solution = client.solve_captcha(&request).await?; - let token = solution["gRecaptchaResponse"].as_str().unwrap_or_default(); + let solved = client.solve_captcha(&request).await?; + let token = solved.solution["gRecaptchaResponse"].as_str().unwrap_or_default(); println!("{token}"); Ok(()) } @@ -279,7 +281,7 @@ Add `capmonstercloud-client` to `Cargo.toml`, create a `CapMonsterClient` with y Yes. This repository is the official Rust client library for the CapMonster Cloud captcha solving service. **How do I bypass reCAPTCHA v2 in Rust?** -Create a client, build a `RecaptchaV2Request` with the page URL and sitekey, call `client.solve_captcha(&request).await?` and read `solution["gRecaptchaResponse"]`. See the [reCAPTCHA v2 documentation](https://docs.capmonster.cloud/docs/captchas/no-captcha-task/?utm_source=github&utm_medium=referral&utm_campaign=rust_repo_readme). +Create a client, build a `RecaptchaV2Request` with the page URL and sitekey, call `client.solve_captcha(&request).await?` and read `solved.solution["gRecaptchaResponse"]`. See the [reCAPTCHA v2 documentation](https://docs.capmonster.cloud/docs/captchas/no-captcha-task/?utm_source=github&utm_medium=referral&utm_campaign=rust_repo_readme). **How do I bypass Cloudflare Turnstile in Rust?** Use `TurnstileRequest` with `TurnstileStandard` (optionally with a proxy), as in example 2 above. According to the [Turnstile documentation](https://docs.capmonster.cloud/docs/captchas/turnstile-task/?utm_source=github&utm_medium=referral&utm_campaign=rust_repo_readme), all Turnstile subtypes are supported automatically: manual, non-interactive and invisible. diff --git a/examples/image_to_text.rs b/examples/image_to_text.rs index 5086526..49bc7c0 100644 --- a/examples/image_to_text.rs +++ b/examples/image_to_text.rs @@ -15,6 +15,6 @@ async fn main() -> capmonstercloud_client::Result<()> { println!("balance: {}", client.get_balance().await?); let request = ImageToTextRequest::new(image).with_module_name(TextModule::Universal); - println!("{}", client.solve_captcha(&request).await?); + println!("{}", client.solve_captcha(&request).await?.solution); Ok(()) } diff --git a/examples/recaptcha_v2.rs b/examples/recaptcha_v2.rs index c54f74d..a9bbaef 100644 --- a/examples/recaptcha_v2.rs +++ b/examples/recaptcha_v2.rs @@ -14,7 +14,8 @@ async fn main() -> capmonstercloud_client::Result<()> { "https://lessons.zennolab.com/captchas/recaptcha/v2_simple.php?level=high", "6Lcg7CMUAAAAANphynKgn9YAgA4tQ2KI_iqRyTwd", ); - let solution = client.solve_captcha(&request).await?; - println!("{solution}"); + let solved = client.solve_captcha(&request).await?; + println!("{}", solved.solution); + println!("cost: {:?}", solved.cost); Ok(()) } diff --git a/src/client.rs b/src/client.rs index 699d542..6be5ec0 100644 --- a/src/client.rs +++ b/src/client.rs @@ -94,6 +94,7 @@ struct ApiResponse { status: Option, solution: Option, balance: Option, + cost: Option, } impl ApiResponse { @@ -105,12 +106,21 @@ impl ApiResponse { } } +/// A solved task: the `solution` object and the solving cost. +#[derive(Debug, Clone, PartialEq)] +pub struct SolvedTask { + /// The solution object; its shape depends on the captcha type. + pub solution: Value, + /// Solution cost in US dollars (`cost` of `getTaskResult`); `None` if the API did not return it. + pub cost: Option, +} + /// State of a task returned by [`CapMonsterClient::get_task_result`]. #[derive(Debug, Clone, PartialEq)] pub enum TaskStatus { Processing, - /// The solution object; its shape depends on the captcha type. - Ready(Value), + /// The solution and its cost. + Ready(SolvedTask), } /// Asynchronous CapMonster Cloud client. Cheap to clone (the HTTP pool is shared). @@ -203,15 +213,19 @@ impl CapMonsterClient { }); } match resp.status.as_deref() { - Some("ready") => Ok(TaskStatus::Ready(resp.solution.unwrap_or(Value::Null))), + Some("ready") => Ok(TaskStatus::Ready(SolvedTask { + solution: resp.solution.unwrap_or(Value::Null), + cost: resp.cost, + })), _ => Ok(TaskStatus::Processing), } } - /// Creates a task, polls until it is solved and returns the `solution` object. + /// Creates a task, polls until it is solved and returns the `solution` object + /// together with the cost. /// /// Returns `Error::Timeout` if the captcha type's maximum waiting time is exceeded. - pub async fn solve_captcha(&self, request: &R) -> Result { + pub async fn solve_captcha(&self, request: &R) -> Result { let timeouts = self .options .timeouts_override @@ -225,8 +239,8 @@ impl CapMonsterClient { .unwrap_or_else(|| now + Duration::from_secs(365 * 24 * 3600)); sleep(timeouts.first_request_delay).await; while Instant::now() < deadline { - if let TaskStatus::Ready(solution) = self.get_task_result(task_id).await? { - return Ok(solution); + if let TaskStatus::Ready(solved) = self.get_task_result(task_id).await? { + return Ok(solved); } sleep(timeouts.requests_interval).await; } diff --git a/src/lib.rs b/src/lib.rs index d158a74..fc5d1df 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,8 +10,8 @@ //! "https://lessons.zennolab.com/captchas/recaptcha/v2_simple.php?level=high", //! "6Lcg7CMUAAAAANphynKgn9YAgA4tQ2KI_iqRyTwd", //! ); -//! let solution = client.solve_captcha(&request).await?; -//! println!("{}", solution["gRecaptchaResponse"]); +//! let solved = client.solve_captcha(&request).await?; +//! println!("{}", solved.solution["gRecaptchaResponse"]); //! # Ok(()) } //! ``` @@ -22,7 +22,8 @@ pub mod requests; mod timeouts; pub use client::{ - CapMonsterClient, ClientOptions, TaskStatus, DEFAULT_SERVICE_URL, DEFAULT_SOFT_ID, + CapMonsterClient, ClientOptions, SolvedTask, TaskStatus, DEFAULT_SERVICE_URL, + DEFAULT_SOFT_ID, }; pub use error::{Error, Result}; pub use proxy::{ClientProxy, ProxyInfo, ProxyType}; diff --git a/tests/client.rs b/tests/client.rs index 26d401b..ccbd84c 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -3,7 +3,8 @@ use std::time::Duration; use capmonstercloud_client::requests::RecaptchaV2Request; use capmonstercloud_client::{ - CapMonsterClient, ClientOptions, ClientProxy, Error, GetResultTimeouts, ProxyType, TaskStatus, + CapMonsterClient, ClientOptions, ClientProxy, Error, GetResultTimeouts, ProxyType, + SolvedTask, TaskStatus, }; use serde_json::json; use wiremock::matchers::{body_partial_json, header_exists, method, path}; @@ -61,11 +62,12 @@ async fn solve_captcha_creates_task_and_polls_until_ready() { .mount(&server) .await; - let solution = fast_client(&server) + let solved = fast_client(&server) .solve_captcha(&request()) .await .unwrap(); - assert_eq!(solution["gRecaptchaResponse"], "TOKEN"); + assert_eq!(solved.solution["gRecaptchaResponse"], "TOKEN"); + assert_eq!(solved.cost, None); } #[tokio::test] @@ -166,6 +168,73 @@ async fn get_balance_returns_number() { assert_eq!(fast_client(&server).get_balance().await.unwrap(), 12.5); } +#[tokio::test] +async fn get_task_result_ready_returns_cost() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/getTaskResult")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "errorId": 0, "status": "ready", "cost": 0.0003, + "solution": {"gRecaptchaResponse": "TOKEN"} + }))) + .mount(&server) + .await; + + let status = fast_client(&server).get_task_result(7).await.unwrap(); + assert_eq!( + status, + TaskStatus::Ready(SolvedTask { + solution: json!({"gRecaptchaResponse": "TOKEN"}), + cost: Some(0.0003), + }) + ); +} + +#[tokio::test] +async fn get_task_result_ready_without_cost_has_none() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/getTaskResult")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "errorId": 0, "status": "ready", "solution": {"text": "abc"} + }))) + .mount(&server) + .await; + + let status = fast_client(&server).get_task_result(7).await.unwrap(); + assert_eq!( + status, + TaskStatus::Ready(SolvedTask { + solution: json!({"text": "abc"}), + cost: None, + }) + ); +} + +#[tokio::test] +async fn solve_captcha_returns_cost() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/createTask")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({"errorId": 0, "taskId": 5}))) + .mount(&server) + .await; + Mock::given(method("POST")) + .and(path("/getTaskResult")) + .respond_with(ResponseTemplate::new(200).set_body_json(json!({ + "errorId": 0, "status": "ready", "cost": 0.0003, + "solution": {"gRecaptchaResponse": "TOKEN"} + }))) + .mount(&server) + .await; + + let solved = fast_client(&server) + .solve_captcha(&request()) + .await + .unwrap(); + assert_eq!(solved.cost, Some(0.0003)); +} + #[tokio::test] async fn invalid_request_fails_before_any_http_call() { // No mock mounted: any HTTP call would return 404 and be reported as Error::Status. From 597fff014fc6f1390f3cd41f7a6f145a1239ee57 Mon Sep 17 00:00:00 2001 From: capmonster-sdk-bot Date: Thu, 19 Nov 2026 10:00:20 +0000 Subject: [PATCH 2/2] Expose solution cost from getTaskResult via SolvedTask --- src/lib.rs | 3 +-- tests/client.rs | 4 ++-- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index fc5d1df..661ed6e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,8 +22,7 @@ pub mod requests; mod timeouts; pub use client::{ - CapMonsterClient, ClientOptions, SolvedTask, TaskStatus, DEFAULT_SERVICE_URL, - DEFAULT_SOFT_ID, + CapMonsterClient, ClientOptions, SolvedTask, TaskStatus, DEFAULT_SERVICE_URL, DEFAULT_SOFT_ID, }; pub use error::{Error, Result}; pub use proxy::{ClientProxy, ProxyInfo, ProxyType}; diff --git a/tests/client.rs b/tests/client.rs index ccbd84c..2988343 100644 --- a/tests/client.rs +++ b/tests/client.rs @@ -3,8 +3,8 @@ use std::time::Duration; use capmonstercloud_client::requests::RecaptchaV2Request; use capmonstercloud_client::{ - CapMonsterClient, ClientOptions, ClientProxy, Error, GetResultTimeouts, ProxyType, - SolvedTask, TaskStatus, + CapMonsterClient, ClientOptions, ClientProxy, Error, GetResultTimeouts, ProxyType, SolvedTask, + TaskStatus, }; use serde_json::json; use wiremock::matchers::{body_partial_json, header_exists, method, path};