Skip to main content

twilight_http/request/guild/message/
search_guild_messages.rs

1//! HTTP request for searching for [`Message`]s within a [`Guild`].
2//!
3//! This endpoint supports a suite of filters for narrowing search results.
4//! While all parameters—such as [`channel_id`], which narrows results to only
5//! messages within a list of channels—include only results with those values,
6//! some fields support *negating* a given value to exclude those results. Refer
7//! to [`Negate`] for those fields. Each field's method in the
8//! [`SearchGuildMessages`] request builder also notes whether the field can be
9//! negated.
10//!
11//! # Indexing
12//!
13//! If the entity you are searching has not yet been indexed the endpoint will
14//! return a 202 Accepted response and the response body variant will be
15//! [`SearchGuildMessagesResponseBody::Accepted`]; otherwise, the response body
16//! variant will be [`SearchGuildMessagesResponseBody::Ok`] with message
17//! results.
18//!
19//! # Pagination
20//!
21//! Due to speed optimizations, search may return slightly fewer results than
22//! the limit specified when messages have not been accessed for a long time.
23//! Applications should not rely on the length of the messages array to paginate
24//! results.
25//!
26//! Additionally, when messages are actively being created or deleted,
27//! [`SearchGuildMessagesOkResponseBody::total_results`] may not be accurate.
28//!
29//! # Examples
30//!
31//! Search for messages within two channels, including only messages with an
32//! image but excluding messages authored by bot users:
33//!
34//! ```rust,no_run
35//! use std::env;
36//! use twilight_http::{
37//!     Client,
38//!     request::guild::message::search_guild_messages::{
39//!         AuthorType, SearchFilter, SearchGuildMessages, SearchGuildMessagesResponseBody,
40//!         SearchHasType,
41//!     },
42//! };
43//! use twilight_model::id::Id;
44//!
45//! # fn find_channels() -> Vec<Id<twilight_model::id::marker::ChannelMarker>> {
46//! #     Vec::new()
47//! # }
48//! #
49//! # #[tokio::main]
50//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
51//! # let guild_id = Id::new(1);
52//! let client = Client::new(env::var("DISCORD_TOKEN")?);
53//! let channel_ids = find_channels();
54//!
55//! let response = client
56//!     .search_guild_messages(guild_id)
57//!     .channel_id(&channel_ids)
58//!     // Include only messages with polls
59//!     .has(&[SearchFilter::Include(SearchHasType::Poll)])
60//!     // Exclude messages authored by bots
61//!     .author_type(&[SearchFilter::Exclude(AuthorType::Bot)])
62//!     .await?;
63//! let body = response.model().await?;
64//!
65//! match body {
66//!     SearchGuildMessagesResponseBody::Accepted(accepted) => {
67//!         println!(
68//!             "message indexing in progress; retry in {} seconds",
69//!             accepted.retry_after
70//!         );
71//!     }
72//!     SearchGuildMessagesResponseBody::Ok(results) => {
73//!         println!("there are {} total results", results.total_results);
74//!     }
75//! }
76//! # Ok(()) }
77//! ```
78//!
79//! [`channel_id`]: SearchGuildMessages::channel_id
80//! [`Guild`]: twilight_model::guild::Guild
81
82pub use twilight_model::http::message_search::*;
83
84use crate::{
85    client::Client,
86    error::Error,
87    request::{Request, TryIntoRequest},
88    response::{Response, ResponseFuture},
89    routing::Route,
90};
91use serde::{Deserialize, Serialize};
92use std::future::IntoFuture;
93use twilight_model::{
94    channel::{Channel, Message, thread::ThreadMember},
95    id::{
96        Id,
97        marker::{ChannelMarker, GuildMarker, MessageMarker, RoleMarker, UserMarker},
98    },
99};
100use twilight_validate::search_guild_messages::{
101    SearchGuildMessagesError, attachment_extension as validate_attachment_extension,
102    attachment_filename as validate_attachment_filename, author_id as validate_author_id,
103    channel_id as validate_channel_id, content as validate_content,
104    embed_provider as validate_embed_provider, limit as validate_limit,
105    link_hostname as validate_link_hostname, mentions as validate_mentions,
106    mentions_role_id as validate_mentions_role_id, offset as validate_offset,
107    replied_to_message_id as validate_replied_to_message_id,
108    replied_to_user_id as validate_replied_to_user_id, slop as validate_slop,
109};
110
111mod response_body_messages {
112    //! serde deserializer and serializer for
113    //! [`SearchGuildMessagesOkResponseBody::messages`].
114    //!
115    //! The `messages` field is an array of array of message objects for
116    //! historical and now unused reasons. To simplify things for users, we
117    //! remove one layer of this nested array so users simply get an array of
118    //! messages.
119    //!
120    //! The JSON view of expected data is:
121    //!
122    //! ```json
123    //! [
124    //!   [
125    //!     {
126    //!       # message 1...
127    //!     }
128    //!   ],
129    //!   [
130    //!     {
131    //!       # message 2...
132    //!     }
133    //!   ]
134    //! ]
135    //! ```
136    //!
137    //! [`SearchGuildMessagesOkResponseBody::messages`]: super::SearchGuildMessagesOkResponseBody::messages
138
139    use serde::{
140        de::{Deserialize, Deserializer, Error as _},
141        ser::Serializer,
142    };
143    use twilight_model::channel::Message;
144
145    /// Deserialize a nested list of messages into a flattened list of messages.
146    pub fn deserialize<'de, D: Deserializer<'de>>(
147        deserializer: D,
148    ) -> Result<Vec<Message>, D::Error> {
149        let mut nested_array = Vec::<Vec<Message>>::deserialize(deserializer)?;
150
151        nested_array
152            .iter_mut()
153            .map(|wrapped_message| match wrapped_message.len() {
154                1 => Ok(wrapped_message.remove(0)),
155                0 | 2.. => Err(D::Error::invalid_length(
156                    wrapped_message.len(),
157                    &"nested array with 1 element, an array of messages",
158                )),
159            })
160            .collect()
161    }
162
163    /// Serialize a flattened list of messages into a nested list of messages,
164    /// where each entry in the top-level list contains only one item: the
165    /// message.
166    pub fn serialize<S: Serializer>(value: &[Message], serializer: S) -> Result<S::Ok, S::Error> {
167        serializer.collect_seq(value.iter().map(|message| [message]))
168    }
169}
170
171/// Potential successful response bodies.
172#[derive(Clone, Debug, Deserialize, Serialize)]
173#[serde(untagged)]
174pub enum SearchGuildMessagesResponseBody {
175    /// The request has been completed and indexed messages have been provided.
176    ///
177    /// The response is a 200 OK HTTP status code.
178    Ok(SearchGuildMessagesOkResponseBody),
179    /// The request has been accepted and the server is now indexing messages in
180    /// the guild.
181    ///
182    /// The request will have to be retried later. Refer to the documentation
183    /// for [`SearchGuildMessagesAcceptedResponseBody`] for more information.
184    ///
185    /// The response is a 202 Accepted HTTP status code.
186    Accepted(SearchGuildMessagesAcceptedResponseBody),
187}
188
189/// Body of the response when the returned status code is 200 OK.
190#[derive(Clone, Debug, Deserialize, Serialize)]
191pub struct SearchGuildMessagesOkResponseBody {
192    /// Whether the guild is undergoing a deep historical indexing operation.
193    pub doing_deep_historical_index: bool,
194    /// The number of documents that have been indexed during the current index
195    /// operation, if any.
196    #[serde(skip_serializing_if = "Option::is_none")]
197    pub documents_indexed: Option<u64>,
198    /// A thread member object for each thread returned in [`threads`] the
199    /// current user has joined.
200    ///
201    /// [`threads`]: Self::threads
202    #[serde(skip_serializing_if = "Option::is_none")]
203    pub members: Option<Vec<ThreadMember>>,
204    /// Messages that match the query.
205    #[serde(with = "response_body_messages")]
206    pub messages: Vec<Message>,
207    /// The threads that contain the returned messages.
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub threads: Option<Vec<Channel>>,
210    /// The total number of results that match the query.
211    pub total_results: u64,
212}
213
214/// Body of the response when the returned status code is 202 Accepted.
215#[derive(Clone, Debug, Deserialize, Serialize)]
216pub struct SearchGuildMessagesAcceptedResponseBody {
217    /// Unique identifying code for the error response.
218    pub code: u32,
219    /// The number of documents that have been indexed during the current index
220    /// operation, if any.
221    #[serde(default)]
222    pub documents_indexed: u64,
223    /// Human-legible reason for the [`code`][Self::code].
224    pub message: String,
225    /// Number of seconds to wait before trying again. If the value is 0 you
226    /// should retry the request after a short delay.
227    #[serde(default)]
228    pub retry_after: u64,
229}
230
231struct SearchGuildMessagesFields<'a> {
232    /// Filter messages by attachment extension (e.g. `txt`).
233    attachment_extension: Option<&'a [&'a str]>,
234    /// Filter messages by attachment filename.
235    attachment_filename: Option<&'a [&'a str]>,
236    /// Filter messages by these authors.
237    author_id: Option<&'a [Id<UserMarker>]>,
238    /// Filter messages by author type.
239    author_type: Option<&'a [SearchFilter<AuthorType>]>,
240    /// Filter messages by these channels.
241    channel_id: Option<&'a [Id<ChannelMarker>]>,
242    /// Filter messages by content.
243    content: Option<&'a str>,
244    /// Filter messages by embed provider (case-sensitive, e.g. `Tenor`).
245    embed_provider: Option<&'a [&'a str]>,
246    /// Filter messages by embed type.
247    embed_type: Option<&'a [SearchEmbedType]>,
248    /// Filter messages by whether or not they have specific things.
249    has: Option<&'a [SearchFilter<SearchHasType>]>,
250    /// Whether to include results from age-restricted channels.
251    ///
252    /// Discord defaults this to `false`.
253    include_nsfw: Option<bool>,
254    /// Max number of messages to return.
255    ///
256    /// Discord defaults this to 25.
257    limit: Option<u8>,
258    /// Filter messages by link hostname (e.g. `discordapp.com`).
259    link_hostname: Option<&'a [&'a str]>,
260    /// Get messages before this message ID.
261    max_id: Option<Id<MessageMarker>>,
262    /// Filter messages that do or do not mention `@everyone`.
263    mention_everyone: Option<bool>,
264    /// Filter messages that mention these users.
265    mentions: Option<&'a [Id<UserMarker>]>,
266    /// Filter messages that mention these roles.
267    mentions_role_id: Option<&'a [Id<RoleMarker>]>,
268    /// Get messages after this message ID.
269    min_id: Option<Id<MessageMarker>>,
270    /// Number to offset the returned messages by.
271    offset: Option<u16>,
272    /// Filter messages by whether they are or are not pinned.
273    pinned: Option<bool>,
274    /// Filter messages that reply to these messages.
275    replied_to_message_id: Option<&'a [Id<MessageMarker>]>,
276    /// Filter messages that reply to these users.
277    replied_to_user_id: Option<&'a [Id<UserMarker>]>,
278    /// Max number of words to skip between matching tokens in the search
279    /// content.
280    slop: Option<u16>,
281    /// The sorting algorithm to use.
282    sort_by: Option<SearchSortMode>,
283    /// The direction to sort.
284    ///
285    /// Discord defaults this to [`SearchSortOrder::Descending`].
286    sort_order: Option<SearchSortOrder>,
287}
288
289/// Search a guild's messages.
290///
291/// Returned messages do not have the `reactions` field.
292///
293/// Refer to the module-level documentation for more information about message
294/// indexing and pagination, as well as for examples.
295///
296/// Requires the [`READ_MESSAGE_HISTORY`] permission. This endpoint is
297/// restricted according to whether the [`MESSAGE_CONTENT` Privileged Intent]
298/// is enabled for your application.
299///
300/// [`READ_MESSAGE_HISTORY`]: twilight_model::guild::Permissions::READ_MESSAGE_HISTORY
301/// [`MESSAGE_CONTENT` Privileged Intent]: twilight_model::gateway::Intents::MESSAGE_CONTENT
302#[must_use = "requests must be configured and executed"]
303pub struct SearchGuildMessages<'a> {
304    fields: Result<SearchGuildMessagesFields<'a>, SearchGuildMessagesError>,
305    guild_id: Id<GuildMarker>,
306    http: &'a Client,
307}
308
309impl<'a> SearchGuildMessages<'a> {
310    pub(crate) const fn new(http: &'a Client, guild_id: Id<GuildMarker>) -> Self {
311        Self {
312            fields: Ok(SearchGuildMessagesFields {
313                attachment_extension: None,
314                attachment_filename: None,
315                author_id: None,
316                author_type: None,
317                channel_id: None,
318                content: None,
319                embed_provider: None,
320                embed_type: None,
321                has: None,
322                include_nsfw: None,
323                limit: None,
324                link_hostname: None,
325                max_id: None,
326                mention_everyone: None,
327                mentions: None,
328                mentions_role_id: None,
329                min_id: None,
330                offset: None,
331                pinned: None,
332                replied_to_message_id: None,
333                replied_to_user_id: None,
334                slop: None,
335                sort_by: None,
336                sort_order: None,
337            }),
338            guild_id,
339            http,
340        }
341    }
342
343    /// Filter messages by attachment extension (e.g. `txt`).
344    ///
345    /// # Errors
346    ///
347    /// Returns an error of type [`AttachmentExtensionCount`] if the number of
348    /// attachment extension entries is invalid.
349    ///
350    /// Returns an error of type [`AttachmentExtensionEntryLength`] if one of the
351    /// attachment extension entries has an invalid length.
352    ///
353    /// [`AttachmentExtensionCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::AttachmentExtensionCount
354    /// [`AttachmentExtensionEntryLength`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::AttachmentExtensionEntryLength
355    pub fn attachment_extension(mut self, attachment_extension: &'a [&'a str]) -> Self {
356        self.fields = self.fields.and_then(|mut fields| {
357            validate_attachment_extension(attachment_extension)?;
358            fields.attachment_extension = Some(attachment_extension);
359
360            Ok(fields)
361        });
362
363        self
364    }
365
366    /// Filter messages by attachment filename.
367    ///
368    /// # Errors
369    ///
370    /// Returns an error of type [`AttachmentFilenameCount`] if the number of
371    /// attachment filename entries is invalid.
372    ///
373    /// Returns an error of type [`AttachmentFilenameEntryLength`] if one of the
374    /// attachment filename entries has an invalid length.
375    ///
376    /// [`AttachmentFilenameCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::AttachmentFilenameCount
377    /// [`AttachmentFilenameEntryLength`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::AttachmentFilenameEntryLength
378    pub fn attachment_filename(mut self, attachment_filename: &'a [&'a str]) -> Self {
379        self.fields = self.fields.and_then(|mut fields| {
380            validate_attachment_filename(attachment_filename)?;
381            fields.attachment_filename = Some(attachment_filename);
382
383            Ok(fields)
384        });
385
386        self
387    }
388
389    /// Filter messages by these authors.
390    ///
391    /// # Errors
392    ///
393    /// Returns an error of type [`AuthorIdCount`] if the number of author IDs is
394    /// invalid.
395    ///
396    /// [`AuthorIdCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::AuthorIdCount
397    pub fn author_id(mut self, author_id: &'a [Id<UserMarker>]) -> Self {
398        self.fields = self.fields.and_then(|mut fields| {
399            validate_author_id(author_id)?;
400            fields.author_id = Some(author_id);
401
402            Ok(fields)
403        });
404
405        self
406    }
407
408    /// Filter messages by author type.
409    ///
410    /// This field can be negated, causing results to exclude a particular type.
411    /// Use [`SearchFilter::Exclude`] to exclude results.
412    pub fn author_type(mut self, author_type: &'a [SearchFilter<AuthorType>]) -> Self {
413        self.fields = self.fields.map(|mut fields| {
414            fields.author_type = Some(author_type);
415
416            fields
417        });
418
419        self
420    }
421
422    /// Filter messages by these channels.
423    ///
424    /// # Errors
425    ///
426    /// Returns an error of type [`ChannelIdCount`] if the number of channel IDs is
427    /// invalid.
428    ///
429    /// [`ChannelIdCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::ChannelIdCount
430    pub fn channel_id(mut self, channel_id: &'a [Id<ChannelMarker>]) -> Self {
431        self.fields = self.fields.and_then(|mut fields| {
432            validate_channel_id(channel_id)?;
433            fields.channel_id = Some(channel_id);
434
435            Ok(fields)
436        });
437
438        self
439    }
440
441    /// Filter messages by content.
442    ///
443    /// # Errors
444    ///
445    /// Returns an error of type [`ContentLength`] is the content is too long.
446    ///
447    /// [`ContentLength`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::ContentLength
448    pub fn content(mut self, content: &'a str) -> Self {
449        self.fields = self.fields.and_then(|mut fields| {
450            validate_content(content)?;
451            fields.content = Some(content);
452
453            Ok(fields)
454        });
455
456        self
457    }
458
459    /// Filter messages by embed provider (case-sensitive, e.g. `Tenor`).
460    ///
461    /// # Errors
462    ///
463    /// Returns an error of type [`EmbedProviderCount`] if the number of
464    /// embed provider entries is invalid.
465    ///
466    /// Returns an error of type [`EmbedProviderEntryLength`] if one of the
467    /// embed provider entries has an invalid length.
468    ///
469    /// [`EmbedProviderCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::EmbedProviderCount
470    /// [`EmbedProviderEntryLength`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::EmbedProviderEntryLength
471    pub fn embed_provider(mut self, embed_provider: &'a [&'a str]) -> Self {
472        self.fields = self.fields.and_then(|mut fields| {
473            validate_embed_provider(embed_provider)?;
474            fields.embed_provider = Some(embed_provider);
475
476            Ok(fields)
477        });
478
479        self
480    }
481
482    /// Filter messages by embed type.
483    pub fn embed_type(mut self, embed_type: &'a [SearchEmbedType]) -> Self {
484        self.fields = self.fields.map(|mut fields| {
485            fields.embed_type = Some(embed_type);
486
487            fields
488        });
489
490        self
491    }
492
493    /// Filter messages by whether or not they have specific things.
494    ///
495    /// This field can be negated, causing results to exclude a particular type.
496    /// Use [`SearchFilter::Exclude`] to exclude results.
497    pub fn has(mut self, has: &'a [SearchFilter<SearchHasType>]) -> Self {
498        self.fields = self.fields.map(|mut fields| {
499            fields.has = Some(has);
500
501            fields
502        });
503
504        self
505    }
506
507    /// Whether to include results from age-restricted channels.
508    ///
509    /// Discord defaults this to `false`.
510    pub fn include_nsfw(mut self, include_nsfw: bool) -> Self {
511        self.fields = self.fields.map(|mut fields| {
512            fields.include_nsfw = Some(include_nsfw);
513
514            fields
515        });
516
517        self
518    }
519
520    /// Max number of messages to return.
521    ///
522    /// Discord defaults this to 25.
523    ///
524    /// # Errors
525    ///
526    /// Returns an error of type [`Limit`] if the limit is invalid.
527    ///
528    /// [`Limit`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::Limit
529    pub fn limit(mut self, limit: u8) -> Self {
530        self.fields = self.fields.and_then(|mut fields| {
531            validate_limit(usize::from(limit))?;
532            fields.limit = Some(limit);
533
534            Ok(fields)
535        });
536
537        self
538    }
539
540    /// Filter messages by link hostname (e.g. `discordapp.com`).
541    ///
542    /// # Errors
543    ///
544    /// Returns an error of type [`LinkHostnameCount`] if the number of
545    /// link hostname entries is invalid.
546    ///
547    /// Returns an error of type [`LinkHostnameEntryLength`] if one of the
548    /// link hostname entries has an invalid length.
549    ///
550    /// [`LinkHostnameCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::LinkHostnameCount
551    /// [`LinkHostnameEntryLength`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::LinkHostnameEntryLength
552    pub fn link_hostname(mut self, link_hostname: &'a [&'a str]) -> Self {
553        self.fields = self.fields.and_then(|mut fields| {
554            validate_link_hostname(link_hostname)?;
555            fields.link_hostname = Some(link_hostname);
556
557            Ok(fields)
558        });
559
560        self
561    }
562
563    /// Get messages before this message ID.
564    pub fn max_id(mut self, max_id: Id<MessageMarker>) -> Self {
565        self.fields = self.fields.map(|mut fields| {
566            fields.max_id = Some(max_id);
567
568            fields
569        });
570
571        self
572    }
573
574    /// Filter messages that do or do not mention `@everyone`.
575    pub fn mention_everyone(mut self, mention_everyone: bool) -> Self {
576        self.fields = self.fields.map(|mut fields| {
577            fields.mention_everyone = Some(mention_everyone);
578
579            fields
580        });
581
582        self
583    }
584
585    /// Filter messages that mention these users.
586    ///
587    /// # Errors
588    ///
589    /// Returns an error of type [`MentionsCount`] if the number of mentions is
590    /// invalid.
591    ///
592    /// [`MentionsCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::MentionsCount
593    pub fn mentions(mut self, mentions: &'a [Id<UserMarker>]) -> Self {
594        self.fields = self.fields.and_then(|mut fields| {
595            validate_mentions(mentions)?;
596            fields.mentions = Some(mentions);
597
598            Ok(fields)
599        });
600
601        self
602    }
603
604    /// Filter messages that mention these roles.
605    ///
606    /// # Errors
607    ///
608    /// Returns an error of type [`MentionsRoleIdCount`] if the number of mention
609    /// roles is invalid.
610    ///
611    /// [`MentionsRoleIdCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::MentionsRoleIdCount
612    pub fn mentions_role_id(mut self, mentions_role_id: &'a [Id<RoleMarker>]) -> Self {
613        self.fields = self.fields.and_then(|mut fields| {
614            validate_mentions_role_id(mentions_role_id)?;
615            fields.mentions_role_id = Some(mentions_role_id);
616
617            Ok(fields)
618        });
619
620        self
621    }
622
623    /// Get messages after this message ID.
624    pub fn min_id(mut self, min_id: Id<MessageMarker>) -> Self {
625        self.fields = self.fields.map(|mut fields| {
626            fields.min_id = Some(min_id);
627
628            fields
629        });
630
631        self
632    }
633
634    /// Number to offset the returned messages by.
635    ///
636    /// # Errors
637    ///
638    /// Returns an error of type [`Offset`] if the offset is invalid.
639    ///
640    /// [`Offset`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::Offset
641    pub fn offset(mut self, offset: u16) -> Self {
642        self.fields = self.fields.and_then(|mut fields| {
643            validate_offset(usize::from(offset))?;
644            fields.offset = Some(offset);
645
646            Ok(fields)
647        });
648
649        self
650    }
651
652    /// Filter messages by whether they are or are not pinned.
653    pub fn pinned(mut self, pinned: bool) -> Self {
654        self.fields = self.fields.map(|mut fields| {
655            fields.pinned = Some(pinned);
656
657            fields
658        });
659
660        self
661    }
662
663    /// Filter messages that reply to these messages.
664    ///
665    /// # Errors
666    ///
667    /// Returns an error of type [`RepliedToMessageIdCount`] if the number of
668    /// replied to message IDs is invalid.
669    ///
670    /// [`RepliedToMessageIdCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::RepliedToMessageIdCount
671    pub fn replied_to_message_id(mut self, replied_to_message_id: &'a [Id<MessageMarker>]) -> Self {
672        self.fields = self.fields.and_then(|mut fields| {
673            validate_replied_to_message_id(replied_to_message_id)?;
674            fields.replied_to_message_id = Some(replied_to_message_id);
675
676            Ok(fields)
677        });
678
679        self
680    }
681
682    /// Filter messages that reply to these users.
683    ///
684    /// # Errors
685    ///
686    /// Returns an error of type [`RepliedToUserIdCount`] if the number of replied
687    /// to user IDs is invalid.
688    ///
689    /// [`RepliedToUserIdCount`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::RepliedToUserIdCount
690    pub fn replied_to_user_id(mut self, replied_to_user_id: &'a [Id<UserMarker>]) -> Self {
691        self.fields = self.fields.and_then(|mut fields| {
692            validate_replied_to_user_id(replied_to_user_id)?;
693            fields.replied_to_user_id = Some(replied_to_user_id);
694
695            Ok(fields)
696        });
697
698        self
699    }
700
701    /// Max number of words to skip between matching tokens in the search
702    /// content.
703    ///
704    /// Discord defaults this to 2.
705    ///
706    /// # Errors
707    ///
708    /// Returns an error of type [`Slop`] if the slop is invalid.
709    ///
710    /// [`Slop`]: twilight_validate::search_guild_messages::SearchGuildMessagesErrorType::Slop
711    pub fn slop(mut self, slop: u16) -> Self {
712        self.fields = self.fields.and_then(|mut fields| {
713            validate_slop(usize::from(slop))?;
714            fields.slop = Some(slop);
715
716            Ok(fields)
717        });
718
719        self
720    }
721
722    /// The sorting algorithm to use.
723    ///
724    /// When the sort mode is set to [`SearchSortMode::Relevance`] Discord will
725    /// not respect the sort order set via [`sort_order`][Self::sort_order].
726    ///
727    /// Discord defaults this to [`SearchSortMode::Timestamp`].
728    pub fn sort_by(mut self, sort_by: SearchSortMode) -> Self {
729        self.fields = self.fields.map(|mut fields| {
730            fields.sort_by = Some(sort_by);
731
732            fields
733        });
734
735        self
736    }
737
738    /// The direction to sort.
739    ///
740    /// Discord will not respect the sort order when the sort mode is
741    /// [`SearchSortMode::Relevance`] via [`sort_by`][Self::sort_by].
742    ///
743    /// Discord defaults this to [`SearchSortOrder::Descending`].
744    pub fn sort_order(mut self, sort_order: SearchSortOrder) -> Self {
745        self.fields = self.fields.map(|mut fields| {
746            fields.sort_order = Some(sort_order);
747
748            fields
749        });
750
751        self
752    }
753}
754
755impl IntoFuture for SearchGuildMessages<'_> {
756    type Output = Result<Response<SearchGuildMessagesResponseBody>, Error>;
757
758    type IntoFuture = ResponseFuture<SearchGuildMessagesResponseBody>;
759
760    fn into_future(self) -> Self::IntoFuture {
761        let http = self.http;
762
763        match self.try_into_request() {
764            Ok(request) => http.request(request),
765            Err(source) => ResponseFuture::error(source),
766        }
767    }
768}
769
770impl TryIntoRequest for SearchGuildMessages<'_> {
771    fn try_into_request(self) -> Result<Request, Error> {
772        let fields = self.fields.map_err(Error::validation)?;
773
774        Ok(Request::from_route(&Route::SearchGuildMessages {
775            attachment_extension: fields.attachment_extension,
776            attachment_filename: fields.attachment_filename,
777            author_id: fields.author_id,
778            author_type: fields.author_type,
779            channel_id: fields.channel_id,
780            content: fields.content,
781            embed_provider: fields.embed_provider,
782            embed_type: fields.embed_type,
783            guild_id: self.guild_id.get(),
784            has: fields.has,
785            include_nsfw: fields.include_nsfw,
786            limit: fields.limit,
787            link_hostname: fields.link_hostname,
788            max_id: fields.max_id.map(Id::get),
789            mention_everyone: fields.mention_everyone,
790            mentions: fields.mentions,
791            mentions_role_id: fields.mentions_role_id,
792            min_id: fields.min_id.map(Id::get),
793            offset: fields.offset,
794            pinned: fields.pinned,
795            replied_to_message_id: fields.replied_to_message_id,
796            replied_to_user_id: fields.replied_to_user_id,
797            slop: fields.slop,
798            sort_by: fields.sort_by,
799            sort_order: fields.sort_order,
800        }))
801    }
802}
803
804#[cfg(test)]
805mod tests {
806    use super::{SearchGuildMessagesResponseBody, response_body_messages};
807    use serde_json::Deserializer;
808    use twilight_model::{
809        channel::{Attachment, Message, message::MessageType},
810        id::Id,
811        user::User,
812        util::Timestamp,
813    };
814
815    fn message() -> Message {
816        Message {
817            activity: None,
818            application: None,
819            application_id: None,
820            attachments: Vec::from_iter([Attachment {
821                content_type: Some("image/png".to_owned()),
822                ephemeral: false,
823                duration_secs: None,
824                filename: "image.png".to_owned(),
825                flags: None,
826                description: None,
827                height: Some(1080),
828                id: Id::new(3),
829                placeholder: Some("zSeKDQIoCLiHeIKeiLyfrsBqCIaYaHJ2Vg".to_owned()),
830                placeholder_version: Some(1),
831                proxy_url: "https://media.discordapp.net/attachments/1/2/image.png".to_owned(),
832                size: 2_416_286,
833                title: None,
834                url: "https://cdn.discordapp.com/attachments/1/2/image.png".to_owned(),
835                waveform: None,
836                width: Some(1920),
837            }]),
838            author: User {
839                accent_color: None,
840                avatar: None,
841                avatar_decoration: None,
842                avatar_decoration_data: None,
843                banner: None,
844                bot: true,
845                discriminator: 1234,
846                email: None,
847                flags: None,
848                global_name: None,
849                id: Id::new(4),
850                locale: None,
851                mfa_enabled: None,
852                name: "bot".to_owned(),
853                premium_type: None,
854                primary_guild: None,
855                public_flags: None,
856                system: None,
857                verified: None,
858            },
859            call: None,
860            channel_id: Id::new(1),
861            components: Vec::new(),
862            content: "a message".to_owned(),
863            edited_timestamp: None,
864            embeds: Vec::new(),
865            flags: None,
866            guild_id: None,
867            id: Id::new(2),
868            #[expect(deprecated)]
869            interaction: None,
870            interaction_metadata: None,
871            kind: MessageType::Regular,
872            member: None,
873            mention_channels: Vec::new(),
874            mention_everyone: false,
875            mention_roles: Vec::new(),
876            mentions: Vec::new(),
877            message_snapshots: Vec::new(),
878            pinned: false,
879            poll: None,
880            reactions: Vec::new(),
881            reference: None,
882            referenced_message: None,
883            role_subscription_data: None,
884            sticker_items: Vec::new(),
885            timestamp: Timestamp::parse("2026-11-23T01:23:45.678000+00:00").unwrap(),
886            thread: None,
887            tts: false,
888            webhook_id: Some(Id::new(4)),
889        }
890    }
891
892    /// Assert that the custom deserializer for
893    /// [`SearchGuildMessagesOkResponseBody::messages`] deserializes nested
894    /// messages into a flattened list.
895    #[test]
896    fn response_body_messages_deserialization() {
897        let value = [[message()]];
898
899        let serialized = serde_json::to_string(&value).unwrap();
900        let mut deserializer = Deserializer::from_str(&serialized);
901        let actual = response_body_messages::deserialize(&mut deserializer).unwrap();
902        let expected = Vec::from_iter([message()]);
903
904        assert_eq!(actual, expected);
905    }
906
907    /// Assert that an Accepted response deserializes into the Accepted response
908    /// body variant.
909    #[test]
910    fn response_body_accepted_variant() {
911        let value = serde_json::json!({
912            "code": 110_000,
913            "documents_indexed": 0,
914            "message": "Index not yet available. Try again later",
915            "retry_after": 2,
916        });
917        let body: SearchGuildMessagesResponseBody = serde_json::from_value(value).unwrap();
918
919        assert!(matches!(body, SearchGuildMessagesResponseBody::Accepted(_)));
920    }
921
922    /// Assert that an Ok response deserializes into the Ok response body
923    /// variant.
924    #[test]
925    fn response_body_ok_variant() {
926        let value = serde_json::json!({
927            "doing_deep_historical_index": false,
928            "total_results": 1,
929            "messages": [[message()]],
930        });
931        let body: SearchGuildMessagesResponseBody = serde_json::from_value(value).unwrap();
932        let SearchGuildMessagesResponseBody::Ok(ok) = body else {
933            panic!("expected body to be Ok")
934        };
935
936        assert!(!ok.doing_deep_historical_index);
937        assert_eq!(ok.total_results, 1);
938        assert_eq!(ok.messages, Vec::from_iter([message()]));
939    }
940}