teloxide-fork 0.20.0

An elegant Telegram bots framework for Rust
Documentation
//! Support for user dialogues.
//!
//! The main type is (surprise!) [`Dialogue`]. Under the hood, it is just a
//! wrapper over [`Storage`] and a [`DialogueKey`]. It provides convenient
//! method for manipulating the dialogue state. [`Storage`] is where all
//! dialogue states are stored; it can be either [`InMemStorage`], which is a
//! simple hash map from [`std::collections`], or an advanced database wrapper
//! such as [`SqliteStorage`]. In the latter case, your dialogues are
//! _persistent_, meaning that you can safely restart your bot and all ongoing
//! dialogues will remain in the database -- this is a preferred method for
//! production bots.
//!
//! [`examples/dialogue.rs`] clearly demonstrates the typical usage of
//! dialogues. Your dialogue state can be represented as an enumeration:
//!
//! ```no_run
//! #[derive(Clone, Default)]
//! pub enum State {
//!     #[default]
//!     Start,
//!     ReceiveFullName,
//!     ReceiveAge {
//!         full_name: String,
//!     },
//!     ReceiveLocation {
//!         full_name: String,
//!         age: u8,
//!     },
//! }
//! ```
//!
//! Each state is associated with its respective handler: e.g., when a dialogue
//! state is `ReceiveAge`, `receive_age` is invoked:
//!
//! ```no_run
//! # use teloxide::{dispatching::dialogue::InMemStorage, prelude::*};
//! # type MyDialogue = Dialogue<State, InMemStorage<State>>;
//! # type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
//! # #[derive(Clone, Debug)] enum State { ReceiveLocation { full_name: String, age: u8 } }
//! async fn receive_age(
//!     bot: Bot,
//!     dialogue: MyDialogue,
//!     full_name: String, // Available from `State::ReceiveAge`.
//!     msg: Message,
//! ) -> HandlerResult {
//!     match msg.text().map(|text| text.parse::<u8>()) {
//!         Some(Ok(age)) => {
//!             bot.send_message("What's your location?").chat_id(msg.chat.id).await?;
//!             dialogue.update(State::ReceiveLocation { full_name, age }).await?;
//!         }
//!         _ => {
//!             bot.send_message("Send me a number.").chat_id(msg.chat.id).await?;
//!         }
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! Variant's fields are passed to state handlers as single arguments like
//! `full_name: String` or tuples in case of two or more variant parameters (see
//! below). Using [`Dialogue::update`], you can update the dialogue with a new
//! state, in our case -- `State::ReceiveLocation { full_name, age }`. To exit
//! the dialogue, just call [`Dialogue::exit`] and it will be removed from the
//! underlying storage:
//!
//! ```no_run
//! # use teloxide::{dispatching::dialogue::InMemStorage, prelude::*};
//! # type MyDialogue = Dialogue<State, InMemStorage<State>>;
//! # type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
//! # #[derive(Clone, Debug)] enum State {}
//! async fn receive_location(
//!     bot: Bot,
//!     dialogue: MyDialogue,
//!     (full_name, age): (String, u8), // Available from `State::ReceiveLocation`.
//!     msg: Message,
//! ) -> HandlerResult {
//!     match msg.text() {
//!         Some(location) => {
//!             let message =
//!                 format!("Full name: {}\nAge: {}\nLocation: {}", full_name, age, location);
//!             bot.send_message(message).chat_id(msg.chat.id).await?;
//!             dialogue.exit().await?;
//!         }
//!         None => {
//!             bot.send_message("Send me a text message.").chat_id(msg.chat.id).await?;
//!         }
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! [`examples/dialogue.rs`]: https://github.com/teloxide/teloxide/blob/master/crates/teloxide/examples/dialogue.rs

#[cfg(feature = "redis-storage")]
pub use self::{RedisStorage, RedisStorageError};

#[cfg(any(feature = "sqlite-storage-nativetls", feature = "sqlite-storage-rustls"))]
pub use self::{SqliteStorage, SqliteStorageError};

#[cfg(any(feature = "postgres-storage-nativetls", feature = "postgres-storage-rustls"))]
pub use self::{PostgresStorage, PostgresStorageError};

pub use get_chat_id::GetChatId;
pub use key::DialogueKey;
pub use storage::*;

use dptree::Handler;
use teloxide_core::types::ChatId;

use std::{fmt::Debug, marker::PhantomData, sync::Arc};

use super::DpHandlerDescription;

mod get_chat_id;
mod key;
mod storage;

const TELOXIDE_DIALOGUE_BEHAVIOUR: &str = "TELOXIDE_DIALOGUE_BEHAVIOUR";

/// A handle for controlling dialogue state.
#[derive(Debug)]
pub struct Dialogue<D, S>
where
    S: ?Sized,
{
    storage: Arc<S>,
    key: DialogueKey,
    _phantom: PhantomData<D>,
}

// `#[derive]` requires generics to implement `Clone`, but `S` is wrapped around
// `Arc`, and `D` is wrapped around PhantomData.
impl<D, S> Clone for Dialogue<D, S>
where
    S: ?Sized,
{
    fn clone(&self) -> Self {
        Dialogue { storage: self.storage.clone(), key: self.key.clone(), _phantom: PhantomData }
    }
}

impl<D, S> Dialogue<D, S>
where
    D: Send + 'static,
    S: Storage<D> + ?Sized,
{
    /// Constructs a new dialogue with `storage` (where dialogues are stored)
    /// and its key. A plain `ChatId` selects the dialogue outside business
    /// connections.
    #[must_use]
    pub fn new(storage: Arc<S>, key: impl Into<DialogueKey>) -> Self {
        Self { storage, key: key.into(), _phantom: PhantomData }
    }

    /// Returns a chat ID associated with this dialogue.
    #[must_use]
    pub fn chat_id(&self) -> ChatId {
        self.key.chat_id
    }

    /// Returns the full key, including the business connection, if any.
    #[must_use]
    pub fn key(&self) -> &DialogueKey {
        &self.key
    }

    /// Retrieves the current state of the dialogue or `None` if there is no
    /// dialogue.
    pub async fn get(&self) -> Result<Option<D>, S::Error> {
        self.storage.clone().get_dialogue(self.key.clone()).await
    }

    /// Like [`Dialogue::get`] but returns a default value if there is no
    /// dialogue.
    pub async fn get_or_default(&self) -> Result<D, S::Error>
    where
        D: Default,
    {
        self.storage.clone().get_or_insert_dialogue(self.key.clone(), D::default, false).await
    }

    /// Updates the dialogue state.
    ///
    /// The dialogue type `D` must implement `From<State>` to allow implicit
    /// conversion from `State` to `D`.
    pub async fn update<State>(&self, state: State) -> Result<(), S::Error>
    where
        D: From<State>,
    {
        let new_dialogue = state.into();
        self.storage.clone().update_dialogue(self.key.clone(), new_dialogue).await?;
        Ok(())
    }

    /// Updates the dialogue with a default value.
    pub async fn reset(&self) -> Result<(), S::Error>
    where
        D: Default,
    {
        self.update(D::default()).await
    }

    /// Removes the dialogue from the storage provided to [`Dialogue::new`].
    pub async fn exit(&self) -> Result<(), S::Error> {
        self.storage.clone().remove_dialogue(self.key.clone()).await
    }
}

/// Enters a dialogue context.
///
/// With `TELOXIDE_DIALOGUE_BEHAVIOUR=default`, an unreadable serialized state
/// is replaced with the default (for example, after a state enum changes).
/// Other storage errors are logged and skip the dialogue handler, just as with
/// the unset variable or the legacy `panic` setting.
///
/// A call to this function is the same as `dptree::entry().enter_dialogue()`.
///
/// See [`HandlerExt::enter_dialogue`].
///
/// ## Dependency requirements
///
///  - `Arc<S>`
///  - `Upd`
///
/// [`HandlerExt::enter_dialogue`]: super::HandlerExt::enter_dialogue
#[must_use]
pub fn enter<Upd, S, D, Output>() -> Handler<'static, Output, DpHandlerDescription>
where
    S: Storage<D> + ?Sized + Send + Sync + 'static,
    <S as Storage<D>>::Error: Debug + Send,
    D: Default + Clone + Send + Sync + 'static,
    Upd: GetChatId + Clone + Send + Sync + 'static,
    Output: Send + Sync + 'static,
{
    dptree::filter_map(|storage: Arc<S>, upd: Upd| {
        Some(Dialogue::new(storage, upd.dialogue_key()?))
    })
    .filter_map_async(|dialogue: Dialogue<D, S>| async move {
        let behaviour = std::env::var(TELOXIDE_DIALOGUE_BEHAVIOUR);
        let reset_incompatible = behaviour.as_deref() == Ok("default");
        match dialogue
            .storage
            .get_or_insert_dialogue(dialogue.key, D::default, reset_incompatible)
            .await
        {
            Ok(state) => Some(state),
            Err(err) => {
                if !matches!(behaviour.as_deref(), Ok("default" | "panic") | Err(_)) {
                    panic!("`TELOXIDE_DIALOGUE_BEHAVIOUR` should be one of: default/panic");
                }
                log::error!("could not load dialogue state: {err:?}");
                None
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct State(usize);

    static DEFAULTS: AtomicUsize = AtomicUsize::new(0);

    impl Default for State {
        fn default() -> Self {
            Self(DEFAULTS.fetch_add(1, Ordering::Relaxed))
        }
    }

    #[tokio::test]
    async fn concurrent_get_or_default_returns_the_stored_state() {
        let dialogue = Dialogue::new(InMemStorage::new(), ChatId(42));
        let (one, two) = tokio::join!(dialogue.get_or_default(), dialogue.get_or_default());
        assert_eq!(one.unwrap(), State(0));
        assert_eq!(two.unwrap(), State(0));
        assert_eq!(dialogue.get().await.unwrap(), Some(State(0)));
        assert_eq!(DEFAULTS.load(Ordering::Relaxed), 1);
    }
}