-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathguild.py
5626 lines (4560 loc) · 195 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
# SPDX-License-Identifier: MIT
from __future__ import annotations
import copy
import datetime
import unicodedata
from typing import (
TYPE_CHECKING,
Any,
ClassVar,
Dict,
Iterable,
List,
Literal,
NamedTuple,
NewType,
Optional,
Sequence,
Set,
Tuple,
Union,
cast,
overload,
)
from . import abc, utils
from .app_commands import GuildApplicationCommandPermissions
from .asset import Asset
from .automod import AutoModAction, AutoModRule
from .bans import BanEntry, BulkBanResult
from .channel import (
CategoryChannel,
ForumChannel,
MediaChannel,
StageChannel,
TextChannel,
VoiceChannel,
_guild_channel_factory,
_threaded_guild_channel_factory,
)
from .colour import Colour
from .emoji import Emoji
from .enums import (
AuditLogAction,
AutoModEventType,
AutoModTriggerType,
ChannelType,
ContentFilter,
GuildScheduledEventEntityType,
GuildScheduledEventPrivacyLevel,
Locale,
NotificationLevel,
NSFWLevel,
ThreadLayout,
ThreadSortOrder,
VerificationLevel,
VideoQualityMode,
WidgetStyle,
try_enum,
try_enum_to_int,
)
from .errors import ClientException, HTTPException, InvalidData
from .file import File
from .flags import SystemChannelFlags
from .guild_scheduled_event import GuildScheduledEvent, GuildScheduledEventMetadata
from .integrations import Integration, _integration_factory
from .invite import Invite
from .iterators import AuditLogIterator, BanIterator, MemberIterator
from .member import Member, VoiceState
from .mixins import Hashable
from .object import Object
from .onboarding import Onboarding
from .partial_emoji import PartialEmoji
from .permissions import PermissionOverwrite
from .role import Role
from .soundboard import GuildSoundboardSound
from .stage_instance import StageInstance
from .sticker import GuildSticker
from .threads import Thread, ThreadMember
from .user import User
from .voice_region import VoiceRegion
from .welcome_screen import WelcomeScreen, WelcomeScreenChannel
from .widget import Widget, WidgetSettings
__all__ = (
"Guild",
"GuildBuilder",
)
VocalGuildChannel = Union[VoiceChannel, StageChannel]
MISSING = utils.MISSING
if TYPE_CHECKING:
from .abc import Snowflake, SnowflakeTime
from .app_commands import APIApplicationCommand
from .asset import AssetBytes
from .automod import AutoModTriggerMetadata
from .permissions import Permissions
from .state import ConnectionState
from .template import Template
from .threads import AnyThreadArchiveDuration, ForumTag
from .types.channel import PermissionOverwrite as PermissionOverwritePayload
from .types.guild import (
Ban as BanPayload,
CreateGuildPlaceholderChannel,
CreateGuildPlaceholderRole,
Guild as GuildPayload,
GuildFeature,
MFALevel,
)
from .types.integration import IntegrationType
from .types.role import CreateRole as CreateRolePayload
from .types.sticker import CreateGuildSticker as CreateStickerPayload
from .types.threads import Thread as ThreadPayload, ThreadArchiveDurationLiteral
from .types.voice import GuildVoiceState
from .voice_client import VoiceProtocol
from .webhook import Webhook
GuildMessageable = Union[TextChannel, Thread, VoiceChannel, StageChannel]
GuildChannel = Union[
VoiceChannel, StageChannel, TextChannel, CategoryChannel, ForumChannel, MediaChannel
]
ByCategoryItem = Tuple[Optional[CategoryChannel], List[GuildChannel]]
class _GuildLimit(NamedTuple):
emoji: int
stickers: int
bitrate: float
filesize: int
sounds: int
class Guild(Hashable):
"""Represents a Discord guild.
This is referred to as a "server" in the official Discord UI.
.. collapse:: operations
.. describe:: x == y
Checks if two guilds are equal.
.. describe:: x != y
Checks if two guilds are not equal.
.. describe:: hash(x)
Returns the guild's hash.
.. describe:: str(x)
Returns the guild's name.
Attributes
----------
name: :class:`str`
The guild's name.
emojis: Tuple[:class:`Emoji`, ...]
All emojis that the guild owns.
stickers: Tuple[:class:`GuildSticker`, ...]
All stickers that the guild owns.
.. versionadded:: 2.0
soundboard_sounds: Tuple[:class:`GuildSoundboardSound`, ...]
All soundboard sounds that the guild owns.
.. versionadded:: 2.10
afk_timeout: :class:`int`
The timeout to get sent to the AFK channel.
afk_channel: Optional[:class:`VoiceChannel`]
The channel that denotes the AFK channel. ``None`` if it doesn't exist.
id: :class:`int`
The guild's ID.
owner_id: :class:`int`
The guild owner's ID. Use :attr:`Guild.owner` if you need a :class:`Member` object instead.
unavailable: :class:`bool`
Whether the guild is unavailable. If this is ``True`` then the
reliability of other attributes outside of :attr:`Guild.id` is slim and they might
all be ``None``. It is best to not do anything with the guild if it is unavailable.
Check :func:`on_guild_unavailable` and :func:`on_guild_available` events.
max_presences: Optional[:class:`int`]
The maximum amount of presences for the guild.
max_members: Optional[:class:`int`]
The maximum amount of members for the guild.
.. note::
This attribute is only available via :meth:`.Client.fetch_guild`.
max_video_channel_users: Optional[:class:`int`]
The maximum amount of users in a video channel.
.. versionadded:: 1.4
max_stage_video_channel_users: Optional[:class:`int`]
The maximum amount of users in a stage video channel.
.. versionadded: 2.9
description: Optional[:class:`str`]
The guild's description.
mfa_level: :class:`int`
Indicates the guild's two-factor authentication level. If this value is 0 then
the guild does not require 2FA for their administrative members
to take moderation actions. If the value is 1, then 2FA is required.
verification_level: :class:`VerificationLevel`
The guild's verification level.
explicit_content_filter: :class:`ContentFilter`
The guild's explicit content filter.
default_notifications: :class:`NotificationLevel`
The guild's notification settings.
features: List[:class:`str`]
A list of features that the guild has. The features that a guild can have are
subject to arbitrary change by Discord.
A partial list of features is below:
- ``ANIMATED_BANNER``: Guild can upload an animated banner.
- ``ANIMATED_ICON``: Guild can upload an animated icon.
- ``AUTO_MODERATION``: Guild has set up auto moderation rules.
- ``BANNER``: Guild can upload and use a banner. (i.e. :attr:`.banner`)
- ``COMMUNITY``: Guild is a community server.
- ``CREATOR_MONETIZABLE_PROVISIONAL``: Guild has enabled monetization.
- ``CREATOR_STORE_PAGE``: Guild has enabled the role subscription promo page.
- ``DEVELOPER_SUPPORT_SERVER``: Guild is set as a support server in the app directory.
- ``DISCOVERABLE``: Guild shows up in Server Discovery.
- ``ENABLED_DISCOVERABLE_BEFORE``: Guild had Server Discovery enabled at least once.
- ``FEATURABLE``: Guild is able to be featured in Server Discovery.
- ``HAS_DIRECTORY_ENTRY``: Guild is listed in a student hub.
- ``HUB``: Guild is a student hub.
- ``INVITE_SPLASH``: Guild's invite page can have a special splash.
- ``INVITES_DISABLED``: Guild has paused invites, preventing new users from joining.
- ``LINKED_TO_HUB``: Guild is linked to a student hub.
- ``MEMBER_VERIFICATION_GATE_ENABLED``: Guild has Membership Screening enabled.
- ``MORE_EMOJI``: Guild has increased custom emoji slots.
- ``MORE_SOUNDBOARD``: Guild has increased custom soundboard slots.
- ``MORE_STICKERS``: Guild has increased custom sticker slots.
- ``NEWS``: Guild can create news channels.
- ``NEW_THREAD_PERMISSIONS``: Guild is using the new thread permission system.
- ``PARTNERED``: Guild is a partnered server.
- ``PREVIEW_ENABLED``: Guild can be viewed before being accepted via Membership Screening.
- ``PRIVATE_THREADS``: Guild has access to create private threads (no longer has any effect).
- ``RAID_ALERTS_DISABLED``: Guild has disabled alerts for join raids in the configured safety alerts channel.
- ``ROLE_ICONS``: Guild has access to role icons.
- ``ROLE_SUBSCRIPTIONS_AVAILABLE_FOR_PURCHASE``: Guild has role subscriptions that can be purchased.
- ``ROLE_SUBSCRIPTIONS_ENABLED``: Guild has enabled role subscriptions.
- ``SEVEN_DAY_THREAD_ARCHIVE``: Guild has access to the seven day archive time for threads (no longer has any effect).
- ``SOUNDBOARD``: Guild has created soundboard sounds.
- ``TEXT_IN_VOICE_ENABLED``: Guild has text in voice channels enabled (no longer has any effect).
- ``THREE_DAY_THREAD_ARCHIVE``: Guild has access to the three day archive time for threads (no longer has any effect).
- ``THREADS_ENABLED``: Guild has access to threads (no longer has any effect).
- ``TICKETED_EVENTS_ENABLED``: Guild has enabled ticketed events (no longer has any effect).
- ``VANITY_URL``: Guild can have a vanity invite URL (e.g. discord.gg/disnake).
- ``VERIFIED``: Guild is a verified server.
- ``VIP_REGIONS``: Guild has VIP voice regions.
- ``WELCOME_SCREEN_ENABLED``: Guild has enabled the welcome screen.
premium_progress_bar_enabled: :class:`bool`
Whether the server boost progress bar is enabled.
premium_tier: :class:`int`
The premium tier for this guild. Corresponds to "Nitro Server" in the official UI.
The number goes from 0 to 3 inclusive.
premium_subscription_count: :class:`int`
The number of "boosts" this guild currently has.
preferred_locale: :class:`Locale`
The preferred locale for the guild. Used when filtering Server Discovery
results to a specific language.
.. versionchanged:: 2.5
Changed to :class:`Locale` instead of :class:`str`.
nsfw_level: :class:`NSFWLevel`
The guild's NSFW level.
.. versionadded:: 2.0
approximate_member_count: Optional[:class:`int`]
The approximate number of members in the guild.
Only available for manually fetched guilds.
.. versionadded:: 2.3
approximate_presence_count: Optional[:class:`int`]
The approximate number of members currently active in the guild.
This includes idle, dnd, online, and invisible members. Offline members are excluded.
Only available for manually fetched guilds.
.. versionadded:: 2.3
widget_enabled: Optional[:class:`bool`]
Whether the widget is enabled.
.. versionadded:: 2.5
.. note::
This value is unreliable and will only be set after the guild was updated at least once.
Avoid using this and use :func:`widget_settings` instead.
widget_channel_id: Optional[:class:`int`]
The widget channel ID, if set.
.. versionadded:: 2.5
.. note::
This value is unreliable and will only be set after the guild was updated at least once.
Avoid using this and use :func:`widget_settings` instead.
vanity_url_code: Optional[:class:`str`]
The vanity invite code for this guild, if set.
To get a full :class:`Invite` object, see :attr:`Guild.vanity_invite`.
.. versionadded:: 2.5
"""
__slots__ = (
"afk_timeout",
"afk_channel",
"name",
"id",
"unavailable",
"owner_id",
"mfa_level",
"emojis",
"stickers",
"soundboard_sounds",
"features",
"verification_level",
"explicit_content_filter",
"default_notifications",
"description",
"max_presences",
"max_members",
"max_video_channel_users",
"max_stage_video_channel_users",
"premium_progress_bar_enabled",
"premium_tier",
"premium_subscription_count",
"preferred_locale",
"nsfw_level",
"approximate_member_count",
"approximate_presence_count",
"widget_enabled",
"widget_channel_id",
"vanity_url_code",
"_members",
"_channels",
"_icon",
"_banner",
"_state",
"_roles",
"_member_count",
"_large",
"_splash",
"_voice_states",
"_system_channel_id",
"_system_channel_flags",
"_discovery_splash",
"_rules_channel_id",
"_public_updates_channel_id",
"_stage_instances",
"_scheduled_events",
"_threads",
"_region",
"_safety_alerts_channel_id",
)
_PREMIUM_GUILD_LIMITS: ClassVar[Dict[Optional[int], _GuildLimit]] = {
None: _GuildLimit(emoji=50, stickers=5, bitrate=96e3, filesize=26214400, sounds=8),
0: _GuildLimit(emoji=50, stickers=5, bitrate=96e3, filesize=26214400, sounds=8),
1: _GuildLimit(emoji=100, stickers=15, bitrate=128e3, filesize=26214400, sounds=24),
2: _GuildLimit(emoji=150, stickers=30, bitrate=256e3, filesize=52428800, sounds=36),
3: _GuildLimit(emoji=250, stickers=60, bitrate=384e3, filesize=104857600, sounds=48),
}
def __init__(self, *, data: GuildPayload, state: ConnectionState) -> None:
self._channels: Dict[int, GuildChannel] = {}
self._members: Dict[int, Member] = {}
self._voice_states: Dict[int, VoiceState] = {}
self._threads: Dict[int, Thread] = {}
self._stage_instances: Dict[int, StageInstance] = {}
self._scheduled_events: Dict[int, GuildScheduledEvent] = {}
self._state: ConnectionState = state
self._from_data(data)
def _add_channel(self, channel: GuildChannel, /) -> None:
self._channels[channel.id] = channel
def _remove_channel(self, channel: Snowflake, /) -> None:
self._channels.pop(channel.id, None)
def _voice_state_for(self, user_id: int, /) -> Optional[VoiceState]:
return self._voice_states.get(user_id)
def _add_member(self, member: Member, /) -> None:
self._members[member.id] = member
def _store_thread(self, payload: ThreadPayload, /) -> Thread:
thread = Thread(guild=self, state=self._state, data=payload)
self._threads[thread.id] = thread
return thread
def _remove_member(self, member: Snowflake, /) -> None:
self._members.pop(member.id, None)
def _add_thread(self, thread: Thread, /) -> None:
self._threads[thread.id] = thread
def _remove_thread(self, thread: Snowflake, /) -> None:
self._threads.pop(thread.id, None)
def _clear_threads(self) -> None:
self._threads.clear()
def _remove_threads_by_channel(self, channel_id: int) -> None:
to_remove = [k for k, t in self._threads.items() if t.parent_id == channel_id]
for k in to_remove:
del self._threads[k]
def _filter_threads(self, channel_ids: Set[int]) -> Dict[int, Thread]:
to_remove: Dict[int, Thread] = {
k: t for k, t in self._threads.items() if t.parent_id in channel_ids
}
for k in to_remove:
del self._threads[k]
return to_remove
def __str__(self) -> str:
return self.name or ""
def __repr__(self) -> str:
attrs = (
("id", self.id),
("name", self.name),
("shard_id", self.shard_id),
("chunked", self.chunked),
("member_count", getattr(self, "_member_count", None)),
)
inner = " ".join(f"{k!s}={v!r}" for k, v in attrs)
return f"<Guild {inner}>"
def _update_voice_state(
self, data: GuildVoiceState, channel_id: Optional[int]
) -> Tuple[Optional[Member], VoiceState, VoiceState]:
user_id = int(data["user_id"])
channel: Optional[VocalGuildChannel] = self.get_channel(channel_id) # type: ignore
try:
# check if we should remove the voice state from cache
if channel is None:
after = self._voice_states.pop(user_id)
else:
after = self._voice_states[user_id]
before = copy.copy(after)
after._update(data, channel)
except KeyError:
# if we're here then we're getting added into the cache
after = VoiceState(data=data, channel=channel)
before = VoiceState(data=data, channel=None)
self._voice_states[user_id] = after
member = self.get_member(user_id)
if member is None:
try:
member = Member(data=data["member"], state=self._state, guild=self)
except KeyError:
member = None
return member, before, after
def _add_role(self, role: Role, /) -> None:
# roles get added to the bottom (position 1, pos 0 is @everyone)
# so since self.roles has the @everyone role, we can't increment
# its position because it's stuck at position 0. Luckily x += False
# is equivalent to adding 0. So we cast the position to a bool and
# increment it.
for r in self._roles.values():
r.position += not r.is_default()
self._roles[role.id] = role
def _remove_role(self, role_id: int, /) -> Role:
# this raises KeyError if it fails..
role = self._roles.pop(role_id)
# since it didn't, we can change the positions now
# basically the same as above except we only decrement
# the position if we're above the role we deleted.
for r in self._roles.values():
r.position -= r.position > role.position
return role
def get_command(self, application_command_id: int, /) -> Optional[APIApplicationCommand]:
"""Gets a cached application command matching the specified ID.
Parameters
----------
application_command_id: :class:`int`
The application command ID to search for.
Returns
-------
Optional[Union[:class:`.APIUserCommand`, :class:`.APIMessageCommand`, :class:`.APISlashCommand`]]
The application command if found, or ``None`` otherwise.
"""
return self._state._get_guild_application_command(self.id, application_command_id)
def get_command_named(self, name: str, /) -> Optional[APIApplicationCommand]:
"""Gets a cached application command matching the specified name.
Parameters
----------
name: :class:`str`
The application command name to search for.
Returns
-------
Optional[Union[:class:`.APIUserCommand`, :class:`.APIMessageCommand`, :class:`.APISlashCommand`]]
The application command if found, or ``None`` otherwise.
"""
return self._state._get_guild_command_named(self.id, name)
def _from_data(self, guild: GuildPayload) -> None:
# according to Stan, this is always available even if the guild is unavailable
# I don't have this guarantee when someone updates the guild.
member_count = guild.get("member_count", None)
if member_count is not None:
self._member_count: int = member_count
self.name: str = guild.get("name", "")
self._region: str = guild.get("region", "")
self.verification_level: VerificationLevel = try_enum(
VerificationLevel, guild.get("verification_level")
)
self.default_notifications: NotificationLevel = try_enum(
NotificationLevel, guild.get("default_message_notifications")
)
self.explicit_content_filter: ContentFilter = try_enum(
ContentFilter, guild.get("explicit_content_filter", 0)
)
self.afk_timeout: int = guild.get("afk_timeout", 0)
self._icon: Optional[str] = guild.get("icon")
self._banner: Optional[str] = guild.get("banner")
self.unavailable: bool = guild.get("unavailable", False)
self.id: int = int(guild["id"])
self._roles: Dict[int, Role] = {}
state = self._state # speed up attribute access
for r in guild.get("roles", []):
role = Role(guild=self, data=r, state=state)
self._roles[role.id] = role
self.mfa_level: MFALevel = guild.get("mfa_level", 0)
self.emojis: Tuple[Emoji, ...] = tuple(
state.store_emoji(self, d) for d in guild.get("emojis", [])
)
self.stickers: Tuple[GuildSticker, ...] = tuple(
state.store_sticker(self, d) for d in guild.get("stickers", [])
)
self.soundboard_sounds: Tuple[GuildSoundboardSound, ...] = tuple(
state.store_soundboard_sound(self, d) for d in guild.get("soundboard_sounds", [])
)
self.features: List[GuildFeature] = guild.get("features", [])
self._splash: Optional[str] = guild.get("splash")
self._system_channel_id: Optional[int] = utils._get_as_snowflake(guild, "system_channel_id")
self.description: Optional[str] = guild.get("description")
self.max_presences: Optional[int] = guild.get("max_presences")
self.max_members: Optional[int] = guild.get("max_members")
self.max_video_channel_users: Optional[int] = guild.get("max_video_channel_users")
self.max_stage_video_channel_users: Optional[int] = guild.get(
"max_stage_video_channel_users"
)
self.premium_tier: int = guild.get("premium_tier", 0)
self.premium_subscription_count: int = guild.get("premium_subscription_count") or 0
self._system_channel_flags: int = guild.get("system_channel_flags", 0)
self.preferred_locale: Locale = try_enum(Locale, guild.get("preferred_locale"))
self._discovery_splash: Optional[str] = guild.get("discovery_splash")
self._rules_channel_id: Optional[int] = utils._get_as_snowflake(guild, "rules_channel_id")
self._public_updates_channel_id: Optional[int] = utils._get_as_snowflake(
guild, "public_updates_channel_id"
)
self.nsfw_level: NSFWLevel = try_enum(NSFWLevel, guild.get("nsfw_level", 0))
self.premium_progress_bar_enabled: bool = guild.get("premium_progress_bar_enabled", False)
self.approximate_presence_count: Optional[int] = guild.get("approximate_presence_count")
self.approximate_member_count: Optional[int] = guild.get("approximate_member_count")
self.widget_enabled: Optional[bool] = guild.get("widget_enabled")
self.widget_channel_id: Optional[int] = utils._get_as_snowflake(guild, "widget_channel_id")
self.vanity_url_code: Optional[str] = guild.get("vanity_url_code")
self._safety_alerts_channel_id: Optional[int] = utils._get_as_snowflake(
guild, "safety_alerts_channel_id"
)
stage_instances = guild.get("stage_instances")
if stage_instances is not None:
self._stage_instances = {}
for s in stage_instances:
stage_instance = StageInstance(guild=self, data=s, state=state)
self._stage_instances[stage_instance.id] = stage_instance
scheduled_events = guild.get("guild_scheduled_events")
if scheduled_events is not None:
self._scheduled_events = {}
for e in scheduled_events:
scheduled_event = GuildScheduledEvent(state=state, data=e)
self._scheduled_events[scheduled_event.id] = scheduled_event
cache_joined = self._state.member_cache_flags.joined
self_id = self._state.self_id
for mdata in guild.get("members", []):
# NOTE: Are we sure it's fine to not have the user part here?
member = Member(data=mdata, guild=self, state=state) # type: ignore
if cache_joined or member.id == self_id:
self._add_member(member)
self._sync(guild)
self._large: Optional[bool] = None if member_count is None else self._member_count >= 250
self.owner_id: Optional[int] = utils._get_as_snowflake(guild, "owner_id")
self.afk_channel: Optional[VocalGuildChannel] = self.get_channel(utils._get_as_snowflake(guild, "afk_channel_id")) # type: ignore
for obj in guild.get("voice_states", []):
self._update_voice_state(obj, utils._get_as_snowflake(obj, "channel_id"))
# TODO: refactor/remove?
def _sync(self, data: GuildPayload) -> None:
try:
self._large = data["large"]
except KeyError:
pass
empty_tuple = ()
for presence in data.get("presences", []):
user_id = int(presence["user"]["id"])
member = self.get_member(user_id)
if member is not None:
member._presence_update(presence, empty_tuple) # type: ignore
if "channels" in data:
channels = data["channels"]
for c in channels:
factory, _ = _guild_channel_factory(c["type"])
if factory:
self._add_channel(factory(guild=self, data=c, state=self._state)) # type: ignore
if "threads" in data:
threads = data["threads"]
for thread in threads:
self._add_thread(Thread(guild=self, state=self._state, data=thread))
@property
def channels(self) -> List[GuildChannel]:
"""List[:class:`abc.GuildChannel`]: A list of channels that belong to this guild."""
return list(self._channels.values())
@property
def threads(self) -> List[Thread]:
"""List[:class:`Thread`]: A list of threads that you have permission to view.
.. versionadded:: 2.0
"""
return list(self._threads.values())
@property
def large(self) -> bool:
""":class:`bool`: Whether the guild is a 'large' guild.
A large guild is defined as having more than ``large_threshold`` count
members, which for this library is set to the maximum of 250.
"""
if self._large is None:
try:
return self._member_count >= 250
except AttributeError:
return len(self._members) >= 250
return self._large
@property
def voice_channels(self) -> List[VoiceChannel]:
"""List[:class:`VoiceChannel`]: A list of voice channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, VoiceChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
@property
def stage_channels(self) -> List[StageChannel]:
"""List[:class:`StageChannel`]: A list of stage channels that belong to this guild.
.. versionadded:: 1.7
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, StageChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
@property
def forum_channels(self) -> List[ForumChannel]:
"""List[:class:`ForumChannel`]: A list of forum channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
.. versionadded:: 2.5
"""
r = [ch for ch in self._channels.values() if isinstance(ch, ForumChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
@property
def media_channels(self) -> List[MediaChannel]:
"""List[:class:`MediaChannel`]: A list of media channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
.. versionadded:: 2.10
"""
r = [ch for ch in self._channels.values() if isinstance(ch, MediaChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
@property
def me(self) -> Member:
""":class:`Member`: Similar to :attr:`Client.user` except an instance of :class:`Member`.
This is essentially used to get the member version of yourself.
"""
self_id = self._state.user.id
# The self member is *always* cached
return self.get_member(self_id) # type: ignore
@property
def voice_client(self) -> Optional[VoiceProtocol]:
"""Optional[:class:`VoiceProtocol`]: Returns the :class:`VoiceProtocol` associated with this guild, if any."""
return self._state._get_voice_client(self.id)
@property
def text_channels(self) -> List[TextChannel]:
"""List[:class:`TextChannel`]: A list of text channels that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, TextChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
@property
def categories(self) -> List[CategoryChannel]:
"""List[:class:`CategoryChannel`]: A list of categories that belong to this guild.
This is sorted by the position and are in UI order from top to bottom.
"""
r = [ch for ch in self._channels.values() if isinstance(ch, CategoryChannel)]
r.sort(key=lambda c: (c.position, c.id))
return r
def by_category(self) -> List[ByCategoryItem]:
"""Returns every :class:`CategoryChannel` and their associated channels.
These channels and categories are sorted in the official Discord UI order.
If the channels do not have a category, then the first element of the tuple is
``None``.
Returns
-------
List[Tuple[Optional[:class:`CategoryChannel`], List[:class:`abc.GuildChannel`]]]:
The categories and their associated channels.
"""
grouped: Dict[Optional[int], List[GuildChannel]] = {}
for channel in self._channels.values():
if isinstance(channel, CategoryChannel):
grouped.setdefault(channel.id, [])
continue
try:
grouped[channel.category_id].append(channel)
except KeyError:
grouped[channel.category_id] = [channel]
def key(t: ByCategoryItem) -> Tuple[Tuple[int, int], List[GuildChannel]]:
k, v = t
return ((k.position, k.id) if k else (-1, -1), v)
_get = self._channels.get
as_list: List[ByCategoryItem] = [(_get(k), v) for k, v in grouped.items()] # type: ignore
as_list.sort(key=key)
for _, channels in as_list:
channels.sort(key=lambda c: (c._sorting_bucket, c.position, c.id))
return as_list
def _resolve_channel(self, id: Optional[int], /) -> Optional[Union[GuildChannel, Thread]]:
if id is None:
return
return self._channels.get(id) or self._threads.get(id)
def get_channel_or_thread(self, channel_id: int, /) -> Optional[Union[Thread, GuildChannel]]:
"""Returns a channel or thread with the given ID.
.. versionadded:: 2.0
Parameters
----------
channel_id: :class:`int`
The ID to search for.
Returns
-------
Optional[Union[:class:`Thread`, :class:`.abc.GuildChannel`]]
The returned channel or thread or ``None`` if not found.
"""
return self._channels.get(channel_id) or self._threads.get(channel_id)
def get_channel(self, channel_id: int, /) -> Optional[GuildChannel]:
"""Returns a channel with the given ID.
.. note::
This does *not* search for threads.
Parameters
----------
channel_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`.abc.GuildChannel`]
The returned channel or ``None`` if not found.
"""
return self._channels.get(channel_id)
def get_thread(self, thread_id: int, /) -> Optional[Thread]:
"""Returns a thread with the given ID.
.. versionadded:: 2.0
Parameters
----------
thread_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Thread`]
The returned thread or ``None`` if not found.
"""
return self._threads.get(thread_id)
@property
def system_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Returns the guild's channel used for system messages.
If no channel is set, then this returns ``None``.
"""
channel_id = self._system_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
@property
def system_channel_flags(self) -> SystemChannelFlags:
""":class:`SystemChannelFlags`: Returns the guild's system channel settings."""
return SystemChannelFlags._from_value(self._system_channel_flags)
@property
def rules_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Returns the guild's channel used for the rules.
The guild must be a Community guild.
If no channel is set, then this returns ``None``.
.. versionadded:: 1.3
"""
channel_id = self._rules_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
@property
def public_updates_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Returns the guild's channel where admins and
moderators of the guild receive notices from Discord. The guild must be a
Community guild.
If no channel is set, then this returns ``None``.
.. versionadded:: 1.4
"""
channel_id = self._public_updates_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
@property
def safety_alerts_channel(self) -> Optional[TextChannel]:
"""Optional[:class:`TextChannel`]: Returns the guild's channel where admins and
moderators of the guild receive safety alerts from Discord. The guild must be a
Community guild.
If no channel is set, then this returns ``None``.
.. versionadded:: 2.9
"""
channel_id = self._safety_alerts_channel_id
return channel_id and self._channels.get(channel_id) # type: ignore
@property
def emoji_limit(self) -> int:
""":class:`int`: The maximum number of emoji slots this guild has.
Premium emojis (i.e. those associated with subscription roles) count towards a
separate limit of 25.
"""
more_emoji = 200 if "MORE_EMOJI" in self.features else 50
return max(more_emoji, self._PREMIUM_GUILD_LIMITS[self.premium_tier].emoji)
@property
def sticker_limit(self) -> int:
""":class:`int`: The maximum number of sticker slots this guild has.
.. versionadded:: 2.0
"""
more_stickers = 60 if "MORE_STICKERS" in self.features else 0
return max(more_stickers, self._PREMIUM_GUILD_LIMITS[self.premium_tier].stickers)
@property
def bitrate_limit(self) -> float:
""":class:`float`: The maximum bitrate for voice channels this guild can have.
For stage channels, the maximum bitrate is 64000.
"""
vip_guild = self._PREMIUM_GUILD_LIMITS[3].bitrate if "VIP_REGIONS" in self.features else 0
return max(vip_guild, self._PREMIUM_GUILD_LIMITS[self.premium_tier].bitrate)
@property
def filesize_limit(self) -> int:
""":class:`int`: The maximum number of bytes files can have when uploaded to this guild."""
return self._PREMIUM_GUILD_LIMITS[self.premium_tier].filesize
@property
def soundboard_limit(self) -> int:
""":class:`int`: The maximum number of soundboard slots this guild has.
.. versionadded:: 2.10
"""
more_soundboard = 96 if "MORE_SOUNDBOARD" in self.features else 0
return max(more_soundboard, self._PREMIUM_GUILD_LIMITS[self.premium_tier].sounds)
@property
def members(self) -> List[Member]:
"""List[:class:`Member`]: A list of members that belong to this guild."""
return list(self._members.values())
def get_member(self, user_id: int, /) -> Optional[Member]:
"""Returns a member with the given ID.
Parameters
----------
user_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Member`]
The member or ``None`` if not found.
"""
return self._members.get(user_id)
@property
def premium_subscribers(self) -> List[Member]:
"""List[:class:`Member`]: A list of members who have "boosted" this guild."""
return [member for member in self.members if member.premium_since is not None]
@property
def roles(self) -> List[Role]:
"""List[:class:`Role`]: Returns a :class:`list` of the guild's roles in hierarchy order.
The first element of this list will be the lowest role in the
hierarchy.
"""
return sorted(self._roles.values())
def get_role(self, role_id: int, /) -> Optional[Role]:
"""Returns a role with the given ID.
Parameters
----------
role_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Role`]
The role or ``None`` if not found.
"""
return self._roles.get(role_id)
@property