-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathlib.rs
1754 lines (1618 loc) · 52.8 KB
/
lib.rs
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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Client library for the [Discord](https://discord.com) API.
//!
//! The Discord API can be divided into three main components: the RESTful API
//! to which calls can be made to take actions, a websocket-based permanent
//! connection over which state updates are received, and the voice calling
//! system.
//!
//! Log in to Discord with `Discord::new`, `new_cache`, or `from_bot_token` as appropriate.
//! The resulting value can be used to make REST API calls to post messages and manipulate Discord
//! state. Calling `connect()` will open a websocket connection, through which events can be
//! received. These two channels are enough to write a simple chatbot which can
//! read and respond to messages.
//!
//! For more in-depth tracking of Discord state, a `State` can be seeded with
//! the `ReadyEvent` obtained when opening a `Connection` and kept updated with
//! the events received over it.
//!
#![cfg_attr(
not(feature = "voice"),
doc = "*<b>NOTE</b>: The library has been compiled without voice support.*"
)]
//! To join voice servers, call `Connection::voice` to get a `VoiceConnection` and use `connect`
//! to join a channel, then `play` and `stop` to control playback. Manipulating deaf/mute state
//! and receiving audio are also possible.
//!
//! For examples, see the `examples` directory in the source tree.
#![warn(missing_docs)]
#![allow(deprecated)]
extern crate base64;
extern crate chrono;
extern crate flate2;
extern crate hyper;
extern crate hyper_native_tls;
extern crate multipart;
extern crate serde;
extern crate websocket;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate serde_json;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate log;
#[cfg(feature = "voice")]
extern crate byteorder;
#[cfg(feature = "voice")]
extern crate opus;
#[cfg(feature = "voice")]
extern crate sodiumoxide;
use std::collections::BTreeMap;
use std::time;
type Object = serde_json::Map<String, serde_json::Value>;
mod connection;
mod error;
mod ratelimit;
mod state;
#[cfg(feature = "voice")]
pub mod voice;
macro_rules! cdn_concat {
($e:expr) => {
// Out of everything, only the CDN still uses the old domain.
concat!("https://cdn.discordapp.com", $e)
};
}
#[macro_use]
mod serial;
pub mod builders;
pub mod model;
use builders::*;
pub use connection::Connection;
pub use error::{Error, Result};
use model::*;
use ratelimit::RateLimits;
pub use state::{ChannelRef, State};
const USER_AGENT: &'static str = concat!(
"DiscordBot (https://github.com/SpaceManiac/discord-rs, ",
env!("CARGO_PKG_VERSION"),
")"
);
macro_rules! api_concat {
($e:expr) => {
concat!("https://discord.com/api/v6", $e)
};
}
macro_rules! status_concat {
($e:expr) => {
concat!("https://status.discord.com/api/v2", $e)
};
}
macro_rules! request {
($self_:ident, $method:ident($body:expr), $url:expr, $($rest:tt)*) => {{
let path = format!(api_concat!($url), $($rest)*);
$self_.request(&path, || $self_.client.$method(&path).body(&$body))?
}};
($self_:ident, $method:ident, $url:expr, $($rest:tt)*) => {{
let path = format!(api_concat!($url), $($rest)*);
$self_.request(&path, || $self_.client.$method(&path))?
}};
($self_:ident, $method:ident($body:expr), $url:expr) => {{
let path = api_concat!($url);
$self_.request(path, || $self_.client.$method(path).body(&$body))?
}};
($self_:ident, $method:ident, $url:expr) => {{
let path = api_concat!($url);
$self_.request(path, || $self_.client.$method(path))?
}};
}
/// Client for the Discord REST API.
///
/// Log in to the API with a user's email and password using `new()`. Call
/// `connect()` to create a `Connection` on which to receive events. If desired,
/// use `logout()` to invalidate the token when done. Other methods manipulate
/// the Discord REST API.
pub struct Discord {
rate_limits: RateLimits,
client: hyper::Client,
token: String,
}
fn tls_client() -> hyper::Client {
let tls = hyper_native_tls::NativeTlsClient::new().expect("Error initializing NativeTlsClient");
let connector = hyper::net::HttpsConnector::new(tls);
hyper::Client::with_connector(connector)
}
impl Discord {
/// Log in to the Discord Rest API and acquire a token.
#[deprecated(note = "Login automation is not recommended. Use `from_user_token` instead.")]
pub fn new(email: &str, password: &str) -> Result<Discord> {
let mut map = BTreeMap::new();
map.insert("email", email);
map.insert("password", password);
let client = tls_client();
let response = check_status(
client
.post(api_concat!("/auth/login"))
.header(hyper::header::ContentType::json())
.header(hyper::header::UserAgent(USER_AGENT.to_owned()))
.body(&serde_json::to_string(&map)?)
.send(),
)?;
let mut json: BTreeMap<String, String> = serde_json::from_reader(response)?;
let token = match json.remove("token") {
Some(token) => token,
None => {
return Err(Error::Protocol(
"Response missing \"token\" in Discord::new()",
))
}
};
Ok(Discord {
rate_limits: RateLimits::default(),
client: client,
token: token,
})
}
/// Log in to the Discord Rest API, possibly using a cached login token.
///
/// Cached login tokens are keyed to the email address and will be read from
/// and written to the specified path. If no cached token was found and no
/// password was specified, an error is returned.
#[deprecated(note = "Login automation is not recommended. Use `from_user_token` instead.")]
#[allow(deprecated)]
pub fn new_cache<P: AsRef<std::path::Path>>(
path: P,
email: &str,
password: Option<&str>,
) -> Result<Discord> {
use std::fs::File;
use std::io::{BufRead, BufReader, Write};
// Read the cache, looking for our token
let path = path.as_ref();
let mut initial_token: Option<String> = None;
if let Ok(file) = File::open(path) {
for line in BufReader::new(file).lines() {
let line = line?;
let parts: Vec<_> = line.split('\t').collect();
if parts.len() == 2 && parts[0] == email {
initial_token = Some(parts[1].trim().into());
break;
}
}
}
// Perform the login
let discord = if let Some(ref initial_token) = initial_token {
let mut map = BTreeMap::new();
map.insert("email", email);
if let Some(password) = password {
map.insert("password", password);
}
let client = tls_client();
let response = check_status(
client
.post(api_concat!("/auth/login"))
.header(hyper::header::ContentType::json())
.header(hyper::header::UserAgent(USER_AGENT.to_owned()))
.header(hyper::header::Authorization(initial_token.clone()))
.body(&serde_json::to_string(&map)?)
.send(),
)?;
let mut json: BTreeMap<String, String> = serde_json::from_reader(response)?;
let token = match json.remove("token") {
Some(token) => token,
None => {
return Err(Error::Protocol(
"Response missing \"token\" in Discord::new()",
))
}
};
Discord {
rate_limits: RateLimits::default(),
client: client,
token: token,
}
} else if let Some(password) = password {
Discord::new(email, password)?
} else {
return Err(Error::Other(
"No password was specified and no cached token was found",
));
};
// Write the token back out, if needed
if initial_token.as_ref() != Some(&discord.token) {
let mut tokens = Vec::new();
tokens.push(format!("{}\t{}", email, discord.token));
if let Ok(file) = File::open(path) {
for line in BufReader::new(file).lines() {
let line = line?;
if line.split('\t').next() != Some(email) {
tokens.push(line);
}
}
}
let mut file = File::create(path)?;
for line in tokens {
file.write_all(line.as_bytes())?;
file.write_all(&[b'\n'])?;
}
}
Ok(discord)
}
fn from_token_raw(token: String) -> Discord {
Discord {
rate_limits: RateLimits::default(),
client: tls_client(),
token: token,
}
}
/// Log in as a bot account using the given authentication token.
///
/// The token will automatically be prefixed with "Bot ".
pub fn from_bot_token(token: &str) -> Result<Discord> {
Ok(Discord::from_token_raw(format!("Bot {}", token.trim())))
}
/// Log in as a user account using the given authentication token.
pub fn from_user_token(token: &str) -> Result<Discord> {
Ok(Discord::from_token_raw(token.trim().to_owned()))
}
/// Log out from the Discord API, invalidating this clients's token.
#[deprecated(note = "Accomplishes nothing and may fail for no reason.")]
pub fn logout(self) -> Result<()> {
let map = json! {{
"provider": null,
"token": null,
}};
let body = serde_json::to_string(&map)?;
check_empty(request!(self, post(body), "/auth/logout"))
}
fn request<'a, F: Fn() -> hyper::client::RequestBuilder<'a>>(
&self,
url: &str,
f: F,
) -> Result<hyper::client::Response> {
self.rate_limits.pre_check(url);
let f2 = || {
f().header(hyper::header::ContentType::json())
.header(hyper::header::Authorization(self.token.clone()))
};
let result = retry(&f2);
if let Ok(response) = result.as_ref() {
if self.rate_limits.post_update(url, response) {
// we were rate limited, we have slept, it is time to retry
// the request once. if it fails the second time, give up
debug!("Retrying after having been ratelimited");
let result = retry(f2);
if let Ok(response) = result.as_ref() {
self.rate_limits.post_update(url, response);
}
return check_status(result);
}
}
check_status(result)
}
/// Create a channel.
pub fn create_channel(
&self,
server: ServerId,
name: &str,
kind: ChannelType,
) -> Result<Channel> {
let map = json! {{
"name": name,
"type": kind.num(),
}};
let body = serde_json::to_string(&map)?;
let response = request!(self, post(body), "/guilds/{}/channels", server);
Channel::decode(serde_json::from_reader(response)?)
}
/// Get the list of channels in a server.
pub fn get_server_channels(&self, server: ServerId) -> Result<Vec<PublicChannel>> {
let response = request!(self, get, "/guilds/{}/channels", server);
decode_array(serde_json::from_reader(response)?, PublicChannel::decode)
}
/// Get information about a channel.
pub fn get_channel(&self, channel: ChannelId) -> Result<Channel> {
let response = request!(self, get, "/channels/{}", channel);
Channel::decode(serde_json::from_reader(response)?)
}
/// Edit a channel's details. See `EditChannel` for the editable fields.
///
/// ```ignore
/// // Edit a channel's name and topic
/// discord.edit_channel(channel_id, "general", |ch| ch
/// .topic("Welcome to the general chat!")
/// );
/// ```
pub fn edit_channel<F: FnOnce(EditChannel) -> EditChannel>(
&self,
channel: ChannelId,
f: F,
) -> Result<PublicChannel> {
// Work around the fact that this supposed PATCH call actually requires all fields
let mut map = Object::new();
match self.get_channel(channel)? {
Channel::Private(_) => return Err(Error::Other("Can not edit private channels")),
Channel::Public(channel) => {
map.insert("name".into(), channel.name.into());
map.insert("position".into(), channel.position.into());
match channel.kind {
ChannelType::Text => {
map.insert("topic".into(), json!(channel.topic));
}
ChannelType::Voice => {
map.insert("bitrate".into(), json!(channel.bitrate));
map.insert("user_limit".into(), json!(channel.user_limit));
}
_ => {
return Err(Error::Other(stringify!(format!(
"Unreachable channel type: {:?}",
channel.kind
))))
}
}
}
Channel::Group(group) => {
map.insert("name".into(), json!(group.name));
}
Channel::Category(_) => {}
Channel::News => {}
Channel::Store => {}
};
let map = EditChannel::__apply(f, map);
let body = serde_json::to_string(&map)?;
let response = request!(self, patch(body), "/channels/{}", channel);
PublicChannel::decode(serde_json::from_reader(response)?)
}
/// Delete a channel.
pub fn delete_channel(&self, channel: ChannelId) -> Result<Channel> {
let response = request!(self, delete, "/channels/{}", channel);
Channel::decode(serde_json::from_reader(response)?)
}
/// Indicate typing on a channel for the next 5 seconds.
pub fn broadcast_typing(&self, channel: ChannelId) -> Result<()> {
check_empty(request!(self, post, "/channels/{}/typing", channel))
}
/// Get a single message by ID from a given channel.
pub fn get_message(&self, channel: ChannelId, message: MessageId) -> Result<Message> {
let response = request!(self, get, "/channels/{}/messages/{}", channel, message);
from_reader(response)
}
/// Get messages in the backlog for a given channel.
///
/// The `what` argument should be one of the options in the `GetMessages`
/// enum, and will determine which messages will be returned. A message
/// limit can also be specified, and defaults to 50. More recent messages
/// will appear first in the list.
pub fn get_messages(
&self,
channel: ChannelId,
what: GetMessages,
limit: Option<u64>,
) -> Result<Vec<Message>> {
use std::fmt::Write;
let mut url = format!(
api_concat!("/channels/{}/messages?limit={}"),
channel,
limit.unwrap_or(50)
);
match what {
GetMessages::MostRecent => {}
GetMessages::Before(id) => {
let _ = write!(url, "&before={}", id);
}
GetMessages::After(id) => {
let _ = write!(url, "&after={}", id);
}
GetMessages::Around(id) => {
let _ = write!(url, "&around={}", id);
}
}
let response = self.request(&url, || self.client.get(&url))?;
from_reader(response)
}
/// Gets the pinned messages for a given channel.
pub fn get_pinned_messages(&self, channel: ChannelId) -> Result<Vec<Message>> {
let response = request!(self, get, "/channels/{}/pins", channel);
from_reader(response)
}
/// Pin the given message to the given channel.
///
/// Requires that the logged in account have the "MANAGE_MESSAGES" permission.
pub fn pin_message(&self, channel: ChannelId, message: MessageId) -> Result<()> {
check_empty(request!(
self,
put,
"/channels/{}/pins/{}",
channel,
message
))
}
/// Removes the given message from being pinned to the given channel.
///
/// Requires that the logged in account have the "MANAGE_MESSAGES" permission.
pub fn unpin_message(&self, channel: ChannelId, message: MessageId) -> Result<()> {
check_empty(request!(
self,
delete,
"/channels/{}/pins/{}",
channel,
message
))
}
/// Send a message to a given channel.
///
/// The `nonce` will be returned in the result and also transmitted to other
/// clients. The empty string is a good default if you don't care.
pub fn send_message_ex<F: FnOnce(SendMessage) -> SendMessage>(
&self,
channel: ChannelId,
f: F,
) -> Result<Message> {
let map = SendMessage::__build(f);
let body = serde_json::to_string(&map)?;
let response = request!(self, post(body), "/channels/{}/messages", channel);
from_reader(response)
}
/// Edit a previously posted message.
///
/// Requires that either the message was posted by this user, or this user
/// has permission to manage other members' messages.
///
/// Not all fields can be edited; see the [docs] for more.
/// [docs]: https://discord.com/developers/docs/resources/channel#edit-message
pub fn edit_message_ex<F: FnOnce(SendMessage) -> SendMessage>(
&self,
channel: ChannelId,
message: MessageId,
f: F,
) -> Result<Message> {
let map = SendMessage::__build(f);
let body = serde_json::to_string(&map)?;
let response = request!(
self,
patch(body),
"/channels/{}/messages/{}",
channel,
message
);
from_reader(response)
}
/// Send a message to a given channel.
///
/// The `nonce` will be returned in the result and also transmitted to other
/// clients. The empty string is a good default if you don't care.
pub fn send_message(
&self,
channel: ChannelId,
text: &str,
nonce: &str,
tts: bool,
) -> Result<Message> {
self.send_message_ex(channel, |b| b.content(text).nonce(nonce).tts(tts))
}
/// Edit a previously posted message.
///
/// Requires that either the message was posted by this user, or this user
/// has permission to manage other members' messages.
pub fn edit_message(
&self,
channel: ChannelId,
message: MessageId,
text: &str,
) -> Result<Message> {
self.edit_message_ex(channel, message, |b| b.content(text))
}
/// Delete a previously posted message.
///
/// Requires that either the message was posted by this user, or this user
/// has permission to manage other members' messages.
pub fn delete_message(&self, channel: ChannelId, message: MessageId) -> Result<()> {
check_empty(request!(
self,
delete,
"/channels/{}/messages/{}",
channel,
message
))
}
/// Bulk deletes a list of `MessageId`s from a given channel.
///
/// A minimum of 2 unique messages and a maximum of 100 unique messages may
/// be supplied, otherwise an `Error::Other` will be returned.
///
/// Each MessageId *should* be unique as duplicates will be removed from the
/// array before being sent to the Discord API.
///
/// Only bots can use this endpoint. Regular user accounts can not use this
/// endpoint under any circumstance.
///
/// Requires that either the message was posted by this user, or this user
/// has permission to manage other members' messages.
pub fn delete_messages(&self, channel: ChannelId, messages: &[MessageId]) -> Result<()> {
// Create a Vec of the underlying u64's of the message ids, then remove
// duplicates in it.
let mut ids: Vec<u64> = messages.into_iter().map(|m| m.0).collect();
ids.sort();
ids.dedup();
if ids.len() < 2 {
return Err(Error::Other("A minimum of 2 message ids must be supplied"));
} else if ids.len() > 100 {
return Err(Error::Other("A maximum of 100 message ids may be supplied"));
}
let map = json! {{ "messages": ids }};
let body = serde_json::to_string(&map)?;
check_empty(request!(
self,
post(body),
"/channels/{}/messages/bulk_delete",
channel
))
}
/// Send some embedded rich content attached to a message on a given channel.
///
/// See the `EmbedBuilder` struct for the editable fields.
/// `text` may be empty.
pub fn send_embed<F: FnOnce(EmbedBuilder) -> EmbedBuilder>(
&self,
channel: ChannelId,
text: &str,
f: F,
) -> Result<Message> {
self.send_message_ex(channel, |b| b.content(text).embed(f))
}
/// Edit the embed portion of a previously posted message.
///
/// The text is unmodified, but the previous embed is entirely replaced.
pub fn edit_embed<F: FnOnce(EmbedBuilder) -> EmbedBuilder>(
&self,
channel: ChannelId,
message: MessageId,
f: F,
) -> Result<Message> {
self.edit_message_ex(channel, message, |b| b.embed(f))
}
/// Send a file attached to a message on a given channel.
///
/// The `text` is allowed to be empty, but the filename must always be specified.
pub fn send_file<R: ::std::io::Read>(
&self,
channel: ChannelId,
text: &str,
mut file: R,
filename: &str,
) -> Result<Message> {
use std::io::Write;
let url = match hyper::Url::parse(&format!(api_concat!("/channels/{}/messages"), channel)) {
Ok(url) => url,
Err(_) => return Err(Error::Other("Invalid URL in send_file")),
};
// NB: We're NOT using the Hyper itegration of multipart in order not to wrestle with the openssl-sys dependency hell.
let cr = multipart::mock::ClientRequest::default();
let mut multi = multipart::client::Multipart::from_request(cr)?;
multi.write_text("content", text)?;
multi.write_stream("file", &mut file, Some(filename), None)?;
let http_buffer: multipart::mock::HttpBuffer = multi.send()?;
fn multipart_mime(bound: &str) -> hyper::mime::Mime {
use hyper::mime::{Attr, Mime, SubLevel, TopLevel, Value};
Mime(
TopLevel::Multipart,
SubLevel::Ext("form-data".into()),
vec![(Attr::Ext("boundary".into()), Value::Ext(bound.into()))],
)
}
let tls = hyper_native_tls::NativeTlsClient::new().expect("Error initializing NativeTlsClient");
let connector = hyper::net::HttpsConnector::new(tls);
let mut request = hyper::client::Request::with_connector(hyper::method::Method::Post, url, &connector)?;
request
.headers_mut()
.set(hyper::header::Authorization(self.token.clone()));
request
.headers_mut()
.set(hyper::header::UserAgent(USER_AGENT.to_owned()));
request
.headers_mut()
.set(hyper::header::ContentType(multipart_mime(
&http_buffer.boundary,
)));
let mut request = request.start()?;
request.write(&http_buffer.buf[..])?;
Message::decode(serde_json::from_reader(check_status(request.send())?)?)
}
/// Acknowledge this message as "read" by this client.
pub fn ack_message(&self, channel: ChannelId, message: MessageId) -> Result<()> {
check_empty(request!(
self,
post,
"/channels/{}/messages/{}/ack",
channel,
message
))
}
/// Create permissions for a `Channel` for a `Member` or `Role`.
///
/// # Examples
///
/// An example of creating channel role permissions for a `Member`:
///
/// ```ignore
/// use discord::model::{PermissionOverwriteType, permissions};
///
/// // Assuming that a `Discord` instance, member, and channel have already
/// // been defined previously.
/// let target = PermissionOverwrite {
/// kind: PermissionOverwriteType::Member(member.user.id),
/// allow: permissions::VOICE_CONNECT | permissions::VOICE_SPEAK,
/// deny: permissions::VOICE_MUTE_MEMBERS | permissions::VOICE_MOVE_MEMBERS,
/// };
/// let result = discord.create_permission(channel.id, target);
/// ```
///
/// The same can similarly be accomplished for a `Role`:
///
/// ```ignore
/// use discord::model::{PermissionOverwriteType, permissions};
///
/// // Assuming that a `Discord` instance, role, and channel have already
/// // been defined previously.
/// let target = PermissionOverwrite {
/// kind: PermissionOverwriteType::Role(role.id),
/// allow: permissions::VOICE_CONNECT | permissions::VOICE_SPEAK,
/// deny: permissions::VOICE_MUTE_MEMBERS | permissions::VOICE_MOVE_MEMBERS,
/// };
/// let result = discord.create_permission(channel.id, target);
/// ```
pub fn create_permission(&self, channel: ChannelId, target: PermissionOverwrite) -> Result<()> {
let (id, kind) = match target.kind {
PermissionOverwriteType::Member(id) => (id.0, "member"),
PermissionOverwriteType::Role(id) => (id.0, "role"),
};
let map = json! {{
"id": id,
"kind": kind,
"allow": target.allow.bits(),
"deny": target.deny.bits(),
}};
let body = serde_json::to_string(&map)?;
check_empty(request!(
self,
put(body),
"/channels/{}/permissions/{}",
channel,
id
))
}
/// Delete a `Member` or `Role`'s permissions for a `Channel`.
///
/// # Examples
///
/// Delete a `Member`'s permissions for a `Channel`:
///
/// ```ignore
/// use discord::model::PermissionOverwriteType;
///
/// // Assuming that a `Discord` instance, channel, and member have already
/// // been previously defined.
/// let target = PermissionOverwriteType::Member(member.user.id);
/// let response = discord.delete_permission(channel.id, target);
/// ```
///
/// The same can be accomplished for a `Role` similarly:
///
/// ```ignore
/// use discord::model::PermissionOverwriteType;
///
/// // Assuming that a `Discord` instance, channel, and role have already
/// // been previously defined.
/// let target = PermissionOverwriteType::Role(role.id);
/// let response = discord.delete_permission(channel.id, target);
/// ```
pub fn delete_permission(
&self,
channel: ChannelId,
permission_type: PermissionOverwriteType,
) -> Result<()> {
let id = match permission_type {
PermissionOverwriteType::Member(id) => id.0,
PermissionOverwriteType::Role(id) => id.0,
};
check_empty(request!(
self,
delete,
"/channels/{}/permissions/{}",
channel,
id
))
}
/// Add a `Reaction` to a `Message`.
///
/// # Examples
/// Add an unicode emoji to a `Message`:
///
/// ```ignore
/// // Assuming that a `Discord` instance, channel, message have
/// // already been previously defined.
/// use discord::model::ReactionEmoji;
///
/// let _ = discord.add_reaction(&channel.id, message.id, ReactionEmoji::Unicode("👌".to_string));
/// ```
///
/// Add a custom emoji to a `Message`:
///
/// ```ignore
/// // Assuming that a `Discord` instance, channel, message have
/// // already been previously defined.
/// use discord::model::{EmojiId, ReactionEmoji};
///
/// let _ = discord.add_reaction(&channel.id, message.id, ReactionEmoji::Custom {
/// name: "ThisIsFine",
/// id: EmojiId(1234)
/// });
/// ```
///
/// Requires the `ADD_REACTIONS` permission.
pub fn add_reaction(
&self,
channel: ChannelId,
message: MessageId,
emoji: ReactionEmoji,
) -> Result<()> {
let emoji = match emoji {
ReactionEmoji::Custom { name, id } => format!("{}:{}", name, id.0),
ReactionEmoji::Unicode(name) => name,
};
check_empty(request!(
self,
put,
"/channels/{}/messages/{}/reactions/{}/@me",
channel,
message,
emoji
))
}
/// Delete a `Reaction` from a `Message`.
///
/// # Examples
/// Delete a `Reaction` from a `Message` (unicode emoji):
///
/// ```ignore
/// // Assuming that a `Discord` instance, channel, message, state have
/// // already been previously defined.
/// use discord::model::ReactionEmoji;
///
/// let _ = discord.delete_reaction(&channel.id, message.id, None, ReactionEmoji::Unicode("👌".to_string()));
/// ```
///
/// Delete your `Reaction` from a `Message` (custom emoji):
///
/// ```ignore
/// // Assuming that a `Discord` instance, channel, message have
/// // already been previously defined.
/// use discord::model::ReactionEmoji;
///
/// let _ = discord.delete_reaction(&channel.id, message.id, None, ReactionEmoji::Custom {
/// name: "ThisIsFine",
/// id: EmojiId(1234)
/// });
/// ```
///
/// Delete someone else's `Reaction` from a `Message` (custom emoji):
///
/// ```ignore
/// // Assuming that a `Discord` instance, channel, message have
/// // already been previously defined.
/// use discord::model::{EmojiId, ReactionEmoji};
///
/// let _ = discord.delete_reaction(&channel.id, message.id, Some(UserId(1234)), ReactionEmoji::Custom {
/// name: "ThisIsFine",
/// id: EmojiId(1234)
/// });
/// ```
///
/// Requires `MANAGE_MESSAGES` if deleting someone else's `Reaction`.
pub fn delete_reaction(
&self,
channel: ChannelId,
message: MessageId,
user_id: Option<UserId>,
emoji: ReactionEmoji,
) -> Result<()> {
let emoji = match emoji {
ReactionEmoji::Custom { name, id } => format!("{}:{}", name, id.0),
ReactionEmoji::Unicode(name) => name,
};
let endpoint = format!(
"/channels/{}/messages/{}/reactions/{}/{}",
channel,
message,
emoji,
match user_id {
Some(id) => id.0.to_string(),
None => "@me".to_string(),
}
);
check_empty(request!(self, delete, "{}", endpoint))
}
/// Get reactors for the `Emoji` in a `Message`.
///
/// The default `limit` is 50. The optional value of `after` is the ID of
/// the user to retrieve the next reactions after.
pub fn get_reactions(
&self,
channel: ChannelId,
message: MessageId,
emoji: ReactionEmoji,
limit: Option<i32>,
after: Option<UserId>,
) -> Result<Vec<User>> {
let emoji = match emoji {
ReactionEmoji::Custom { name, id } => format!("{}:{}", name, id.0),
ReactionEmoji::Unicode(name) => name,
};
let mut endpoint = format!(
"/channels/{}/messages/{}/reactions/{}?limit={}",
channel,
message,
emoji,
limit.unwrap_or(50)
);
if let Some(amount) = after {
use std::fmt::Write;
let _ = write!(endpoint, "&after={}", amount);
}
let response = request!(self, get, "{}", endpoint);
from_reader(response)
}
/// Get the list of servers this user knows about.
pub fn get_servers(&self) -> Result<Vec<ServerInfo>> {
let response = request!(self, get, "/users/@me/guilds");
from_reader(response)
}
/// Gets a specific server.
pub fn get_server(&self, server_id: ServerId) -> Result<Server> {
let response = request!(self, get, "/guilds/{}", server_id);
from_reader(response)
}
/// Gets the list of a specific server's members.
pub fn get_server_members(&self, server_id: ServerId, limit: Option<u32>, after: Option<u32>) -> Result<Vec<Member>> {
let limit = limit.unwrap_or(1);
let after = after.unwrap_or(0);
let response = request!(self, get, "/guilds/{}/members?limit={}&after={}", server_id, limit, after);
from_reader(response)
}
/// Create a new server with the given name.
pub fn create_server(&self, name: &str, region: &str, icon: Option<&str>) -> Result<Server> {
let map = json! {{
"name": name,
"region": region,
"icon": icon,
}};
let body = serde_json::to_string(&map)?;
let response = request!(self, post(body), "/guilds");
from_reader(response)
}
/// Edit a server's information. See `EditServer` for the editable fields.
///
/// ```ignore
/// // Rename a server
/// discord.edit_server(server_id, |server| server.name("My Cool Server"));
/// // Edit many properties at once
/// discord.edit_server(server_id, |server| server
/// .name("My Cool Server")
/// .icon(Some("data:image/jpg;base64,..."))
/// .afk_timeout(300)
/// .region("us-south")
/// );
/// ```
pub fn edit_server<F: FnOnce(EditServer) -> EditServer>(
&self,
server_id: ServerId,
f: F,
) -> Result<Server> {
let map = EditServer::__build(f);
let body = serde_json::to_string(&map)?;
let response = request!(self, patch(body), "/guilds/{}", server_id);
from_reader(response)
}
/// Leave the given server.
pub fn leave_server(&self, server: ServerId) -> Result<Server> {
let response = request!(self, delete, "/users/@me/guilds/{}", server);
from_reader(response)
}
/// Delete the given server. Only available to the server owner.
pub fn delete_server(&self, server: ServerId) -> Result<Server> {
let response = request!(self, delete, "/guilds/{}", server);
from_reader(response)
}
/// Creates an emoji in a server.
///
/// `read_image` may be used to build an `image` string. Requires that the
/// logged in account be a user and have the `ADMINISTRATOR` or
/// `MANAGE_EMOJIS` permission.
pub fn create_emoji(&self, server: ServerId, name: &str, image: &str) -> Result<Emoji> {
let map = json! {{
"name": name,
"image": image,
}};