Skip to main content

teloxide/dispatching/
dialogue.rs

1//! Support for user dialogues.
2//!
3//! The main type is (surprise!) [`Dialogue`]. Under the hood, it is just a
4//! wrapper over [`Storage`] and a [`DialogueKey`]. It provides convenient
5//! method for manipulating the dialogue state. [`Storage`] is where all
6//! dialogue states are stored; it can be either [`InMemStorage`], which is a
7//! simple hash map from [`std::collections`], or an advanced database wrapper
8//! such as [`SqliteStorage`]. In the latter case, your dialogues are
9//! _persistent_, meaning that you can safely restart your bot and all ongoing
10//! dialogues will remain in the database -- this is a preferred method for
11//! production bots.
12//!
13//! [`examples/dialogue.rs`] clearly demonstrates the typical usage of
14//! dialogues. Your dialogue state can be represented as an enumeration:
15//!
16//! ```no_run
17//! #[derive(Clone, Default)]
18//! pub enum State {
19//!     #[default]
20//!     Start,
21//!     ReceiveFullName,
22//!     ReceiveAge {
23//!         full_name: String,
24//!     },
25//!     ReceiveLocation {
26//!         full_name: String,
27//!         age: u8,
28//!     },
29//! }
30//! ```
31//!
32//! Each state is associated with its respective handler: e.g., when a dialogue
33//! state is `ReceiveAge`, `receive_age` is invoked:
34//!
35//! ```no_run
36//! # use teloxide::{dispatching::dialogue::InMemStorage, prelude::*};
37//! # type MyDialogue = Dialogue<State, InMemStorage<State>>;
38//! # type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
39//! # #[derive(Clone, Debug)] enum State { ReceiveLocation { full_name: String, age: u8 } }
40//! async fn receive_age(
41//!     bot: Bot,
42//!     dialogue: MyDialogue,
43//!     full_name: String, // Available from `State::ReceiveAge`.
44//!     msg: Message,
45//! ) -> HandlerResult {
46//!     match msg.text().map(|text| text.parse::<u8>()) {
47//!         Some(Ok(age)) => {
48//!             bot.send_message("What's your location?").chat_id(msg.chat.id).await?;
49//!             dialogue.update(State::ReceiveLocation { full_name, age }).await?;
50//!         }
51//!         _ => {
52//!             bot.send_message("Send me a number.").chat_id(msg.chat.id).await?;
53//!         }
54//!     }
55//!
56//!     Ok(())
57//! }
58//! ```
59//!
60//! Variant's fields are passed to state handlers as single arguments like
61//! `full_name: String` or tuples in case of two or more variant parameters (see
62//! below). Using [`Dialogue::update`], you can update the dialogue with a new
63//! state, in our case -- `State::ReceiveLocation { full_name, age }`. To exit
64//! the dialogue, just call [`Dialogue::exit`] and it will be removed from the
65//! underlying storage:
66//!
67//! ```no_run
68//! # use teloxide::{dispatching::dialogue::InMemStorage, prelude::*};
69//! # type MyDialogue = Dialogue<State, InMemStorage<State>>;
70//! # type HandlerResult = Result<(), Box<dyn std::error::Error + Send + Sync>>;
71//! # #[derive(Clone, Debug)] enum State {}
72//! async fn receive_location(
73//!     bot: Bot,
74//!     dialogue: MyDialogue,
75//!     (full_name, age): (String, u8), // Available from `State::ReceiveLocation`.
76//!     msg: Message,
77//! ) -> HandlerResult {
78//!     match msg.text() {
79//!         Some(location) => {
80//!             let message =
81//!                 format!("Full name: {}\nAge: {}\nLocation: {}", full_name, age, location);
82//!             bot.send_message(message).chat_id(msg.chat.id).await?;
83//!             dialogue.exit().await?;
84//!         }
85//!         None => {
86//!             bot.send_message("Send me a text message.").chat_id(msg.chat.id).await?;
87//!         }
88//!     }
89//!
90//!     Ok(())
91//! }
92//! ```
93//!
94//! [`examples/dialogue.rs`]: https://github.com/teloxide/teloxide/blob/master/crates/teloxide/examples/dialogue.rs
95
96#[cfg(feature = "redis-storage")]
97pub use self::{RedisStorage, RedisStorageError};
98
99#[cfg(any(feature = "sqlite-storage-nativetls", feature = "sqlite-storage-rustls"))]
100pub use self::{SqliteStorage, SqliteStorageError};
101
102#[cfg(any(feature = "postgres-storage-nativetls", feature = "postgres-storage-rustls"))]
103pub use self::{PostgresStorage, PostgresStorageError};
104
105pub use get_chat_id::GetChatId;
106pub use key::DialogueKey;
107pub use storage::*;
108
109use dptree::Handler;
110use teloxide_core::types::ChatId;
111
112use std::{fmt::Debug, marker::PhantomData, sync::Arc};
113
114use super::DpHandlerDescription;
115
116mod get_chat_id;
117mod key;
118mod storage;
119
120const TELOXIDE_DIALOGUE_BEHAVIOUR: &str = "TELOXIDE_DIALOGUE_BEHAVIOUR";
121
122/// A handle for controlling dialogue state.
123#[derive(Debug)]
124pub struct Dialogue<D, S>
125where
126    S: ?Sized,
127{
128    storage: Arc<S>,
129    key: DialogueKey,
130    _phantom: PhantomData<D>,
131}
132
133// `#[derive]` requires generics to implement `Clone`, but `S` is wrapped around
134// `Arc`, and `D` is wrapped around PhantomData.
135impl<D, S> Clone for Dialogue<D, S>
136where
137    S: ?Sized,
138{
139    fn clone(&self) -> Self {
140        Dialogue { storage: self.storage.clone(), key: self.key.clone(), _phantom: PhantomData }
141    }
142}
143
144impl<D, S> Dialogue<D, S>
145where
146    D: Send + 'static,
147    S: Storage<D> + ?Sized,
148{
149    /// Constructs a new dialogue with `storage` (where dialogues are stored)
150    /// and its key. A plain `ChatId` selects the dialogue outside business
151    /// connections.
152    #[must_use]
153    pub fn new(storage: Arc<S>, key: impl Into<DialogueKey>) -> Self {
154        Self { storage, key: key.into(), _phantom: PhantomData }
155    }
156
157    /// Returns a chat ID associated with this dialogue.
158    #[must_use]
159    pub fn chat_id(&self) -> ChatId {
160        self.key.chat_id
161    }
162
163    /// Returns the full key, including the business connection, if any.
164    #[must_use]
165    pub fn key(&self) -> &DialogueKey {
166        &self.key
167    }
168
169    /// Retrieves the current state of the dialogue or `None` if there is no
170    /// dialogue.
171    pub async fn get(&self) -> Result<Option<D>, S::Error> {
172        self.storage.clone().get_dialogue(self.key.clone()).await
173    }
174
175    /// Like [`Dialogue::get`] but returns a default value if there is no
176    /// dialogue.
177    pub async fn get_or_default(&self) -> Result<D, S::Error>
178    where
179        D: Default,
180    {
181        self.storage.clone().get_or_insert_dialogue(self.key.clone(), D::default, false).await
182    }
183
184    /// Updates the dialogue state.
185    ///
186    /// The dialogue type `D` must implement `From<State>` to allow implicit
187    /// conversion from `State` to `D`.
188    pub async fn update<State>(&self, state: State) -> Result<(), S::Error>
189    where
190        D: From<State>,
191    {
192        let new_dialogue = state.into();
193        self.storage.clone().update_dialogue(self.key.clone(), new_dialogue).await?;
194        Ok(())
195    }
196
197    /// Updates the dialogue with a default value.
198    pub async fn reset(&self) -> Result<(), S::Error>
199    where
200        D: Default,
201    {
202        self.update(D::default()).await
203    }
204
205    /// Removes the dialogue from the storage provided to [`Dialogue::new`].
206    pub async fn exit(&self) -> Result<(), S::Error> {
207        self.storage.clone().remove_dialogue(self.key.clone()).await
208    }
209}
210
211/// Enters a dialogue context.
212///
213/// With `TELOXIDE_DIALOGUE_BEHAVIOUR=default`, an unreadable serialized state
214/// is replaced with the default (for example, after a state enum changes).
215/// Other storage errors are logged and skip the dialogue handler, just as with
216/// the unset variable or the legacy `panic` setting.
217///
218/// A call to this function is the same as `dptree::entry().enter_dialogue()`.
219///
220/// See [`HandlerExt::enter_dialogue`].
221///
222/// ## Dependency requirements
223///
224///  - `Arc<S>`
225///  - `Upd`
226///
227/// [`HandlerExt::enter_dialogue`]: super::HandlerExt::enter_dialogue
228#[must_use]
229pub fn enter<Upd, S, D, Output>() -> Handler<'static, Output, DpHandlerDescription>
230where
231    S: Storage<D> + ?Sized + Send + Sync + 'static,
232    <S as Storage<D>>::Error: Debug + Send,
233    D: Default + Clone + Send + Sync + 'static,
234    Upd: GetChatId + Clone + Send + Sync + 'static,
235    Output: Send + Sync + 'static,
236{
237    dptree::filter_map(|storage: Arc<S>, upd: Upd| {
238        Some(Dialogue::new(storage, upd.dialogue_key()?))
239    })
240    .filter_map_async(|dialogue: Dialogue<D, S>| async move {
241        let behaviour = std::env::var(TELOXIDE_DIALOGUE_BEHAVIOUR);
242        let reset_incompatible = behaviour.as_deref() == Ok("default");
243        match dialogue
244            .storage
245            .get_or_insert_dialogue(dialogue.key, D::default, reset_incompatible)
246            .await
247        {
248            Ok(state) => Some(state),
249            Err(err) => {
250                if !matches!(behaviour.as_deref(), Ok("default" | "panic") | Err(_)) {
251                    panic!("`TELOXIDE_DIALOGUE_BEHAVIOUR` should be one of: default/panic");
252                }
253                log::error!("could not load dialogue state: {err:?}");
254                None
255            }
256        }
257    })
258}
259
260#[cfg(test)]
261mod tests {
262    use std::sync::atomic::{AtomicUsize, Ordering};
263
264    use super::*;
265
266    #[derive(Clone, Debug, PartialEq, Eq)]
267    struct State(usize);
268
269    static DEFAULTS: AtomicUsize = AtomicUsize::new(0);
270
271    impl Default for State {
272        fn default() -> Self {
273            Self(DEFAULTS.fetch_add(1, Ordering::Relaxed))
274        }
275    }
276
277    #[tokio::test]
278    async fn concurrent_get_or_default_returns_the_stored_state() {
279        let dialogue = Dialogue::new(InMemStorage::new(), ChatId(42));
280        let (one, two) = tokio::join!(dialogue.get_or_default(), dialogue.get_or_default());
281        assert_eq!(one.unwrap(), State(0));
282        assert_eq!(two.unwrap(), State(0));
283        assert_eq!(dialogue.get().await.unwrap(), Some(State(0)));
284        assert_eq!(DEFAULTS.load(Ordering::Relaxed), 1);
285    }
286}