aboutsummaryrefslogtreecommitdiff
path: root/src/http/mod.rs
blob: 880809dc758d8166e46705b95e97126549122117 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
//! 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 [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
//! [model]: ../model/index.html

#[macro_use] mod macros;

pub mod ratelimiting;

mod error;
mod routing;
mod utils;

pub use hyper::StatusCode;
pub use self::error::{Error as HttpError, Result};
pub use self::routing::{Path, Route};

use futures::{Future, Stream, future};
use hyper::client::{Client as HyperClient, Config as HyperConfig, HttpConnector};
use hyper::header::{Authorization, ContentType};
use hyper::{Body, Method, Request, Response};
use hyper_multipart_rfc7578::client::multipart::{Body as MultipartBody, Form};
use hyper_tls::HttpsConnector;
use model::prelude::*;
use self::ratelimiting::RateLimiter;
use serde::de::DeserializeOwned;
use serde_json::{self, Number, Value};
use std::cell::RefCell;
use std::fmt::Write;
use std::fs::File;
use std::io::Cursor;
use std::rc::Rc;
use std::str::FromStr;
use tokio_core::reactor::Handle;
use ::builder::*;
use ::{Error, utils as serenity_utils};

/// An method used for ratelimiting special routes.
///
/// This is needed because `hyper`'s `Method` enum does not derive Copy.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum LightMethod {
    /// Indicates that a route is for the `DELETE` method only.
    Delete,
    /// Indicates that a route is for the `GET` method only.
    Get,
    /// Indicates that a route is for the `PATCH` method only.
    Patch,
    /// Indicates that a route is for the `POST` method only.
    Post,
    /// Indicates that a route is for the `PUT` method only.
    Put,
}

impl LightMethod {
    pub fn hyper_method(&self) -> Method {
        match *self {
            LightMethod::Delete => Method::Delete,
            LightMethod::Get => Method::Get,
            LightMethod::Patch => Method::Patch,
            LightMethod::Post => Method::Post,
            LightMethod::Put => Method::Put,
        }
    }
}

#[derive(Clone, Debug)]
pub struct Client {
    pub client: Rc<HyperClient<HttpsConnector<HttpConnector>, Body>>,
    pub handle: Handle,
    pub multiparter: Rc<HyperClient<HttpsConnector<HttpConnector>, MultipartBody>>,
    pub ratelimiter: Rc<RefCell<RateLimiter>>,
    pub token: Rc<String>,
}

impl Client {
    pub fn new(
        client: Rc<HyperClient<HttpsConnector<HttpConnector>, Body>>,
        handle: Handle,
        token: Rc<String>,
    ) -> Result<Self> {
        let connector = HttpsConnector::new(4, &handle)?;

        let multiparter = Rc::new(HyperConfig::default()
            .body::<MultipartBody>()
            .connector(connector)
            .keep_alive(true)
            .build(&handle));

        Ok(Self {
            ratelimiter: Rc::new(RefCell::new(RateLimiter::new(handle.clone()))),
            client,
            handle,
            multiparter,
            token,
        })
    }

    pub fn set_token(&mut self, token: Rc<String>) {
        self.token = token;
    }

    /// Adds a [`User`] as a recipient to a [`Group`].
    ///
    /// **Note**: Groups have a limit of 10 recipients, including the current
    /// user.
    ///
    /// [`Group`]: ../model/channel/struct.Group.html
    /// [`Group::add_recipient`]: ../model/channel/struct.Group.html#method.add_recipient
    /// [`User`]: ../model/user/struct.User.html
    pub fn add_group_recipient(&self, group_id: u64, user_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::AddGroupRecipient { group_id, user_id }, None)
    }

    /// Adds a single [`Role`] to a [`Member`] in a [`Guild`].
    ///
    /// **Note**: Requires the [Manage Roles] permission and respect of role
    /// hierarchy.
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    /// [`Member`]: ../model/guild/struct.Member.html
    /// [`Role`]: ../model/guild/struct.Role.html
    /// [Manage Roles]: ../model/permissions/constant.MANAGE_ROLES.html
    pub fn add_member_role(
        &self,
        guild_id: u64,
        user_id: u64,
        role_id: u64
    ) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::AddMemberRole { guild_id, user_id, role_id }, None)
    }

    /// 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/guild/struct.Guild.html
    /// [`User`]: ../model/user/struct.User.html
    /// [Ban Members]: ../model/permissions/constant.BAN_MEMBERS.html
    pub fn ban_user(
        &self,
        guild_id: u64,
        user_id: u64,
        delete_message_days: u8,
        reason: &str,
    ) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::GuildBanUser {
            delete_message_days: Some(delete_message_days),
            reason: Some(reason),
            guild_id,
            user_id,
        }, None)
    }

    /// Ban zeyla from a [`Guild`], removing her 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/guild/struct.Guild.html
    /// [Ban Members]: ../model/permissions/constant.BAN_MEMBERS.html
    pub fn ban_zeyla(
        &self,
        guild_id: u64,
        delete_message_days: u8,
        reason: &str,
    ) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::GuildBanUser {
            delete_message_days: Some(delete_message_days),
            reason: Some(reason),
            guild_id,
            user_id: 114941315417899012,
        }, None)
    }

    /// 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/channel/enum.Channel.html
    pub fn broadcast_typing(&self, channel_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::BroadcastTyping { channel_id }, None)
    }

    /// 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/guild/struct.Guild.html
    /// [`GuildChannel`]: ../model/channel/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(
        &self,
        guild_id: u64,
        name: &str,
        kind: ChannelType,
        category_id: Option<u64>,
    ) -> impl Future<Item = GuildChannel, Error = Error> {
        self.post(Route::CreateChannel { guild_id }, Some(&json!({
            "name": name,
            "parent_id": category_id,
            "type": kind as u8,
        })))
    }

    /// 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/guild/struct.Guild.html
    /// [Manage Emojis]: ../model/permissions/constant.MANAGE_EMOJIS.html
    pub fn create_emoji(&self, guild_id: u64, name: &str, image: &str)
        -> impl Future<Item = Emoji, Error = Error> {
        self.post(Route::CreateEmoji { guild_id }, Some(&json!({
            "image": image,
            "name": name,
        })))
    }

    /// 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 currently limited to 10 active guilds. The
    /// limits are raised for whitelisted [GameBridge] applications. See the
    /// [documentation on this endpoint] for more info.
    ///
    /// # 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::http;
    ///
    /// let map = ObjectBuilder::new()
    ///     .insert("name", "test")
    ///     .insert("region", "us-west")
    ///     .build();
    ///
    /// let _result = http::create_guild(map);
    /// ```
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    /// [`PartialGuild`]: ../model/guild/struct.PartialGuild.html
    /// [`Shard`]: ../gateway/struct.Shard.html
    /// [GameBridge]: https://discordapp.com/developers/docs/topics/gamebridge
    /// [US West Region]: ../model/enum.Region.html#variant.UsWest
    /// [documentation on this endpoint]:
    /// https://discordapp.com/developers/docs/resources/guild#create-guild
    /// [whitelist]: https://discordapp.com/developers/docs/resources/guild#create-guild
    pub fn create_guild(&self, map: &Value)
        -> impl Future<Item = PartialGuild, Error = Error> {
        self.post(Route::CreateGuild, Some(map))
    }

    /// Creates an [`Integration`] for a [`Guild`].
    ///
    /// Refer to Discord's [docs] for field information.
    ///
    /// **Note**: Requires the [Manage Guild] permission.
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    /// [`Integration`]: ../model/guild/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(
        &self,
        guild_id: u64,
        integration_id: u64,
        kind: &str,
    ) -> impl Future<Item = (), Error = Error> {
        let json = json!({
            "id": integration_id,
            "type": kind,
        });
        self.verify(Route::CreateGuildIntegration {
            guild_id,
            integration_id,
        }, Some(&json))
    }

    /// 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/channel/struct.GuildChannel.html
    /// [`RichInvite`]: ../model/guild/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<F>(&self, channel_id: u64, f: F)
        -> impl Future<Item = RichInvite, Error = Error>
        where F: FnOnce(CreateInvite) -> CreateInvite {
        let map = serenity_utils::vecmap_to_json_map(f(CreateInvite::default()).0);

        self.post(Route::CreateInvite { channel_id }, Some(&Value::Object(map)))
    }

    /// Creates a permission override for a member or a role in a channel.
    pub fn create_permission(
        &self,
        channel_id: u64,
        target: &PermissionOverwrite,
    ) -> impl Future<Item = (), Error = Error> {
        let (id, kind) = match target.kind {
            PermissionOverwriteType::Member(id) => (id.0, "member"),
            PermissionOverwriteType::Role(id) => (id.0, "role"),
        };
        let map = json!({
            "allow": target.allow.bits(),
            "deny": target.deny.bits(),
            "id": id,
            "type": kind,
        });

        self.verify(Route::CreatePermission {
            target_id: id,
            channel_id,
        }, Some(&map))
    }

    /// Creates a private channel with a user.
    pub fn create_private_channel(&self, user_id: u64)
        -> impl Future<Item = PrivateChannel, Error = Error> {
        let map = json!({
            "recipient_id": user_id,
        });

        self.post(Route::CreatePrivateChannel, Some(&map))
    }

    /// Reacts to a message.
    pub fn create_reaction(
        &self,
        channel_id: u64,
        message_id: u64,
        reaction_type: &ReactionType
    ) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::CreateReaction {
            reaction: &utils::reaction_type_data(reaction_type),
            channel_id,
            message_id,
        }, None)
    }

    /// Creates a role.
    pub fn create_role<F>(&self, guild_id: u64, f: F) -> impl Future<Item = Role, Error = Error>
        where F: FnOnce(EditRole) -> EditRole {
        let map = serenity_utils::vecmap_to_json_map(f(EditRole::default()).0);

        self.post(Route::CreateRole { guild_id }, Some(&Value::Object(map)))
    }

    /// 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::http;
    ///
    /// let channel_id = 81384788765712384;
    /// let map = ObjectBuilder::new().insert("name", "test").build();
    ///
    /// let webhook = http::create_webhook(channel_id, map)
    ///     .expect("Error creating");
    /// ```
    ///
    /// [`GuildChannel`]: ../model/channel/struct.GuildChannel.html
    pub fn create_webhook(&self, channel_id: u64, map: &Value)
        -> impl Future<Item = Webhook, Error = Error> {
        self.post(Route::CreateWebhook { channel_id }, Some(map))
    }

    /// Deletes a private channel or a channel in a guild.
    pub fn delete_channel(&self, channel_id: u64) -> impl Future<Item = Channel, Error = Error> {
        self.delete(Route::DeleteChannel { channel_id }, None)
    }

    /// Deletes an emoji from a server.
    pub fn delete_emoji(&self, guild_id: u64, emoji_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.delete(Route::DeleteEmoji { guild_id, emoji_id }, None)
    }

    /// Deletes a guild, only if connected account owns it.
    pub fn delete_guild(&self, guild_id: u64)
        -> impl Future<Item = PartialGuild, Error = Error> {
        self.delete(Route::DeleteGuild { guild_id }, None)
    }

    /// Remvoes an integration from a guild.
    pub fn delete_guild_integration(
        &self,
        guild_id: u64,
        integration_id: u64,
    ) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeleteGuildIntegration {
            guild_id,
            integration_id,
        }, None)
    }

    /// Deletes an invite by code.
    pub fn delete_invite(&self, code: &str) -> impl Future<Item = Invite, Error = Error> {
        self.delete(Route::DeleteInvite { code }, None)
    }

    /// Deletes a message if created by us or we have specific permissions.
    pub fn delete_message(&self, channel_id: u64, message_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeleteMessage { channel_id, message_id }, None)
    }

    /// Deletes a bunch of messages, only works for bots.
    pub fn delete_messages<T, It>(&self, channel_id: u64, message_ids: It)
        -> impl Future<Item = (), Error = Error>
        where T: AsRef<MessageId>, It: IntoIterator<Item=T> {
        let ids = message_ids
            .into_iter()
            .map(|id| id.as_ref().0)
            .collect::<Vec<u64>>();

        let map = json!({
            "messages": ids,
        });

        self.verify(Route::DeleteMessages { channel_id }, Some(&map))
    }

    /// Deletes all of the [`Reaction`]s associated with a [`Message`].
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use serenity::http;
    /// use serenity::model::{ChannelId, MessageId};
    ///
    /// let channel_id = ChannelId(7);
    /// let message_id = MessageId(8);
    ///
    /// let _ = http::delete_message_reactions(channel_id.0, message_id.0)
    ///     .expect("Error deleting reactions");
    /// ```
    ///
    /// [`Message`]: ../model/channel/struct.Message.html
    /// [`Reaction`]: ../model/channel/struct.Reaction.html
    pub fn delete_message_reactions(&self, channel_id: u64, message_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeleteMessageReactions {
            channel_id,
            message_id,
        }, None)
    }

    /// Deletes a permission override from a role or a member in a channel.
    pub fn delete_permission(&self, channel_id: u64, target_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeletePermission { channel_id, target_id }, None)
    }

    /// Deletes a reaction from a message if owned by us or
    /// we have specific permissions.
    pub fn delete_reaction(
        &self,
        channel_id: u64,
        message_id: u64,
        user_id: Option<u64>,
        reaction_type: &ReactionType,
    ) -> impl Future<Item = (), Error = Error> {
        let reaction_type = utils::reaction_type_data(reaction_type);
        let user = user_id
            .map(|uid| uid.to_string())
            .unwrap_or_else(|| "@me".to_string());

        self.verify(Route::DeleteReaction {
            reaction: &reaction_type,
            user: &user,
            channel_id,
            message_id,
        }, None)
    }

    /// Deletes a role from a server. Can't remove the default everyone role.
    pub fn delete_role(&self, guild_id: u64, role_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeleteRole { guild_id, role_id }, None)
    }

    /// 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, http};
    /// use std::env;
    ///
    /// // Due to the `delete_webhook` function requiring you to authenticate,
    /// // you must have set the token first.
    /// http::set_token(&env::var("DISCORD_TOKEN").unwrap());
    ///
    /// http::delete_webhook(245037420704169985)
    ///     .expect("Error deleting webhook");
    /// ```
    ///
    /// [`Webhook`]: ../model/webhook/struct.Webhook.html
    /// [`delete_webhook_with_token`]: fn.delete_webhook_with_token.html
    pub fn delete_webhook(&self, webhook_id: u64) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeleteWebhook { webhook_id }, None)
    }

    /// 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::http;
    ///
    /// let id = 245037420704169985;
    /// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
    ///
    /// http::delete_webhook_with_token(id, token)
    ///     .expect("Error deleting webhook");
    /// ```
    ///
    /// [`Webhook`]: ../model/webhook/struct.Webhook.html
    pub fn delete_webhook_with_token(&self, webhook_id: u64, token: &str)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeleteWebhookWithToken { webhook_id, token }, None)
    }

    /// Changes channel information.
    pub fn edit_channel<F>(&self, channel_id: u64, f: F)
        -> impl Future<Item = GuildChannel, Error = Error>
        where F: FnOnce(EditChannel) -> EditChannel {
        let channel = f(EditChannel::default()).0;
        let map = Value::Object(serenity_utils::vecmap_to_json_map(channel));

        self.patch(Route::EditChannel { channel_id }, Some(&map))
    }

    /// Changes emoji information.
    pub fn edit_emoji(&self, guild_id: u64, emoji_id: u64, name: &str)
        -> impl Future<Item = Emoji, Error = Error> {
        let map = json!({
            "name": name,
        });

        self.patch(Route::EditEmoji { guild_id, emoji_id }, Some(&map))
    }

    /// Changes guild information.
    pub fn edit_guild<F>(&self, guild_id: u64, f: F)
        -> impl Future<Item = PartialGuild, Error = Error>
        where F: FnOnce(EditGuild) -> EditGuild {
        let guild = f(EditGuild::default()).0;
        let map = Value::Object(serenity_utils::vecmap_to_json_map(guild));

        self.patch(Route::EditGuild { guild_id }, Some(&map))
    }

    /// Edits the positions of a guild's channels.
    pub fn edit_guild_channel_positions<It>(&self, guild_id: u64, channels: It)
        -> impl Future<Item = (), Error = Error> where It: IntoIterator<Item = (ChannelId, u64)> {
        let items = channels.into_iter().map(|(id, pos)| json!({
            "id": id,
            "position": pos,
        })).collect();

        let map = Value::Array(items);

        self.patch(Route::EditGuildChannels { guild_id }, Some(&map))
    }

    /// Edits a [`Guild`]'s embed setting.
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    // todo
    pub fn edit_guild_embed(&self, guild_id: u64, map: &Value)
        -> impl Future<Item = GuildEmbed, Error = Error> {
        self.patch(Route::EditGuildEmbed { guild_id }, Some(map))
    }

    /// Does specific actions to a member.
    pub fn edit_member<F>(&self, guild_id: u64, user_id: u64, f: F)
        -> impl Future<Item = (), Error = Error> where F: FnOnce(EditMember) -> EditMember {
        let member = f(EditMember::default()).0;
        let map = Value::Object(serenity_utils::vecmap_to_json_map(member));

        self.verify(Route::EditMember { guild_id, user_id }, Some(&map))
    }

    /// Edits a message by Id.
    ///
    /// **Note**: Only the author of a message can modify it.
    pub fn edit_message<F: FnOnce(EditMessage) -> EditMessage>(
        &self,
        channel_id: u64,
        message_id: u64,
        f: F,
    ) -> impl Future<Item = Message, Error = Error> {
        let msg = f(EditMessage::default());
        let map = Value::Object(serenity_utils::vecmap_to_json_map(msg.0));

        self.patch(Route::EditMessage { channel_id, message_id }, Some(&map))
    }

    /// Edits the current user's nickname for the provided [`Guild`] via its Id.
    ///
    /// Pass `None` to reset the nickname.
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    pub fn edit_nickname(&self, guild_id: u64, new_nickname: Option<&str>)
        -> impl Future<Item = (), Error = Error> {
        self.patch(Route::EditNickname { guild_id }, Some(&json!({
            "nick": new_nickname,
        })))
    }

    /// Edits the current user's profile settings.
    pub fn edit_profile(&self, map: &Value) -> impl Future<Item = CurrentUser, Error = Error> {
        self.patch(Route::EditProfile, Some(map))
    }

    /// Changes a role in a guild.
    pub fn edit_role<F>(&self, guild_id: u64, role_id: u64, f: F)
        -> impl Future<Item = Role, Error = Error> where F: FnOnce(EditRole) -> EditRole {
        let role = f(EditRole::default()).0;
        let map = Value::Object(serenity_utils::vecmap_to_json_map(role));

        self.patch(Route::EditRole { guild_id, role_id }, Some(&map))
    }

    /// Changes the position of a role in a guild.
    pub fn edit_role_position(
        &self,
        guild_id: u64,
        role_id: u64,
        position: u64,
    ) -> impl Future<Item = Vec<Role>, Error = Error> {
        self.patch(Route::EditRole { guild_id, role_id }, Some(&json!({
            "id": role_id,
            "position": position,
        })))
    }

    /// 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::http;
    ///
    /// 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 = http::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(
        &self,
        webhook_id: u64,
        name: Option<&str>,
        avatar: Option<&str>,
    ) -> impl Future<Item = Webhook, Error = Error> {
        let map = json!({
            "avatar": avatar,
            "name": name,
        });

        self.patch(Route::EditWebhook { webhook_id }, Some(&map))
    }

    /// 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::http;
    ///
    /// let id = 245037420704169985;
    /// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
    /// let map = ObjectBuilder::new().insert("name", "new name").build();
    ///
    /// let edited = http::edit_webhook_with_token(id, token, map)
    ///     .expect("Error editing webhook");
    /// ```
    ///
    /// [`edit_webhook`]: fn.edit_webhook.html
    pub fn edit_webhook_with_token(
        &self,
        webhook_id: u64,
        token: &str,
        name: Option<&str>,
        avatar: Option<&str>,
    ) -> impl Future<Item = Webhook, Error = Error> {
        let map = json!({
            "avatar": avatar,
            "name": name,
        });
        let route = Route::EditWebhookWithToken {
            token,
            webhook_id,
        };

        self.patch(route, Some(&map))
    }

    /// 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::http;
    ///
    /// let id = 245037420704169985;
    /// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
    /// let map = ObjectBuilder::new().insert("content", "test").build();
    ///
    /// let message = match http::execute_webhook(id, token, true, map) {
    ///     Ok(Some(message)) => message,
    ///     Ok(None) => {
    ///         println!("Expected a webhook message");
    ///
    ///         return;
    ///     },
    ///     Err(why) => {
    ///         println!("Error executing webhook: {:?}", why);
    ///
    ///         return;
    ///     },
    /// };
    /// ```
    ///
    /// [`Channel`]: ../model/channel/enum.Channel.html
    /// [`Message`]: ../model/channel/struct.Message.html
    /// [Discord docs]: https://discordapp.com/developers/docs/resources/webhook#querystring-params
    pub fn execute_webhook<F: FnOnce(ExecuteWebhook) -> ExecuteWebhook>(
        &self,
        webhook_id: u64,
        token: &str,
        wait: bool,
        f: F,
    ) -> impl Future<Item = Option<Message>, Error = Error> {
        let execution = f(ExecuteWebhook::default()).0;
        let map = Value::Object(serenity_utils::vecmap_to_json_map(execution));

        let route = Route::ExecuteWebhook {
            token,
            wait,
            webhook_id,
        };

        if wait {
            self.post(route, Some(&map))
        } else {
            Box::new(self.verify(route, Some(&map)).map(|_| None))
        }
    }

    /// Gets the active maintenances from Discord's Status API.
    ///
    /// Does not require authentication.
    // pub fn get_active_maintenances() -> impl Future<Item = Vec<Maintenance>, Error = Error> {
    //     let client = request_client!();

    //     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) => serde_json::from_value::<Vec<Maintenance>>(v)
    //             .map_err(From::from),
    //         None => Ok(vec![]),
    //     }
    // }

    /// Gets all the users that are banned in specific guild.
    pub fn get_bans(&self, guild_id: u64) -> impl Future<Item = Vec<Ban>, Error = Error> {
        self.get(Route::GetBans { guild_id })
    }

    /// Gets all audit logs in a specific guild.
    pub fn get_audit_logs(
        &self,
        guild_id: u64,
        action_type: Option<u8>,
        user_id: Option<u64>,
        before: Option<u64>,
        limit: Option<u8>,
    ) -> impl Future<Item = AuditLogs, Error = Error> {
        self.get(Route::GetAuditLogs {
            action_type,
            before,
            guild_id,
            limit,
            user_id,
        })
    }

    /// Gets current bot gateway.
    pub fn get_bot_gateway(&self) -> impl Future<Item = BotGateway, Error = Error> {
        self.get(Route::GetBotGateway)
    }

    /// Gets all invites for a channel.
    pub fn get_channel_invites(&self, channel_id: u64)
        -> impl Future<Item = Vec<RichInvite>, Error = Error> {
        self.get(Route::GetChannelInvites { channel_id })
    }

    /// 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::http;
    ///
    /// let channel_id = 81384788765712384;
    ///
    /// let webhooks = http::get_channel_webhooks(channel_id)
    ///     .expect("Error getting channel webhooks");
    /// ```
    ///
    /// [`GuildChannel`]: ../model/channel/struct.GuildChannel.html
    pub fn get_channel_webhooks(&self, channel_id: u64)
        -> impl Future<Item = Vec<Webhook>, Error = Error> {
        self.get(Route::GetChannelWebhooks { channel_id })
    }

    /// Gets channel information.
    pub fn get_channel(&self, channel_id: u64) -> impl Future<Item = Channel, Error = Error> {
        self.get(Route::GetChannel { channel_id })
    }

    /// Gets all channels in a guild.
    pub fn get_channels(&self, guild_id: u64)
        -> impl Future<Item = Vec<GuildChannel>, Error = Error> {
        self.get(Route::GetChannels { guild_id })
    }

    /// Gets information about the current application.
    ///
    /// **Note**: Only applications may use this endpoint.
    pub fn get_current_application_info(&self)
        -> impl Future<Item = CurrentApplicationInfo, Error = Error> {
        self.get(Route::GetCurrentApplicationInfo)
    }

    /// Gets information about the user we're connected with.
    pub fn get_current_user(&self, ) -> impl Future<Item = CurrentUser, Error = Error> {
        self.get(Route::GetCurrentUser)
    }

    /// Gets current gateway.
    pub fn get_gateway(&self) -> impl Future<Item = Gateway, Error = Error> {
        self.get(Route::GetGateway)
    }

    /// Gets guild information.
    pub fn get_guild(&self, guild_id: u64) -> impl Future<Item = PartialGuild, Error = Error> {
        self.get(Route::GetGuild { guild_id })
    }

    /// Gets a guild embed information.
    pub fn get_guild_embed(&self, guild_id: u64)
        -> impl Future<Item = GuildEmbed, Error = Error> {
        self.get(Route::GetGuildEmbed { guild_id })
    }

    /// Gets integrations that a guild has.
    pub fn get_guild_integrations(&self, guild_id: u64)
        -> impl Future<Item = Vec<Integration>, Error = Error> {
        self.get(Route::GetGuildIntegrations { guild_id })
    }

    /// Gets all invites to a guild.
    pub fn get_guild_invites(&self, guild_id: u64)
        -> impl Future<Item = Vec<RichInvite>, Error = Error> {
        self.get(Route::GetGuildInvites { guild_id })
    }

    /// Gets the members of a guild. Optionally pass a `limit` and the Id of the
    /// user to offset the result by.
    pub fn get_guild_members(
        &self,
        guild_id: u64,
        limit: Option<u64>,
        after: Option<u64>
    ) -> impl Future<Item = Vec<Member>, Error = Error> {
        let done = self.get(Route::GetGuildMembers { after, guild_id, limit })
            .and_then(move |mut v: Value| {
                if let Some(values) = v.as_array_mut() {
                    let num = Value::Number(Number::from(guild_id));

                    for value in values {
                        if let Some(element) = value.as_object_mut() {
                            element.insert("guild_id".to_string(), num.clone());
                        }
                    }
                }

                serde_json::from_value::<Vec<Member>>(v).map_err(From::from)
            });

        Box::new(done)
    }

    /// Gets the amount of users that can be pruned.
    pub fn get_guild_prune_count(&self, guild_id: u64, days: u16)
        -> impl Future<Item = GuildPrune, Error = Error> {
        self.get(Route::GetGuildPruneCount {
            days: days as u64,
            guild_id,
        })
    }

    /// Gets regions that a guild can use. If a guild has
    /// [`Feature::VipRegions`] enabled, then additional VIP-only regions are
    /// returned.
    ///
    /// [`Feature::VipRegions`]: ../model/enum.Feature.html#variant.VipRegions
    pub fn get_guild_regions(&self, guild_id: u64)
        -> impl Future<Item = Vec<VoiceRegion>, Error = Error> {
        self.get(Route::GetGuildRegions { guild_id })
    }

    /// Retrieves a list of roles in a [`Guild`].
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    pub fn get_guild_roles(&self, guild_id: u64)
        -> impl Future<Item = Vec<Role>, Error = Error> {
        self.get(Route::GetGuildRoles { guild_id })
    }

    /// Gets a guild's vanity URL if it has one.
    pub fn get_guild_vanity_url(&self, guild_id: u64)
        -> impl Future<Item = String, Error = Error> {
        #[derive(Deserialize)]
        struct GuildVanityUrl {
            code: String,
        }

        let done = self.get::<GuildVanityUrl>(
            Route::GetGuildVanityUrl { guild_id },
        ).map(|resp| {
            resp.code
        });

        Box::new(done)
    }

    /// Retrieves the webhooks for the given [guild][`Guild`]'s Id.
    ///
    /// This method requires authentication.
    ///
    /// # Examples
    ///
    /// Retrieve all of the webhooks owned by a guild:
    ///
    /// ```rust,no_run
    /// use serenity::http;
    ///
    /// let guild_id = 81384788765712384;
    ///
    /// let webhooks = http::get_guild_webhooks(guild_id)
    ///     .expect("Error getting guild webhooks");
    /// ```
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    pub fn get_guild_webhooks(&self, guild_id: u64)
        -> impl Future<Item = Vec<Webhook>, Error = Error> {
        self.get(Route::GetGuildWebhooks { guild_id })
    }

    /// Gets a paginated list of the current user's guilds.
    ///
    /// The `limit` has a maximum value of 100.
    ///
    /// [Discord's documentation][docs]
    ///
    /// # Examples
    ///
    /// Get the first 10 guilds after a certain guild's Id:
    ///
    /// ```rust,no_run
    /// use serenity::http::{GuildPagination, get_guilds};
    /// use serenity::model::GuildId;
    ///
    /// let guild_id = GuildId(81384788765712384);
    ///
    /// let guilds = get_guilds(&GuildPagination::After(guild_id), 10).unwrap();
    /// ```
    ///
    /// [docs]: https://discordapp.com/developers/docs/resources/user#get-current-user-guilds
    pub fn get_guilds(&self, target: &GuildPagination, limit: u64)
        -> impl Future<Item = Vec<GuildInfo>, Error = Error> {
        let (after, before) = match *target {
            GuildPagination::After(v) => (Some(v.0), None),
            GuildPagination::Before(v) => (None, Some(v.0)),
        };

        self.get(Route::GetGuilds { after, before, limit })
    }

    /// Gets information about a specific invite.
    pub fn get_invite<'a>(&self, code: &'a str, stats: bool)
        -> Box<Future<Item = Invite, Error = Error> + 'a> {
        self.get(Route::GetInvite { code, stats })
    }

    /// Gets member of a guild.
    pub fn get_member(&self, guild_id: u64, user_id: u64)
        -> impl Future<Item = Member, Error = Error> {
        let done = self.get::<Value>(Route::GetMember { guild_id, user_id })
            .and_then(move |mut v| {
                if let Some(map) = v.as_object_mut() {
                    map.insert("guild_id".to_string(), Value::Number(Number::from(guild_id)));
                }

                serde_json::from_value(v).map_err(From::from)
            });

        Box::new(done)
    }

    /// Gets a message by an Id, bots only.
    pub fn get_message(&self, channel_id: u64, message_id: u64)
        -> impl Future<Item = Message, Error = Error> {
        self.get(Route::GetMessage { channel_id, message_id })
    }

    /// Gets X messages from a channel.
    pub fn get_messages<'a, F: FnOnce(GetMessages) -> GetMessages>(
        &'a self,
        channel_id: u64,
        f: F,
    ) -> Box<Future<Item = Vec<Message>, Error = Error> + 'a> {
        let mut map = f(GetMessages::default()).0;

        let limit = map.remove(&"limit").unwrap_or(50);
        let mut query = format!("?limit={}", limit);

        if let Some(after) = map.remove(&"after") {
            ftry!(write!(query, "&after={}", after));
        }

        if let Some(around) = map.remove(&"around") {
            ftry!(write!(query, "&around={}", around));
        }

        if let Some(before) = map.remove(&"before") {
            ftry!(write!(query, "&before={}", before));
        }

        self.get(Route::GetMessages {
            channel_id,
            query,
        })
    }

    /// Gets all pins of a channel.
    pub fn get_pins(&self, channel_id: u64) -> impl Future<Item = Vec<Message>, Error = Error> {
        self.get(Route::GetPins { channel_id })
    }

    /// Gets user Ids based on their reaction to a message.
    pub fn get_reaction_users(
        &self,
        channel_id: u64,
        message_id: u64,
        reaction_type: &ReactionType,
        limit: Option<u8>,
        after: Option<u64>
    ) -> impl Future<Item = Vec<User>, Error = Error> {
        let reaction = utils::reaction_type_data(reaction_type);
        self.get(Route::GetReactionUsers {
            limit: limit.unwrap_or(50),
            after,
            channel_id,
            message_id,
            reaction,
        })
    }

    // /// Gets the current unresolved incidents from Discord's Status API.
    // ///
    // /// Does not require authentication.
    // pub fn get_unresolved_incidents(&self) -> impl Future<Item = Vec<Incident>, Error = Error> {
    //     let client = request_client!();

    //     let response = retry(|| client.get(status!("/incidents/unresolved.json")))?;

    //     let mut map: BTreeMap<String, Value> = serde_json::from_reader(response)?;

    //     match map.remove("incidents") {
    //         Some(v) => serde_json::from_value::<Vec<Incident>>(v)
    //             .map_err(From::from),
    //         None => Ok(vec![]),
    //     }
    // }

    // /// Gets the upcoming (planned) maintenances from Discord's Status API.
    // ///
    // /// Does not require authentication.
    // pub fn get_upcoming_maintenances(&self) -> impl Future<Item = Vec<Maintenance>, Error = Error> {
    //     let client = request_client!();

    //     let response = retry(|| {
    //         client.get(status!("/scheduled-maintenances/upcoming.json"))
    //     })?;

    //     let mut map: BTreeMap<String, Value> = serde_json::from_reader(response)?;

    //     match map.remove("scheduled_maintenances") {
    //         Some(v) => serde_json::from_value::<Vec<Maintenance>>(v)
    //             .map_err(From::from),
    //         None => Ok(vec![]),
    //     }
    // }

    /// Gets a user by Id.
    pub fn get_user(&self, user_id: u64) -> impl Future<Item = User, Error = Error> {
        self.get(Route::GetUser { user_id })
    }

    /// Gets our DM channels.
    pub fn get_user_dm_channels(&self)
        -> impl Future<Item = Vec<PrivateChannel>, Error = Error> {
        self.get(Route::GetUserDmChannels)
    }

    /// Gets all voice regions.
    pub fn get_voice_regions(&self) -> impl Future<Item = Vec<VoiceRegion>, Error = Error> {
        self.get(Route::GetVoiceRegions)
    }

    /// Retrieves a webhook given its Id.
    ///
    /// This method requires authentication, whereas [`get_webhook_with_token`] does
    /// not.
    ///
    /// # Examples
    ///
    /// Retrieve a webhook by Id:
    ///
    /// ```rust,no_run
    /// use serenity::http;
    ///
    /// let id = 245037420704169985;
    /// let webhook = http::get_webhook(id).expect("Error getting webhook");
    /// ```
    ///
    /// [`get_webhook_with_token`]: fn.get_webhook_with_token.html
    pub fn get_webhook(&self, webhook_id: u64) -> impl Future<Item = Webhook, Error = Error> {
        self.get(Route::GetWebhook { webhook_id })
    }

    /// Retrieves a webhook given its Id and unique token.
    ///
    /// This method does _not_ require authentication.
    ///
    /// # Examples
    ///
    /// Retrieve a webhook by Id and its unique token:
    ///
    /// ```rust,no_run
    /// use serenity::http;
    ///
    /// let id = 245037420704169985;
    /// let token = "ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV";
    ///
    /// let webhook = http::get_webhook_with_token(id, token)
    ///     .expect("Error getting webhook");
    /// ```
    pub fn get_webhook_with_token<'a>(
        &self,
        webhook_id: u64,
        token: &'a str,
    ) -> Box<Future<Item = Webhook, Error = Error> + 'a> {
        self.get(Route::GetWebhookWithToken { token, webhook_id })
    }

    /// Kicks a member from a guild.
    pub fn kick_member(&self, guild_id: u64, user_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::KickMember { guild_id, user_id }, None)
    }

    /// Leaves a group DM.
    pub fn leave_group(&self, group_id: u64) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::DeleteChannel {
            channel_id: group_id,
        }, None)
    }

    /// Leaves a guild.
    pub fn leave_guild(&self, guild_id: u64) -> impl Future<Item = (), Error = Error> {
        self.verify(Route::LeaveGuild { guild_id }, None)
    }

    /// Deletes a user from group DM.
    pub fn remove_group_recipient(&self, group_id: u64, user_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::RemoveGroupRecipient { group_id, user_id }, None)
    }

    // /// Sends file(s) to a channel.
    // ///
    // /// # Errors
    // ///
    // /// Returns an
    // /// [`HttpError::InvalidRequest(PayloadTooLarge)`][`HttpError::InvalidRequest`]
    // /// if the file is too large to send.
    // ///
    // /// [`HttpError::InvalidRequest`]: enum.HttpError.html#variant.InvalidRequest
    pub fn send_files<F, T, It>(
        &self,
        channel_id: u64,
        files: It,
        f: F,
    ) -> Box<Future<Item = Message, Error = Error>>
        where F: FnOnce(CreateMessage) -> CreateMessage,
              T: Into<AttachmentType>,
              It: IntoIterator<Item = T> {
        let msg = f(CreateMessage::default());
        let map = serenity_utils::vecmap_to_json_map(msg.0);

        let uri = try_uri!(Path::channel_messages(channel_id).as_ref());
        let mut form = Form::default();
        let mut file_num = "0".to_string();

        for file in files {
            match file.into() {
                AttachmentType::Bytes((mut bytes, filename)) => {
                    form.add_reader_file(
                        file_num.to_owned(),
                        Cursor::new(bytes),
                        filename,
                    );
                },
                AttachmentType::File((mut f, filename)) => {
                    form.add_reader_file(
                        file_num.to_owned(),
                        f,
                        filename,
                    );
                },
            }

            unsafe {
                let vec = file_num.as_mut_vec();
                vec[0] += 1;
            }
        }

        for (k, v) in map.into_iter() {
            match v {
                Value::Bool(false) => form.add_text(k, "false"),
                Value::Bool(true) => form.add_text(k, "true"),
                Value::Number(inner) => form.add_text(k, inner.to_string()),
                Value::String(inner) => form.add_text(k, inner),
                Value::Object(inner) => form.add_text(k, ftry!(serde_json::to_string(&inner))),
                _ => continue,
            }
        }

        let mut request = Request::new(Method::Get, uri);
        form.set_body(&mut request);

        let client = Rc::clone(&self.multiparter);

        let done = client.request(request)
            .from_err()
            .and_then(verify_status)
            .and_then(|res| res.body().concat2().map_err(From::from))
            .and_then(|body| serde_json::from_slice(&body).map_err(From::from));

        Box::new(done)
    }

    /// Sends a message to a channel.
    pub fn send_message<F>(&self, channel_id: u64, f: F) -> impl Future<Item = Message, Error = Error>
        where F: FnOnce(CreateMessage) -> CreateMessage {
        let msg = f(CreateMessage::default());
        let map = Value::Object(serenity_utils::vecmap_to_json_map(msg.0));

        self.post(Route::CreateMessage { channel_id }, Some(&map))
    }

    /// Pins a message in a channel.
    pub fn pin_message(&self, channel_id: u64, message_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::PinMessage { channel_id, message_id }, None)
    }

    /// Unbans a user from a guild.
    pub fn remove_ban(&self, guild_id: u64, user_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::RemoveBan { guild_id, user_id }, None)
    }

    /// Deletes a single [`Role`] from a [`Member`] in a [`Guild`].
    ///
    /// **Note**: Requires the [Manage Roles] permission and respect of role
    /// hierarchy.
    ///
    /// [`Guild`]: ../model/guild/struct.Guild.html
    /// [`Member`]: ../model/guild/struct.Member.html
    /// [`Role`]: ../model/guild/struct.Role.html
    /// [Manage Roles]: ../model/permissions/constant.MANAGE_ROLES.html
    pub fn remove_member_role(
        &self,
        guild_id: u64,
        user_id: u64,
        role_id: u64,
    ) -> impl Future<Item = (), Error = Error> {
        self.verify(
            Route::RemoveMemberRole { guild_id, role_id, user_id },
            None,
        )
    }

    /// Starts removing some members from a guild based on the last time they've been online.
    pub fn start_guild_prune(&self, guild_id: u64, days: u16)
        -> impl Future<Item = GuildPrune, Error = Error> {
        self.post(Route::StartGuildPrune {
            days: days as u64,
            guild_id,
        }, None)
    }

    /// Starts syncing an integration with a guild.
    pub fn start_integration_sync(&self, guild_id: u64, integration_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(
            Route::StartIntegrationSync { guild_id, integration_id },
            None,
        )
    }

    /// Unpins a message from a channel.
    pub fn unpin_message(&self, channel_id: u64, message_id: u64)
        -> impl Future<Item = (), Error = Error> {
        self.verify(Route::UnpinMessage { channel_id, message_id }, None)
    }

    fn delete<'a, T: DeserializeOwned + 'static>(
        &self,
        route: Route<'a>,
        map: Option<&Value>,
    ) -> Box<Future<Item = T, Error = Error>> {
        self.request(route, map)
    }

    fn get<'a, T: DeserializeOwned + 'static>(&self, route: Route<'a>)
        -> Box<Future<Item = T, Error = Error> + 'a> {
        self.request(route, None)
    }

    fn patch<'a, T: DeserializeOwned + 'static>(
        &self,
        route: Route<'a>,
        map: Option<&Value>,
    ) -> Box<Future<Item = T, Error = Error>> {
        self.request(route, map)
    }

    fn post<'a, T: DeserializeOwned + 'static>(
        &self,
        route: Route<'a>,
        map: Option<&Value>,
    ) -> Box<Future<Item = T, Error = Error>> {
        self.request(route, map)
    }

    fn request<'a, T: DeserializeOwned + 'static>(
        &self,
        route: Route<'a>,
        map: Option<&Value>,
    ) -> Box<Future<Item = T, Error = Error>> {
        let (method, path, url) = route.deconstruct();

        let built_uri = try_uri!(url.as_ref());
        let mut request = Request::new(method.hyper_method(), built_uri);

        if let Some(value) = map {
            request.set_body(ftry!(serde_json::to_string(value)));
        }

        {
            let headers = request.headers_mut();
            headers.set(Authorization(self.token()));
            headers.set(ContentType::json());
        }

        let client = Rc::clone(&self.client);

        Box::new(ftry!(self.ratelimiter.try_borrow_mut()).take(&path)
            .and_then(move |_| client.request(request).map_err(From::from))
            .from_err()
            .and_then(verify_status)
            .and_then(|res| res.body().concat2().map_err(From::from))
            .and_then(|body| serde_json::from_slice(&body).map_err(From::from)))
    }

    fn verify<'a>(
        &self,
        route: Route<'a>,
        map: Option<&Value>,
    ) -> Box<Future<Item = (), Error = Error>> {
        let (method, path, url) = route.deconstruct();

        let mut request = Request::new(
            method.hyper_method(),
            try_uri!(url.as_ref()),
        );

        if let Some(value) = map {
            request.set_body(ftry!(serde_json::to_string(value)));
        }

        {
            let headers = request.headers_mut();
            headers.set(Authorization(self.token()));
            headers.set(ContentType::json());
        }

        let client = Rc::clone(&self.client);

        Box::new(ftry!(self.ratelimiter.try_borrow_mut()).take(&path)
            .and_then(move |_| client.request(request).map_err(From::from))
            .map_err(From::from)
            .and_then(verify_status)
            .map(|_| ()))
    }

    fn token(&self) -> String {
        let pointer = Rc::into_raw(Rc::clone(&self.token));
        let token = unsafe {
            (*pointer).clone()
        };

        unsafe {
            drop(Rc::from_raw(pointer));
        }

        token
    }
}


/// Verifies the status of the response according to the method used to create
/// the accompanying request.
///
/// If the status code is correct (a 200 is expected and the response status is
/// also 200), then the future resolves. Otherwise, a leaf future is returned
/// with an error as the `Error` type.
///
/// # Errors
///
/// Returns [`Error::InvalidRequest`] if the response status code is unexpected.
///
/// [`Error::InvalidRequest`]: enum.Error.html#variant.InvalidRequest
fn verify_status(response: Response) ->
    Box<Future<Item = Response, Error = Error>> {
    if response.status().is_success() {
        Box::new(future::ok(response))
    } else {
        Box::new(future::err(Error::Http(HttpError::InvalidRequest(response))))
    }
}

/// Enum that allows a user to pass a `Path` or a `File` type to `send_files`.
#[derive(Debug)]
pub enum AttachmentType {
    /// Indicates that the `AttachmentType` is a byte slice with a filename.
    Bytes((Vec<u8>, String)),
    /// Indicates that the `AttachmentType` is a `File`
    File((File, String)),
}

impl From<(Vec<u8>, String)> for AttachmentType {
    fn from(params: (Vec<u8>, String)) -> AttachmentType {
        AttachmentType::Bytes(params)
    }
}

impl From<(File, String)> for AttachmentType {
    fn from(f: (File, String)) -> AttachmentType {
        AttachmentType::File((f.0, f.1))
    }
}

/// Representation of the method of a query to send for the [`get_guilds`]
/// function.
///
/// [`get_guilds`]: fn.get_guilds.html
pub enum GuildPagination {
    /// The Id to get the guilds after.
    After(GuildId),
    /// The Id to get the guilds before.
    Before(GuildId),
}