Skip to main content

djs_rest/endpoints/
message.rs

1//! [Message endpoints](https://docs.discord.com/developers/resources/message#get-channel-messages):
2//! messages, reactions and pins.
3
4use djs_model::{
5    id::{ChannelId, GuildId, MessageId, UserId},
6    message::Message,
7    rest::{
8        BulkDeleteMessages, ChannelPins, CreateMessage, EditMessage, GetChannelMessages,
9        GetChannelPins, GetReactions, MessageSearchResults, SearchGuildMessages,
10    },
11    user::User,
12};
13use http::StatusCode;
14
15use crate::{
16    Error, ErrorKind, ReactionEmoji, Request, Rest, Route, client::boxed, error::not_yet_indexed,
17};
18
19impl Rest {
20    /// [Get Channel Messages](https://docs.discord.com/developers/resources/message#get-channel-messages):
21    /// returns messages of a channel, newest first.
22    ///
23    /// Needs `VIEW_CHANNEL` (and `CONNECT` in voice channels); without
24    /// `READ_MESSAGE_HISTORY` the list is empty.
25    ///
26    /// discord.js counterpart: `MessageManager#fetch` with options.
27    ///
28    /// # Examples
29    ///
30    /// ```no_run
31    /// # async fn example(rest: djs_rest::Rest, channel_id: djs_model::id::ChannelId) -> Result<(), djs_rest::Error> {
32    /// use djs_model::rest::GetChannelMessages;
33    ///
34    /// let mut query = GetChannelMessages::default();
35    /// query.limit = Some(10);
36    /// for message in rest.get_channel_messages(channel_id, &query).await? {
37    ///     println!("{}: {}", message.author.username, message.content);
38    /// }
39    /// # Ok(())
40    /// # }
41    /// ```
42    ///
43    /// # Errors
44    ///
45    /// See [`Rest::request`].
46    pub fn get_channel_messages<'a>(
47        &'a self,
48        channel_id: ChannelId,
49        query: &'a GetChannelMessages,
50    ) -> impl Future<Output = Result<Vec<Message>, Error>> + Send + 'a {
51        boxed(async move {
52            self.call(Request::new(Route::GetChannelMessages { channel_id }).query(query))
53                .await
54        })
55    }
56
57    /// [Search Guild Messages](https://docs.discord.com/developers/resources/message#search-guild-messages):
58    /// searches the messages of a guild (without their reactions).
59    ///
60    /// Needs `READ_MESSAGE_HISTORY`, and depends on the `MESSAGE_CONTENT` privileged intent.
61    /// The search may return fewer messages than the limit, so page with `offset` or the IDs
62    /// rather than by counting.
63    ///
64    /// discord.js counterpart: none (discord.js does not wrap this endpoint).
65    ///
66    /// # Examples
67    ///
68    /// ```no_run
69    /// # async fn example(rest: djs_rest::Rest, guild_id: djs_model::id::GuildId) -> Result<(), djs_rest::Error> {
70    /// use djs_model::rest::SearchGuildMessages;
71    /// use djs_rest::ErrorKind;
72    ///
73    /// let mut query = SearchGuildMessages::default();
74    /// query.content = Some("release notes".into());
75    /// let results = loop {
76    ///     match rest.search_guild_messages(guild_id, &query).await {
77    ///         Err(error) => match error.kind() {
78    ///             ErrorKind::NotYetIndexed { retry_after, .. } => {
79    ///                 tokio::time::sleep((*retry_after).max(std::time::Duration::from_secs(1))).await;
80    ///             }
81    ///             _ => return Err(error),
82    ///         },
83    ///         Ok(results) => break results,
84    ///     }
85    /// };
86    /// println!("{} matching messages", results.total_results);
87    /// # Ok(())
88    /// # }
89    /// ```
90    ///
91    /// # Errors
92    ///
93    /// [`ErrorKind::NotYetIndexed`] while the guild is not indexed yet (D-104); otherwise see
94    /// [`Rest::request`].
95    pub fn search_guild_messages<'a>(
96        &'a self,
97        guild_id: GuildId,
98        query: &'a SearchGuildMessages,
99    ) -> impl Future<Output = Result<MessageSearchResults, Error>> + Send + 'a {
100        boxed(async move {
101            let request = Request::new(Route::SearchGuildMessages { guild_id }).query(query);
102            let (status, body) = self.execute(request).await?;
103            if status == StatusCode::ACCEPTED {
104                return Err(not_yet_indexed(&body));
105            }
106            serde_json::from_slice(&body)
107                .map_err(|source| Error::with_source(ErrorKind::Deserialize, source))
108        })
109    }
110
111    /// [Get Channel Message](https://docs.discord.com/developers/resources/message#get-channel-message):
112    /// returns one message.
113    ///
114    /// Needs `VIEW_CHANNEL` and `READ_MESSAGE_HISTORY` (and `CONNECT` in voice channels).
115    ///
116    /// discord.js counterpart: `MessageManager#fetch` with an ID.
117    ///
118    /// # Errors
119    ///
120    /// See [`Rest::request`]; `10008` Unknown Message if it does not exist.
121    pub fn get_channel_message(
122        &self,
123        channel_id: ChannelId,
124        message_id: MessageId,
125    ) -> impl Future<Output = Result<Message, Error>> + Send + '_ {
126        boxed(async move {
127            self.call(Request::new(Route::GetChannelMessage {
128                channel_id,
129                message_id,
130            }))
131            .await
132        })
133    }
134
135    /// [Create Message](https://docs.discord.com/developers/resources/message#create-message):
136    /// sends a message to a channel and returns it. With files, the request is sent as
137    /// `multipart/form-data`.
138    ///
139    /// Requires the `SEND_MESSAGES` permission in guild channels (and
140    /// `SEND_MESSAGES_IN_THREADS` in threads); replies need `READ_MESSAGE_HISTORY`, TTS
141    /// messages `SEND_TTS_MESSAGES`.
142    ///
143    /// discord.js counterpart: `TextChannel#send`.
144    ///
145    /// # Errors
146    ///
147    /// See [`Rest::request`]. Common API errors: `50001` Missing Access, `50013` Missing
148    /// Permissions, `50035` Invalid Form Body.
149    pub fn create_message<'a>(
150        &'a self,
151        channel_id: ChannelId,
152        body: &'a CreateMessage,
153    ) -> impl Future<Output = Result<Message, Error>> + Send + 'a {
154        boxed(async move {
155            self.call(
156                Request::new(Route::CreateMessage { channel_id })
157                    .json(body)?
158                    .files(&body.files),
159            )
160            .await
161        })
162    }
163
164    /// [Crosspost Message](https://docs.discord.com/developers/resources/message#crosspost-message):
165    /// publishes a message of an announcement channel to the channels following it.
166    ///
167    /// Needs `SEND_MESSAGES` for the bot's own messages, plus `MANAGE_MESSAGES` for others'.
168    ///
169    /// discord.js counterpart: `Message#crosspost`.
170    ///
171    /// # Errors
172    ///
173    /// See [`Rest::request`]; `40033` if the message was already published.
174    pub fn crosspost_message(
175        &self,
176        channel_id: ChannelId,
177        message_id: MessageId,
178    ) -> impl Future<Output = Result<Message, Error>> + Send + '_ {
179        boxed(async move {
180            self.call(Request::new(Route::CrosspostMessage {
181                channel_id,
182                message_id,
183            }))
184            .await
185        })
186    }
187
188    /// [Create Reaction](https://docs.discord.com/developers/resources/message#create-reaction):
189    /// reacts to a message as the bot.
190    ///
191    /// Needs `READ_MESSAGE_HISTORY`, and `ADD_REACTIONS` when nobody has reacted with this
192    /// emoji yet.
193    ///
194    /// discord.js counterpart: `Message#react`.
195    ///
196    /// # Examples
197    ///
198    /// ```no_run
199    /// # async fn example(rest: djs_rest::Rest, channel_id: djs_model::id::ChannelId, message_id: djs_model::id::MessageId) -> Result<(), djs_rest::Error> {
200    /// use djs_rest::ReactionEmoji;
201    ///
202    /// rest.create_reaction(channel_id, message_id, ReactionEmoji::Unicode("👍"))
203    ///     .await?;
204    /// # Ok(())
205    /// # }
206    /// ```
207    ///
208    /// # Errors
209    ///
210    /// See [`Rest::request`]; `10014` Unknown Emoji for an emoji the bot cannot use.
211    pub fn create_reaction<'a>(
212        &'a self,
213        channel_id: ChannelId,
214        message_id: MessageId,
215        emoji: ReactionEmoji<'a>,
216    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
217        boxed(async move {
218            self.call(Request::new(Route::CreateReaction {
219                channel_id,
220                message_id,
221                emoji,
222            }))
223            .await
224        })
225    }
226
227    /// [Delete Own Reaction](https://docs.discord.com/developers/resources/message#delete-own-reaction):
228    /// removes the bot's reaction.
229    ///
230    /// discord.js counterpart: `ReactionUserManager#remove` for the client user.
231    ///
232    /// # Errors
233    ///
234    /// See [`Rest::request`].
235    pub fn delete_own_reaction<'a>(
236        &'a self,
237        channel_id: ChannelId,
238        message_id: MessageId,
239        emoji: ReactionEmoji<'a>,
240    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
241        boxed(async move {
242            self.call(Request::new(Route::DeleteOwnReaction {
243                channel_id,
244                message_id,
245                emoji,
246            }))
247            .await
248        })
249    }
250
251    /// [Delete User Reaction](https://docs.discord.com/developers/resources/message#delete-user-reaction):
252    /// removes another user's reaction. Needs `MANAGE_MESSAGES`.
253    ///
254    /// discord.js counterpart: `ReactionUserManager#remove`.
255    ///
256    /// # Errors
257    ///
258    /// See [`Rest::request`].
259    pub fn delete_user_reaction<'a>(
260        &'a self,
261        channel_id: ChannelId,
262        message_id: MessageId,
263        emoji: ReactionEmoji<'a>,
264        user_id: UserId,
265    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
266        boxed(async move {
267            self.call(Request::new(Route::DeleteUserReaction {
268                channel_id,
269                message_id,
270                emoji,
271                user_id,
272            }))
273            .await
274        })
275    }
276
277    /// [Get Reactions](https://docs.discord.com/developers/resources/message#get-reactions):
278    /// returns the users who reacted with an emoji.
279    ///
280    /// discord.js counterpart: `ReactionUserManager#fetch`.
281    ///
282    /// # Errors
283    ///
284    /// See [`Rest::request`].
285    pub fn get_reactions<'a>(
286        &'a self,
287        channel_id: ChannelId,
288        message_id: MessageId,
289        emoji: ReactionEmoji<'a>,
290        query: &'a GetReactions,
291    ) -> impl Future<Output = Result<Vec<User>, Error>> + Send + 'a {
292        boxed(async move {
293            self.call(
294                Request::new(Route::GetReactions {
295                    channel_id,
296                    message_id,
297                    emoji,
298                })
299                .query(query),
300            )
301            .await
302        })
303    }
304
305    /// [Delete All Reactions](https://docs.discord.com/developers/resources/message#delete-all-reactions):
306    /// removes every reaction of a message. Needs `MANAGE_MESSAGES`.
307    ///
308    /// discord.js counterpart: `ReactionManager#removeAll`.
309    ///
310    /// # Errors
311    ///
312    /// See [`Rest::request`].
313    pub fn delete_all_reactions(
314        &self,
315        channel_id: ChannelId,
316        message_id: MessageId,
317    ) -> impl Future<Output = Result<(), Error>> + Send + '_ {
318        boxed(async move {
319            self.call(Request::new(Route::DeleteAllReactions {
320                channel_id,
321                message_id,
322            }))
323            .await
324        })
325    }
326
327    /// [Delete All Reactions for Emoji](https://docs.discord.com/developers/resources/message#delete-all-reactions-for-emoji):
328    /// removes every reaction with one emoji. Needs `MANAGE_MESSAGES`.
329    ///
330    /// discord.js counterpart: `MessageReaction#remove`.
331    ///
332    /// # Errors
333    ///
334    /// See [`Rest::request`].
335    pub fn delete_all_reactions_for_emoji<'a>(
336        &'a self,
337        channel_id: ChannelId,
338        message_id: MessageId,
339        emoji: ReactionEmoji<'a>,
340    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
341        boxed(async move {
342            self.call(Request::new(Route::DeleteAllReactionsForEmoji {
343                channel_id,
344                message_id,
345                emoji,
346            }))
347            .await
348        })
349    }
350
351    /// [Edit Message](https://docs.discord.com/developers/resources/message#edit-message):
352    /// changes a message and returns it. With files, the request is sent as
353    /// `multipart/form-data`; see [`EditMessage`] for how attachments are kept.
354    ///
355    /// The author can edit everything; others with `MANAGE_MESSAGES` only the flags.
356    ///
357    /// discord.js counterpart: `Message#edit`.
358    ///
359    /// # Errors
360    ///
361    /// See [`Rest::request`]; `50005` when editing someone else's content.
362    pub fn edit_message<'a>(
363        &'a self,
364        channel_id: ChannelId,
365        message_id: MessageId,
366        body: &'a EditMessage,
367    ) -> impl Future<Output = Result<Message, Error>> + Send + 'a {
368        boxed(async move {
369            self.call(
370                Request::new(Route::EditMessage {
371                    channel_id,
372                    message_id,
373                })
374                .json(body)?
375                .files(&body.files),
376            )
377            .await
378        })
379    }
380
381    /// [Delete Message](https://docs.discord.com/developers/resources/message#delete-message):
382    /// deletes a message; others' messages need `MANAGE_MESSAGES` in guild channels.
383    ///
384    /// Messages older than two weeks are deleted under a separate, stricter rate limit, which
385    /// the client tracks on its own.
386    ///
387    /// discord.js counterpart: `Message#delete`.
388    ///
389    /// # Errors
390    ///
391    /// See [`Rest::request`].
392    pub fn delete_message(
393        &self,
394        channel_id: ChannelId,
395        message_id: MessageId,
396    ) -> impl Future<Output = Result<(), Error>> + Send + '_ {
397        boxed(async move {
398            self.call(Request::new(Route::DeleteMessage {
399                channel_id,
400                message_id,
401            }))
402            .await
403        })
404    }
405
406    /// [Bulk Delete Messages](https://docs.discord.com/developers/resources/message#bulk-delete-messages):
407    /// deletes 2 to 100 messages at once (guild channels only, none older than two weeks).
408    /// Needs `MANAGE_MESSAGES`.
409    ///
410    /// `reason` is shown in the audit log (D-086).
411    ///
412    /// discord.js counterpart: `TextChannel#bulkDelete`.
413    ///
414    /// # Errors
415    ///
416    /// See [`Rest::request`]; `50034` if a message is too old, `50016` for fewer than 2 or
417    /// more than 100 messages.
418    pub fn bulk_delete_messages<'a>(
419        &'a self,
420        channel_id: ChannelId,
421        body: &'a BulkDeleteMessages,
422        reason: Option<&'a str>,
423    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
424        boxed(async move {
425            self.call(
426                Request::new(Route::BulkDeleteMessages { channel_id })
427                    .json(body)?
428                    .reason(reason),
429            )
430            .await
431        })
432    }
433
434    /// [Get Channel Pins](https://docs.discord.com/developers/resources/message#get-channel-pins):
435    /// returns a page of the pinned messages, newest first.
436    ///
437    /// Needs `VIEW_CHANNEL`; without `READ_MESSAGE_HISTORY` the list is empty.
438    ///
439    /// discord.js counterpart: `MessageManager#fetchPins`.
440    ///
441    /// # Errors
442    ///
443    /// See [`Rest::request`].
444    pub fn get_channel_pins<'a>(
445        &'a self,
446        channel_id: ChannelId,
447        query: &'a GetChannelPins,
448    ) -> impl Future<Output = Result<ChannelPins, Error>> + Send + 'a {
449        boxed(async move {
450            self.call(Request::new(Route::GetChannelPins { channel_id }).query(query))
451                .await
452        })
453    }
454
455    /// [Pin Message](https://docs.discord.com/developers/resources/message#pin-message):
456    /// pins a message. Needs `PIN_MESSAGES`.
457    ///
458    /// `reason` is shown in the audit log (D-086).
459    ///
460    /// discord.js counterpart: `Message#pin`.
461    ///
462    /// # Errors
463    ///
464    /// See [`Rest::request`]; `30003` when the channel has the maximum number of pins.
465    pub fn pin_message<'a>(
466        &'a self,
467        channel_id: ChannelId,
468        message_id: MessageId,
469        reason: Option<&'a str>,
470    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
471        boxed(async move {
472            self.call(
473                Request::new(Route::PinMessage {
474                    channel_id,
475                    message_id,
476                })
477                .reason(reason),
478            )
479            .await
480        })
481    }
482
483    /// [Unpin Message](https://docs.discord.com/developers/resources/message#unpin-message):
484    /// unpins a message. Needs `PIN_MESSAGES`.
485    ///
486    /// `reason` is shown in the audit log (D-086).
487    ///
488    /// discord.js counterpart: `Message#unpin`.
489    ///
490    /// # Errors
491    ///
492    /// See [`Rest::request`].
493    pub fn unpin_message<'a>(
494        &'a self,
495        channel_id: ChannelId,
496        message_id: MessageId,
497        reason: Option<&'a str>,
498    ) -> impl Future<Output = Result<(), Error>> + Send + 'a {
499        boxed(async move {
500            self.call(
501                Request::new(Route::UnpinMessage {
502                    channel_id,
503                    message_id,
504                })
505                .reason(reason),
506            )
507            .await
508        })
509    }
510}