-
Notifications
You must be signed in to change notification settings - Fork 562
/
mod.rs
1641 lines (1437 loc) · 55.9 KB
/
mod.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
//! The HTTP module which provides functions for performing requests to
//! endpoints in Discord's API.
//!
//! An important function of the REST API is ratelimiting. Requests to endpoints
//! are ratelimited to prevent spam, and once ratelimited Discord will stop
//! performing requests. The library implements protection to pre-emptively
//! ratelimit, to ensure that no wasted requests are made.
//!
//! The HTTP module comprises of two types of requests:
//!
//! - REST API requests, which require an authorization token;
//! - Other requests, which do not require an authorization token.
//!
//! The former require a [`Client`] to have logged in, while the latter may be
//! made regardless of any other usage of the library.
//!
//! If a request spuriously fails, it will be retried once.
//!
//! Note that you may want to perform requests through a [`Context`] or through
//! [model]s' instance methods where possible, as they each offer different
//! levels of a high-level interface to the HTTP module.
//!
//! [`Client`]: ../struct.Client.html
//! [`Context`]: ../struct.Context.html
//! [model]: ../../model/index.html
pub mod ratelimiting;
use hyper::client::{
Client as HyperClient,
RequestBuilder,
Response as HyperResponse,
Request,
};
use hyper::method::Method;
use hyper::status::StatusCode;
use hyper::{Error as HyperError, Result as HyperResult, Url, header};
use multipart::client::Multipart;
use self::ratelimiting::Route;
use serde_json::builder::ObjectBuilder;
use serde_json;
use std::collections::BTreeMap;
use std::default::Default;
use std::fmt::Write as FmtWrite;
use std::io::{ErrorKind as IoErrorKind, Read};
use std::sync::{Arc, Mutex};
use ::constants::{self, ErrorCode};
use ::internal::prelude::*;
use ::model::*;
use ::utils::decode_array;
lazy_static! {
static ref TOKEN: Arc<Mutex<String>> = Arc::new(Mutex::new(String::default()));
}
/// Sets the token to be used across all requests which require authentication.
///
/// This is really only for internal use, and if you are reading this as a user,
/// you should _not_ use this yourself.
#[doc(hidden)]
pub fn set_token(token: &str) {
TOKEN.lock().unwrap().clone_from(&token.to_owned());
}
/// Accepts the [`Invite`] given its code, placing the current user in the
/// [`Guild`] that the invite was for.
///
/// Use [`utils::parse_invite`] to retrieve codes from URLs.
///
/// Refer to the documentation for [`Context::accept_invite`] for restrictions on
/// accepting an invite.
///
/// This will fire the [`Client::on_guild_create`] handler once the associated
/// event is received.
///
/// **Note**: This will fail if you are already in the guild, or are banned. A
/// ban is equivalent to an IP ban.
///
/// **Note**: Requires that the current user be a user account. Bots can not
/// accept invites. Instead, they must be accepted via OAuth2 authorization
/// links. These are in the format of:
///
/// `https://discordapp.com/oauth2/authorize?client_id=CLIENT_ID&scope=bot`
///
/// # Examples
///
/// Accept an invite given a code from a URL:
///
/// ```rust,no_run
/// use serenity::client::rest;
/// use serenity::utils;
///
/// let url = "https://discord.gg/0cDvIgU2voY8RSYL";
/// let code = utils::parse_invite(url);
///
/// let _result = rest::accept_invite(code);
/// ```
///
/// [`Client::on_guild_create`]: ../struct.Client.html#method.on_guild_create
/// [`Context::accept_invite`]: ../struct.Context.html#method.accept_invite
/// [`Guild`]: ../../model/struct.Guild.html
/// [`Invite`]: ../../model/struct.Invite.html
/// [`utils::parse_invite`]: ../../utils/fn.parse_invite.html
pub fn accept_invite(code: &str) -> Result<Invite> {
let response = request!(Route::InvitesCode, post, "/invites/{}", code);
Invite::decode(serde_json::from_reader(response)?)
}
/// Marks a [`Channel`] as being "read" up to a certain [`Message`]. Any
/// message past the given one will not be marked as read.
///
/// Usually you should use this to mark the latest message as being read.
///
/// **Note**: Bot users should not use this, as it has no bearing on them
/// whatsoever.
///
/// [`Channel`]: ../../model/enum.Channel.html
/// [`Message`]: ../../model/struct.Message.html
pub fn ack_message(channel_id: u64, message_id: u64) -> Result<()> {
verify(204, request!(Route::ChannelsIdMessagesIdAck(channel_id),
post,
"/channels/{}/messages/{}/ack",
channel_id,
message_id))
}
/// Adds a [`User`] as a recipient to a [`Group`].
///
/// **Note**: Groups have a limit of 10 recipients, including the current user.
///
/// [`Group`]: ../../model/struct.Group.html
/// [`Group::add_recipient`]: ../../model/struct.Group.html#method.add_recipient
/// [`User`]: ../../model/struct.User.html
pub fn add_group_recipient(group_id: u64, user_id: u64) -> Result<()> {
verify(204, request!(Route::None,
put,
"/channels/{}/recipients/{}",
group_id,
user_id))
}
/// Adds a single [`Role`] to a [`Member`] in a [`Guild`].
///
/// **Note**: Requires the [Manage Roles] permission and respect of role
/// hierarchy.
///
/// [`Guild`]: ../../model/struct.Guild.html
/// [`Member`]: ../../model/struct.Member.html
/// [`Role`]: ../../model/struct.Role.html
/// [Manage Roles]: ../../model/permissions/constant.MANAGE_ROLES.html
pub fn add_member_role(guild_id: u64, user_id: u64, role_id: u64) -> Result<()> {
verify(204, request!(Route::GuildsIdMembersIdRolesId(guild_id),
put,
"/guilds/{}/members/{}/roles/{}",
guild_id,
user_id,
role_id))
}
/// Bans a [`User`] from a [`Guild`], removing their messages sent in the last
/// X number of days.
///
/// Passing a `delete_message_days` of `0` is equivalent to not removing any
/// messages. Up to `7` days' worth of messages may be deleted.
///
/// **Note**: Requires that you have the [Ban Members] permission.
///
/// [`Guild`]: ../../model/struct.Guild.html
/// [`User`]: ../../model/struct.User.html
/// [Ban Members]: ../../model/permissions/constant.BAN_MEMBERS.html
pub fn ban_user(guild_id: u64, user_id: u64, delete_message_days: u8) -> Result<()> {
verify(204, request!(Route::GuildsIdBansUserId(guild_id),
put,
"/guilds/{}/bans/{}?delete_message_days={}",
guild_id,
user_id,
delete_message_days))
}
/// Broadcasts that the current user is typing in the given [`Channel`].
///
/// This lasts for about 10 seconds, and will then need to be renewed to
/// indicate that the current user is still typing.
///
/// This should rarely be used for bots, although it is a good indicator that a
/// long-running command is still being processed.
///
/// [`Channel`]: ../../model/enum.Channel.html
pub fn broadcast_typing(channel_id: u64) -> Result<()> {
verify(204, request!(Route::ChannelsIdTyping(channel_id),
post,
"/channels/{}/typing",
channel_id))
}
/// Creates a [`GuildChannel`] in the [`Guild`] given its Id.
///
/// Refer to the Discord's [docs] for information on what fields this requires.
///
/// **Note**: Requires the [Manage Channels] permission.
///
/// [`Guild`]: ../../model/struct.Guild.html
/// [`GuildChannel`]: ../../model/struct.GuildChannel.html
/// [docs]: https://discordapp.com/developers/docs/resources/guild#create-guild-channel
/// [Manage Channels]: ../../model/permissions/constant.MANAGE_CHANNELS.html
pub fn create_channel(guild_id: u64, map: Value) -> Result<GuildChannel> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsIdChannels(guild_id),
post(body),
"/guilds/{}/channels",
guild_id);
GuildChannel::decode(serde_json::from_reader(response)?)
}
/// Creates an emoji in the given [`Guild`] with the given data.
///
/// View the source code for [`Context::create_emoji`] to see what fields this
/// requires.
///
/// **Note**: Requires the [Manage Emojis] permission.
///
/// [`Context::create_emoji`]: ../struct.Context.html#method.create_emoji
/// [`Guild`]: ../../model/struct.Guild.html
/// [Manage Emojis]: ../../model/permissions/constant.MANAGE_EMOJIS.html
pub fn create_emoji(guild_id: u64, map: Value) -> Result<Emoji> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsIdEmojis(guild_id),
post(body),
"/guilds/{}/emojis",
guild_id);
Emoji::decode(serde_json::from_reader(response)?)
}
/// Creates a guild with the data provided.
///
/// Only a [`PartialGuild`] will be immediately returned, and a full [`Guild`]
/// will be received over a [`Shard`], if at least one is running.
///
/// **Note**: This endpoint is usually only available for user accounts. Refer
/// to Discord's documentation for the endpoint [here][whitelist] for more
/// information. If your bot requires this, re-think what you are doing and
/// whether it _really_ needs to be doing this.
///
/// # Examples
///
/// Create a guild called `"test"` in the [US West region]:
///
/// ```rust,ignore
/// extern crate serde_json;
///
/// use serde_json::builder::ObjectBuilder;
/// use serde_json::Value;
/// use serenity::client::rest;
///
/// let map = ObjectBuilder::new()
/// .insert("name", "test")
/// .insert("region", "us-west")
/// .build();
///
/// let _result = rest::create_guild(map);
/// ```
///
/// [`Guild`]: ../../model/struct.Guild.html
/// [`PartialGuild`]: ../../model/struct.PartialGuild.html
/// [`Shard`]: ../gateway/struct.Shard.html
/// [US West Region]: ../../model/enum.Region.html#variant.UsWest
/// [whitelist]: https://discordapp.com/developers/docs/resources/guild#create-guild
pub fn create_guild(map: Value) -> Result<PartialGuild> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::Guilds, post(body), "/guilds");
PartialGuild::decode(serde_json::from_reader(response)?)
}
/// Creates an [`Integration`] for a [`Guild`].
///
/// Refer to Discord's [docs] for field information.
///
/// **Note**: Requires the [Manage Guild] permission.
///
/// [`Guild`]: ../../model/struct.Guild.html
/// [`Integration`]: ../../model/struct.Integration.html
/// [Manage Guild]: ../../model/permissions/constant.MANAGE_GUILD.html
/// [docs]: https://discordapp.com/developers/docs/resources/guild#create-guild-integration
pub fn create_guild_integration(guild_id: u64, integration_id: u64, map: Value) -> Result<()> {
let body = serde_json::to_string(&map)?;
verify(204, request!(Route::GuildsIdIntegrations(guild_id),
post(body),
"/guilds/{}/integrations/{}",
guild_id,
integration_id))
}
/// Creates a [`RichInvite`] for the given [channel][`GuildChannel`].
///
/// Refer to Discord's [docs] for field information.
///
/// All fields are optional.
///
/// **Note**: Requires the [Create Invite] permission.
///
/// [`GuildChannel`]: ../../model/struct.GuildChannel.html
/// [`RichInvite`]: ../../model/struct.RichInvite.html
/// [Create Invite]: ../../model/permissions/constant.CREATE_INVITE.html
/// [docs]: https://discordapp.com/developers/docs/resources/channel#create-channel-invite
pub fn create_invite(channel_id: u64, map: Value) -> Result<RichInvite> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::ChannelsIdInvites(channel_id),
post(body),
"/channels/{}/invites",
channel_id);
RichInvite::decode(serde_json::from_reader(response)?)
}
/// Creates a permission override for a member or a role in a channel.
pub fn create_permission(channel_id: u64, target_id: u64, map: Value) -> Result<()> {
let body = serde_json::to_string(&map)?;
verify(204, request!(Route::ChannelsIdPermissionsOverwriteId(channel_id),
put(body),
"/channels/{}/permissions/{}",
channel_id,
target_id))
}
/// Creates a private channel with a user.
pub fn create_private_channel(map: Value) -> Result<PrivateChannel> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::UsersMeChannels,
post(body),
"/users/@me/channels");
PrivateChannel::decode(serde_json::from_reader(response)?)
}
/// Reacts to a message.
pub fn create_reaction(channel_id: u64,
message_id: u64,
reaction_type: ReactionType)
-> Result<()> {
verify(204, request!(Route::ChannelsIdMessagesIdReactionsUserIdType(channel_id),
put,
"/channels/{}/messages/{}/reactions/{}/@me",
channel_id,
message_id,
reaction_type.as_data()))
}
/// Creates a role.
pub fn create_role(guild_id: u64, map: Value) -> Result<Role> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsIdRoles(guild_id),
post(body),
"/guilds/{}/roles",
guild_id);
Role::decode(serde_json::from_reader(response)?)
}
/// Creates a webhook for the given [channel][`GuildChannel`]'s Id, passing in
/// the given data.
///
/// This method requires authentication.
///
/// The Value is a map with the values of:
///
/// - **avatar**: base64-encoded 128x128 image for the webhook's default avatar
/// (_optional_);
/// - **name**: the name of the webhook, limited to between 2 and 100 characters
/// long.
///
/// # Examples
///
/// Creating a webhook named `test`:
///
/// ```rust,ignore
/// extern crate serde_json;
/// extern crate serenity;
///
/// use serde_json::builder::ObjectBuilder;
/// use serenity::client::rest;
///
/// let channel_id = 81384788765712384;
/// let map = ObjectBuilder::new().insert("name", "test").build();
///
/// let webhook = rest::create_webhook(channel_id, map).expect("Error creating");
/// ```
///
/// [`GuildChannel`]: ../../model/struct.GuildChannel.html
pub fn create_webhook(channel_id: u64, map: Value) -> Result<Webhook> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::ChannelsIdWebhooks(channel_id),
post(body),
"/channels/{}/webhooks",
channel_id);
Webhook::decode(serde_json::from_reader(response)?)
}
/// Deletes a private channel or a channel in a guild.
pub fn delete_channel(channel_id: u64) -> Result<Channel> {
let response = request!(Route::ChannelsId(channel_id),
delete,
"/channels/{}",
channel_id);
Channel::decode(serde_json::from_reader(response)?)
}
/// Deletes an emoji from a server.
pub fn delete_emoji(guild_id: u64, emoji_id: u64) -> Result<()> {
verify(204, request!(Route::GuildsIdEmojisId(guild_id),
delete,
"/guilds/{}/emojis/{}",
guild_id,
emoji_id))
}
/// Deletes a guild, only if connected account owns it.
pub fn delete_guild(guild_id: u64) -> Result<PartialGuild> {
let response = request!(Route::GuildsId(guild_id),
delete,
"/guilds/{}",
guild_id);
PartialGuild::decode(serde_json::from_reader(response)?)
}
/// Remvoes an integration from a guild.
pub fn delete_guild_integration(guild_id: u64, integration_id: u64) -> Result<()> {
verify(204, request!(Route::GuildsIdIntegrationsId(guild_id),
delete,
"/guilds/{}/integrations/{}",
guild_id,
integration_id))
}
/// Deletes an invite by code.
pub fn delete_invite(code: &str) -> Result<Invite> {
let response = request!(Route::InvitesCode, delete, "/invites/{}", code);
Invite::decode(serde_json::from_reader(response)?)
}
/// Deletes a message if created by us or we have
/// specific permissions.
pub fn delete_message(channel_id: u64, message_id: u64) -> Result<()> {
verify(204, request!(Route::ChannelsIdMessagesId(channel_id),
delete,
"/channels/{}/messages/{}",
channel_id,
message_id))
}
/// Deletes a bunch of messages, only works for bots.
pub fn delete_messages(channel_id: u64, map: Value) -> Result<()> {
let body = serde_json::to_string(&map)?;
verify(204, request!(Route::ChannelsIdMessagesBulkDelete(channel_id),
post(body),
"/channels/{}/messages/bulk_delete",
channel_id))
}
/// Deletes all of the [`Reaction`]s associated with a [`Message`].
///
/// # Examples
///
/// ```rust,no_run
/// use serenity::client::rest;
/// use serenity::model::{ChannelId, MessageId};
///
/// let channel_id = ChannelId(7);
/// let message_id = MessageId(8);
///
/// let _ = rest::delete_message_reactions(channel_id.0, message_id.0)
/// .expect("Error deleting reactions");
/// ```
///
/// [`Message`]: ../../model/struct.Message.html
/// [`Reaction`]: ../../model/struct.Reaction.html
pub fn delete_message_reactions(channel_id: u64, message_id: u64) -> Result<()> {
verify(204, request!(Route::ChannelsIdMessagesIdReactions(channel_id),
delete,
"/channels/{}/messages/{}/reactions",
channel_id,
message_id))
}
/// Deletes a permission override from a role or a member in a channel.
pub fn delete_permission(channel_id: u64, target_id: u64) -> Result<()> {
verify(204, request!(Route::ChannelsIdPermissionsOverwriteId(channel_id),
delete,
"/channels/{}/permissions/{}",
channel_id,
target_id))
}
/// Deletes a reaction from a message if owned by us or
/// we have specific permissions.
pub fn delete_reaction(channel_id: u64,
message_id: u64,
user_id: Option<u64>,
reaction_type: ReactionType)
-> Result<()> {
let user = user_id.map(|uid| uid.to_string()).unwrap_or_else(|| "@me".to_string());
verify(204, request!(Route::ChannelsIdMessagesIdReactionsUserIdType(channel_id),
delete,
"/channels/{}/messages/{}/reactions/{}/{}",
channel_id,
message_id,
reaction_type.as_data(),
user))
}
/// Deletes a role from a server. Can't remove the default everyone role.
pub fn delete_role(guild_id: u64, role_id: u64) -> Result<()> {
verify(204, request!(Route::GuildsIdRolesId(guild_id),
delete,
"/guilds/{}/roles/{}",
guild_id,
role_id))
}
/// Deletes a [`Webhook`] given its Id.
///
/// This method requires authentication, whereas [`delete_webhook_with_token`]
/// does not.
///
/// # Examples
///
/// Deletes a webhook given its Id:
///
/// ```rust,no_run
/// use serenity::client::{Client, rest};
/// use std::env;
///
/// // Due to the `delete_webhook` function requiring you to authenticate, you
/// // must have initialized a client first.
/// let client = Client::login_user(&env::var("DISCORD_TOKEN").unwrap());
///
/// rest::delete_webhook(245037420704169985).expect("Error deleting webhook");
/// ```
///
/// [`Webhook`]: ../../model/struct.Webhook.html
/// [`delete_webhook_with_token`]: fn.delete_webhook_with_token.html
pub fn delete_webhook(webhook_id: u64) -> Result<()> {
verify(204, request!(Route::WebhooksId, delete, "/webhooks/{}", webhook_id))
}
/// Deletes a [`Webhook`] given its Id and unique token.
///
/// This method does _not_ require authentication.
///
/// # Examples
///
/// Deletes a webhook given its Id and unique token:
///
/// ```rust,no_run
/// use serenity::client::rest;
///
/// let id = 245037420704169985;
/// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
///
/// rest::delete_webhook_with_token(id, token).expect("Error deleting webhook");
///
/// [`Webhook`]: ../../model/struct.Webhook.html
pub fn delete_webhook_with_token(webhook_id: u64, token: &str) -> Result<()> {
let client = HyperClient::new();
verify(204, retry(|| client
.delete(&format!(api!("/webhooks/{}/{}"), webhook_id, token)))
.map_err(Error::Hyper)?)
}
/// Changes channel information.
pub fn edit_channel(channel_id: u64, map: Value) -> Result<GuildChannel> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::ChannelsId(channel_id),
patch(body),
"/channels/{}",
channel_id);
GuildChannel::decode(serde_json::from_reader(response)?)
}
/// Changes emoji information.
pub fn edit_emoji(guild_id: u64, emoji_id: u64, map: Value) -> Result<Emoji> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsIdEmojisId(guild_id),
patch(body),
"/guilds/{}/emojis/{}",
guild_id,
emoji_id);
Emoji::decode(serde_json::from_reader(response)?)
}
/// Changes guild information.
pub fn edit_guild(guild_id: u64, map: Value) -> Result<PartialGuild> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsId(guild_id),
patch(body),
"/guilds/{}",
guild_id);
PartialGuild::decode(serde_json::from_reader(response)?)
}
/// Edits a [`Guild`]'s embed setting.
///
/// [`Guild`]: ../../model/struct.Guild.html
pub fn edit_guild_embed(guild_id: u64, map: Value) -> Result<GuildEmbed> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsIdEmbed(guild_id),
patch(body),
"/guilds/{}/embed",
guild_id);
GuildEmbed::decode(serde_json::from_reader(response)?)
}
/// Does specific actions to a member.
pub fn edit_member(guild_id: u64, user_id: u64, map: Value) -> Result<()> {
let body = serde_json::to_string(&map)?;
verify(204, request!(Route::GuildsIdMembersId(guild_id),
patch(body),
"/guilds/{}/members/{}",
guild_id,
user_id))
}
/// Edits a message by Id.
///
/// **Note**: Only the author of a message can modify it.
pub fn edit_message(channel_id: u64, message_id: u64, map: Value) -> Result<Message> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::ChannelsIdMessagesId(channel_id),
patch(body),
"/channels/{}/messages/{}",
channel_id,
message_id);
Message::decode(serde_json::from_reader(response)?)
}
/// Edits the current user's nickname for the provided [`Guild`] via its Id.
///
/// Pass `None` to reset the nickname.
///
/// [`Guild`]: ../../model/struct.Guild.html
pub fn edit_nickname(guild_id: u64, new_nickname: Option<&str>) -> Result<()> {
let map = ObjectBuilder::new().insert("nick", new_nickname).build();
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsIdMembersMeNick(guild_id),
patch(body),
"/guilds/{}/members/@me/nick",
guild_id);
verify(200, response)
}
/// Changes a profile note.
pub fn edit_note(user_id: u64, map: Value) -> Result<()> {
let body = serde_json::to_string(&map)?;
verify(204, request!(Route::None,
put(body),
"/users/@me/notes/{}",
user_id))
}
/// Edits the current user's profile settings.
///
/// For bot users, the password is optional.
///
/// # User Accounts
///
/// If a new token is received due to a password change, then the stored token
/// internally will be updated.
///
/// **Note**: this token change may cause requests made between the actual token
/// change and when the token is internally changed to be invalid requests, as
/// the token may be outdated.
pub fn edit_profile(map: Value) -> Result<CurrentUser> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::UsersMe, patch(body), "/users/@me");
let mut map: BTreeMap<String, Value> = serde_json::from_reader(response)?;
if !TOKEN.lock().unwrap().starts_with("Bot ") {
if let Some(Value::String(token)) = map.remove("token") {
set_token(&token);
}
}
CurrentUser::decode(Value::Object(map))
}
/// Changes a role in a guild.
pub fn edit_role(guild_id: u64, role_id: u64, map: Value)
-> Result<Role> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::GuildsIdRolesId(guild_id),
patch(body),
"/guilds/{}/roles/{}",
guild_id,
role_id);
Role::decode(serde_json::from_reader(response)?)
}
/// Edits a the webhook with the given data.
///
/// The Value is a map with optional values of:
///
/// - **avatar**: base64-encoded 128x128 image for the webhook's default avatar
/// (_optional_);
/// - **name**: the name of the webhook, limited to between 2 and 100 characters
/// long.
///
/// Note that, unlike with [`create_webhook`], _all_ values are optional.
///
/// This method requires authentication, whereas [`edit_webhook_with_token`]
/// does not.
///
/// # Examples
///
/// Edit the image of a webhook given its Id and unique token:
///
/// ```rust,ignore
/// extern crate serde_json;
/// extern crate serenity;
///
/// use serde_json::builder::ObjectBuilder;
/// use serenity::client::rest;
///
/// let id = 245037420704169985;
/// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
/// let image = serenity::utils::read_image("./webhook_img.png")
/// .expect("Error reading image");
/// let map = ObjectBuilder::new().insert("avatar", image).build();
///
/// let edited = rest::edit_webhook_with_token(id, token, map)
/// .expect("Error editing webhook");
/// ```
///
/// [`create_webhook`]: fn.create_webhook.html
/// [`edit_webhook_with_token`]: fn.edit_webhook_with_token.html
// The tests are ignored, rather than no_run'd, due to rustdoc tests with
// external crates being incredibly messy and misleading in the end user's view.
pub fn edit_webhook(webhook_id: u64, map: Value) -> Result<Webhook> {
let body = serde_json::to_string(&map)?;
let response = request!(Route::WebhooksId,
patch(body),
"/webhooks/{}",
webhook_id);
Webhook::decode(serde_json::from_reader(response)?)
}
/// Edits the webhook with the given data.
///
/// Refer to the documentation for [`edit_webhook`] for more information.
///
/// This method does _not_ require authentication.
///
/// # Examples
///
/// Edit the name of a webhook given its Id and unique token:
///
/// ```rust,ignore
/// extern crate serde_json;
/// extern crate serenity;
///
/// use serde_json::builder::ObjectBuilder;
/// use serenity::client::rest;
///
/// let id = 245037420704169985;
/// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
/// let map = ObjectBuilder::new().insert("name", "new name").build();
///
/// let edited = rest::edit_webhook_with_token(id, token, map)
/// .expect("Error editing webhook");
/// ```
///
/// [`edit_webhook`]: fn.edit_webhook.html
pub fn edit_webhook_with_token(webhook_id: u64, token: &str, map: Value) -> Result<Webhook> {
let body = serde_json::to_string(&map)?;
let client = HyperClient::new();
let response = retry(|| client
.patch(&format!(api!("/webhooks/{}/{}"), webhook_id, token))
.body(&body))
.map_err(Error::Hyper)?;
Webhook::decode(serde_json::from_reader(response)?)
}
/// Executes a webhook, posting a [`Message`] in the webhook's associated
/// [`Channel`].
///
/// This method does _not_ require authentication.
///
/// Pass `true` to `wait` to wait for server confirmation of the message sending
/// before receiving a response. From the [Discord docs]:
///
/// > waits for server confirmation of message send before response, and returns
/// > the created message body (defaults to false; when false a message that is
/// > not saved does not return an error)
///
/// The map can _optionally_ contain the following data:
///
/// - `avatar_url`: Override the default avatar of the webhook with a URL.
/// - `tts`: Whether this is a text-to-speech message (defaults to `false`).
/// - `username`: Override the default username of the webhook.
///
/// Additionally, _at least one_ of the following must be given:
///
/// - `content`: The content of the message.
/// - `embeds`: An array of rich embeds.
///
/// **Note**: For embed objects, all fields are registered by Discord except for
/// `height`, `provider`, `proxy_url`, `type` (it will always be `rich`),
/// `video`, and `width`. The rest will be determined by Discord.
///
/// # Examples
///
/// Sending a webhook with message content of `test`:
///
/// ```rust,ignore
/// extern crate serde_json;
/// extern crate serenity;
///
/// use serde_json::builder::ObjectBuilder;
/// use serenity::client::rest;
///
/// let id = 245037420704169985;
/// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
/// let map = ObjectBuilder::new().insert("content", "test").build();
///
/// let message = match rest::execute_webhook(id, token, map) {
/// Ok(message) => message,
/// Err(why) => {
/// println!("Error executing webhook: {:?}", why);
///
/// return;
/// },
/// };
///
/// [`Channel`]: ../../model/enum.Channel.html
/// [`Message`]: ../../model/struct.Message.html
/// [Discord docs]: https://discordapp.com/developers/docs/resources/webhook#querystring-params
pub fn execute_webhook(webhook_id: u64, token: &str, map: Value) -> Result<Message> {
let body = serde_json::to_string(&map)?;
let client = HyperClient::new();
let response = retry(|| client
.post(&format!(api!("/webhooks/{}/{}"), webhook_id, token))
.body(&body))
.map_err(Error::Hyper)?;
Message::decode(serde_json::from_reader(response)?)
}
/// Gets the active maintenances from Discord's Status API.
///
/// Does not require authentication.
pub fn get_active_maintenances() -> Result<Vec<Maintenance>> {
let client = HyperClient::new();
let response = retry(|| client.get(
status!("/scheduled-maintenances/active.json")))?;
let mut map: BTreeMap<String, Value> = serde_json::from_reader(response)?;
match map.remove("scheduled_maintenances") {
Some(v) => decode_array(v, Maintenance::decode),
None => Ok(vec![]),
}
}
/// Gets information about an oauth2 application that the current user owns.
///
/// **Note**: Only user accounts may use this endpoint.
pub fn get_application_info(id: u64) -> Result<ApplicationInfo> {
let response = request!(Route::None, get, "/oauth2/applications/{}", id);
ApplicationInfo::decode(serde_json::from_reader(response)?)
}
/// Gets all oauth2 applications we've made.
///
/// **Note**: Only user accounts may use this endpoint.
pub fn get_applications() -> Result<Vec<ApplicationInfo>> {
let response = request!(Route::None, get, "/oauth2/applications");
let decoded = serde_json::from_reader(response)?;
decode_array(decoded, ApplicationInfo::decode)
}
/// Gets all the users that are banned in specific guild.
pub fn get_bans(guild_id: u64) -> Result<Vec<Ban>> {
let response = request!(Route::GuildsIdBans(guild_id),
get,
"/guilds/{}/bans",
guild_id);
decode_array(serde_json::from_reader(response)?, Ban::decode)
}
/// Gets current bot gateway.
pub fn get_bot_gateway() -> Result<BotGateway> {
let response = request!(Route::GatewayBot, get, "/gateway/bot");
BotGateway::decode(serde_json::from_reader(response)?)
}
/// Gets all invites for a channel.
pub fn get_channel_invites(channel_id: u64) -> Result<Vec<RichInvite>> {
let response = request!(Route::ChannelsIdInvites(channel_id),
get,
"/channels/{}/invites",
channel_id);
decode_array(serde_json::from_reader(response)?,
RichInvite::decode)
}
/// Retrieves the webhooks for the given [channel][`GuildChannel`]'s Id.
///
/// This method requires authentication.
///
/// # Examples
///
/// Retrieve all of the webhooks owned by a channel:
///
/// ```rust,no_run
/// use serenity::client::rest;
///
/// let channel_id = 81384788765712384;
///
/// let webhooks = rest::get_channel_webhooks(channel_id)
/// .expect("Error getting channel webhooks");
/// ```
///
/// [`GuildChannel`]: ../../model/struct.GuildChannel.html
pub fn get_channel_webhooks(channel_id: u64) -> Result<Vec<Webhook>> {
let response = request!(Route::ChannelsIdWebhooks(channel_id),
get,
"/channels/{}/webhooks",
channel_id);
decode_array(serde_json::from_reader(response)?, Webhook::decode)
}
/// Gets channel information.
pub fn get_channel(channel_id: u64) -> Result<Channel> {
let response = request!(Route::ChannelsId(channel_id),
get,
"/channels/{}",
channel_id);
Channel::decode(serde_json::from_reader(response)?)
}
/// Gets all channels in a guild.
pub fn get_channels(guild_id: u64) -> Result<Vec<GuildChannel>> {
let response = request!(Route::ChannelsId(guild_id),
get,
"/guilds/{}/channels",
guild_id);
decode_array(serde_json::from_reader(response)?,
GuildChannel::decode)
}
/// Gets information about the current application.
///
/// **Note**: Only applications may use this endpoint.
pub fn get_current_application_info() -> Result<CurrentApplicationInfo> {
let response = request!(Route::None, get, "/oauth2/applications/@me");
CurrentApplicationInfo::decode(serde_json::from_reader(response)?)
}
/// Gets information about the user we're connected with.
pub fn get_current_user() -> Result<CurrentUser> {
let response = request!(Route::UsersMe, get, "/users/@me");
CurrentUser::decode(serde_json::from_reader(response)?)
}
/// Gets current gateway.
pub fn get_gateway() -> Result<Gateway> {
let response = request!(Route::Gateway, get, "/gateway");