djs_rs/manager/message.rs
1//! [`MessageManager`].
2
3use std::{future::Future, sync::Arc};
4
5use djs_cache::{Backend, CachedMessage, CachedUser, ChannelView};
6use djs_collection::Collection;
7use djs_model::{
8 channel::Channel,
9 id::{ChannelId, MessageId, UserId},
10 rest::{
11 BulkDeleteMessages, CreateMessage, EditMessage, GetChannelMessages, GetReactions,
12 StartThreadFromMessage,
13 },
14};
15use djs_rest::{Error, ReactionEmoji};
16
17use super::Fetch;
18use crate::Context;
19
20/// The messages of one channel. Returned by [`Context::messages`].
21///
22/// discord.js counterpart: `MessageManager` (`channel.messages`), plus `TextChannel#send`
23/// and `TextChannel#bulkDelete`.
24#[derive(Debug)]
25pub struct MessageManager<'a, B: Backend> {
26 ctx: &'a Context<B>,
27 channel_id: ChannelId,
28}
29
30impl<B: Backend> Clone for MessageManager<'_, B> {
31 fn clone(&self) -> Self {
32 *self
33 }
34}
35
36impl<B: Backend> Copy for MessageManager<'_, B> {}
37
38impl<'a, B: Backend> MessageManager<'a, B> {
39 pub(crate) const fn new(ctx: &'a Context<B>, channel_id: ChannelId) -> Self {
40 Self { ctx, channel_id }
41 }
42
43 /// The channel these messages belong to.
44 ///
45 /// discord.js counterpart: `MessageManager#channel`.
46 #[must_use]
47 pub const fn channel_id(self) -> ChannelId {
48 self.channel_id
49 }
50
51 /// The cached messages of the channel, if the client has a cache.
52 ///
53 /// discord.js counterpart: `MessageManager#cache`.
54 #[must_use]
55 pub fn cache(self) -> Option<ChannelView<'a, MessageId, CachedMessage, B>> {
56 self.ctx
57 .cache()
58 .map(|cache| cache.messages(self.channel_id))
59 }
60
61 /// A message: the cached one, or [Get Channel
62 /// Message](djs_rest::Rest::get_channel_message), whose result is cached.
63 ///
64 /// discord.js counterpart: `MessageManager#fetch(id)`.
65 ///
66 /// # Errors
67 ///
68 /// Returns the REST error if Discord was asked and the request failed (it needs
69 /// `READ_MESSAGE_HISTORY` in guild channels).
70 pub fn fetch(
71 self,
72 message_id: MessageId,
73 ) -> Fetch<
74 Arc<CachedMessage>,
75 impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send + 'a,
76 > {
77 let cached = self.ctx.ops().message(self.channel_id, message_id);
78 let Self { ctx, channel_id } = self;
79 Fetch::new(cached, async move {
80 let message = ctx
81 .rest()
82 .get_channel_message(channel_id, message_id)
83 .await?;
84 Ok(ctx.store_message(&message))
85 })
86 }
87
88 /// Up to 100 messages, newest first ([Get Channel
89 /// Messages](djs_rest::Rest::get_channel_messages)); the messages are cached.
90 ///
91 /// discord.js counterpart: `MessageManager#fetch(options)`.
92 ///
93 /// # Errors
94 ///
95 /// Returns the REST error if the request failed.
96 pub async fn list(
97 self,
98 query: &GetChannelMessages,
99 ) -> Result<Collection<MessageId, Arc<CachedMessage>>, Error> {
100 let messages = self
101 .ctx
102 .rest()
103 .get_channel_messages(self.channel_id, query)
104 .await?;
105 Ok(messages
106 .iter()
107 .map(|message| (message.id, self.ctx.store_message(message)))
108 .collect())
109 }
110
111 /// Sends a message ([Create Message](djs_rest::Rest::create_message)); accepts anything
112 /// that converts into a [`CreateMessage`], such as `&str`. The sent message is cached.
113 ///
114 /// discord.js counterpart: `TextChannel#send`.
115 ///
116 /// # Errors
117 ///
118 /// Returns the REST error if the message could not be sent.
119 pub fn send(
120 self,
121 body: impl Into<CreateMessage>,
122 ) -> impl Future<Output = Result<Arc<CachedMessage>, Error>> + Send + 'a {
123 let body = body.into();
124 let Self { ctx, channel_id } = self;
125 async move {
126 let message = ctx.rest().create_message(channel_id, &body).await?;
127 Ok(ctx.store_message(&message))
128 }
129 }
130
131 /// Edits a message ([Edit Message](djs_rest::Rest::edit_message)); the result is cached.
132 ///
133 /// discord.js counterpart: `MessageManager#edit`.
134 ///
135 /// # Errors
136 ///
137 /// Returns the REST error if the request failed (only the author can edit the content).
138 pub async fn edit(
139 self,
140 message_id: MessageId,
141 body: &EditMessage,
142 ) -> Result<Arc<CachedMessage>, Error> {
143 let message = self
144 .ctx
145 .rest()
146 .edit_message(self.channel_id, message_id, body)
147 .await?;
148 Ok(self.ctx.store_message(&message))
149 }
150
151 /// Deletes a message ([Delete Message](djs_rest::Rest::delete_message)).
152 ///
153 /// discord.js counterpart: `MessageManager#delete`.
154 ///
155 /// # Errors
156 ///
157 /// Returns the REST error if the request failed (other users' messages need
158 /// `MANAGE_MESSAGES`).
159 pub async fn delete(self, message_id: MessageId) -> Result<(), Error> {
160 self.ctx
161 .rest()
162 .delete_message(self.channel_id, message_id)
163 .await
164 }
165
166 /// Deletes 2 to 100 messages at once, none older than two weeks ([Bulk Delete
167 /// Messages](djs_rest::Rest::bulk_delete_messages)).
168 ///
169 /// discord.js counterpart: `TextChannel#bulkDelete`.
170 ///
171 /// # Errors
172 ///
173 /// Returns the REST error if the request failed (it needs `MANAGE_MESSAGES`).
174 pub async fn bulk_delete(
175 self,
176 message_ids: Vec<MessageId>,
177 reason: Option<&str>,
178 ) -> Result<(), Error> {
179 self.ctx
180 .rest()
181 .bulk_delete_messages(
182 self.channel_id,
183 &BulkDeleteMessages::new(message_ids),
184 reason,
185 )
186 .await
187 }
188
189 /// Reacts to a message with an emoji: a `&str` for a Unicode emoji, or a custom
190 /// [`ReactionEmoji`].
191 ///
192 /// discord.js counterpart: `Message#react`.
193 ///
194 /// # Errors
195 ///
196 /// Returns the REST error if the request failed (`10014` Unknown Emoji for an emoji the
197 /// bot cannot use).
198 pub fn react<'e>(
199 self,
200 message_id: MessageId,
201 emoji: impl Into<ReactionEmoji<'e>>,
202 ) -> impl Future<Output = Result<(), Error>> + Send {
203 let emoji = emoji.into();
204 let Self { ctx, channel_id } = self;
205 async move {
206 ctx.rest()
207 .create_reaction(channel_id, message_id, emoji)
208 .await
209 }
210 }
211
212 /// Pins a message ([Pin Message](djs_rest::Rest::pin_message)).
213 ///
214 /// discord.js counterpart: `MessageManager#pin`.
215 ///
216 /// # Errors
217 ///
218 /// Returns the REST error if the request failed (it needs `PIN_MESSAGES`).
219 pub async fn pin(self, message_id: MessageId, reason: Option<&str>) -> Result<(), Error> {
220 self.ctx
221 .rest()
222 .pin_message(self.channel_id, message_id, reason)
223 .await
224 }
225
226 /// Unpins a message ([Unpin Message](djs_rest::Rest::unpin_message)).
227 ///
228 /// discord.js counterpart: `MessageManager#unpin`.
229 ///
230 /// # Errors
231 ///
232 /// Returns the REST error if the request failed.
233 pub async fn unpin(self, message_id: MessageId, reason: Option<&str>) -> Result<(), Error> {
234 self.ctx
235 .rest()
236 .unpin_message(self.channel_id, message_id, reason)
237 .await
238 }
239
240 /// Starts a thread from a message ([Start Thread from
241 /// Message](djs_rest::Rest::start_thread_from_message)); the thread is cached.
242 ///
243 /// discord.js counterpart: `Message#startThread`.
244 ///
245 /// # Errors
246 ///
247 /// Returns the REST error if the request failed.
248 pub async fn start_thread(
249 self,
250 message_id: MessageId,
251 body: &StartThreadFromMessage,
252 reason: Option<&str>,
253 ) -> Result<Arc<Channel>, Error> {
254 let thread = self
255 .ctx
256 .rest()
257 .start_thread_from_message(self.channel_id, message_id, body, reason)
258 .await?;
259 Ok(self.ctx.store_channel(&thread))
260 }
261
262 /// Publishes a message of an announcement channel to the channels following it
263 /// ([Crosspost Message](djs_rest::Rest::crosspost_message)).
264 ///
265 /// discord.js counterpart: `MessageManager#crosspost`.
266 ///
267 /// # Errors
268 ///
269 /// Returns the REST error if the request failed.
270 pub async fn crosspost(self, message_id: MessageId) -> Result<Arc<CachedMessage>, Error> {
271 let message = self
272 .ctx
273 .rest()
274 .crosspost_message(self.channel_id, message_id)
275 .await?;
276 Ok(self.ctx.store_message(&message))
277 }
278 /// The users who reacted to a message with an emoji ([Get
279 /// Reactions](djs_rest::Rest::get_reactions), up to 100 per page); the users are cached.
280 ///
281 /// discord.js counterpart: `ReactionUserManager#fetch`.
282 ///
283 /// # Errors
284 ///
285 /// Returns the REST error if the request failed.
286 pub async fn reaction_users(
287 self,
288 message_id: MessageId,
289 emoji: ReactionEmoji<'_>,
290 query: &GetReactions,
291 ) -> Result<Collection<UserId, Arc<CachedUser>>, Error> {
292 let users = self
293 .ctx
294 .rest()
295 .get_reactions(self.channel_id, message_id, emoji, query)
296 .await?;
297 Ok(users
298 .iter()
299 .map(|user| (user.id, self.ctx.store_user(user)))
300 .collect())
301 }
302
303 /// Removes a reaction: the bot's own with `user: None`, or another user's ([Delete Own
304 /// Reaction](djs_rest::Rest::delete_own_reaction) / [Delete User
305 /// Reaction](djs_rest::Rest::delete_user_reaction)).
306 ///
307 /// discord.js counterpart: `ReactionUserManager#remove`.
308 ///
309 /// # Errors
310 ///
311 /// Returns the REST error if the request failed (other users' reactions need
312 /// `MANAGE_MESSAGES`).
313 pub fn remove_reaction<'e>(
314 self,
315 message_id: MessageId,
316 emoji: impl Into<ReactionEmoji<'e>>,
317 user: Option<UserId>,
318 ) -> impl Future<Output = Result<(), Error>> + Send {
319 let emoji = emoji.into();
320 let Self { ctx, channel_id } = self;
321 async move {
322 match user {
323 None => {
324 ctx.rest()
325 .delete_own_reaction(channel_id, message_id, emoji)
326 .await
327 }
328 Some(user_id) => {
329 ctx.rest()
330 .delete_user_reaction(channel_id, message_id, emoji, user_id)
331 .await
332 }
333 }
334 }
335 }
336
337 /// Removes every reaction with one emoji ([Delete All Reactions for
338 /// Emoji](djs_rest::Rest::delete_all_reactions_for_emoji)).
339 ///
340 /// discord.js counterpart: `MessageReaction#remove`.
341 ///
342 /// # Errors
343 ///
344 /// Returns the REST error if the request failed (it needs `MANAGE_MESSAGES`).
345 pub fn remove_emoji_reactions<'e>(
346 self,
347 message_id: MessageId,
348 emoji: impl Into<ReactionEmoji<'e>>,
349 ) -> impl Future<Output = Result<(), Error>> + Send {
350 let emoji = emoji.into();
351 let Self { ctx, channel_id } = self;
352 async move {
353 ctx.rest()
354 .delete_all_reactions_for_emoji(channel_id, message_id, emoji)
355 .await
356 }
357 }
358
359 /// Removes every reaction from a message ([Delete All
360 /// Reactions](djs_rest::Rest::delete_all_reactions)).
361 ///
362 /// discord.js counterpart: `ReactionManager#removeAll`.
363 ///
364 /// # Errors
365 ///
366 /// Returns the REST error if the request failed (it needs `MANAGE_MESSAGES`).
367 pub async fn remove_all_reactions(self, message_id: MessageId) -> Result<(), Error> {
368 self.ctx
369 .rest()
370 .delete_all_reactions(self.channel_id, message_id)
371 .await
372 }
373}