Skip to main content

teloxide/dispatching/
handler_ext.rs

1use crate::{
2    dispatching::{
3        dialogue::{GetChatId, Storage},
4        DpHandlerDescription,
5    },
6    types::{BotFullInfo, Message},
7    utils::command::BotCommands,
8};
9use dptree::Handler;
10
11use std::fmt::Debug;
12
13/// Extension methods for working with `dptree` handlers.
14pub trait HandlerExt<Output> {
15    /// Returns a handler that accepts a parsed command `C`.
16    ///
17    /// ## Dependency requirements
18    ///
19    ///  - [`crate::types::Message`]
20    ///  - [`crate::types::BotFullInfo`]
21    #[must_use]
22    fn filter_command<C>(self) -> Self
23    where
24        C: BotCommands + Send + Sync + 'static;
25
26    /// Returns a handler that accepts a parsed command `C` if the command
27    /// contains a bot mention, for example `/start@my_bot`.
28    ///
29    /// ## Dependency requirements
30    ///
31    ///  - [`crate::types::Message`]
32    ///  - [`crate::types::BotFullInfo`]
33    #[must_use]
34    fn filter_mention_command<C>(self) -> Self
35    where
36        C: BotCommands + Send + Sync + 'static;
37
38    /// Passes [`Dialogue<D, S>`] and `D` as handler dependencies.
39    ///
40    /// It does so by the following steps:
41    ///
42    ///  1. If an incoming update has no chat ID ([`GetChatId::chat_id`] returns
43    ///     `None`), the rest of the chain will not be executed. Otherwise,
44    ///     passes `Dialogue::new(storage, chat_id)` forwards.
45    ///  2. If [`Dialogue::get_or_default`] on the passed dialogue returns `Ok`,
46    ///     passes the dialogue state forwards. Otherwise, logs an error and the
47    ///     rest of the chain is not executed.
48    ///
49    /// If `TELOXIDE_DIALOGUE_BEHAVIOUR` environmental variable exists and is
50    /// equal to "default", this function will not panic if it can't get the
51    /// dialogue (if, for example, the state enum was updated). Setting the
52    /// value to "panic" will return the initial behaviour.
53    ///
54    /// ## Dependency requirements
55    ///
56    ///  - `Arc<S>`
57    ///  - `Upd`
58    ///
59    /// [`Dialogue<D, S>`]: super::dialogue::Dialogue
60    /// [`Dialogue::get_or_default`]: super::dialogue::Dialogue::get_or_default
61    #[must_use]
62    fn enter_dialogue<Upd, S, D>(self) -> Self
63    where
64        S: Storage<D> + ?Sized + Send + Sync + 'static,
65        <S as Storage<D>>::Error: Debug + Send,
66        D: Default + Clone + Send + Sync + 'static,
67        Upd: GetChatId + Clone + Send + Sync + 'static;
68}
69
70impl<Output> HandlerExt<Output> for Handler<'static, Output, DpHandlerDescription>
71where
72    Output: Send + Sync + 'static,
73{
74    fn filter_command<C>(self) -> Self
75    where
76        C: BotCommands + Send + Sync + 'static,
77    {
78        self.chain(filter_command::<C, Output>())
79    }
80
81    fn filter_mention_command<C>(self) -> Self
82    where
83        C: BotCommands + Send + Sync + 'static,
84    {
85        self.chain(filter_mention_command::<C, Output>())
86    }
87
88    fn enter_dialogue<Upd, S, D>(self) -> Self
89    where
90        S: Storage<D> + ?Sized + Send + Sync + 'static,
91        <S as Storage<D>>::Error: Debug + Send,
92        D: Default + Clone + Send + Sync + 'static,
93        Upd: GetChatId + Clone + Send + Sync + 'static,
94    {
95        self.chain(super::dialogue::enter::<Upd, S, D, Output>())
96    }
97}
98
99/// Returns a handler that accepts a parsed command `C`.
100///
101/// A call to this function is the same as `dptree::entry().filter_command()`.
102///
103/// See [`HandlerExt::filter_command`].
104///
105/// ## Dependency requirements
106///
107///  - [`crate::types::Message`]
108///  - [`crate::types::BotFullInfo`]
109#[must_use]
110pub fn filter_command<C, Output>() -> Handler<'static, Output, DpHandlerDescription>
111where
112    C: BotCommands + Send + Sync + 'static,
113    Output: Send + Sync + 'static,
114{
115    dptree::filter_map(move |message: Message, me: BotFullInfo| {
116        let text = message.text().or_else(|| message.caption())?;
117        parse_for_bot::<C>(text, &me)
118    })
119}
120
121/// Returns a handler that accepts a parsed command `C` if the command
122/// contains a bot mention, for example `/start@my_bot`.
123///
124/// A call to this function is the same as
125/// `dptree::entry().filter_mention_command()`.
126///
127/// See [`HandlerExt::filter_mention_command`].
128///
129/// ## Dependency requirements
130///
131///  - [`crate::types::Message`]
132///  - [`crate::types::BotFullInfo`]
133#[must_use]
134pub fn filter_mention_command<C, Output>() -> Handler<'static, Output, DpHandlerDescription>
135where
136    C: BotCommands + Send + Sync + 'static,
137    Output: Send + Sync + 'static,
138{
139    dptree::filter_map(move |message: Message, me: BotFullInfo| {
140        let text = message.text().or_else(|| message.caption())?;
141        // If the parsing succeeds with a bot name but fails without it,
142        // the command mentions this bot.
143        if C::parse(text, "").is_ok() {
144            return None;
145        }
146        parse_for_bot::<C>(text, &me)
147    })
148}
149
150fn parse_for_bot<C: BotCommands>(text: &str, me: &BotFullInfo) -> Option<C> {
151    // Bots can have multiple active usernames or no primary username.
152    C::parse(text, me.username.as_deref().unwrap_or_default()).ok().or_else(|| {
153        me.active_usernames.as_ref()?.iter().find_map(|username| C::parse(text, username).ok())
154    })
155}
156
157#[cfg(test)]
158#[cfg(feature = "macros")]
159mod tests {
160    use crate::{self as teloxide, dispatching::UpdateFilterExt, utils::command::BotCommands};
161    use chrono::DateTime;
162    use dptree::deps;
163    use teloxide_core::types::{
164        BotFullInfo, Chat, ChatId, ChatKind, ChatPrivate, LinkPreviewOptions, MediaKind, MediaText,
165        Message, MessageCommon, MessageId, MessageKind, Update, UpdateId, UpdateKind, User, UserId,
166    };
167
168    use super::HandlerExt;
169
170    #[derive(BotCommands, Clone)]
171    #[command(rename_rule = "lowercase")]
172    enum Cmd {
173        Test,
174    }
175
176    fn make_update(text: String) -> Update {
177        let timestamp = 1_569_518_829;
178        let date = DateTime::from_timestamp(timestamp, 0).unwrap();
179        Update {
180            id: UpdateId(326_170_274),
181            kind: UpdateKind::Message(Message {
182                via_bot: None,
183                id: MessageId(5042),
184                thread_id: None,
185                from: Some(User {
186                    id: UserId(109_998_024),
187                    is_bot: false,
188                    first_name: String::from("Laster"),
189                    last_name: None,
190                    username: Some(String::from("laster_alex")),
191                    language_code: Some(String::from("en")),
192                    is_premium: false,
193                    added_to_attachment_menu: false,
194                }),
195                sender_chat: None,
196                is_topic_message: false,
197                is_paid_post: false,
198                suggested_post_info: None,
199                sender_business_bot: None,
200                guest_query_id: None,
201                guest_bot_caller_user: None,
202                guest_bot_caller_chat: None,
203                receiver_user: None,
204                ephemeral_message_id: None,
205                date,
206                chat: Chat {
207                    id: ChatId(109_998_024),
208                    kind: ChatKind::Private(ChatPrivate {
209                        username: Some(String::from("Laster")),
210                        first_name: Some(String::from("laster_alex")),
211                        last_name: None,
212                    }),
213                },
214                direct_messages_topic: None,
215                kind: MessageKind::Common(MessageCommon {
216                    reply_to_message: None,
217                    forward_origin: None,
218                    external_reply: None,
219                    quote: None,
220                    edit_date: None,
221                    media_kind: MediaKind::Text(MediaText {
222                        text,
223                        entities: vec![],
224                        link_preview_options: Some(LinkPreviewOptions {
225                            is_disabled: true,
226                            url: None,
227                            prefer_small_media: false,
228                            prefer_large_media: false,
229                            show_above_text: false,
230                        }),
231                    }),
232                    reply_markup: None,
233                    author_signature: None,
234                    sender_tag: None,
235                    paid_star_count: None,
236                    effect_id: None,
237                    is_automatic_forward: false,
238                    has_protected_content: false,
239                    reply_to_checklist_task_id: None,
240                    reply_to_poll_option_id: None,
241                    reply_to_story: None,
242                    sender_boost_count: None,
243                    is_from_offline: false,
244                    business_connection_id: None,
245                }),
246            }),
247        }
248    }
249
250    fn make_me() -> BotFullInfo {
251        BotFullInfo {
252            id: UserId(42),
253            is_bot: teloxide_core::types::True,
254            first_name: "First".to_owned(),
255            username: Some("SomethingSomethingBot".to_owned()),
256            active_usernames: Some(vec!["OtherActiveBot".to_owned()]),
257            inline_query_placeholder: None,
258            needs_inline_query_location: false,
259            has_topics_enabled: false,
260            allows_users_to_create_topics: false,
261            has_topic_sidebar: false,
262            can_manage_bots: false,
263            supports_guest_queries: false,
264            supports_join_request_queries: false,
265            can_join_groups: false,
266            can_read_all_group_messages: false,
267            supports_inline_queries: false,
268            can_connect_to_business: false,
269            has_main_web_app: false,
270        }
271    }
272
273    #[tokio::test]
274    async fn test_filter_command() {
275        let h = dptree::entry()
276            .branch(Update::filter_message().filter_command::<Cmd>().endpoint(|| async {}));
277        let me = make_me();
278
279        let update = make_update("/test@".to_owned() + me.username().unwrap());
280        let result = h.dispatch(deps![update, me.clone()]).await;
281        assert!(result.is_break());
282
283        let update = make_update("/test@OtherActiveBot".to_owned());
284        let result = h.dispatch(deps![update, me.clone()]).await;
285        assert!(result.is_break());
286
287        let update = make_update("/test@".to_owned() + "SomeOtherBot");
288        let result = h.dispatch(deps![update, me.clone()]).await;
289        assert!(result.is_continue());
290
291        let update = make_update("/test".to_owned());
292        let result = h.dispatch(deps![update, me.clone()]).await;
293        assert!(result.is_break());
294    }
295
296    #[tokio::test]
297    async fn test_filter_mention_command() {
298        let h = dptree::entry()
299            .branch(Update::filter_message().filter_mention_command::<Cmd>().endpoint(|| async {}));
300        let me = make_me();
301
302        let update = make_update("/test@".to_owned() + me.username().unwrap());
303        let result = h.dispatch(deps![update, me.clone()]).await;
304        assert!(result.is_break());
305
306        let update = make_update("/test@".to_owned() + "SomeOtherBot");
307        let result = h.dispatch(deps![update, me.clone()]).await;
308        assert!(result.is_continue());
309
310        let update = make_update("/test".to_owned());
311        let result = h.dispatch(deps![update, me.clone()]).await;
312        assert!(result.is_continue());
313    }
314
315    #[tokio::test]
316    async fn command_filters_without_primary_username() {
317        let command = dptree::entry()
318            .branch(Update::filter_message().filter_command::<Cmd>().endpoint(|| async {}));
319        let mention = dptree::entry()
320            .branch(Update::filter_message().filter_mention_command::<Cmd>().endpoint(|| async {}));
321        let mut me = make_me();
322        me.username = None;
323        for (text, is_command, is_mention) in [
324            ("/test", true, false),
325            ("/test@OtherActiveBot", true, true),
326            ("/test@UnknownBot", false, false),
327        ] {
328            let update = make_update(text.to_owned());
329            assert_eq!(
330                command.dispatch(deps![update.clone(), me.clone()]).await.is_break(),
331                is_command
332            );
333            assert_eq!(mention.dispatch(deps![update, me.clone()]).await.is_break(), is_mention);
334        }
335    }
336}