Skip to main content

teloxide/dispatching/
handler_description.rs

1use std::collections::HashSet;
2
3use dptree::{
4    description::{EventKind, InterestSet},
5    HandlerDescription,
6};
7use teloxide_core::types::AllowedUpdate;
8
9/// Handler description that is used by [`Dispatcher`].
10///
11/// [`Dispatcher`]: crate::dispatching::Dispatcher
12#[derive(Debug, Clone)]
13pub struct DpHandlerDescription {
14    allowed: InterestSet<Kind>,
15}
16
17impl DpHandlerDescription {
18    pub(crate) fn of(allowed: AllowedUpdate) -> Self {
19        let mut set = HashSet::with_capacity(1);
20        set.insert(Kind(allowed));
21        Self { allowed: InterestSet::new_filter(set) }
22    }
23
24    pub(crate) fn allowed_updates(&self) -> Vec<AllowedUpdate> {
25        self.allowed.observed.iter().map(|&Kind(x)| x).collect()
26    }
27}
28
29impl HandlerDescription for DpHandlerDescription {
30    fn entry() -> Self {
31        Self { allowed: HandlerDescription::entry() }
32    }
33
34    fn user_defined() -> Self {
35        Self { allowed: HandlerDescription::user_defined() }
36    }
37
38    fn merge_chain(&self, other: &Self) -> Self {
39        Self { allowed: self.allowed.merge_chain(&other.allowed) }
40    }
41
42    fn merge_branch(&self, other: &Self) -> Self {
43        Self { allowed: self.allowed.merge_branch(&other.allowed) }
44    }
45}
46
47#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq)]
48struct Kind(AllowedUpdate);
49
50impl EventKind for Kind {
51    fn full_set() -> HashSet<Self> {
52        use AllowedUpdate::*;
53
54        // NB: We need to specify all update kinds by hand, because telegram doesn't
55        //     enable `ChatMember` by default:
56        //
57        //     > A JSON-serialized list of the update types you want your bot to
58        //     > receive. For example, specify [“message”, “edited_channel_post”,
59        //     > “callback_query”] to only receive updates of these types. See Update
60        //     > for a complete list of available update types. Specify an empty list
61        //     > to receive all update types except chat_member (default). If not
62        //     > specified, the previous setting will be used.
63
64        [
65            Message,
66            GuestMessage,
67            EditedMessage,
68            ChannelPost,
69            EditedChannelPost,
70            BusinessConnection,
71            BusinessMessage,
72            EditedBusinessMessage,
73            DeletedBusinessMessages,
74            MessageReaction,
75            MessageReactionCount,
76            InlineQuery,
77            ChosenInlineResult,
78            CallbackQuery,
79            ShippingQuery,
80            PreCheckoutQuery,
81            PurchasedPaidMedia,
82            Poll,
83            PollAnswer,
84            MyChatMember,
85            ChatMember,
86            ChatJoinRequest,
87            ChatBoost,
88            RemovedChatBoost,
89            ManagedBot,
90            StoppedMessageGeneration,
91            WidgetQuery,
92            SharedWidgetQuery,
93        ]
94        .into_iter()
95        .map(Kind)
96        .collect()
97    }
98
99    fn empty_set() -> HashSet<Self> {
100        HashSet::new()
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use crate::{
107        dispatching::UpdateFilterExt,
108        types::{AllowedUpdate, Update as CoreUpdate},
109    };
110
111    #[cfg(feature = "macros")]
112    use crate::{
113        self as teloxide, // fixup for the `BotCommands` macro
114        dispatching::{handler_description::Kind, HandlerExt},
115        types::{AllowedUpdate::*, Update},
116        utils::command::BotCommands,
117    };
118    #[cfg(feature = "macros")]
119    use dptree::description::EventKind;
120
121    #[cfg(feature = "macros")]
122    #[derive(BotCommands, Clone)]
123    #[command(rename_rule = "lowercase")]
124    enum Cmd {
125        B,
126    }
127
128    // <https://github.com/teloxide/teloxide/discussions/648>
129    #[test]
130    #[cfg(feature = "macros")]
131    fn discussion_648() {
132        let h =
133            dptree::entry().branch(Update::filter_my_chat_member().endpoint(|| async {})).branch(
134                Update::filter_message()
135                    .branch(dptree::entry().filter_command::<Cmd>().endpoint(|| async {}))
136                    .endpoint(|| async {}),
137            );
138
139        let mut v = h.description().allowed_updates();
140
141        // Hash set randomizes element order, so to compare we need to sort
142        v.sort_by_key(|&a| a as u8);
143
144        assert_eq!(v, [Message, MyChatMember])
145    }
146
147    #[test]
148    #[ignore = "this test requires `macros` feature"]
149    #[cfg(not(feature = "macros"))]
150    fn discussion_648() {
151        panic!("this test requires `macros` feature")
152    }
153
154    #[test]
155    fn guest_message() {
156        let handler = dptree::entry().branch(
157            <CoreUpdate as UpdateFilterExt<()>>::filter_guest_message().endpoint(|| async {}),
158        );
159        let allowed_updates = handler.description().allowed_updates();
160
161        assert_eq!(allowed_updates, [AllowedUpdate::GuestMessage]);
162    }
163
164    #[test]
165    fn stopped_message_generation() {
166        let handler = dptree::entry().branch(
167            <CoreUpdate as UpdateFilterExt<()>>::filter_stopped_message_generation()
168                .endpoint(|| async {}),
169        );
170        let allowed_updates = handler.description().allowed_updates();
171
172        assert_eq!(allowed_updates, [AllowedUpdate::StoppedMessageGeneration]);
173    }
174
175    // Test that all possible updates are specified in `Kind::full_set()`
176    #[test]
177    #[cfg(feature = "macros")]
178    fn allowed_updates_full_set() {
179        let full_set = Kind::full_set();
180        let allowed_updates_reference = vec![
181            Message,
182            GuestMessage,
183            EditedMessage,
184            ChannelPost,
185            EditedChannelPost,
186            MessageReaction,
187            MessageReactionCount,
188            InlineQuery,
189            ChosenInlineResult,
190            CallbackQuery,
191            ShippingQuery,
192            PreCheckoutQuery,
193            PurchasedPaidMedia,
194            Poll,
195            PollAnswer,
196            MyChatMember,
197            ChatMember,
198            ChatJoinRequest,
199            ChatBoost,
200            RemovedChatBoost,
201            ManagedBot,
202            StoppedMessageGeneration,
203            WidgetQuery,
204            SharedWidgetQuery,
205        ];
206
207        for update in allowed_updates_reference {
208            match update {
209                // CAUTION: Don't forget to add new `UpdateKind` to `allowed_updates_reference`!
210                Message
211                | GuestMessage
212                | EditedMessage
213                | ChannelPost
214                | EditedChannelPost
215                | MessageReaction
216                | MessageReactionCount
217                | InlineQuery
218                | ChosenInlineResult
219                | CallbackQuery
220                | ShippingQuery
221                | PreCheckoutQuery
222                | PurchasedPaidMedia
223                | Poll
224                | PollAnswer
225                | MyChatMember
226                | ChatMember
227                | ChatJoinRequest
228                | ChatBoost
229                | RemovedChatBoost
230                | ManagedBot
231                | StoppedMessageGeneration
232                | WidgetQuery
233                | SharedWidgetQuery
234                | BusinessMessage
235                | BusinessConnection
236                | EditedBusinessMessage
237                | DeletedBusinessMessages => {
238                    assert!(full_set.contains(&Kind(update)))
239                }
240            }
241        }
242    }
243}