CryptoBot

Struct CryptoBot 

Source
pub struct CryptoBot { /* private fields */ }

Implementations§

Source§

impl CryptoBot

Source

pub fn builder() -> ClientBuilder<NoAPIToken>

Returns a new builder for creating a customized CryptoBot client

The builder pattern allows you to customize all aspects of the client, including timeout, base URL and headers settings.

§Available Settings
  • api_token - Required, the API token from @CryptoBot
  • base_url - Optional, defaults to “https://pay.crypt.bot/api”
  • timeout - Optional, defaults to 30 seconds
  • headers - Optional, custom headers for all requests
§Example
use crypto_pay_api::prelude::*;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder()
        .api_token("YOUR_API_TOKEN")
        .base_url("https://testnet-pay.crypt.bot/api")  // Use testnet
        .timeout(Duration::from_secs(60))               // 60 second timeout
    .headers(vec![(
        HeaderName::from_static("x-custom-header"),
        HeaderValue::from_static("custom_value")
    )])
    .build()?;

    Ok(())
}
§See Also
Source§

impl CryptoBot

Source

pub fn webhook_handler(&self, config: WebhookHandlerConfig) -> WebhookHandler

Creates a new webhook handler with the given config

§Example
use crypto_pay_api::prelude::*;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();

    let config = WebhookHandlerConfigBuilder::new()
        .expiration_time(Duration::from_secs(60 * 10))
        .build();

    let webhook_handler = client.webhook_handler(config);
    Ok(())
}

Trait Implementations§

Source§

impl BalanceAPI for CryptoBot

Source§

fn get_balance<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<Vec<Balance>, CryptoBotError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Gets current balance for all supported cryptocurrencies in your CryptoBot wallet

This method returns the current balance for all cryptocurrencies that are available in your CryptoBot wallet, including both crypto and test currencies.

§Returns
  • Ok(Vec<Balance>) - A vector of balances for each currency
  • Err(CryptoBotError) - If the request fails
§Errors

This method will return an error if:

  • The API request fails
  • The response cannot be parsed
  • The API token is invalid
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    let balances = client.get_balance().await?;
     
    for balance in balances {
        println!("Available: {}", balance.available);
    }
     
    Ok(())
}
§See Also
Source§

impl CheckAPI for CryptoBot

Source§

fn create_check<'life0, 'life1, 'async_trait>( &'life0 self, params: &'life1 CreateCheckParams, ) -> Pin<Box<dyn Future<Output = Result<Check, CryptoBotError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Creates a new cryptocurrency check

A check is a unique link that can be used once to transfer cryptocurrency. Anyone who opens the link first can activate the check and get the cryptocurrency.

§Arguments
§Returns
  • Ok(Check) - The created check
  • Err(CryptoBotError) - If validation fails or the request fails
§Errors

This method will return an error if:

  • The parameters are invalid (e.g., negative amount)
  • The currency is not supported
  • The API request fails
  • The exchange rate validation fails
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    let params = CreateCheckParamsBuilder::new()
        .asset(CryptoCurrencyCode::Ton)
        .amount(dec!(10.5))
        .build(&client).await?;
     
    let check = client.create_check(&params).await?;
    println!("Check created: {}", check.check_id);
     
    Ok(())
}
§See Also
Source§

fn delete_check<'life0, 'async_trait>( &'life0 self, check_id: u64, ) -> Pin<Box<dyn Future<Output = Result<bool, CryptoBotError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Deletes an existing cryptocurrency check

Once deleted, the check link will become invalid and cannot be activated.

§Arguments
  • check_id - The unique identifier of the check to delete
§Returns
  • Ok(true) - If the check was successfully deleted
  • Err(CryptoBotError) - If the check doesn’t exist or the request fails
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    match client.delete_check(12345).await {
        Ok(_) => println!("Check deleted successfully"),
        Err(e) => eprintln!("Failed to delete check: {}", e),
    }
     
    Ok(())
}
Source§

fn get_checks<'life0, 'life1, 'async_trait>( &'life0 self, params: Option<&'life1 GetChecksParams>, ) -> Pin<Box<dyn Future<Output = Result<Vec<Check>, CryptoBotError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Gets a list of created cryptocurrency checks

Retrieves all checks matching the specified filter parameters. If no parameters are provided, returns all checks.

§Arguments
  • params - Optional filter parameters. See GetChecksParams for available filters.
§Returns
  • Ok(Vec<Check>) - List of checks matching the filter criteria
  • Err(CryptoBotError) - If the parameters are invalid or the request fails
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    // Get all checks
    let all_checks = client.get_checks(None).await?;
     
    // Get checks with filters
    let params = GetChecksParamsBuilder::new()
        .asset(CryptoCurrencyCode::Ton)
        .status(CheckStatus::Active)
        .build()
        .unwrap();
     
    let filtered_checks = client.get_checks(Some(&params)).await?;
     
    for check in filtered_checks {
        println!("Check ID: {}, Amount: {}",
            check.check_id,
            check.amount,
        );
    }
     
    Ok(())
}
§See Also
Source§

impl Debug for CryptoBot

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl ExchangeRateAPI for CryptoBot

Source§

fn get_exchange_rates<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<Vec<ExchangeRate>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Gets current exchange rates for all supported cryptocurrencies

This method returns exchange rates between supported cryptocurrencies and target currencies. Exchange rates are updated regularly by CryptoBot.

§Returns
  • Ok(Vec<ExchangeRate>) - A list of current exchange rates
  • Err(CryptoBotError) - If the request fails
§Exchange Rate Pairs

Exchange rates are provided for various pairs:

  • Cryptocurrency to fiat (e.g., TON/USD, BTC/EUR)
  • Cryptocurrency to cryptocurrency (e.g., TON/BTC, ETH/BTC)
  • Test currencies are also included in testnet mode
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    let rates = client.get_exchange_rates().await?;
     
    for rate in rates {
        println!("Exchange Rate: {} {} = {}",
            rate.source,
            rate.target,
            rate.rate,
        );
    }
     
    Ok(())
}
§See Also
  • ExchangeRate - The structure representing an exchange rate
Source§

impl InvoiceAPI for CryptoBot

Source§

fn create_invoice<'life0, 'life1, 'async_trait>( &'life0 self, params: &'life1 CreateInvoiceParams, ) -> Pin<Box<dyn Future<Output = Result<Invoice, CryptoBotError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Creates a new cryptocurrency invoice

An invoice is a request for cryptocurrency payment with a specific amount and currency. Once created, the invoice can be paid by any user.

§Arguments
§Returns
  • Ok(Invoice) - The created invoice
  • Err(CryptoBotError) - If validation fails or the request fails
§Errors

This method will return an error if:

  • The parameters are invalid (e.g., negative amount)
  • The currency is not supported
  • The API request fails
  • The exchange rate validation fails (for paid_amount/paid_currency)
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    let params = CreateInvoiceParamsBuilder::new()
        .asset(CryptoCurrencyCode::Ton)
        .amount(dec!(10.5))
        .description("Payment for service")
        .paid_btn_name(PayButtonName::ViewItem)
        .paid_btn_url("https://example.com/order/123")
        .build(&client)
        .await
        .unwrap();
     
    let invoice = client.create_invoice(&params).await?;
    println!("Invoice created: {}", invoice.amount);
     
    Ok(())
}
§See Also
Source§

fn delete_invoice<'life0, 'async_trait>( &'life0 self, invoice_id: u64, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<bool>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Deletes an existing invoice

Once deleted, the invoice becomes invalid and cannot be paid. This is useful for cancelling unpaid invoices.

§Arguments
  • invoice_id - The unique identifier of the invoice to delete
§Returns
  • Ok(true) - If the invoice was successfully deleted
  • Err(CryptoBotError) - If the invoice doesn’t exist or the request fails
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    match client.delete_invoice(12345).await {
        Ok(_) => println!("Invoice deleted successfully"),
        Err(e) => eprintln!("Failed to delete invoice: {}", e),
    }
     
    Ok(())
}
§See Also
Source§

fn get_invoices<'life0, 'life1, 'async_trait>( &'life0 self, params: Option<&'life1 GetInvoicesParams>, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<Vec<Invoice>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Gets a list of invoices with optional filtering

Retrieves all invoices matching the specified filter parameters. If no parameters are provided, returns all invoices.

§Arguments
§Returns
  • Ok(Vec<Invoice>) - List of invoices matching the filter criteria
  • Err(CryptoBotError) - If the parameters are invalid or the request fails
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();

    let params = GetInvoicesParamsBuilder::new()
        .asset(CryptoCurrencyCode::Ton)
        .status(InvoiceStatus::Paid)
        .build()
        .unwrap();

    let invoices = client.get_invoices(Some(&params)).await?;

    for invoice in invoices {
        println!("Invoice #{}: {} {} (paid at: {})",
            invoice.invoice_id,
            invoice.amount,
            invoice.asset.unwrap().to_string(),
            invoice.paid_at.unwrap_or_default()
        );
    }

    Ok(())
}
§See Also
Source§

impl MiscAPI for CryptoBot

Source§

fn get_me<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<GetMeResponse>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Gets basic information about your application

Retrieves information about your application, including app ID, name, and payment processing bot username.

§Returns
  • Ok(GetMeResponse) - Basic information about your application
  • Err(CryptoBotError) - If the request fails
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    let app_info = client.get_me().await?;
    println!("App ID: {}", app_info.app_id);
    println!("App Name: {}", app_info.name);
    println!("Bot Username: {}", app_info.payment_processing_bot_username);
     
    Ok(())
}
§See Also
Source§

fn get_currencies<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<Vec<Currency>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Gets a list of all supported cryptocurrencies

Returns information about all cryptocurrencies supported by CryptoBot, including both crypto and fiat currencies.

§Returns
  • Ok(Vec<Currency>) - List of supported currencies with their properties
  • Err(CryptoBotError) - If the request fails
§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    let currencies = client.get_currencies().await?;
     
    for currency in currencies {
        println!("Currency: {}", currency.name);
        println!("Type: {}", if currency.is_blockchain { "Crypto" }
            else if currency.is_fiat { "Fiat" }
            else { "Stablecoin" });
        println!("Decimals: {}", currency.decimals);
        if let Some(url) = currency.url {
            println!("Website: {}", url);
        }
        println!("---");
    }
     
    Ok(())
}
§See Also
  • Currency - The structure representing a currency
Source§

fn get_stats<'life0, 'life1, 'async_trait>( &'life0 self, params: Option<&'life1 GetStatsParams>, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<AppStats>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Gets application statistics for a specified time period

Retrieves statistics about your application’s usage, including transaction volumes, number of invoices, and user counts.

§Arguments
  • params - Optional parameters to filter statistics by date range. See GetStatsParams for available options.
§Returns
  • Ok(AppStats) - Application statistics for the specified period
  • Err(CryptoBotError) - If the parameters are invalid or the request fails
§Example
use crypto_pay_api::prelude::*;
use chrono::{Utc, Duration};

#[tokio::main]
async fn main() -> Result<(), CryptoBotError> {
    let client = CryptoBot::builder().api_token("YOUR_API_TOKEN").build().unwrap();
     
    // Get stats for the last 7 days
    let end_date = Utc::now();
    let start_date = end_date - Duration::days(7);
     
    let params = GetStatsParamsBuilder::new()
        .start_at(start_date)
        .end_at(end_date)
        .build()
        .unwrap();
     
    let stats = client.get_stats(Some(&params)).await?;
     
    println!("Statistics for the last 7 days:");
    println!("Total volume: {}", stats.volume);
    println!("Number of invoices created: {}", stats.created_invoice_count);
    println!("Number of paid invoices: {}", stats.paid_invoice_count);
    println!("Unique users: {}", stats.unique_users_count);
     
    Ok(())
}
§See Also
  • AppStats - The structure representing application statistics
  • GetStatsParams - Parameters for filtering statistics
Source§

impl TransferAPI for CryptoBot

Source§

fn transfer<'life0, 'life1, 'async_trait>( &'life0 self, params: &'life1 TransferParams, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<Transfer>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Transfer cryptocurrency to a user

§Arguments
  • params - Parameters for the transfer, including:
    • user_id: Telegram user ID
    • asset: Cryptocurrency code (e.g., “TON”, “BTC”)
    • amount: Amount to transfer
    • spend_id: Optional unique ID to ensure idempotence
    • comment: Optional comment for transfer
    • disable_send_notification: Optional flag to disable notification
§Returns

Returns Result containing transfer information or CryptoBotError

§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> CryptoBotResult<()> {
    let client = CryptoBot::builder().api_token("your_token").build()?;

    let params = TransferParamsBuilder::new()
        .user_id(123456789)
        .asset(CryptoCurrencyCode::Ton)
        .amount(dec!(10.5))
        .spend_id("unique_id")
        .comment("Payment for services")
        .build(&client)
        .await?;

    let transfer = client.transfer(&params).await?;
     
    println!("Transfer ID: {}", transfer.transfer_id);
     
    Ok(())
}
§See also
Source§

fn get_transfers<'life0, 'life1, 'async_trait>( &'life0 self, params: Option<&'life1 GetTransfersParams>, ) -> Pin<Box<dyn Future<Output = CryptoBotResult<Vec<Transfer>>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Get transfers history

§Arguments
  • params - Optional parameters to filter transfers:
    • asset: Filter by cryptocurrency code
    • transfer_ids: List of specific transfer IDs to retrieve
    • spend_id: Unique ID to filter transfers by spend ID
    • offset: Number of records to skip (for pagination)
    • count: Maximum number of records to return (1-1000)
§Returns

Returns Result containing a vector of transfers or CryptoBotError

§Example
use crypto_pay_api::prelude::*;

#[tokio::main]
async fn main() -> CryptoBotResult<()> {
    let client = CryptoBot::builder().api_token("your_token").build()?;

    // Get all transfers
    let all_transfers = client.get_transfers(None).await?;

    // Get filtered transfers
    let params = GetTransfersParamsBuilder::new()
        .asset(CryptoCurrencyCode::Ton)
        .transfer_ids(vec![1, 2, 3])
        .count(10)
        .build()?;

    let filtered_transfers = client.get_transfers(Some(&params)).await?;

    Ok(())
}
§See also

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more