Skip to main content

Crate ferogram

Crate ferogram 

Source
Expand description

Async Rust client for the Telegram MTProto API.

ferogram talks to Telegram directly over MTProto with no Bot API proxy. It works for both bots and user accounts. Most things you’d want to do with Telegram are already covered. If something isn’t, you can always drop down to client.invoke() and call any TL function directly.

Still in development but already covers major use cases for production. Check the CHANGELOG before upgrading.

§Quick start: bot

use ferogram::{Client, update::Update};

const API_ID: i32 = 0; // from https://my.telegram.org
const API_HASH: &str = ""; // from https://my.telegram.org

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let (client, _) = Client::quick_connect("bot.session", API_ID, API_HASH).await?;

    let mut stream = client.stream_updates();
    while let Some(upd) = stream.next().await {
        if let Update::NewMessage(msg) = upd {
            if !msg.outgoing() {
                msg.reply(msg.text().unwrap_or_default()).await.ok();
            }
        }
    }
    Ok(())
}

§Quick start: user account

use ferogram::Client;

const API_ID: i32 = 0; // from https://my.telegram.org
const API_HASH: &str = ""; // from https://my.telegram.org

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let (client, _) = Client::quick_connect("my.session", API_ID, API_HASH).await?;

    client.send_message("me", "Hello from ferogram!").await?;
    Ok(())
}

§Dispatcher and filters

use ferogram::filters::{Dispatcher, command, private, text_contains};

let mut dp = Dispatcher::new();

dp.on_message(command("start"), |msg| async move {
    msg.reply("Hello!").await.ok();
});

dp.on_message(private() & text_contains("help"), |msg| async move {
    msg.reply("Type /start to begin.").await.ok();
});

while let Some(upd) = stream.next().await {
    dp.dispatch(upd).await;
}

Filters compose with &, |, !. Built-ins: command, private, group, channel, text, media, photo, forwarded, reply, album, regex, and more.

§FSM

use std::sync::Arc;

#[derive(FsmState, Clone, Debug, PartialEq)]
enum Form { Name, Age }

dp.with_state_storage(Arc::new(MemoryStorage::new()));

dp.on_message_fsm(text(), Form::Name, |msg, state| async move {
    state.set_data("name", msg.text().unwrap()).await.ok();
    state.transition(Form::Age).await.ok();
    msg.reply("How old are you?").await.ok();
});

§Raw API

If something isn’t wrapped yet, you can call any Layer 225 TL function directly:

use ferogram::tl;

let req = tl::functions::messages::SendMessage {
    peer: peer.into(),
    message: "Hello!".into(),
    random_id: ferogram::random_i64_pub(),
    ..Default::default()
};
client.invoke(&req).await?;

§Session backends

Binary file by default. Switch to SQLite, libSQL, or a base64 string with a feature flag. Bring your own backend by implementing SessionBackend.

// Portable string session, useful for serverless or env-var setups
let s = client.export_session_string().await?;
let (client, _) = Client::builder().session_string(s).connect().await?;

§Features

Most common use cases are already covered. Full list in FEATURES.md.

If something’s missing, feel free to open a feature request or PR. Check the contributing guidelines first.

§Community

Re-exports§

pub use media::DownloadIter;
pub use builder::BuilderError;
pub use builder::ClientBuilder;
pub use guest_chat::GuestChatQuery;
pub use keyboard::Button;
pub use keyboard::InlineKeyboard;
pub use keyboard::ReplyKeyboard;
pub use media::Document;
pub use media::Downloadable;
pub use media::Photo;
pub use media::Sticker;
pub use media::UploadedFile;
pub use participants::Participant;
pub use participants::ParticipantStatus;
pub use participants::ProfilePhotoIter;
pub use peer_ext::OptionPeerExt;
pub use peer_ext::PeerExt;
pub use peer_ref::PeerRef;
pub use poll::PollBuilder;
pub use search::GlobalSearchBuilder;
pub use search::SearchBuilder;
pub use types::ChannelKind;
pub use types::Channel;
pub use types::Chat;
pub use types::Group;
pub use types::User;
pub use typing_guard::TypingGuard;
pub use update::BotStoppedUpdate;
pub use update::MessageReactionUpdate;
pub use update::PollVoteUpdate;
pub use update::ButtonFilter;
pub use update::Update;
pub use update::ChatActionUpdate;
pub use update::JoinRequestUpdate;
pub use update::ParticipantUpdate;
pub use update::UserStatusUpdate;
pub use update::ChatBoostUpdate;
pub use update::PreCheckoutQueryUpdate;
pub use update::ShippingQueryUpdate;
pub use update_config::OverflowStrategy;
pub use update_config::UpdateConfig;
pub use ferogram_tl_types as tl;
pub use ferogram_mtproto as mtproto;
pub use ferogram_crypto as crypto;
pub use ferogram_tl_parser as parser;parser
pub use ferogram_tl_gen as codegen;codegen

Modules§

authentication
MTProto authentication key generation (DH handshake steps).
builder
cdn_download
Telegram CDN DC file downloads.
conversation
dc_migration
dc_pool
dns_resolver
DNS-over-HTTPS resolver.
filters
fsm
guest_chat
inline_iter
keyboard
macros
media
message_box
middleware
parsers
participants
peer_ext
peer_ref
persist
poll
proxy
reactions
search
session_backend
socks5
special_config
Firebase / Google special-config fallback.
transport_intermediate
transport_obfuscated
types
typing_guard
update
update_config
Configuration for user-facing update buffering.
util

Macros§

dispatch

Structs§

AuthKey
A Telegram authorization key (256 bytes) plus pre-computed identifiers.
AutoSleep
Automatically sleep on FLOOD_WAIT and retry once on transient I/O errors.
BinaryFileBackend
Stores the session in a compact binary file (v2 format).
CircuitBreaker
A RetryPolicy that stops retrying after threshold consecutive failures and stays silent for a cooldown window before resetting.
Client
The main Telegram client. Cheap to clone: internally Arc-wrapped.
Config
Configuration for Client::connect.
DcEntry
One entry in the DC address table.
DcFlags
Per-DC option flags.
Dialog
A Telegram dialog (chat, user, channel).
DialogIter
Cursor-based iterator over dialogs. Created by Client::iter_dialogs.
ExperimentalFeatures
Opt-in experimental behaviours that deviate from strict Telegram spec.
ExponentialBackoff
Exponential backoff with jitter.
Finished
The final output of a successful auth key handshake.
FixedInterval
ForwardOptions
Options for forwarding messages.
InMemoryBackend
Ephemeral in-process session: nothing persisted to disk.
InputMessage
Builder for composing outgoing messages.
InvoiceOptions
Groups all invoice parameters for crate::Client::send_invoice.
LoginToken
Opaque token returned by crate::Client::request_login_code.
MessageIter
Cursor-based iterator over message history. Created by Client::iter_messages.
MiniAppSession
An active mini-app session returned by Client::open_mini_app.
MtProxyConfig
Decoded MTProxy configuration.
NeverRestart
NoRetries
Never retry: propagate every error immediately.
PasswordToken
Opaque 2FA challenge token returned in SignInError::PasswordRequired.
PeerCache
All fields are pub so that save_session / connect can read/write them directly, and so that advanced callers can inspect the cache.
RetryContext
Context passed to RetryPolicy::should_retry on each failure.
RpcError
An error returned by Telegram’s servers in response to an RPC call.
SetProfileBuilder
Builder returned by Client::set_profile.
Socks5Config
SOCKS5 proxy configuration.
SqliteBackendsqlite-session
SQLite-backed session (via rusqlite).
StringSessionBackend
Portable base64 string session backend.
UpdateStream
Asynchronous stream of [Update]s.

Enums§

ChannelStats
Return type of Client::stats.
InvocationError
The error type returned from any Client method that talks to Telegram.
LinkKind
Selects which flavour of message link [Client::export_message_link] should produce.
MiniApp
Which kind of mini-app to open.
PeerType
Caches access hashes for users and channels so every API call carries the correct hash without re-resolving peers. Discriminates the kind of peer stored in PeerCache::username_to_peer.
QuickConnectError
Errors returned by Client::quick_connect.
SignInError
Errors returned by crate::Client::sign_in.
TransportKind
Which MTProto wire framing to use for a connection.
UpdateStateChange
A single update-sequence change, applied via SessionBackend::apply_update_state.

Constants§

LAYER
The API layer this code was generated from.

Traits§

ConnectionRestartPolicy
FsmState
A type that can be used as an FSM state.
Identifiable
Every generated type has a unique 32-bit constructor ID.
RetryPolicy
Controls how the client reacts when an RPC call fails.
Serializable
SessionBackend
Synchronous snapshot backend: saves and loads the full session at once.

Functions§

finish
Finalise the handshake.
random_i64_pub
step1
Generate a req_pq_multi request. Returns the request + opaque state.
step2
Process ResPQ and generate req_DH_params.
step3
Process ServerDhParams into a reusable DhParamsForRetry + send the first set_client_DH_params request.

Type Aliases§

ShutdownToken
A token that can be used to gracefully shut down a Client.