Skip to main content

teloxide/dispatching/
filter_ext.rs

1#![allow(clippy::redundant_closure_call)]
2// Required for the `filter_from` currently
3#![allow(deprecated)]
4
5use dptree::Handler;
6
7use crate::{
8    dispatching::DpHandlerDescription,
9    types::{AllowedUpdate, Message, Update, UpdateKind},
10};
11
12/// A message that another message replies to.
13///
14/// This is the dependency inserted by
15/// [`MessageFilterExt::filter_reply_to_message`]. It is a newtype so that it
16/// does not override the original [`Message`] in the dependency map, so
17/// handlers can accept both.
18///
19/// [`MessageFilterExt::filter_reply_to_message`]: crate::dispatching::MessageFilterExt::filter_reply_to_message
20#[derive(Debug, Clone)]
21pub struct ReplyToMessage(pub Message);
22
23macro_rules! define_ext {
24    ($ext_name:ident, $for_ty:ty => $( ($func:ident, $proj_fn:expr, $fn_doc:expr $(, $Allowed:ident)? ) ,)*) => {
25        #[doc = concat!("Filter methods for [`", stringify!($for_ty), "`].")]
26        pub trait $ext_name<Out>: private::Sealed {
27            $( define_ext!(@sig $func, $fn_doc); )*
28        }
29
30        impl<Out> $ext_name<Out> for $for_ty
31        where
32            Out: Send + Sync + 'static,
33        {
34            $( define_ext!(@impl $for_ty, $func, $proj_fn $(, $Allowed )? ); )*
35        }
36    };
37
38    (@sig $func:ident, $fn_doc:expr) => {
39        #[doc = $fn_doc]
40        fn $func() -> Handler<'static, Out, DpHandlerDescription>;
41    };
42
43    (@impl $for_ty:ty, $func:ident, $proj_fn:expr, $Allowed:ident) => {
44        fn $func() -> Handler<'static, Out, DpHandlerDescription> {
45            dptree::filter_map_with_description(DpHandlerDescription::of(AllowedUpdate::$Allowed), move |input: $for_ty| {
46                $proj_fn(input)
47            })
48        }
49    };
50
51    (@impl $for_ty:ty, $func:ident, $proj_fn:expr) => {
52        fn $func() -> Handler<'static, Out, DpHandlerDescription> {
53            dptree::filter_map(move |input: $for_ty| {
54                $proj_fn(input)
55            })
56        }
57    };
58}
59
60mod private {
61    use teloxide_core::types::{Message, Update};
62
63    pub trait Sealed {}
64
65    impl Sealed for Update {}
66    impl Sealed for Message {}
67}
68
69// FIXME: rewrite this macro to allow the usage of functions returning small
70// values without borrowing
71macro_rules! define_message_ext {
72    ($( ($func:ident, $fn_name:path $(, $wrap:path)?) ,)*) => {
73        define_ext! {
74            MessageFilterExt, Message =>
75            $((
76                $func,
77                (|x| $fn_name(&x).map(ToOwned::to_owned) $(.map($wrap))?),
78                concat!("Applies the [`", stringify!($fn_name), "`] filter.")
79            ),)*
80        }
81    }
82}
83
84// FIXME: change macro so that we can filter things without getters
85// May be expanded in the future.
86define_message_ext! {
87    // MessageCommon
88    (filter_from, Message::from),
89    // MediaKind variants of the MessageKind::Common
90    (filter_animation, Message::animation),
91    (filter_audio, Message::audio),
92    (filter_contact, Message::contact),
93    (filter_document, Message::document),
94    (filter_paid_media, Message::paid_media),
95    (filter_game, Message::game),
96    (filter_venue, Message::venue),
97    (filter_location, Message::location),
98    (filter_photo, Message::photo),
99    (filter_poll, Message::poll),
100    (filter_checklist, Message::checklist),
101    (filter_sticker, Message::sticker),
102    (filter_story, Message::story),
103    (filter_text, Message::text),
104    (filter_video, Message::video),
105    (filter_video_note, Message::video_note),
106    (filter_voice, Message::voice),
107    (filter_migration, Message::chat_migration),
108    (filter_migration_from, Message::migrate_from_chat_id),
109    (filter_migration_to, Message::migrate_to_chat_id),
110    (filter_reply_to_message, Message::reply_to_message, ReplyToMessage),
111    (filter_forward_origin, Message::forward_origin),
112    (filter_reply_to_story, Message::reply_to_story),
113    // Rest variants of a MessageKind
114    (filter_new_chat_members, Message::new_chat_members),
115    (filter_left_chat_member, Message::left_chat_member),
116    (filter_new_chat_title, Message::new_chat_title),
117    (filter_new_chat_photo, Message::new_chat_photo),
118    (filter_delete_chat_photo, Message::delete_chat_photo),
119    (filter_group_chat_created, Message::group_chat_created),
120    (filter_supergroup_chat_created, Message::super_group_chat_created),
121    (filter_channel_chat_created, Message::channel_chat_created),
122    (filter_message_auto_delete_timer_changed, Message::message_auto_delete_timer_changed),
123    (filter_pinned, Message::pinned_message),
124    (filter_invoice, Message::invoice),
125    (filter_successful_payment, Message::successful_payment),
126    (filter_connected_website, Message::connected_website),
127    (filter_write_access_allowed, Message::write_access_allowed),
128    (filter_widget, Message::widget),
129    (filter_paid_messages_waived, Message::paid_messages_waived),
130    (filter_ton_wallet_transfer, Message::ton_wallet_transfer),
131    (filter_passport_data, Message::passport_data),
132    (filter_dice, Message::dice),
133    (filter_proximity_alert_triggered, Message::proximity_alert_triggered),
134    (filter_boost_added, Message::boost_added),
135    (filter_chat_background_set, Message::chat_background_set),
136    (filter_checklist_tasks_done, Message::checklist_tasks_done),
137    (filter_checklist_tasks_added, Message::checklist_tasks_added),
138    (filter_direct_message_price_changed, Message::direct_message_price_changed),
139    (filter_forum_topic_created, Message::forum_topic_created),
140    (filter_forum_topic_edited, Message::forum_topic_edited),
141    (filter_forum_topic_closed, Message::forum_topic_closed),
142    (filter_forum_topic_reopened, Message::forum_topic_reopened),
143    (filter_general_forum_topic_hidden, Message::general_forum_topic_hidden),
144    (filter_general_forum_topic_unhidden, Message::general_forum_topic_unhidden),
145    (filter_giveaway, Message::giveaway),
146    (filter_giveaway_completed, Message::giveaway_completed),
147    (filter_giveaway_created, Message::giveaway_created),
148    (filter_giveaway_winners, Message::giveaway_winners),
149    (filter_paid_message_price_changed, Message::paid_message_price_changed),
150    (filter_suggested_post_approved, Message::suggested_post_approved),
151    (filter_suggested_post_approval_failed, Message::suggested_post_approval_failed),
152    (filter_suggested_post_declined, Message::suggested_post_declined),
153    (filter_suggested_post_paid, Message::suggested_post_paid),
154    (filter_suggested_post_refunded, Message::suggested_post_refunded),
155    (filter_gift_info, Message::gift_info),
156    (filter_unique_gift_info, Message::unique_gift_info),
157    (filter_managed_bot_created, Message::managed_bot_created),
158    (filter_poll_option_added, Message::poll_option_added),
159    (filter_poll_option_deleted, Message::poll_option_deleted),
160    (filter_video_chat_scheduled, Message::video_chat_scheduled),
161    (filter_video_chat_started, Message::video_chat_started),
162    (filter_video_chat_ended, Message::video_chat_ended),
163    (filter_video_chat_participants_invited, Message::video_chat_participants_invited),
164    (filter_web_app_data, Message::web_app_data),
165}
166
167macro_rules! define_update_ext {
168    ($( ($func:ident, $kind:ident) ,)*) => {
169        define_ext! {
170            UpdateFilterExt, Update =>
171            $((
172                $func,
173                |update: Update| match update.kind {
174                    UpdateKind::$kind(x) => Some(x),
175                    _ => None,
176                },
177                concat!("Filters out [`UpdateKind::", stringify!($kind), "`] objects."),
178                $kind
179            ),)*
180        }
181
182        // This exhaustiveness check ensures the test list below derives from all
183        // UpdateKind variants, not just a subset of filters.
184        const _: fn(UpdateKind) -> Option<AllowedUpdate> = |kind| match kind {
185            $(UpdateKind::$kind(_) => Some(AllowedUpdate::$kind),)*
186            UpdateKind::Error(_) => None, // deserialization fallback, not a subscribable update
187        };
188
189        #[cfg(test)]
190        pub(super) const ALLOWED_UPDATE_KINDS: &[AllowedUpdate] = &[$(AllowedUpdate::$kind,)*];
191    }
192}
193
194define_update_ext! {
195    (filter_message, Message),
196    (filter_guest_message, GuestMessage),
197    (filter_edited_message, EditedMessage),
198    (filter_channel_post, ChannelPost),
199    (filter_edited_channel_post, EditedChannelPost),
200    (filter_business_connection, BusinessConnection),
201    (filter_business_message, BusinessMessage),
202    (filter_edited_business_message, EditedBusinessMessage),
203    (filter_deleted_business_messages, DeletedBusinessMessages),
204    (filter_message_reaction_updated, MessageReaction),
205    (filter_message_reaction_count_updated, MessageReactionCount),
206    (filter_inline_query, InlineQuery),
207    (filter_chosen_inline_result, ChosenInlineResult),
208    (filter_callback_query, CallbackQuery),
209    (filter_shipping_query, ShippingQuery),
210    (filter_pre_checkout_query, PreCheckoutQuery),
211    (filter_purchased_paid_media, PurchasedPaidMedia),
212    (filter_poll, Poll),
213    (filter_poll_answer, PollAnswer),
214    (filter_my_chat_member, MyChatMember),
215    (filter_chat_member, ChatMember),
216    (filter_chat_join_request, ChatJoinRequest),
217    (filter_chat_boost, ChatBoost),
218    (filter_removed_chat_boost, RemovedChatBoost),
219    (filter_managed_bot_updated, ManagedBot),
220    (filter_stopped_message_generation, StoppedMessageGeneration),
221    (filter_widget_query, WidgetQuery),
222    (filter_shared_widget_query, SharedWidgetQuery),
223    (filter_subscription, Subscription),
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use dptree::deps;
230    use std::ops::ControlFlow;
231
232    fn message(json: &str) -> Message {
233        serde_json::from_str(json).unwrap()
234    }
235
236    #[tokio::test]
237    async fn subscription_filter_injects_update_and_requests_it() {
238        use crate::types::{BotSubscriptionState, BotSubscriptionUpdated};
239
240        let update: Update = serde_json::from_str(
241            r#"{"update_id":1,"subscription":{"user":{"id":2,"is_bot":false,"first_name":"Test"},"invoice_payload":"invoice","state":"active"}}"#,
242        )
243        .unwrap();
244        let handler =
245            Update::filter_subscription().endpoint(|event: BotSubscriptionUpdated| async move {
246                (event.invoice_payload, event.state)
247            });
248        assert_eq!(handler.description().allowed_updates(), [AllowedUpdate::Subscription]);
249        assert_eq!(
250            handler.dispatch(deps![update]).await.break_value(),
251            Some(("invoice".into(), BotSubscriptionState::Active))
252        );
253    }
254
255    #[tokio::test]
256    async fn reply_to_message_does_not_override_message() {
257        let msg = message(
258            r#"{"message_id":2,"date":1675229140,"chat":{"id":1,"type":"private"},
259                "text":"reply",
260                "reply_to_message":{"message_id":1,"date":1675229139,"chat":{"id":1,"type":"private"},"text":"original"}}"#,
261        );
262
263        let handler: Handler<'static, (i32, i32), DpHandlerDescription> =
264            Message::filter_reply_to_message().endpoint(
265                |msg: Message, reply: ReplyToMessage| async move { (msg.id.0, reply.0.id.0) },
266            );
267
268        match handler.dispatch(deps![msg]).await {
269            ControlFlow::Break((msg_id, reply_id)) => {
270                assert_eq!(msg_id, 2);
271                assert_eq!(reply_id, 1);
272            }
273            ControlFlow::Continue(_) => panic!("handler should have matched"),
274        }
275    }
276
277    #[tokio::test]
278    async fn reply_to_message_filters_non_replies() {
279        let msg = message(
280            r#"{"message_id":2,"date":1675229140,"chat":{"id":1,"type":"private"},"text":"x"}"#,
281        );
282
283        let handler: Handler<'static, (), DpHandlerDescription> =
284            Message::filter_reply_to_message().endpoint(|_: ReplyToMessage| async {});
285
286        assert!(matches!(handler.dispatch(deps![msg]).await, ControlFlow::Continue(_)));
287    }
288}