1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
use http::header::CONTENT_DISPOSITION;
use http::HeaderMap;
use reqwest::{multipart, Client};
use serde_json::{from_value, to_string, Value};
use crate::errors::{ChorusError, ChorusResult};
use crate::instance::ChorusUser;
use crate::ratelimiter::ChorusRequest;
use crate::types::{
Channel, CreateGreetMessage, LimitType, Message, MessageAck, MessageModifySchema,
MessageSearchEndpoint, MessageSearchQuery, MessageSendSchema, Snowflake,
};
impl Message {
#[allow(clippy::useless_conversion)]
/// Sends a message in the channel with the provided channel_id.
/// Returns the sent message.
///
/// # Reference
/// See <https://docs.discord.food/resources/message#create-message>
pub async fn send(
user: &mut ChorusUser,
channel_id: Snowflake,
mut message: MessageSendSchema,
) -> ChorusResult<Message> {
let url_api = user.belongs_to.read().unwrap().urls.api.clone();
if message.attachments.is_none() {
let chorus_request = ChorusRequest {
request: Client::new()
.post(format!("{}/channels/{}/messages", url_api, channel_id))
.json(&message),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<Message>(user)
.await
} else {
for (index, attachment) in message.attachments.iter_mut().enumerate() {
attachment.get_mut(index).unwrap().id = Some((index as u64).into());
}
let mut form = reqwest::multipart::Form::new();
let payload_json = to_string(&message).unwrap();
let payload_field = reqwest::multipart::Part::text(payload_json);
form = form.part("payload_json", payload_field);
for (index, attachment) in message.attachments.unwrap().into_iter().enumerate() {
let attachment_content = attachment.content;
let attachment_filename = attachment.filename;
let part_name = format!("files[{}]", index);
let content_disposition = format!(
"form-data; name=\"{}\"'; filename=\"{}\"",
part_name, &attachment_filename
);
let mut header_map = HeaderMap::new();
header_map.insert(CONTENT_DISPOSITION, content_disposition.parse().unwrap());
let part = multipart::Part::bytes(attachment_content)
.file_name(attachment_filename)
.headers(header_map);
form = form.part(part_name, part);
}
let chorus_request = ChorusRequest {
request: Client::new()
.post(format!("{}/channels/{}/messages", url_api, channel_id))
.multipart(form),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<Message>(user)
.await
}
}
/// Returns messages without the reactions key that match a search query in the guild or channel.
/// The messages that are direct results will have an extra hit key set to true.
/// If operating on a guild channel, this endpoint requires the `READ_MESSAGE_HISTORY`
/// permission to be present on the current user.
///
/// If the guild/channel you are searching is not yet indexed, the endpoint will return a 202 accepted response.
/// In this case, the method will return a [`ChorusError::InvalidResponse`] error.
///
/// # Reference:
/// See <https://docs.discord.food/resources/message#search-messages>
pub(crate) async fn search(
endpoint: MessageSearchEndpoint,
query: MessageSearchQuery,
user: &mut ChorusUser,
) -> ChorusResult<Vec<Message>> {
let limit_type = match &endpoint {
MessageSearchEndpoint::Channel(id) => LimitType::Channel(*id),
MessageSearchEndpoint::GuildChannel(id) => LimitType::Guild(*id),
};
let request = ChorusRequest {
limit_type,
request: Client::new()
.get(format!(
"{}/{}/messages/search",
&user.belongs_to.read().unwrap().urls.api,
endpoint
))
.json(&query),
}
.with_headers_for(user);
let result = request.send(user).await?;
let http_status = result.status();
let result_json = result.json::<Value>().await.unwrap();
if !result_json.is_object() {
return Err(ChorusError::InvalidResponse {
error: format!(
"Got unexpected Response, or Response which is not valid JSON. Response: \n{}",
result_json
),
http_status,
});
}
let value_map = result_json.as_object().unwrap();
if let Some(messages) = value_map.get("messages") {
if let Ok(response) = from_value::<Vec<Vec<Message>>>(messages.clone()) {
let result_messages: Vec<Message> = response.into_iter().flatten().collect();
return Ok(result_messages);
}
}
// The code below might be incorrect. We'll cross that bridge when we come to it
if !value_map.contains_key("code") || !value_map.contains_key("retry_after") {
return Err(ChorusError::InvalidResponse {
error: format!(
"Got unexpected Response, or Response which is not valid JSON. Response: \n{}",
result_json
),
http_status,
});
}
let code = value_map.get("code").unwrap().as_u64().unwrap();
let retry_after = value_map.get("retry_after").unwrap().as_u64().unwrap();
Err(ChorusError::NotFound {
error: format!(
"Index not yet available. Try again later. Code: {}. Retry after {}s",
code, retry_after
),
})
}
/// Returns all pinned messages in the channel as a Vector of message objects without the reactions key.
/// # Reference:
/// See: <https://docs.discord.food/resources/message#get-pinned-messages>
pub async fn get_sticky(
channel_id: Snowflake,
user: &mut ChorusUser,
) -> ChorusResult<Vec<Message>> {
let request = ChorusRequest {
request: Client::new().get(format!(
"{}/channels/{}/pins",
user.belongs_to.read().unwrap().urls.api,
channel_id
)),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
request
.send_and_deserialize_response::<Vec<Message>>(user)
.await
}
/// Pins a message in a channel. Requires the `MANAGE_MESSAGES` permission. Returns a 204 empty response on success.
/// The max pinned messages is 50.
///
/// # Reference:
/// See: <https://docs.discord.food/resources/message#pin-message>
pub async fn sticky(
channel_id: Snowflake,
message_id: Snowflake,
audit_log_reason: Option<String>,
user: &mut ChorusUser,
) -> ChorusResult<()> {
let request = ChorusRequest {
request: Client::new().put(format!(
"{}/channels/{}/pins/{}",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
)),
limit_type: LimitType::Channel(channel_id),
}
.with_maybe_audit_log_reason(audit_log_reason)
.with_headers_for(user);
request.send_and_handle_as_result(user).await
}
/// Unpins a message in a channel. Requires the `MANAGE_MESSAGES` permission. Returns a 204 empty response on success.
/// # Reference:
/// See: <https://docs.discord.food/resources/message#unpin-message>
pub async fn unsticky(
channel_id: Snowflake,
message_id: Snowflake,
audit_log_reason: Option<String>,
user: &mut ChorusUser,
) -> ChorusResult<()> {
let request = ChorusRequest {
request: Client::new().delete(format!(
"{}/channels/{}/pins/{}",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
)),
limit_type: LimitType::Channel(channel_id),
}
.with_maybe_audit_log_reason(audit_log_reason)
.with_headers_for(user);
request.send_and_handle_as_result(user).await
}
/// Returns a specific message object in the channel.
/// If operating on a guild channel, this endpoint requires the `READ_MESSAGE_HISTORY` permission to be present on the current user.
/// # Reference:
/// See: <https://docs.discord.food/resources/message#get-message>
pub async fn get(
channel_id: Snowflake,
message_id: Snowflake,
user: &mut ChorusUser,
) -> ChorusResult<Message> {
let chorus_request = ChorusRequest {
request: Client::new().get(format!(
"{}/channels/{}/messages/{}",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
)),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
chorus_request
.send_and_deserialize_response::<Message>(user)
.await
}
/// Posts a greet message to a channel. This endpoint requires the channel is a DM channel or you reply to a system message.
/// # Reference:
/// See: <https://docs.discord.food/resources/message#create-greet-message>
pub async fn create_greet(
channel_id: Snowflake,
schema: CreateGreetMessage,
user: &mut ChorusUser,
) -> ChorusResult<Message> {
let request = ChorusRequest {
request: Client::new()
.post(format!(
"{}/channels/{}/messages/greet",
user.belongs_to.read().unwrap().urls.api,
channel_id,
))
.json(&schema),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
request.send_and_deserialize_response::<Message>(user).await
}
/// Sets the channel's latest acknowledged message (marks a message as read) for the current user.
/// The message ID parameter does not need to be a valid message ID, but it must be a valid snowflake.
/// If the message ID is being set to a message sent prior to the latest acknowledged one,
/// manual should be true or the resulting read state update should be ignored by clients (but is still saved), resulting in undefined behavior.
/// In this case, mention_count should also be set to the amount of mentions unacknowledged as it is not automatically calculated by Discord.
///
/// Returns an optional token, which can be used as the new `ack` token for following `ack`s.
///
/// # Reference:
/// See: <https://docs.discord.food/resources/message#acknowledge-message>
pub async fn acknowledge(
channel_id: Snowflake,
message_id: Snowflake,
schema: MessageAck,
user: &mut ChorusUser,
) -> ChorusResult<Option<String>> {
let request = ChorusRequest {
request: Client::new()
.post(format!(
"{}/channels/{}/messages/{}/ack",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
))
.json(&schema),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
request
.send_and_deserialize_response::<Option<String>>(user)
.await
}
/// Crossposts a message in a News Channel to following channels.
/// This endpoint requires the `SEND_MESSAGES` permission, if the current user sent the message,
/// or additionally the `MANAGE_MESSAGES` permission, for all other messages, to be present for the current user.
///
/// # Reference:
/// See <https://docs.discord.food/resources/message#crosspost-message>
pub async fn crosspost(
channel_id: Snowflake,
message_id: Snowflake,
user: &mut ChorusUser,
) -> ChorusResult<Message> {
let request = ChorusRequest {
request: Client::new().post(format!(
"{}/channels/{}/messages/{}/crosspost",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
)),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
request.send_and_deserialize_response::<Message>(user).await
}
/// Hides a message from the feed of the guild the channel belongs to. Returns a 204 empty response on success.
///
/// # Reference:
/// See <https://docs.discord.food/resources/message#hide-message-from-guild-feed>
pub async fn hide_from_guild_feed(
channel_id: Snowflake,
message_id: Snowflake,
user: &mut ChorusUser,
) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}/hide-guild-feed",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
);
let request = ChorusRequest {
request: Client::new().delete(url),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
request.send_and_handle_as_result(user).await
}
/// Edits a previously sent message. All fields can be edited by the original message author.
/// Other users can only edit flags and only if they have the MANAGE_MESSAGES permission in the corresponding channel.
/// When specifying flags, ensure to include all previously set flags/bits in addition to ones that you are modifying.
/// When the content field is edited, the mentions array in the message object will be reconstructed from scratch based on the new content.
/// The allowed_mentions field of the edit request controls how this happens.
/// If there is no explicit allowed_mentions in the edit request, the content will be parsed with default allowances, that is,
/// without regard to whether or not an allowed_mentions was present in the request that originally created the message.
///
/// # Reference:
/// See: <https://docs.discord.food/resources/message#edit-message>
pub async fn modify(
channel_id: Snowflake,
message_id: Snowflake,
schema: MessageModifySchema,
user: &mut ChorusUser,
) -> ChorusResult<Message> {
let url = format!(
"{}/channels/{}/messages/{}",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
);
let request = ChorusRequest {
request: Client::new().patch(url).json(&schema),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
request.send_and_deserialize_response::<Message>(user).await
}
/// Deletes a message. If operating on a guild channel and trying to delete a message that was not sent by the current user,
/// this endpoint requires the `MANAGE_MESSAGES` permission. Returns a 204 empty response on success.
pub async fn delete(
channel_id: Snowflake,
message_id: Snowflake,
audit_log_reason: Option<String>,
user: &mut ChorusUser,
) -> ChorusResult<()> {
let url = format!(
"{}/channels/{}/messages/{}",
user.belongs_to.read().unwrap().urls.api,
channel_id,
message_id
);
let request = ChorusRequest {
request: Client::new().delete(url),
limit_type: LimitType::Channel(channel_id),
}
.with_maybe_audit_log_reason(audit_log_reason)
.with_headers_for(user);
request.send_and_handle_as_result(user).await
}
/// Deletes multiple messages in a single request. This endpoint can only be used on guild channels and requires the MANAGE_MESSAGES permission.
/// Returns a 204 empty response on success.
///
/// **This endpoint will not delete messages older than 2 weeks, and will fail if any message provided is older than that or if any duplicate message IDs are provided.**
///
/// **This endpoint is not usable by user accounts.** (At least according to Discord.com. Spacebar behaviour may differ.)
///
/// # Reference:
/// See: <https://docs.discord.food/resources/message#bulk-delete-messages>
pub async fn bulk_delete(
channel_id: Snowflake,
messages: Vec<Snowflake>,
audit_log_reason: Option<String>,
user: &mut ChorusUser,
) -> ChorusResult<()> {
if messages.len() < 2 {
return Err(ChorusError::InvalidArguments {
error: "`messages` must contain at least 2 entries.".to_string(),
});
}
let request = ChorusRequest {
request: Client::new()
.post(format!(
"{}/channels/{}/messages/bulk-delete",
user.belongs_to.read().unwrap().urls.api,
channel_id,
))
.json(&messages),
limit_type: LimitType::Channel(channel_id),
}
.with_maybe_audit_log_reason(audit_log_reason)
.with_headers_for(user);
request.send_and_handle_as_result(user).await
}
/// Acknowledges the currently pinned messages in a channel. Returns a 204 empty response on success.
///
/// # Reference:
/// See <https://docs.discord.food/resources/message#acknowledge-pinned-messages>
pub async fn acknowledge_pinned(
channel_id: Snowflake,
user: &mut ChorusUser,
) -> ChorusResult<()> {
let request = ChorusRequest {
request: Client::new().post(format!(
"{}/channels/{}/pins/ack",
user.belongs_to.read().unwrap().urls.api,
channel_id,
)),
limit_type: LimitType::Channel(channel_id),
}
.with_headers_for(user);
request.send_and_handle_as_result(user).await
}
}
impl ChorusUser {
/// Sends a message in the channel with the provided channel_id.
/// Returns the sent message.
///
/// # Notes
/// Shorthand call for [`Message::send`]
///
/// # Reference
/// See <https://docs.discord.food/resources/message#create-message>
pub async fn send_message(
&mut self,
message: MessageSendSchema,
channel_id: Snowflake,
) -> ChorusResult<Message> {
Message::send(self, channel_id, message).await
}
}
impl Channel {
/// Returns messages without the reactions key that match a search query in the channel.
/// The messages that are direct results will have an extra hit key set to true.
/// If operating on a guild channel, this endpoint requires the `READ_MESSAGE_HISTORY`
/// permission to be present on the current user.
///
/// If the guild/channel you are searching is not yet indexed, the endpoint will return a 202 accepted response.
/// In this case, the method will return a [`ChorusError::InvalidResponse`] error.
///
/// # Reference:
/// See <https://docs.discord.food/resources/message#search-messages>
pub async fn search_messages(
channel_id: Snowflake,
query: MessageSearchQuery,
user: &mut ChorusUser,
) -> ChorusResult<Vec<Message>> {
Message::search(MessageSearchEndpoint::Channel(channel_id), query, user).await
}
}