-
Notifications
You must be signed in to change notification settings - Fork 563
/
guild.rs
1172 lines (1024 loc) · 39.1 KB
/
guild.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
use std::cmp::Ordering;
use std::collections::HashMap;
use std::fmt;
use super::utils::{
decode_emojis,
decode_members,
decode_presences,
decode_roles,
decode_voice_states,
into_map,
into_string,
opt,
remove,
};
use super::*;
use ::internal::prelude::*;
use ::utils::decode_array;
#[cfg(feature="methods")]
use serde_json::builder::ObjectBuilder;
#[cfg(all(feature="cache", feature = "methods"))]
use std::mem;
#[cfg(feature = "methods")]
use ::utils::builder::{EditGuild, EditRole};
#[cfg(all(feature="cache", feature="methods"))]
use ::utils::builder::EditMember;
#[cfg(feature = "methods")]
use ::client::rest;
#[cfg(all(feature="cache", feature="methods"))]
use ::client::CACHE;
#[cfg(all(feature="cache", feature="methods"))]
use ::utils::Colour;
impl From<PartialGuild> for GuildContainer {
fn from(guild: PartialGuild) -> GuildContainer {
GuildContainer::Guild(guild)
}
}
impl From<GuildId> for GuildContainer {
fn from(guild_id: GuildId) -> GuildContainer {
GuildContainer::Id(guild_id)
}
}
impl From<u64> for GuildContainer {
fn from(id: u64) -> GuildContainer {
GuildContainer::Id(GuildId(id))
}
}
impl Emoji {
/// Finds the [`Guild`] that owns the emoji by looking through the Cache.
///
/// [`Guild`]: struct.Guild.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn find_guild_id(&self) -> Option<GuildId> {
CACHE.read()
.unwrap()
.guilds
.values()
.find(|guild| guild.emojis.contains_key(&self.id))
.map(|guild| guild.id)
}
/// Deletes the emoji.
///
/// **Note**: The [Manage Emojis] permission is required.
///
/// **Note**: Only user accounts may use this method.
///
/// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn delete(&self) -> Result<()> {
match self.find_guild_id() {
Some(guild_id) => rest::delete_emoji(guild_id.0, self.id.0),
None => Err(Error::Client(ClientError::ItemMissing)),
}
}
/// Edits the emoji by updating it with a new name.
///
/// **Note**: The [Manage Emojis] permission is required.
///
/// **Note**: Only user accounts may use this method.
///
/// [Manage Emojis]: permissions/constant.MANAGE_EMOJIS.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn edit(&mut self, name: &str) -> Result<()> {
match self.find_guild_id() {
Some(guild_id) => {
let map = ObjectBuilder::new()
.insert("name", name)
.build();
match rest::edit_emoji(guild_id.0, self.id.0, map) {
Ok(emoji) => {
mem::replace(self, emoji);
Ok(())
},
Err(why) => Err(why),
}
},
None => Err(Error::Client(ClientError::ItemMissing)),
}
}
/// Generates a URL to the emoji's image.
#[cfg(feature="methods")]
#[inline]
pub fn url(&self) -> String {
format!(cdn!("/emojis/{}.png"), self.id)
}
}
impl fmt::Display for Emoji {
/// Formats the emoji into a string that will cause Discord clients to
/// render the emoji.
///
/// This is in the format of: `<:NAME:EMOJI_ID>`.
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("<:")?;
f.write_str(&self.name)?;
fmt::Write::write_char(f, ':')?;
fmt::Display::fmt(&self.id, f)?;
fmt::Write::write_char(f, '>')
}
}
impl GuildInfo {
/// Returns the formatted URL of the guild's icon, if the guild has an icon.
pub fn icon_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn!("/icons/{}/{}.jpg"), self.id, icon))
}
}
impl InviteGuild {
/// Returns the formatted URL of the guild's splash image, if one exists.
#[cfg(feature="methods")]
pub fn splash_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn!("/splashes/{}/{}.jpg"), self.id, icon))
}
}
impl PartialGuild {
/// Finds a role by Id within the guild.
#[cfg(feature="methods")]
pub fn find_role<R: Into<RoleId>>(&self, role_id: R) -> Option<&Role> {
self.roles.get(&role_id.into())
}
/// Edits the current user's nickname for the guild.
///
/// Pass `None` to reset the nickname.
///
/// **Note**: Requires the [Change Nickname] permission.
///
/// [Change Nickname]: permissions/constant.CHANGE_NICKNAME.html
#[cfg(feature="methods")]
#[inline]
pub fn edit_nickname(&self, new_nickname: Option<&str>) -> Result<()> {
rest::edit_nickname(self.id.0, new_nickname)
}
/// Returns a formatted URL of the guild's icon, if the guild has an icon.
pub fn icon_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn!("/icons/{}/{}.jpg"), self.id, icon))
}
/// Returns the formatted URL of the guild's splash image, if one exists.
#[cfg(feature="methods")]
pub fn splash_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn!("/splashes/{}/{}.jpg"), self.id, icon))
}
/// Retrieves the guild's webhooks.
///
/// **Note**: Requires the [Manage Webhooks] permission.
///
/// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html
#[cfg(feature="methods")]
#[inline]
pub fn webhooks(&self) -> Result<Vec<Webhook>> {
rest::get_guild_webhooks(self.id.0)
}
}
impl Guild {
#[cfg(all(feature="cache", feature="methods"))]
fn has_perms(&self, mut permissions: Permissions) -> Result<bool> {
let member = match self.get_member(CACHE.read().unwrap().user.id) {
Some(member) => member,
None => return Err(Error::Client(ClientError::ItemMissing)),
};
let perms = self.permissions_for(ChannelId(self.id.0), member.user.id);
permissions.remove(perms);
Ok(permissions.is_empty())
}
/// Ban a [`User`] from the guild. All messages by the
/// user within the last given number of days given will be deleted. This
/// may be a range between `0` and `7`.
///
/// **Note**: Requires the [Ban Members] permission.
///
/// # Examples
///
/// Ban a member and remove all messages they've sent in the last 4 days:
///
/// ```rust,ignore
/// // assumes a `user` and `guild` have already been bound
/// let _ = guild.ban(user, 4);
/// ```
///
/// # Errors
///
/// Returns a [`ClientError::InvalidPermissions`] if the current user does
/// not have permission to perform bans.
///
/// Returns a [`ClientError::DeleteMessageDaysAmount`] if the number of
/// days' worth of messages to delete is over the maximum.
///
/// [`ClientError::DeleteMessageDaysAmount`]: ../client/enum.ClientError.html#variant.DeleteMessageDaysAmount
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [`User`]: struct.User.html
/// [Ban Members]: permissions/constant.BAN_MEMBERS.html
#[cfg(feature="methods")]
pub fn ban<U: Into<UserId>>(&self, user: U, delete_message_days: u8)
-> Result<()> {
if delete_message_days > 7 {
return Err(Error::Client(ClientError::DeleteMessageDaysAmount(delete_message_days)));
}
feature_cache_enabled! {{
let req = permissions::BAN_MEMBERS;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
rest::ban_user(self.id.0, user.into().0, delete_message_days)
}
/// Retrieves a list of [`Ban`]s for the guild.
///
/// **Note**: Requires the [Ban Members] permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`Ban`]: struct.Ban.html
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [Ban Members]: permissions/constant.BAN_MEMBERS.html
#[cfg(feature="methods")]
pub fn bans(&self) -> Result<Vec<Ban>> {
feature_cache_enabled! {{
let req = permissions::BAN_MEMBERS;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
rest::get_bans(self.id.0)
}
/// Creates a new [`Channel`] in the guild.
///
/// **Note**: Requires the [Manage Channels] permission.
///
/// # Examples
///
/// ```rust,ignore
/// use serenity::model::ChannelType;
///
/// // assuming a `guild` has already been bound
///
/// let _ = guild.create_channel("my-test-channel", ChannelType::Text);
/// ```
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`Channel`]: struct.Channel.html
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [Manage Channels]: permissions/constants.MANAGE_CHANNELS.html
#[cfg(feature="methods")]
pub fn create_channel(&mut self, name: &str, kind: ChannelType)
-> Result<Channel> {
feature_cache_enabled! {{
let req = permissions::MANAGE_CHANNELS;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
let map = ObjectBuilder::new()
.insert("name", name)
.insert("type", kind.name())
.build();
rest::create_channel(self.id.0, map)
}
/// Creates a new [`Role`] in the guild with the data set, if any.
///
/// See the documentation for [`Context::create_role`] on how to use this.
///
/// **Note**: Requires the [Manage Roles] permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [`Context::create_role`]: ../client/struct.Context.html#method.create_role
/// [`Role`]: struct.Role.html
/// [Manage Roles]: permissions/constants.MANAGE_ROLES.html
#[cfg(feature="methods")]
pub fn create_role<F>(&self, f: F) -> Result<Role>
where F: FnOnce(EditRole) -> EditRole {
feature_cache_enabled! {{
let req = permissions::MANAGE_ROLES;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
let role = rest::create_role(self.id.0)?;
let map = f(EditRole::new(&role)).0.build();
rest::edit_role(self.id.0, role.id.0, map)
}
#[doc(hidden)]
pub fn decode(value: Value) -> Result<Guild> {
let mut map = into_map(value)?;
let id = remove(&mut map, "id").and_then(GuildId::decode)?;
let public_channels = {
let mut public_channels = HashMap::new();
let vals = decode_array(remove(&mut map, "channels")?,
|v| GuildChannel::decode_guild(v, id))?;
for public_channel in vals {
public_channels.insert(public_channel.id, public_channel);
}
public_channels
};
Ok(Guild {
afk_channel_id: opt(&mut map, "afk_channel_id", ChannelId::decode)?,
afk_timeout: req!(remove(&mut map, "afk_timeout")?.as_u64()),
channels: public_channels,
default_message_notifications: req!(remove(&mut map, "default_message_notifications")?.as_u64()),
emojis: remove(&mut map, "emojis").and_then(decode_emojis)?,
features: remove(&mut map, "features").and_then(|v| decode_array(v, Feature::decode_str))?,
icon: opt(&mut map, "icon", into_string)?,
id: id,
joined_at: remove(&mut map, "joined_at").and_then(into_string)?,
large: req!(remove(&mut map, "large")?.as_bool()),
member_count: req!(remove(&mut map, "member_count")?.as_u64()),
members: remove(&mut map, "members").and_then(decode_members)?,
mfa_level: req!(remove(&mut map, "mfa_level")?.as_u64()),
name: remove(&mut map, "name").and_then(into_string)?,
owner_id: remove(&mut map, "owner_id").and_then(UserId::decode)?,
presences: remove(&mut map, "presences").and_then(decode_presences)?,
region: remove(&mut map, "region").and_then(into_string)?,
roles: remove(&mut map, "roles").and_then(decode_roles)?,
splash: opt(&mut map, "splash", into_string)?,
verification_level: remove(&mut map, "verification_level").and_then(VerificationLevel::decode)?,
voice_states: remove(&mut map, "voice_states").and_then(decode_voice_states)?,
})
}
/// Deletes the current guild if the current account is the owner of the
/// guild.
///
/// **Note**: Requires the current user to be the owner of the guild.
///
/// # Errors
///
/// If the `cache` is enabled, then returns a [`ClientError::InvalidUser`]
/// if the current user is not the guild owner.
///
/// [`ClientError::InvalidUser`]: ../client/enum.ClientError.html#variant.InvalidUser
#[cfg(feature="methods")]
pub fn delete(&self) -> Result<PartialGuild> {
feature_cache_enabled! {{
if self.owner_id != CACHE.read().unwrap().user.id {
let req = permissions::MANAGE_GUILD;
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
rest::delete_guild(self.id.0)
}
/// Edits the current guild with new data where specified. See the
/// documentation for [`Context::edit_guild`] on how to use this.
///
/// **Note**: Requires the current user to have the [Manage Guild]
/// permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [`Context::edit_guild`]: ../client/struct.Context.html#method.edit_guild
/// [Manage Guild]: permissions/constants.MANAGE_GUILD.html
#[cfg(feature="methods")]
pub fn edit<F>(&mut self, f: F) -> Result<()>
where F: FnOnce(EditGuild) -> EditGuild {
feature_cache_enabled! {{
let req = permissions::MANAGE_GUILD;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
let map = f(EditGuild::default()).0.build();
match rest::edit_guild(self.id.0, map) {
Ok(guild) => {
self.afk_channel_id = guild.afk_channel_id;
self.afk_timeout = guild.afk_timeout;
self.default_message_notifications = guild.default_message_notifications;
self.emojis = guild.emojis;
self.features = guild.features;
self.icon = guild.icon;
self.mfa_level = guild.mfa_level;
self.name = guild.name;
self.owner_id = guild.owner_id;
self.region = guild.region;
self.roles = guild.roles;
self.splash = guild.splash;
self.verification_level = guild.verification_level;
Ok(())
},
Err(why) => Err(why),
}
}
/// Edits the current user's nickname for the guild.
///
/// Pass `None` to reset the nickname.
///
/// **Note**: Requires the [Change Nickname] permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to change their own
/// nickname.
///
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [Change Nickname]: permissions/constant.CHANGE_NICKNAME.html
#[cfg(feature="methods")]
pub fn edit_nickname(&self, new_nickname: Option<&str>) -> Result<()> {
feature_cache_enabled! {{
let req = permissions::CHANGE_NICKNAME;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
rest::edit_nickname(self.id.0, new_nickname)
}
/// Attempts to retrieve a [`GuildChannel`] with the given Id.
///
/// [`GuildChannel`]: struct.GuildChannel.html
pub fn get_channel<C: Into<ChannelId>>(&self, channel_id: C)
-> Option<&GuildChannel> {
self.channels.get(&channel_id.into())
}
/// Retrieves the active invites for the guild.
///
/// **Note**: Requires the [Manage Guild] permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [Manage Guild]: permissions/constant.MANAGE_GUILD.html
#[cfg(feature="methods")]
pub fn get_invites(&self) -> Result<Vec<RichInvite>> {
feature_cache_enabled! {{
let req = permissions::MANAGE_GUILD;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
rest::get_guild_invites(self.id.0)
}
/// Attempts to retrieve the given user's member instance in the guild.
pub fn get_member<U: Into<UserId>>(&self, user_id: U) -> Option<&Member> {
self.members.get(&user_id.into())
}
/// Retrieves the first [`Member`] found that matches the name - with an
/// optional discriminator - provided.
///
/// Searching with a discriminator given is the most precise form of lookup,
/// as no two people can share the same username *and* discriminator.
///
/// If a member can not be found by username or username#discriminator,
/// then a search will be done for the nickname. When searching by nickname,
/// the hash (`#`) and everything after it is included in the search.
///
/// The following are valid types of searches:
///
/// - **username**: "zey"
/// - **username and discriminator**: "zey#5479"
/// - **nickname**: "zeyla" or "zeylas#nick"
///
/// [`Member`]: struct.Member.html
pub fn get_member_named(&self, name: &str) -> Option<&Member> {
let hash_pos = name.find('#');
let (name, discrim) = if let Some(pos) = hash_pos {
let split = name.split_at(pos);
(split.0, Some(split.1))
} else {
(&name[..], None)
};
self.members
.iter()
.find(|&(_member_id, member)| {
let name_matches = member.user.name == name;
let discrim_matches = match discrim {
Some(discrim) => member.user.discriminator == discrim,
None => true,
};
name_matches && discrim_matches
}).or(self.members.iter().find(|&(_member_id, member)| {
member.nick.as_ref().map_or(false, |nick| nick == name)
})).map(|(_member_id, member)| member)
}
/// Returns the formatted URL of the guild's icon, if one exists.
pub fn icon_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn!("/icons/{}/{}.jpg"), self.id, icon))
}
/// Checks if the guild is 'large'. A guild is considered large if it has
/// more than 250 members.
pub fn is_large(&self) -> bool {
self.members.len() > 250
}
/// Leaves the guild.
#[cfg(feature="methods")]
pub fn leave(&self) -> Result<PartialGuild> {
rest::leave_guild(self.id.0)
}
/// Calculate a [`User`]'s permissions in a given channel in the guild.
///
/// [`User`]: struct.User.html
pub fn permissions_for<C, U>(&self, channel_id: C, user_id: U)
-> Permissions where C: Into<ChannelId>, U: Into<UserId> {
use super::permissions::*;
let user_id = user_id.into();
// The owner has all permissions in all cases.
if user_id == self.owner_id {
return Permissions::all();
}
let channel_id = channel_id.into();
// Start by retrieving the @everyone role's permissions.
let everyone = match self.roles.get(&RoleId(self.id.0)) {
Some(everyone) => everyone,
None => {
error!("@everyone role ({}) missing in {}", self.id, self.name);
return Permissions::empty();
},
};
// Create a base set of permissions, starting with `@everyone`s.
let mut permissions = everyone.permissions;
let member = match self.members.get(&user_id) {
Some(member) => member,
None => return everyone.permissions,
};
for &role in &member.roles {
if let Some(role) = self.roles.get(&role) {
permissions |= role.permissions;
} else {
warn!("perms: {:?} on {:?} has non-existent role {:?}", member.user.id, self.id, role);
}
}
// Administrators have all permissions in any channel.
if permissions.contains(ADMINISTRATOR) {
return Permissions::all();
}
if let Some(channel) = self.channels.get(&channel_id) {
// If this is a text channel, then throw out voice permissions.
if channel.kind == ChannelType::Text {
permissions &= !(CONNECT | SPEAK | MUTE_MEMBERS |
DEAFEN_MEMBERS | MOVE_MEMBERS | USE_VAD);
}
// Apply the permission overwrites for the channel for each of the
// overwrites that - first - applies to the member's roles, and then
// the member itself.
//
// First apply the denied permission overwrites for each, then apply
// the allowed.
// Roles
for overwrite in &channel.permission_overwrites {
if let PermissionOverwriteType::Role(role) = overwrite.kind {
if !member.roles.contains(&role) || role.0 == self.id.0 {
continue;
}
permissions = (permissions & !overwrite.deny) | overwrite.allow;
}
}
// Member
for overwrite in &channel.permission_overwrites {
if PermissionOverwriteType::Member(user_id) != overwrite.kind {
continue;
}
permissions = (permissions & !overwrite.deny) | overwrite.allow;
}
} else {
warn!("Guild {} does not contain channel {}", self.id, channel_id);
}
// The default channel is always readable.
if channel_id.0 == self.id.0 {
permissions |= READ_MESSAGES;
}
// No SEND_MESSAGES => no message-sending-related actions
// If the member does not have the `SEND_MESSAGES` permission, then
// throw out message-able permissions.
if !permissions.contains(SEND_MESSAGES) {
permissions &= !(SEND_TTS_MESSAGES |
MENTION_EVERYONE |
EMBED_LINKS |
ATTACH_FILES);
}
// If the member does not have the `READ_MESSAGES` permission, then
// throw out actionable permissions.
if !permissions.contains(READ_MESSAGES) {
permissions &= KICK_MEMBERS | BAN_MEMBERS | ADMINISTRATOR |
MANAGE_GUILD | CHANGE_NICKNAME | MANAGE_NICKNAMES;
}
permissions
}
/// Retrieves the count of the number of [`Member`]s that would be pruned
/// with the number of given days.
///
/// See the documentation on [`GuildPrune`] for more information.
///
/// **Note**: Requires the [Kick Members] permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [`GuildPrune`]: struct.GuildPrune.html
/// [`Member`]: struct.Member.html
/// [Kick Members]: permissions/constant.KICK_MEMBERS.html
#[cfg(feature="methods")]
pub fn prune_count(&self, days: u16) -> Result<GuildPrune> {
feature_cache_enabled! {{
let req = permissions::KICK_MEMBERS;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
let map = ObjectBuilder::new()
.insert("days", days)
.build();
rest::get_guild_prune_count(self.id.0, map)
}
/// Returns the formatted URL of the guild's splash image, if one exists.
#[cfg(feature="methods")]
pub fn splash_url(&self) -> Option<String> {
self.icon.as_ref().map(|icon|
format!(cdn!("/splashes/{}/{}.jpg"), self.id, icon))
}
/// Starts a prune of [`Member`]s.
///
/// See the documentation on [`GuildPrune`] for more information.
///
/// **Note**: Requires the [Kick Members] permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [`GuildPrune`]: struct.GuildPrune.html
/// [`Member`]: struct.Member.html
/// [Kick Members]: permissions/constant.KICK_MEMBERS.html
#[cfg(feature="methods")]
pub fn start_prune(&self, days: u16) -> Result<GuildPrune> {
feature_cache_enabled! {{
let req = permissions::KICK_MEMBERS;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
let map = ObjectBuilder::new()
.insert("days", days)
.build();
rest::start_guild_prune(self.id.0, map)
}
/// Unbans the given [`User`] from the guild.
///
/// **Note**: Requires the [Ban Members] permission.
///
/// # Errors
///
/// If the `cache` is enabled, returns a [`ClientError::InvalidPermissions`]
/// if the current user does not have permission to perform bans.
///
/// [`ClientError::InvalidPermissions`]: ../client/enum.ClientError.html#variant.InvalidPermissions
/// [`User`]: struct.User.html
/// [Ban Members]: permissions/constant.BAN_MEMBERS.html
#[cfg(feature="methods")]
pub fn unban<U: Into<UserId>>(&self, user: U) -> Result<()> {
feature_cache_enabled! {{
let req = permissions::BAN_MEMBERS;
if !self.has_perms(req)? {
return Err(Error::Client(ClientError::InvalidPermissions(req)));
}
}}
rest::remove_ban(self.id.0, user.into().0)
}
/// Retrieves the guild's webhooks.
///
/// **Note**: Requires the [Manage Webhooks] permission.
///
/// [Manage Webhooks]: permissions/constant.MANAGE_WEBHOOKS.html
#[cfg(feature="methods")]
#[inline]
pub fn webhooks(&self) -> Result<Vec<Webhook>> {
rest::get_guild_webhooks(self.id.0)
}
}
impl Member {
/// Adds a [`Role`] to the member, editing its roles in-place if the request
/// was successful.
///
/// **Note**: Requires the [Manage Roles] permission.
///
/// [`Role`]: struct.Role.html
/// [Manage Roles]: permissions/constant.MANAGE_ROLES.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn add_role<R: Into<RoleId>>(&mut self, role_id: R) -> Result<()> {
let role_id = role_id.into();
if self.roles.contains(&role_id) {
return Ok(());
}
let guild_id = self.find_guild()?;
match rest::add_member_role(guild_id.0, self.user.id.0, role_id.0) {
Ok(()) => {
self.roles.push(role_id);
Ok(())
},
Err(why) => Err(why),
}
}
/// Adds one or multiple [`Role`]s to the member, editing
/// its roles in-place if the request was successful.
///
/// **Note**: Requires the [Manage Roles] permission.
///
/// [`Role`]: struct.Role.html
/// [Manage Roles]: permissions/constant.MANAGE_ROLES.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn add_roles(&mut self, role_ids: &[RoleId]) -> Result<()> {
let guild_id = self.find_guild()?;
self.roles.extend_from_slice(role_ids);
let map = EditMember::default().roles(&self.roles).0.build();
match rest::edit_member(guild_id.0, self.user.id.0, map) {
Ok(()) => Ok(()),
Err(why) => {
self.roles.retain(|r| !role_ids.contains(r));
Err(why)
}
}
}
/// Ban the member from its guild, deleting the last X number of
/// days' worth of messages.
///
/// **Note**: Requires the [Ban Members] role.
///
/// [Ban Members]: permissions/constant.BAN_MEMBERS.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn ban(&self, delete_message_days: u8) -> Result<()> {
let guild_id = self.find_guild()?;
rest::ban_user(guild_id.0,
self.user.id.0,
delete_message_days)
}
/// Calculates the member's display name.
///
/// The nickname takes priority over the member's username if it exists.
pub fn display_name(&self) -> &str {
self.nick.as_ref().unwrap_or(&self.user.name)
}
/// Determines the member's colour.
#[cfg(all(feature="cache", feature="methods"))]
pub fn colour(&self) -> Option<Colour> {
let default = Colour::default();
let guild_id = match self.find_guild() {
Ok(guild_id) => guild_id,
Err(_why) => return None,
};
let cache = CACHE.read().unwrap();
let guild = match cache.guilds.get(&guild_id) {
Some(guild) => guild,
None => return None,
};
let mut roles = self.roles
.iter()
.filter_map(|id| guild.roles.get(id))
.collect::<Vec<&Role>>();
roles.sort_by(|a, b| b.cmp(a));
roles.iter().find(|r| r.colour.value != default.value).map(|r| r.colour)
}
/// Edits the member with the given data. See [`Context::edit_member`] for
/// more information.
///
/// See [`EditMember`] for the permission(s) required for separate builder
/// methods, as well as usage of this.
///
/// [`Context::edit_member`]: ../client/struct.Context.html#method.edit_member
/// [`EditMember`]: ../builder/struct.EditMember.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn edit<F>(&self, f: F) -> Result<()>
where F: FnOnce(EditMember) -> EditMember {
let guild_id = self.find_guild()?;
let map = f(EditMember::default()).0.build();
rest::edit_member(guild_id.0, self.user.id.0, map)
}
/// Finds the Id of the [`Guild`] that the member is in.
///
/// [`Guild`]: struct.Guild.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn find_guild(&self) -> Result<GuildId> {
CACHE.read()
.unwrap()
.guilds
.values()
.find(|guild| {
guild.members
.iter()
.any(|(_member_id, member)| {
let joined_at = member.joined_at == self.joined_at;
let user_id = member.user.id == self.user.id;
joined_at && user_id
})
})
.map(|x| x.id)
.ok_or(Error::Client(ClientError::GuildNotFound))
}
/// Removes a [`Role`] from the member, editing its roles in-place if the
/// request was successful.
///
/// **Note**: Requires the [Manage Roles] permission.
///
/// [`Role`]: struct.Role.html
/// [Manage Roles]: permissions/constant.MANAGE_ROLES.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn remove_role<R: Into<RoleId>>(&mut self, role_id: R) -> Result<()> {
let role_id = role_id.into();
if !self.roles.contains(&role_id) {
return Ok(());
}
let guild_id = self.find_guild()?;
match rest::remove_member_role(guild_id.0, self.user.id.0, role_id.0) {
Ok(()) => {
self.roles.retain(|r| r.0 != role_id.0);
Ok(())
},
Err(why) => Err(why),
}
}
/// Removes one or multiple [`Role`]s from the member.
///
/// **Note**: Requires the [Manage Roles] permission.
///
/// [`Role`]: struct.Role.html
/// [Manage Roles]: permissions/constant.MANAGE_ROLES.html
#[cfg(all(feature="cache", feature="methods"))]
pub fn remove_roles(&mut self, role_ids: &[RoleId]) -> Result<()> {
let guild_id = self.find_guild()?;
self.roles.retain(|r| !role_ids.contains(r));
let map = EditMember::default().roles(&self.roles).0.build();
match rest::edit_member(guild_id.0, self.user.id.0, map) {
Ok(()) => Ok(()),
Err(why) => {
self.roles.extend_from_slice(role_ids);
Err(why)
},
}
}