Skip to main content

Crate simploxide_client

Crate simploxide_client 

Source
Expand description

For first-time users, it’s recommended to get hands-on experience by running some example bots on GitHub before writing their own.

This SDK is intended to be used with the tokio runtime. Here are the steps to implement any bot:

§1. Choose a backend

simploxide supports both WebSocket and FFI SimpleX-Chat backends. All FFI-exclusive methods are reimplemented in native Rust, so in practice the backends differ only in their runtime characteristics: a single-process app via FFI vs. an app that connects to a running SimpleX-Chat WebSocket server.

Since both backends are equally capable, always start development with the WebSocket backend (enabled by default). Switching to FFI later is as simple as replacing ws imports with ffi imports, but FFI requires configuring the crate build and obliges you to use the AGPL-3.0 license. You can read more about switching to FFI in the simploxide-sxcrt-sys crate docs.

§2. Initialise the bot

simploxide provides convenient bot builders to launch and configure your bot.

let (bot, events, mut cli) = ws::BotBuilder::new("YesMan", 5225)
    .db_prefix("db/bot")
    // Create a public bot address that auto-accepts new users with a welcome message.
    .auto_accept_with(
        "Hello, I'm a bot that always agrees with my users",
    )
    // Launch the CLI, connect the client, and initialise the bot.
    .launch()
    .await?;

let address = bot.address().await?;
println!("My address: {address}");

See all available options in ws::BotBuilder and ffi::BotBuilder.

§3. Set up an event dispatcher

Dispatchers are zero-cost and provide a convenient API for handling events.

// into_dispatcher accepts any type and creates a dispatcher from the event stream.
// The value provided here is passed into all event handlers as a second argument.
events.into_dispatcher(bot)
    .on(new_messages)
    .dispatch()
    .await?;

Learn more about dispatchers in the dispatcher and EventStream docs.

§4. Implement event handlers

The first handler argument determines which event the handler processes. The StreamEvents type allows interrupting event dispatching via StreamEvents::Break.

async fn new_msgs(ev: Arc<NewChatItems>, bot: Bot) -> ws::ClientResult<StreamEvents> {
    for (chat, msg, content) in ev.filter_messages() {
        bot.update_msg_reaction(chat, msg, Reaction::Set("👍")).await?;

        bot.send_msg(chat, "I absolutely agree with this!".bold())
           .reply_to(msg)
           .await?;
    }

    Ok(StreamEvents::Continue)
}

Message builders are quite powerful, see messages for details. In most places where an ID is expected you can pass a struct directly; see the type-safe conversions available in id.

§5. Execute cleanup before exiting

bot.shutdown().await;
cli.kill().await?;

§Features

simploxide strives to be a minimal library for simple bots while also coming with batteries included for all sorts of the advanced use cases. The balance is maintained through feature gates documented below:

  • cli (default): WebSocket backend (ws) with a built-in runner that spawns and manages a local simplex-chat process. Use ws::BotBuilder::launch to start everything in one call.

  • websocket: WebSocket backend (ws) without the CLI runner. Use ws::BotBuilder::connect to attach to an already-running simplex-chat server.

  • ffi: FFI backend (ffi) that embeds the SimpleX-Chat library in-process. Requires AGPL-3.0 and additional build configuration; see simploxide-sxcrt-sys.

  • native_crypto: Native Rust implementation of client-side encryption(XSalsa20 + Poly1305). Enables ImagePreview::from_crypto_file and crypto::fs module allowing to encrypt decrypt files directly in the Rust code

  • multimedia: Image transcoding via the image crate. Enables preview::transcoder::Transcoder and automatic thumbnail generation for messages::Image. preview::ImagePreview automatically tries to transcode its sources to JPEGs with this feature on

  • xftp: XFTP file transfer support. Enables xftp::XftpClient, which intercepts streamlines file downlaods with a download_file method.

  • cancellation: Re-exports tokio_util::sync::CancellationToken and enables helper methods for cooperative shutdown.

  • crypto: Low-level cryptographic primitives (zeroize, rand). Pulled in automatically by native_crypto. Useful on its own if you wish to use your own crypto implementation.

  • fullcli: Convenience bundle: cli + native_crypto + multimedia + xftp + cancellation.

  • fullffi: Convenience bundle: ffi + native_crypto + multimedia + xftp + cancellation.

§How to work with this documentation?

The bot page should be your primary reference and the events page your secondary one. From these two pages you should be able to find everything in a structured manner.

Re-exports§

pub use dispatcher::DispatchChain;
pub use simploxide_api_types as types;
pub use tokio_util;cancellation

Modules§

bot
client_api
commands
cryptocrypto
dispatcher
Zero-cost type-safe event dispatchers handling events mostly at compile time(event matching logic should reduce to a jump table used in a loop, the implementation doesn’t use runtime maps or virtual calls giving the compiler full information required to do optimizations). See DispatchChain for a quick start
events
ext
ffiffi
FFI backend that embeds the SimpleX-Chat library in-process via native Rust bindings.
id
Type-safe wrappers for SimpleX Chat integer IDs and conversions from API structs.
messages
Message builders.
preferences
Syntactic sugar for constructing Preferences values.
prelude
Re-exports everything that is needed to send commands, match events and destructure responses
preview
Image previews generation
responses
wswebsocket
WebSocket backend that connects to a simplex-chat WebSocket server.
xftpxftp
XFTP file download manager.

Structs§

CancellationTokencancellation
A token which can be used to signal a cancellation request to one or more tasks.
EventStream
The high level event stream that embeds event filtering.

Enums§

BadResponseError
Event
EventKind
Filter
StreamEvents

Traits§

ClientApi
ClientApiError
CommandSyntax
EventParser
A helper trait meant to be implemented by raw event types
Hook