forked from interactions-py/interactions.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
guild.py
3162 lines (2755 loc) · 119 KB
/
guild.py
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
from datetime import datetime
from enum import Enum, IntEnum
from inspect import isawaitable
from math import inf
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
from warnings import warn
from ...utils.abc.base_iterators import DiscordPaginationIterator
from ...utils.attrs_utils import (
ClientSerializerMixin,
DictSerializerMixin,
convert_list,
define,
field,
)
from ...utils.missing import MISSING
from ..error import LibraryException
from .audit_log import AuditLogEvents, AuditLogs
from .channel import Channel, ChannelType, Thread, ThreadMember
from .emoji import Emoji
from .member import Member
from .message import Sticker, StickerPack
from .misc import (
AutoModAction,
AutoModTriggerMetadata,
AutoModTriggerType,
File,
IDMixin,
Image,
Overwrite,
Snowflake,
)
from .presence import PresenceActivity
from .role import Role
from .team import Application
from .user import User
from .webhook import Webhook
if TYPE_CHECKING:
from ..http.client import HTTPClient
from .gw import AutoModerationRule
from .message import Message
__all__ = (
"VerificationLevel",
"EntityType",
"DefaultMessageNotificationLevel",
"EventMetadata",
"EventStatus",
"GuildTemplate",
"Integration",
"InviteTargetType",
"StageInstance",
"UnavailableGuild",
"WelcomeChannels",
"ExplicitContentFilterLevel",
"ScheduledEvents",
"WelcomeScreen",
"Guild",
"GuildPreview",
"Invite",
"AsyncMembersIterator",
)
class VerificationLevel(IntEnum):
"""An enumerable object representing the verification level of a guild."""
NONE = 0
LOW = 1
MEDIUM = 2
HIGH = 3
VERY_HIGH = 4
class ExplicitContentFilterLevel(IntEnum):
"""An enumerable object representing the explicit content filter level of a guild."""
DISABLED = 0
MEMBERS_WITHOUT_ROLES = 1
ALL_MEMBERS = 2
class DefaultMessageNotificationLevel(IntEnum):
"""An enumerable object representing the default message notification level of a guild."""
ALL_MESSAGES = 0
ONLY_MENTIONS = 1
class EntityType(IntEnum):
"""An enumerable object representing the type of event."""
STAGE_INSTANCE = 1
VOICE = 2
EXTERNAL = 3
class EventStatus(IntEnum):
"""An enumerable object representing the status of an event."""
SCHEDULED = 1
ACTIVE = 2
COMPLETED = 3
CANCELED = 4
class InviteTargetType(IntEnum):
"""An enumerable object representing the different invite target types"""
STREAM = 1
EMBEDDED_APPLICATION = 2
class GuildFeatures(Enum):
ANIMATED_BANNER = "ANIMATED_BANNER"
ANIMATED_ICON = "ANIMATED_ICON"
BANNER = "BANNER"
COMMERCE = "COMMERCE"
COMMUNITY = "COMMUNITY"
DISCOVERABLE = "DISCOVERABLE"
FEATURABLE = "FEATURABLE"
INVITE_SPLASH = "INVITE_SPLASH"
MEMBER_VERIFICATION_GATE_ENABLED = "MEMBER_VERIFICATION_GATE_ENABLED"
MONETIZATION_ENABLED = "MONETIZATION_ENABLED"
MORE_STICKERS = "MORE_STICKERS"
NEWS = "NEWS"
PARTNERED = "PARTNERED"
PREVIEW_ENABLED = "PREVIEW_ENABLED"
PRIVATE_THREADS = "PRIVATE_THREADS"
ROLE_ICONS = "ROLE_ICONS"
TICKETED_EVENTS_ENABLED = "TICKETED_EVENTS_ENABLED"
VANITY_URL = "VANITY_URL"
VERIFIED = "VERIFIED"
VIP_REGIONS = "VIP_REGIONS"
WELCOME_SCREEN_ENABLED = "WELCOME_SCREEN_ENABLED"
@define()
class WelcomeChannels(DictSerializerMixin):
"""
A class object representing a welcome channel on the welcome screen.
.. note::
``emoji_id`` and ``emoji_name`` are given values respectively if the welcome channel
uses an emoji.
:ivar Snowflake channel_id: The ID of the welcome channel.
:ivar str description: The description of the welcome channel.
:ivar Optional[Snowflake] emoji_id?: The ID of the emoji of the welcome channel.
:ivar Optional[str] emoji_name?: The name of the emoji of the welcome channel.
"""
channel_id: int = field()
description: str = field()
emoji_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
emoji_name: Optional[str] = field(default=None)
@define()
class WelcomeScreen(DictSerializerMixin):
"""
A class object representing the welcome screen shown for community guilds.
.. note::
``description`` is ambiguous -- Discord poorly documented this. :)
We assume it's for the welcome screen topic.
:ivar Optional[str] description?: The description of the welcome screen.
:ivar List[WelcomeChannels] welcome_channels: A list of welcome channels of the welcome screen.
"""
description: Optional[str] = field(default=None)
welcome_channels: Optional[List[WelcomeChannels]] = field(
converter=convert_list(WelcomeChannels), default=None
)
@define()
class StageInstance(DictSerializerMixin, IDMixin):
"""
A class object representing an instance of a stage channel in a guild.
:ivar Snowflake id: The ID of the stage.
:ivar Snowflake guild_id: The guild ID the stage is in.
:ivar Snowflake channel_id: The channel ID the stage is instantiated from.
:ivar str topic: The topic of the stage.
:ivar int privacy_level: The "privacy"/inclusive accessibility level of the stage.
:ivar bool discoverable_disabled: Whether the stage can be seen from the stage discovery.
"""
id: Snowflake = field(converter=Snowflake)
guild_id: Snowflake = field(converter=Snowflake)
channel_id: Snowflake = field(converter=Snowflake)
topic: str = field()
privacy_level: int = field() # can be Enum'd
discoverable_disabled: bool = field()
@define()
class UnavailableGuild(DictSerializerMixin, IDMixin):
"""
A class object representing how a guild that is unavailable.
.. note::
This object only seems to show up during the connection process
of the client to the Gateway when the ``READY`` event is dispatched.
This event will pass fields with ``guilds`` where this becomes
present.
:ivar Snowflake id: The ID of the unavailable guild.
:ivar bool unavailable: Whether the guild is unavailable or not.
"""
id: Snowflake = field(converter=Snowflake)
unavailable: bool = field()
class AsyncMembersIterator(DiscordPaginationIterator):
"""
A class object that allows iterating through a channel's history.
:param _client: The HTTPClient of the bot
:type _client: HTTPClient
:param obj: The guild to get the members from
:type obj: Union[int, str, Snowflake, Guild]
:param start_at?: The member ID to start getting members from (gets all members after that member)
:type start_at?: Optional[Union[int, str, Snowflake, Member]]
:param check?: A check to ignore certain members
:type check?: Optional[Callable[[Member], bool]]
:param maximum?: A set maximum of members to get before stopping the iteration
:type maximum?: Optional[int]
"""
def __init__(
self,
_client: "HTTPClient",
obj: Union[int, str, Snowflake, "Guild"],
maximum: Optional[int] = inf,
start_at: Optional[Union[int, str, Snowflake, Member]] = MISSING,
check: Optional[Callable[[Member], bool]] = None,
):
super().__init__(obj, _client, maximum=maximum, start_at=start_at, check=check)
self.after = self.start_at
self.objects: Optional[List[Member]]
async def get_first_objects(self) -> None:
limit = min(self.maximum, 1000)
if self.maximum == limit:
self.__stop = True
members = await self._client.get_list_of_members(
guild_id=self.object_id, after=self.after, limit=limit
)
self.after = int(members[-1]["user"]["id"])
if len(members) < 1000:
# already all messages resolved with one operation
self.__stop = True
self.object_count += limit
self.objects = [Member(**member, _client=self._client) for member in members]
async def get_objects(self) -> None:
limit = min(500, self.maximum - self.object_count)
members = await self._client.get_list_of_members(
guild_id=self.object_id, after=self.after, limit=limit
)
self.after = int(members[-1]["user"]["id"])
if len(members) < limit or limit == self.maximum - self.object_count:
# end of messages reached again
self.__stop = True
self.object_count += limit
self.objects.extend([Member(**member, _client=self._client) for member in members])
async def flatten(self) -> List[Member]:
"""returns all remaining items as list"""
return [item async for item in self]
async def __anext__(self) -> Member:
if self.objects is None:
await self.get_first_objects()
try:
obj = self.objects.pop(0)
if self.check:
res = self.check(obj)
_res = await res if isawaitable(res) else res
while not _res:
if (
not self.__stop
and len(self.objects) < 5
and self.object_count >= self.maximum
):
await self.get_objects()
self.object_count -= 1
obj = self.objects.pop(0)
_res = self.check(obj)
if not self.__stop and len(self.objects) < 5 and self.object_count <= self.maximum:
await self.get_objects()
except IndexError:
raise StopAsyncIteration
else:
return obj
@define()
class Guild(ClientSerializerMixin, IDMixin):
"""
A class object representing how a guild is registered.
.. note::
Most of these optionals are actually declared with their value
upon instantiation but are kept like this since this class object
is meant to be more broad and generalized.
:ivar Snowflake id: The ID of the guild.
:ivar str name: The name of the guild.
:ivar Optional[str] icon?: The icon of the guild.
:ivar Optional[str] icon_hash?: The hashed version of the icon of the guild.
:ivar Optional[str] splash?: The invite splash banner of the guild.
:ivar Optional[str] discovery_splash?: The discovery splash banner of the guild.
:ivar Optional[bool] owner?: Whether the guild is owned.
:ivar Snowflake owner_id: The ID of the owner of the guild.
:ivar Optional[str] permissions?: The permissions of the guild.
:ivar Optional[str] region?: The geographical region of the guild.
:ivar Optional[Snowflake] afk_channel_id?: The AFK voice channel of the guild.
:ivar int afk_timeout: The timeout of the AFK voice channel of the guild.
:ivar Optional[bool] widget_enabled?: Whether widgets are enabled in the guild.
:ivar Optional[Snowflake] widget_channel_id?: The channel ID of the widget in the guild.
:ivar int verification_level: The level of user verification of the guild.
:ivar int default_message_notifications: The default message notifications setting of the guild.
:ivar int explicit_content_filter: The explicit content filter setting level of the guild.
:ivar List[Role] roles: The list of roles in the guild.
:ivar List[Emoji] emojis: The list of emojis from the guild.
:ivar List[GuildFeature] features: The list of features of the guild.
:ivar int mfa_level: The MFA level of the guild.
:ivar Optional[Snowflake] application_id?: The application ID of the guild.
:ivar Optional[Snowflake] system_channel_id?: The channel ID of the system of the guild.
:ivar Optional[Snowflake] rules_channel_id?: The channel ID of Discord's defined "rules" channel of the guild.
:ivar Optional[datetime] joined_at?: The timestamp the member joined the guild.
:ivar Optional[bool] large?: Whether the guild is considered "large."
:ivar Optional[bool] unavailable?: Whether the guild is unavailable to access.
:ivar Optional[int] member_count?: The amount of members in the guild.
:ivar Optional[List[Member]] members?: The members in the guild.
:ivar Optional[List[Channel]] channels?: The channels in the guild.
:ivar Optional[List[Thread]] threads?: All known threads in the guild.
:ivar Optional[List[PresenceUpdate]] presences?: The list of presences in the guild.
:ivar Optional[int] max_presences?: The maximum amount of presences allowed in the guild.
:ivar Optional[int] max_members?: The maximum amount of members allowed in the guild.
:ivar Optional[str] vanity_url_code?: The vanity URL of the guild.
:ivar Optional[str] description?: The description of the guild.
:ivar Optional[str] banner?: The banner of the guild.
:ivar int premium_tier: The server boost level of the guild.
:ivar Optional[int] premium_subscription_count?: The amount of server boosters in the guild.
:ivar str preferred_locale: The "preferred" local region of the guild.
:ivar Optional[Snowflake] public_updates_channel_id?: The channel ID for community updates of the guild.
:ivar Optional[int] max_video_channel_users?: The maximum amount of video streaming members in a channel allowed in a guild.
:ivar Optional[int] approximate_member_count?: The approximate amount of members in the guild.
:ivar Optional[int] approximate_presence_count?: The approximate amount of presences in the guild.
:ivar Optional[WelcomeScreen] welcome_screen?: The welcome screen of the guild.
:ivar int nsfw_level: The NSFW safety filter level of the guild.
:ivar Optional[List[StageInstance]] stage_instances?: The stage instance of the guild.
:ivar Optional[List[Sticker]] stickers?: The list of stickers from the guild.
:ivar Optional[bool] premium_progress_bar_enabled?: Whether the guild has the boost progress bar enabled.
"""
id: Snowflake = field(converter=Snowflake)
name: str = field()
icon: Optional[str] = field(default=None, repr=False)
icon_hash: Optional[str] = field(default=None, repr=False)
splash: Optional[str] = field(default=None, repr=False)
discovery_splash: Optional[str] = field(default=None, repr=False)
owner: Optional[bool] = field(default=None)
owner_id: Snowflake = field(converter=Snowflake, default=None)
permissions: Optional[str] = field(default=None, repr=False)
region: Optional[str] = field(default=None, repr=False) # None, we don't do Voices.
afk_channel_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
afk_timeout: Optional[int] = field(default=None)
widget_enabled: Optional[bool] = field(default=None, repr=False)
widget_channel_id: Optional[Snowflake] = field(converter=Snowflake, default=None, repr=False)
verification_level: int = field(default=0)
default_message_notifications: int = field(default=0)
explicit_content_filter: int = field(default=0)
roles: List[Role] = field(converter=convert_list(Role), factory=list, add_client=True)
emojis: List[Emoji] = field(converter=convert_list(Emoji), factory=list, add_client=True)
mfa_level: int = field(default=0)
application_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
system_channel_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
system_channel_flags: int = field(default=None)
rules_channel_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
joined_at: Optional[datetime] = field(converter=datetime.fromisoformat, default=None)
large: Optional[bool] = field(default=None)
unavailable: Optional[bool] = field(default=None)
member_count: Optional[int] = field(default=None)
members: Optional[List[Member]] = field(
converter=convert_list(Member), default=None, add_client=True
)
channels: Optional[List[Channel]] = field(
converter=convert_list(Channel), default=None, add_client=True
)
threads: Optional[List[Thread]] = field(
converter=convert_list(Thread), default=None, add_client=True
) # threads, because of their metadata
presences: Optional[List[PresenceActivity]] = field(
converter=convert_list(PresenceActivity), default=None
)
max_presences: Optional[int] = field(default=None)
max_members: Optional[int] = field(default=None)
vanity_url_code: Optional[str] = field(default=None)
description: Optional[str] = field(default=None)
banner: Optional[str] = field(default=None, repr=False)
premium_tier: int = field(default=0)
premium_subscription_count: Optional[int] = field(default=None, repr=False)
preferred_locale: str = field(default=None)
public_updates_channel_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
max_video_channel_users: Optional[int] = field(default=None, repr=False)
approximate_member_count: Optional[int] = field(default=None)
approximate_presence_count: Optional[int] = field(default=None)
welcome_screen: Optional[WelcomeScreen] = field(
converter=WelcomeScreen, default=None, repr=False
)
nsfw_level: int = field(default=0)
stage_instances: Optional[List[StageInstance]] = field(
converter=convert_list(StageInstance), default=None
)
stickers: Optional[List[Sticker]] = field(converter=convert_list(Sticker), default=None)
features: List[str] = field()
premium_progress_bar_enabled: Optional[bool] = field(default=None)
# todo assign the correct type
def __attrs_post_init__(self): # sourcery skip: last-if-guard
if self._client:
# update the cache to include info found from guilds
# these values wouldn't be "found out" until an update for them happened otherwise
if self.channels:
self._client.cache[Channel].update({c.id: c for c in self.channels})
if self.threads:
self._client.cache[Thread].update({t.id: t for t in self.threads})
if self.roles:
self._client.cache[Role].update({r.id: r for r in self.roles})
if self.members:
self._client.cache[Member].update({(self.id, m.id): m for m in self.members})
if guild := self._client.cache[Guild].get(self.id):
if not self.channels:
self.channels = guild.channels
if not self.threads:
self.threads = guild.threads
if not self.roles:
self.roles = guild.roles
if not self.members:
self.members = guild.members
if not self.member_count:
self.member_count = guild.member_count
if not self.presences:
self.presences = guild.presences
if not self.emojis:
self.emojis = guild.emojis
if self.members:
for member in self.members:
if not member._extras.get("guild_id"):
member._extras["guild_id"] = self.id
def __repr__(self) -> str:
return self.name
async def ban(
self,
member_id: Union[int, Member, Snowflake],
seconds: Optional[int] = 0,
minutes: Optional[int] = MISSING,
hours: Optional[int] = MISSING,
days: Optional[int] = MISSING,
reason: Optional[str] = None,
) -> None:
"""
Bans a member from the guild.
:param member_id: The id of the member to ban
:type member_id: Union[int, Member, Snowflake]
:param seconds?: Number of seconds to delete messages, from 0 to 604800. Defaults to 0
:type seconds?: Optional[int]
:param minutes?: Number of minutes to delete messages, from 0 to 10080
:type minutes?: Optional[int]
:param hours?: Number of hours to delete messages, from 0 to 168
:type hours?: Optional[int]
:param days?: Number of days to delete messages, from 0 to 7
:type days?: Optional[int]
:param reason?: The reason of the ban
:type reason?: Optional[str]
"""
if not self._client:
raise LibraryException(code=13)
if days is not MISSING:
seconds += days * 24 * 3600
if hours is not MISSING:
seconds += hours * 3600
if minutes is not MISSING:
seconds += minutes * 60
if seconds > 604800:
raise LibraryException(
code=12,
message="The amount of total seconds to delete messages exceeds the limit Discord provides (604800)",
)
_member_id = int(member_id.id) if isinstance(member_id, Member) else int(member_id)
await self._client.create_guild_ban(
guild_id=int(self.id),
user_id=_member_id,
reason=reason,
delete_message_seconds=seconds,
)
if not self.members:
return
for member in self.members:
if int(member.id) == _member_id:
return self.members.remove(member)
async def remove_ban(
self,
user_id: Union[int, Snowflake], # only support ID since there's no member on the guild
reason: Optional[str] = None,
) -> None:
"""
Removes the ban of a user.
:param user_id: The id of the user to remove the ban from
:type user_id: Union[int, Snowflake]
:param reason?: The reason for the removal of the ban
:type reason?: Optional[str]
"""
if not self._client:
raise LibraryException(code=13)
await self._client.remove_guild_ban(
guild_id=int(self.id),
user_id=user_id,
reason=reason,
)
async def kick(
self,
member_id: Union[int, Member, Snowflake],
reason: Optional[str] = None,
) -> None:
"""
Kicks a member from the guild.
:param member_id: The id of the member to kick
:type member_id: Union[int, Member, Snowflake]
:param reason?: The reason for the kick
:type reason?: Optional[str]
"""
if not self._client:
raise LibraryException(code=13)
_member_id = int(member_id.id) if isinstance(member_id, Member) else int(member_id)
await self._client.create_guild_kick(
guild_id=int(self.id),
user_id=_member_id,
reason=reason,
)
for member in self.members:
if int(member.id) == _member_id:
return self.members.remove(member)
async def add_member_role(
self,
role: Union[Role, int, Snowflake],
member_id: Union[Member, int, Snowflake],
reason: Optional[str] = None,
) -> None:
"""
This method adds a role to a member.
:param role: The role to add. Either ``Role`` object or role_id
:type role Union[Role, int, Snowflake]
:param member_id: The id of the member to add the roles to
:type member_id: Union[Member, int, Snowflake]
:param reason?: The reason why the roles are added
:type reason?: Optional[str]
"""
if not self._client:
raise LibraryException(code=13)
_role_id = int(role.id) if isinstance(role, Role) else int(role)
_member_id = int(member_id.id) if isinstance(member_id, Member) else int(member_id)
await self._client.add_member_role(
guild_id=int(self.id),
user_id=_member_id,
role_id=_role_id,
reason=reason,
)
async def remove_member_role(
self,
role: Union[Role, int, Snowflake],
member_id: Union[Member, int, Snowflake],
reason: Optional[str] = None,
) -> None:
"""
This method removes a or multiple role(s) from a member.
:param role: The role to remove. Either ``Role`` object or role_id
:type role: Union[Role, int, Snowflake]
:param member_id: The id of the member to remove the roles from
:type member_id: Union[Member, int, Snowflake]
:param reason?: The reason why the roles are removed
:type reason?: Optional[str]
"""
if not self._client:
raise LibraryException(code=13)
_role_id = int(role.id) if isinstance(role, Role) else int(role)
_member_id = int(member_id.id) if isinstance(member_id, Member) else int(member_id)
await self._client.remove_member_role(
guild_id=int(self.id),
user_id=_member_id,
role_id=_role_id,
reason=reason,
)
async def create_role(
self,
name: str,
permissions: Optional[int] = MISSING,
color: Optional[int] = 0,
hoist: Optional[bool] = False,
icon: Optional[Image] = MISSING,
unicode_emoji: Optional[str] = MISSING,
mentionable: Optional[bool] = False,
reason: Optional[str] = None,
) -> Role:
"""
Creates a new role in the guild.
:param name: The name of the role
:type name: str
:param color?: RGB color value as integer, default ``0``
:type color?: Optional[int]
:param permissions?: Bitwise value of the enabled/disabled permissions
:type permissions?: Optional[int]
:param hoist?: Whether the role should be displayed separately in the sidebar, default ``False``
:type hoist?: Optional[bool]
:param icon?: The role's icon image (if the guild has the ROLE_ICONS feature)
:type icon?: Optional[Image]
:param unicode_emoji?: The role's unicode emoji as a standard emoji (if the guild has the ROLE_ICONS feature)
:type unicode_emoji?: Optional[str]
:param mentionable?: Whether the role should be mentionable, default ``False``
:type mentionable?: Optional[bool]
:param reason?: The reason why the role is created, default ``None``
:type reason?: Optional[str]
:return: The created Role
:rtype: Role
"""
if not self._client:
raise LibraryException(code=13)
_permissions = permissions if permissions is not MISSING else None
_icon = icon if icon is not MISSING else None
_unicode_emoji = unicode_emoji if unicode_emoji is not MISSING else None
payload = dict(
name=name,
permissions=_permissions,
icon=_icon,
unicode_emoji=_unicode_emoji,
color=color,
hoist=hoist,
mentionable=mentionable,
)
res = await self._client.create_guild_role(
guild_id=int(self.id),
reason=reason,
payload=payload,
)
if self.roles is None:
self.roles = []
role = Role(**res, _client=self._client)
self.roles.append(role)
return role
async def get_member(
self,
member_id: Union[int, Snowflake],
) -> Member:
"""
Searches for the member with specified id in the guild and returns the member as member object.
:param member_id: The id of the member to search for
:type member_id: Union[int, Snowflake]
:return: The member searched for
:rtype: Member
"""
if not self._client:
raise LibraryException(code=13)
res = await self._client.get_member(
guild_id=int(self.id),
member_id=int(member_id),
)
member = Member(**res, _client=self._client, guild_id=self.id)
if self.members is None:
self.members = []
for index, _member in enumerate(self.members):
if int(_member.id) == int(member_id):
self.members[index] = member
break
else:
self.members.append(member)
return member
async def delete_channel(
self,
channel_id: Union[int, Snowflake, Channel],
) -> None:
"""
Deletes a channel from the guild.
:param channel_id: The id of the channel to delete
:type channel_id: Union[int, Snowflake, Channel]
"""
if not self._client:
raise LibraryException(code=13)
_channel_id = int(channel_id.id) if isinstance(channel_id, Channel) else int(channel_id)
await self._client.delete_channel(_channel_id)
if not self.channels:
return
for channel in self.channels:
if int(channel.id) == _channel_id:
return self.channels.remove(channel)
async def delete_role(
self,
role_id: Union[int, Snowflake, Role],
reason: Optional[str] = None,
) -> None:
"""
Deletes a role from the guild.
:param role_id: The id of the role to delete
:type role_id: Union[int, Snowflake, Role]
:param reason?: The reason of the deletion
:type reason?: Optional[str]
"""
if not self._client:
raise LibraryException(code=13)
_role_id = int(role_id.id) if isinstance(role_id, Role) else int(role_id)
await self._client.delete_guild_role(
guild_id=int(self.id),
role_id=_role_id,
reason=reason,
)
if not self.roles:
return
for role in self.roles:
if int(role.id) == _role_id:
return self.roles.remove(role)
async def modify_role(
self,
role_id: Union[int, Snowflake, Role],
name: Optional[str] = MISSING,
permissions: Optional[int] = MISSING,
color: Optional[int] = MISSING,
hoist: Optional[bool] = MISSING,
icon: Optional[Image] = MISSING,
unicode_emoji: Optional[str] = MISSING,
mentionable: Optional[bool] = MISSING,
reason: Optional[str] = None,
) -> Role:
"""
Edits a role in the guild.
:param role_id: The id of the role to edit
:type role_id: Union[int, Snowflake, Role]
:param name?: The name of the role, defaults to the current value of the role
:type name?: Optional[str]
:param color?: RGB color value as integer, defaults to the current value of the role
:type color?: Optional[int]
:param permissions?: Bitwise value of the enabled/disabled permissions, defaults to the current value of the role
:type permissions?: Optional[int]
:param hoist?: Whether the role should be displayed separately in the sidebar, defaults to the current value of the role
:type hoist?: Optional[bool]
:param icon?: The role's icon image (if the guild has the ROLE_ICONS feature), defaults to the current value of the role
:type icon?: Optional[Image]
:param unicode_emoji?: The role's unicode emoji as a standard emoji (if the guild has the ROLE_ICONS feature), defaults to the current value of the role
:type unicode_emoji?: Optional[str]
:param mentionable?: Whether the role should be mentionable, defaults to the current value of the role
:type mentionable?: Optional[bool]
:param reason?: The reason why the role is edited, default ``None``
:type reason?: Optional[str]
:return: The modified role object
:rtype: Role
"""
if not self._client:
raise LibraryException(code=13)
if isinstance(role_id, Role):
role = role_id
else:
role = await self.get_role(int(role_id))
_name = role.name if name is MISSING else name
_color = role.color if color is MISSING else color
_hoist = role.hoist if hoist is MISSING else hoist
_mentionable = role.mentionable if mentionable is MISSING else mentionable
_permissions = role.permissions if permissions is MISSING else permissions
_icon = role.icon if icon is MISSING else icon
_unicode_emoji = role.unicode_emoji if unicode_emoji is MISSING else unicode_emoji
payload = dict(
name=_name,
color=_color,
hoist=_hoist,
mentionable=_mentionable,
permissions=_permissions,
unicode_emoji=_unicode_emoji,
icon=_icon,
)
res = await self._client.modify_guild_role(
guild_id=int(self.id),
role_id=role_id,
payload=payload,
reason=reason,
)
_role = Role(**res, _client=self._client)
if self.roles is None:
self.roles = []
for index, item in enumerate(self.roles):
if int(item.id) == int(role.id):
self.roles[index] = _role
break
else:
self.roles.append(_role)
return _role
async def create_thread(
self,
name: str,
channel_id: Union[int, Snowflake, Channel],
type: Optional[ChannelType] = ChannelType.PUBLIC_THREAD,
auto_archive_duration: Optional[int] = MISSING,
invitable: Optional[bool] = MISSING,
message_id: Optional[Union[int, Snowflake, "Message"]] = MISSING,
reason: Optional[str] = None,
) -> Channel:
"""
Creates a thread in the specified channel.
:param name: The name of the thread
:type name: str
:param channel_id: The id of the channel to create the thread in
:type channel_id: Union[int, Snowflake, Channel]
:param auto_archive_duration?: duration in minutes to automatically archive the thread after recent activity,
can be set to: 60, 1440, 4320, 10080
:type auto_archive_duration?: Optional[int]
:param type?: The type of thread, defaults to public. ignored if creating thread from a message
:type type?: Optional[ChannelType]
:param invitable?: Boolean to display if the Thread is open to join or private.
:type invitable?: Optional[bool]
:param message_id?: An optional message to create a thread from.
:type message_id?: Optional[Union[int, Snowflake, "Message"]]
:param reason?: An optional reason for the audit log
:type reason?: Optional[str]
:return: The created thread
:rtype: Channel
"""
if not self._client:
raise LibraryException(code=13)
if type not in [
ChannelType.ANNOUNCEMENT_THREAD,
ChannelType.PUBLIC_THREAD,
ChannelType.PRIVATE_THREAD,
]:
raise LibraryException(message="type must be a thread type!", code=12)
_auto_archive_duration = None if auto_archive_duration is MISSING else auto_archive_duration
_invitable = None if invitable is MISSING else invitable
_message_id = (
None
if message_id is MISSING
else (
int(message_id) if isinstance(message_id, (int, Snowflake)) else int(message_id.id)
)
) # work around Message import
_channel_id = int(channel_id.id) if isinstance(channel_id, Channel) else int(channel_id)
res = await self._client.create_thread(
channel_id=_channel_id,
thread_type=type if isinstance(type, int) else type.value,
name=name,
auto_archive_duration=_auto_archive_duration,
invitable=_invitable,
message_id=_message_id,
reason=reason,
)
return Channel(**res, _client=self._client)
async def create_channel(
self,
name: str,
type: ChannelType,
topic: Optional[str] = MISSING,
bitrate: Optional[int] = MISSING,
user_limit: Optional[int] = MISSING,
rate_limit_per_user: Optional[int] = MISSING,
position: Optional[int] = MISSING,
permission_overwrites: Optional[List[Overwrite]] = MISSING,
parent_id: Optional[Union[int, Channel, Snowflake]] = MISSING,
nsfw: Optional[bool] = MISSING,
reason: Optional[str] = None,
) -> Channel:
"""
Creates a channel in the guild.
:param name: The name of the channel
:type name: str
:param type: The type of the channel
:type type: ChannelType
:param topic?: The topic of that channel
:type topic?: Optional[str]
:param bitrate?: (voice channel only) The bitrate (in bits) of the voice channel
:type bitrate?: Optional[int]
:param user_limit?: (voice channel only) Maximum amount of users in the channel
:type user_limit?: Optional[int]
:param rate_limit_per_use?: Amount of seconds a user has to wait before sending another message (0-21600)
:type rate_limit_per_user: Optional[int]
:param position?: Sorting position of the channel
:type position?: Optional[int]
:param parent_id?: The id of the parent category for a channel
:type parent_id?: Optional[Union[int, Channel, Snowflake]]
:param permission_overwrites?: The permission overwrites, if any
:type permission_overwrites?: Optional[Overwrite]
:param nsfw?: Whether the channel is nsfw or not, default ``False``
:type nsfw?: Optional[bool]
:param reason: The reason for the creation
:type reason: Optional[str]
:return: The created channel
:rtype: Channel
"""
if not self._client:
raise LibraryException(code=13)
if type in [
ChannelType.DM,
ChannelType.DM.value,
ChannelType.GROUP_DM,
ChannelType.GROUP_DM.value,
]:
raise LibraryException(
message="ChannelType must not be a direct-message when creating Guild Channels!",
code=12,
)
if type in [
ChannelType.ANNOUNCEMENT_THREAD,
ChannelType.PUBLIC_THREAD,
ChannelType.PRIVATE_THREAD,
]:
raise LibraryException(
message="Please use `create_thread` for creating threads!", code=12
)
payload = {"name": name, "type": type}
if topic is not MISSING:
payload["topic"] = topic
if bitrate is not MISSING:
payload["bitrate"] = bitrate
if user_limit is not MISSING:
payload["user_limit"] = user_limit
if rate_limit_per_user is not MISSING:
payload["rate_limit_per_user"] = rate_limit_per_user
if position is not MISSING:
payload["position"] = position