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            Subscription,
94        ]
95        .into_iter()
96        .map(Kind)
97        .collect()
98    }
99
100    fn empty_set() -> HashSet<Self> {
101        HashSet::new()
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::{EventKind, Kind};
108    use crate::{
109        dispatching::{filter_ext::ALLOWED_UPDATE_KINDS, UpdateFilterExt},
110        types::{AllowedUpdate, Update as CoreUpdate},
111    };
112
113    #[cfg(feature = "macros")]
114    use crate::{
115        self as teloxide, // fixup for the `BotCommands` macro
116        dispatching::HandlerExt,
117        types::{AllowedUpdate::*, Update},
118        utils::command::BotCommands,
119    };
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]
176    fn allowed_updates_full_set() {
177        let expected: std::collections::HashSet<_> =
178            ALLOWED_UPDATE_KINDS.iter().copied().map(Kind).collect();
179        assert_eq!(expected.len(), ALLOWED_UPDATE_KINDS.len(), "duplicate update mapping");
180        assert_eq!(Kind::full_set(), expected);
181    }
182}