1#![allow(clippy::redundant_closure_call)]
2#![allow(deprecated)]
4
5use dptree::Handler;
6
7use crate::{
8 dispatching::DpHandlerDescription,
9 types::{AllowedUpdate, Message, Update, UpdateKind},
10};
11
12#[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
69macro_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
84define_message_ext! {
87 (filter_from, Message::from),
89 (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 (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:path, $Allowed:ident) ,)*) => {
169 define_ext! {
170 UpdateFilterExt, Update =>
171 $((
172 $func,
173 |update: Update| match update.kind {
174 $kind(x) => Some(x),
175 _ => None,
176 },
177 concat!("Filters out [`", stringify!($kind), "`] objects."),
178 $Allowed
179 ),)*
180 }
181 }
182}
183
184define_update_ext! {
185 (filter_message, UpdateKind::Message, Message),
186 (filter_guest_message, UpdateKind::GuestMessage, GuestMessage),
187 (filter_edited_message, UpdateKind::EditedMessage, EditedMessage),
188 (filter_channel_post, UpdateKind::ChannelPost, ChannelPost),
189 (filter_edited_channel_post, UpdateKind::EditedChannelPost, EditedChannelPost),
190 (filter_business_connection, UpdateKind::BusinessConnection, BusinessConnection),
191 (filter_business_message, UpdateKind::BusinessMessage, BusinessMessage),
192 (filter_edited_business_message, UpdateKind::EditedBusinessMessage, EditedBusinessMessage),
193 (filter_deleted_business_messages, UpdateKind::DeletedBusinessMessages, DeletedBusinessMessages),
194 (filter_message_reaction_updated, UpdateKind::MessageReaction, MessageReaction),
195 (filter_message_reaction_count_updated, UpdateKind::MessageReactionCount, MessageReactionCount),
196 (filter_inline_query, UpdateKind::InlineQuery, InlineQuery),
197 (filter_chosen_inline_result, UpdateKind::ChosenInlineResult, ChosenInlineResult),
198 (filter_callback_query, UpdateKind::CallbackQuery, CallbackQuery),
199 (filter_shipping_query, UpdateKind::ShippingQuery, ShippingQuery),
200 (filter_pre_checkout_query, UpdateKind::PreCheckoutQuery, PreCheckoutQuery),
201 (filter_purchased_paid_media, UpdateKind::PurchasedPaidMedia, PurchasedPaidMedia),
202 (filter_poll, UpdateKind::Poll, Poll),
203 (filter_poll_answer, UpdateKind::PollAnswer, PollAnswer),
204 (filter_my_chat_member, UpdateKind::MyChatMember, MyChatMember),
205 (filter_chat_member, UpdateKind::ChatMember, ChatMember),
206 (filter_chat_join_request, UpdateKind::ChatJoinRequest, ChatJoinRequest),
207 (filter_chat_boost, UpdateKind::ChatBoost, ChatBoost),
208 (filter_removed_chat_boost, UpdateKind::RemovedChatBoost, RemovedChatBoost),
209 (filter_managed_bot_updated, UpdateKind::ManagedBot, ManagedBot),
210 (filter_stopped_message_generation, UpdateKind::StoppedMessageGeneration, StoppedMessageGeneration),
211 (filter_widget_query, UpdateKind::WidgetQuery, WidgetQuery),
212 (filter_shared_widget_query, UpdateKind::SharedWidgetQuery, SharedWidgetQuery),
213}
214
215#[cfg(test)]
216mod tests {
217 use super::*;
218 use dptree::deps;
219 use std::ops::ControlFlow;
220
221 fn message(json: &str) -> Message {
222 serde_json::from_str(json).unwrap()
223 }
224
225 #[tokio::test]
226 async fn reply_to_message_does_not_override_message() {
227 let msg = message(
228 r#"{"message_id":2,"date":1675229140,"chat":{"id":1,"type":"private"},
229 "text":"reply",
230 "reply_to_message":{"message_id":1,"date":1675229139,"chat":{"id":1,"type":"private"},"text":"original"}}"#,
231 );
232
233 let handler: Handler<'static, (i32, i32), DpHandlerDescription> =
234 Message::filter_reply_to_message().endpoint(
235 |msg: Message, reply: ReplyToMessage| async move { (msg.id.0, reply.0.id.0) },
236 );
237
238 match handler.dispatch(deps![msg]).await {
239 ControlFlow::Break((msg_id, reply_id)) => {
240 assert_eq!(msg_id, 2);
241 assert_eq!(reply_id, 1);
242 }
243 ControlFlow::Continue(_) => panic!("handler should have matched"),
244 }
245 }
246
247 #[tokio::test]
248 async fn reply_to_message_filters_non_replies() {
249 let msg = message(
250 r#"{"message_id":2,"date":1675229140,"chat":{"id":1,"type":"private"},"text":"x"}"#,
251 );
252
253 let handler: Handler<'static, (), DpHandlerDescription> =
254 Message::filter_reply_to_message().endpoint(|_: ReplyToMessage| async {});
255
256 assert!(matches!(handler.dispatch(deps![msg]).await, ControlFlow::Continue(_)));
257 }
258}