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_passport_data, Message::passport_data),
129    (filter_dice, Message::dice),
130    (filter_proximity_alert_triggered, Message::proximity_alert_triggered),
131    (filter_boost_added, Message::boost_added),
132    (filter_chat_background_set, Message::chat_background_set),
133    (filter_checklist_tasks_done, Message::checklist_tasks_done),
134    (filter_checklist_tasks_added, Message::checklist_tasks_added),
135    (filter_direct_message_price_changed, Message::direct_message_price_changed),
136    (filter_forum_topic_created, Message::forum_topic_created),
137    (filter_forum_topic_edited, Message::forum_topic_edited),
138    (filter_forum_topic_closed, Message::forum_topic_closed),
139    (filter_forum_topic_reopened, Message::forum_topic_reopened),
140    (filter_general_forum_topic_hidden, Message::general_forum_topic_hidden),
141    (filter_general_forum_topic_unhidden, Message::general_forum_topic_unhidden),
142    (filter_giveaway, Message::giveaway),
143    (filter_giveaway_completed, Message::giveaway_completed),
144    (filter_giveaway_created, Message::giveaway_created),
145    (filter_giveaway_winners, Message::giveaway_winners),
146    (filter_paid_message_price_changed, Message::paid_message_price_changed),
147    (filter_suggested_post_approved, Message::suggested_post_approved),
148    (filter_suggested_post_approval_failed, Message::suggested_post_approval_failed),
149    (filter_suggested_post_declined, Message::suggested_post_declined),
150    (filter_suggested_post_paid, Message::suggested_post_paid),
151    (filter_suggested_post_refunded, Message::suggested_post_refunded),
152    (filter_gift_info, Message::gift_info),
153    (filter_unique_gift_info, Message::unique_gift_info),
154    (filter_managed_bot_created, Message::managed_bot_created),
155    (filter_poll_option_added, Message::poll_option_added),
156    (filter_poll_option_deleted, Message::poll_option_deleted),
157    (filter_video_chat_scheduled, Message::video_chat_scheduled),
158    (filter_video_chat_started, Message::video_chat_started),
159    (filter_video_chat_ended, Message::video_chat_ended),
160    (filter_video_chat_participants_invited, Message::video_chat_participants_invited),
161    (filter_web_app_data, Message::web_app_data),
162}
163
164macro_rules! define_update_ext {
165    ($( ($func:ident, $kind:path, $Allowed:ident) ,)*) => {
166        define_ext! {
167            UpdateFilterExt, Update =>
168            $((
169                $func,
170                |update: Update| match update.kind {
171                    $kind(x) => Some(x),
172                    _ => None,
173                },
174                concat!("Filters out [`", stringify!($kind), "`] objects."),
175                $Allowed
176            ),)*
177        }
178    }
179}
180
181define_update_ext! {
182    (filter_message, UpdateKind::Message, Message),
183    (filter_guest_message, UpdateKind::GuestMessage, GuestMessage),
184    (filter_edited_message, UpdateKind::EditedMessage, EditedMessage),
185    (filter_channel_post, UpdateKind::ChannelPost, ChannelPost),
186    (filter_edited_channel_post, UpdateKind::EditedChannelPost, EditedChannelPost),
187    (filter_business_connection, UpdateKind::BusinessConnection, BusinessConnection),
188    (filter_business_message, UpdateKind::BusinessMessage, BusinessMessage),
189    (filter_edited_business_message, UpdateKind::EditedBusinessMessage, EditedBusinessMessage),
190    (filter_deleted_business_messages, UpdateKind::DeletedBusinessMessages, DeletedBusinessMessages),
191    (filter_message_reaction_updated, UpdateKind::MessageReaction, MessageReaction),
192    (filter_message_reaction_count_updated, UpdateKind::MessageReactionCount, MessageReactionCount),
193    (filter_inline_query, UpdateKind::InlineQuery, InlineQuery),
194    (filter_chosen_inline_result, UpdateKind::ChosenInlineResult, ChosenInlineResult),
195    (filter_callback_query, UpdateKind::CallbackQuery, CallbackQuery),
196    (filter_shipping_query, UpdateKind::ShippingQuery, ShippingQuery),
197    (filter_pre_checkout_query, UpdateKind::PreCheckoutQuery, PreCheckoutQuery),
198    (filter_purchased_paid_media, UpdateKind::PurchasedPaidMedia, PurchasedPaidMedia),
199    (filter_poll, UpdateKind::Poll, Poll),
200    (filter_poll_answer, UpdateKind::PollAnswer, PollAnswer),
201    (filter_my_chat_member, UpdateKind::MyChatMember, MyChatMember),
202    (filter_chat_member, UpdateKind::ChatMember, ChatMember),
203    (filter_chat_join_request, UpdateKind::ChatJoinRequest, ChatJoinRequest),
204    (filter_chat_boost, UpdateKind::ChatBoost, ChatBoost),
205    (filter_removed_chat_boost, UpdateKind::RemovedChatBoost, RemovedChatBoost),
206    (filter_managed_bot_updated, UpdateKind::ManagedBot, ManagedBot),
207    (filter_stopped_message_generation, UpdateKind::StoppedMessageGeneration, StoppedMessageGeneration),
208}
209
210#[cfg(test)]
211mod tests {
212    use super::*;
213    use dptree::deps;
214    use std::ops::ControlFlow;
215
216    fn message(json: &str) -> Message {
217        serde_json::from_str(json).unwrap()
218    }
219
220    #[tokio::test]
221    async fn reply_to_message_does_not_override_message() {
222        let msg = message(
223            r#"{"message_id":2,"date":1675229140,"chat":{"id":1,"type":"private"},
224                "text":"reply",
225                "reply_to_message":{"message_id":1,"date":1675229139,"chat":{"id":1,"type":"private"},"text":"original"}}"#,
226        );
227
228        let handler: Handler<'static, (i32, i32), DpHandlerDescription> =
229            Message::filter_reply_to_message().endpoint(
230                |msg: Message, reply: ReplyToMessage| async move { (msg.id.0, reply.0.id.0) },
231            );
232
233        match handler.dispatch(deps![msg]).await {
234            ControlFlow::Break((msg_id, reply_id)) => {
235                assert_eq!(msg_id, 2);
236                assert_eq!(reply_id, 1);
237            }
238            ControlFlow::Continue(_) => panic!("handler should have matched"),
239        }
240    }
241
242    #[tokio::test]
243    async fn reply_to_message_filters_non_replies() {
244        let msg = message(
245            r#"{"message_id":2,"date":1675229140,"chat":{"id":1,"type":"private"},"text":"x"}"#,
246        );
247
248        let handler: Handler<'static, (), DpHandlerDescription> =
249            Message::filter_reply_to_message().endpoint(|_: ReplyToMessage| async {});
250
251        assert!(matches!(handler.dispatch(deps![msg]).await, ControlFlow::Continue(_)));
252    }
253}