Completed
Push — main ( 3a3ea0...93fa25 )
by Yohann
23s queued 12s
created

pincer.objects.guild.guild.Guild.from_dict()   A

Complexity

Conditions 2

Size

Total Lines 17
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 17
rs 10
c 0
b 0
f 0
cc 2
nop 2
1
# Copyright Pincer 2021-Present
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# Full MIT License can be found in `LICENSE` at the project root.
3
4
from __future__ import annotations
5
6
from dataclasses import dataclass, field
7
from enum import Enum, auto, IntEnum
8
from typing import Optional, List, overload, TYPE_CHECKING
9
10
from .member import GuildMember
11
from ..events.presence import PresenceUpdateEvent
12
from ..guild.channel import Channel
13
from ..guild.role import Role
14
from ..guild.stage import StageInstance
15
from ..guild.welcome_screen import WelcomeScreen
16
from ..message.emoji import Emoji
17
from ..message.sticker import Sticker
18
from ..user.voice_state import VoiceState
19
from ...exceptions import UnavailableGuildError
20
from ...utils.api_object import APIObject
21
from ...utils.types import MISSING
22
23
if TYPE_CHECKING:
24
    from ... import Client
25
    from ...core.http import HTTPClient
26
    from ...utils import APINullable, Snowflake, Timestamp
27
28
29
class PremiumTier(IntEnum):
30
    """
31
    :param NONE:
32
        guild has not unlocked any Server Boost perks
33
34
    :param TIER_1:
35
        guild has unlocked Server Boost level 1 perks
36
37
    :param TIER_2:
38
        guild has unlocked Server Boost level 2 perks
39
40
    :param TIER_3:
41
        guild has unlocked Server Boost level 3 perks
42
    """
43
    NONE = 0
44
    TIER_1 = 1
45
    TIER_2 = 2
46
    TIER_3 = 3
47
48
49
class GuildNSFWLevel(IntEnum):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
50
    DEFAULT = 0
51
    EXPLICIT = 1
52
    SAFE = 2
53
    AGE_RESTRICTED = 3
54
55
56
class ExplicitContentFilterLevel(IntEnum):
57
    """
58
    :param DISABLED:
59
        media content will not be scanned
60
61
    :param MEMBERS_WITHOUT_ROLES:
62
        media content sent by members without roles will be scanned
63
64
    :param ALL_MEMBERS:
65
        media content sent by all members will be scanned
66
    """
67
    DISABLED = 0
68
    MEMBERS_WITHOUT_ROLES = 1
69
    ALL_MEMBERS = 2
70
71
72
class MFALevel(IntEnum):
73
    """
74
    :param NONE:
75
        guild has no MFA/2FA requirement for moderation actions
76
77
    :param ELEVATED:
78
        guild has a 2FA requirement for moderation actions
79
    """
80
    NONE = 0
81
    ELEVATED = 1
82
83
84
class VerificationLevel(IntEnum):
85
    """
86
    :param NONE:
87
        unrestricted
88
89
    :param LOW:
90
        must have verified email on account
91
92
    :param MEDIUM:
93
        must be registered on Discord for longer than 5 minutes
94
95
    :param HIGH:
96
        must be a member of the server for longer than 10 minutes
97
98
    :param VERY_HIGH:
99
        must have a verified phone number
100
    """
101
    NONE = 0
102
    LOW = 1
103
    MEDIUM = 2
104
    HIGH = 3
105
    VERY_HIGH = 4
106
107
108
class DefaultMessageNotificationLevel(IntEnum):
109
    """
110
    :param ALL_MESSAGES:
111
        members will receive notifications for all messages by default
112
113
    :param ONLY_MENTIONS:
114
        members will receive notifications only
115
        for messages that @mention them by default
116
    """
117
    ALL_MESSAGES = 0
118
    ONLY_MENTIONS = 1
119
120
121
class SystemChannelFlags(IntEnum):
122
    """
123
    :param SUPPRESS_JOIN_NOTIFICATIONS:
124
        Suppress member join notifications
125
126
    :param SUPPRESS_PREMIUM_SUBSCRIPTIONS:
127
        Suppress server boost notifications
128
129
    :param SUPPRESS_GUILD_REMINDER_NOTIFICATIONS:
130
        Suppress server setup tips
131
    """
132
    SUPPRESS_JOIN_NOTIFICATIONS = 1 << 0
133
    SUPPRESS_PREMIUM_SUBSCRIPTIONS = 1 << 1
134
    SUPPRESS_GUILD_REMINDER_NOTIFICATIONS = 1 << 2
135
136
137 View Code Duplication
class GuildFeature(Enum):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
138
    """
139
    :param ANIMATED_ICON:
140
        guild has access to set an animated guild icon
141
142
    :param BANNER:
143
        guild has access to set a guild banner image
144
145
    :param COMMERCE:
146
        guild has access to use commerce features (i.e. create store channels)
147
148
    :param COMMUNITY:
149
        guild can enable welcome screen, Membership Screening, stage channels
150
        and discovery, and receives community updates
151
152
    :param DISCOVERABLE:
153
        guild is able to be discovered in the directory
154
155
    :param FEATURABLE:
156
        guild is able to be featured in the directory
157
158
    :param INVITE_SPLASH:
159
        guild has access to set an invite splash background
160
161
    :param MEMBER_VERIFICATION_GATE_ENABLED:
162
        guild has enabled Membership Screening
163
164
    :param NEWS:
165
        guild has access to create news channels
166
167
    :param PARTNERED:
168
        guild is partnered
169
170
    :param PREVIEW_ENABLED:
171
        guild can be previewed before joining via Membership Screening
172
        or the directory
173
174
    :param VANITY_URL:
175
        guild has access to set a vanity URL
176
177
    :param VERIFIED:
178
        guild is verified
179
180
    :param VIP_REGIONS:
181
        guild has access to set 384kbps bitrate in voice
182
        (previously VIP voice servers)
183
184
    :param WELCOME_SCREEN_ENABLED:
185
        guild has enabled the welcome screen
186
187
    :param TICKETED_EVENTS_ENABLED:
188
        guild has enabled ticketed events
189
190
    :param MONETIZATION_ENABLED:
191
        guild has enabled monetization
192
193
    :param MORE_STICKERS:
194
        guild has increased custom sticker slots
195
196
    :param THREE_DAY_THREAD_ARCHIVE:
197
        guild has access to the three day archive time for threads
198
199
    :param SEVEN_DAY_THREAD_ARCHIVE:
200
        guild has access to the seven day archive time for threads
201
202
    :param PRIVATE_THREADS:
203
        guild has access to create private threads
204
    """
205
    ANIMATED_ICON = auto()
206
    BANNER = auto()
207
    COMMERCE = auto()
208
    COMMUNITY = auto()
209
    DISCOVERABLE = auto()
210
    FEATURABLE = auto()
211
    INVITE_SPLASH = auto()
212
    MEMBER_VERIFICATION_GATE_ENABLED = auto()
213
    NEWS = auto()
214
    PARTNERED = auto()
215
    PREVIEW_ENABLED = auto()
216
    VANITY_URL = auto()
217
    VERIFIED = auto()
218
    VIP_REGIONS = auto()
219
    WELCOME_SCREEN_ENABLED = auto()
220
    TICKETED_EVENTS_ENABLED = auto()
221
    MONETIZATION_ENABLED = auto()
222
    MORE_STICKERS = auto()
223
    THREE_DAY_THREAD_ARCHIVE = auto()
224
    SEVEN_DAY_THREAD_ARCHIVE = auto()
225
    PRIVATE_THREADS = auto()
226
227
228
@dataclass
0 ignored issues
show
best-practice introduced by
Too many instance attributes (54/7)
Loading history...
229
class Guild(APIObject):
230
    """
231
    Represents a Discord guild/server in which your client resides.
232
233
    :param _client:
234
        reference to the Client
235
236
    :param _http:
237
        reference to the HTTPClient
238
239
    :param afk_channel_id:
240
        id of afk channel
241
242
    :param afk_timeout:
243
        afk timeout in seconds
244
245
    :param application_id:
246
        application id of the guild creator if it is bot-created
247
248
    :param banner:
249
        banner hash
250
251
    :param default_message_notifications:
252
        default message notifications level
253
254
    :param description:
255
        the description of a Community guild
256
257
    :param discovery_splash:
258
        discovery splash hash;
259
        only present for guilds with the "DISCOVERABLE" feature
260
261
    :param emojis:
262
        custom guild emojis
263
264
    :param explicit_content_filter:
265
        explicit content filter level
266
267
    :param features:
268
        enabled guild features
269
270
    :param id:
271
        guild id
272
273
    :param icon:
274
        icon hash
275
276
    :param mfa_level:
277
        required MFA level for the guild
278
279
    :param name:
280
        guild name (2-100 characters, excluding trailing and leading
281
        whitespace)
282
283
    :param nsfw_level:
284
        guild NSFW level
285
286
    :param owner_id:
287
        id of owner
288
289
    :param preferred_locale:
290
        the preferred locale of a Community guild;
291
        used in server discovery and notices from Discord;
292
        defaults to "en-US"
293
294
    :param premium_tier:
295
        premium tier (Server Boost level)
296
297
    :param public_updates_channel_id:
298
        the id of the channel where admins
299
        and moderators of Community guilds receive notices from Discord
300
301
    :param roles:
302
        roles in the guild
303
304
    :param rules_channel_id:
305
        the id of the channel where Community guilds can display rules
306
        and/or guidelines
307
308
    :param splash:
309
        splash hash
310
311
    :param system_channel_flags:
312
        system channel flags
313
314
    :param system_channel_id:
315
        the id of the channel where guild notices
316
        such as welcome messages and boost events are posted
317
318
    :param vanity_url_code:
319
        the vanity url code for the guild
320
321
    :param verification_level:
322
        verification level required for the guild
323
324
    :param approximate_member_count:
325
        approximate number of members in this guild, returned from the
326
        `GET /guilds/<id>` endpoint when with_counts is true
327
328
    :param approximate_presence_count:
329
        approximate number of non-offline members in this guild,
330
        returned from the `GET /guilds/<id>`
331
        endpoint when with_counts is true
332
333
    :param channels:
334
        channels in the guild
335
336
    :param icon_hash:
337
        icon hash, returned when in the template object
338
339
    :param joined_at:
340
        when this guild was joined at
341
342
    :param large:
343
        true if this is considered a large guild
344
345
    :param max_members:
346
        the maximum number of members for the guild
347
348
    :param max_presences:
349
        the maximum number of presences for the guild
350
        (null is always returned, apart from the largest of guilds)
351
352
    :param max_video_channel_users:
353
        the maximum amount of users in a video channel
354
355
    :param members:
356
        users in the guild
357
358
    :param member_count:
359
        total number of members in this guild
360
361
    :param nsfw:
362
        boolean if the server is NSFW
363
364
    :param owner:
365
        true if the user is the owner of the guild
366
367
    :param permissions:
368
        total permissions for the user in the guild
369
        (excludes overwrites)
370
371
    :param premium_subscription_count:
372
        the number of boosts this guild currently has
373
374
    :param presences:
375
        presences of the members in the guild,
376
        will only include non-offline members if the size is greater
377
        than large threshold
378
379
    :param stage_instances:
380
        Stage instances in the guild
381
382
    :param stickers:
383
        custom guild stickers
384
385
    :param region:
386
        voice region id for the guild (deprecated)
387
388
    :param threads:
389
        all active threads in the guild that current user
390
        has permission to view
391
392
    :param unavailable:
393
        true if this guild is unavailable due to an outage
394
395
    :param voice_states:
396
        states of members currently in voice channels;
397
        lacks the guild_id key
398
399
    :param widget_enabled:
400
        true if the server widget is enabled
401
402
    :param widget_channel_id:
403
        the channel id that the widget will generate an invite to,
404
        or null if set to no invite
405
406
    :param welcome_screen:
407
        the welcome screen of a Community guild, shown to new members,
408
        returned in an Invite's guild object
409
    """
410
411
    _client: Client
412
    _http: HTTPClient
413
414
    afk_channel_id: Optional[Snowflake]
415
    afk_timeout: int
416
    application_id: Optional[Snowflake]
417
    banner: Optional[str]
418
    default_message_notifications: DefaultMessageNotificationLevel
419
    description: Optional[str]
420
    discovery_splash: Optional[str]
421
    emojis: List[Emoji]
422
    explicit_content_filter: ExplicitContentFilterLevel
423
    features: List[GuildFeature]
424
    id: Snowflake
425
    icon: Optional[str]
426
    mfa_level: MFALevel
427
    name: str
428
    nsfw_level: GuildNSFWLevel
429
    owner_id: Snowflake
430
    preferred_locale: str
431
    premium_tier: PremiumTier
432
    public_updates_channel_id: Optional[Snowflake]
433
    roles: List[Role]
434
    rules_channel_id: Optional[Snowflake]
435
    splash: Optional[str]
436
    system_channel_flags: SystemChannelFlags
437
    system_channel_id: Optional[Snowflake]
438
    vanity_url_code: Optional[str]
439
    verification_level: VerificationLevel
440
441
    approximate_member_count: APINullable[int] = MISSING
442
    approximate_presence_count: APINullable[int] = MISSING
443
    channels: APINullable[List[Channel]] = field(default_factory=list)
444
    # TODO: Add type when type is known
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
445
    hub_type: APINullable[...] = MISSING
446
    icon_hash: APINullable[Optional[str]] = MISSING
447
    joined_at: APINullable[Timestamp] = MISSING
448
    large: APINullable[bool] = MISSING
449
    max_members: APINullable[int] = MISSING
450
    max_presences: APINullable[Optional[int]] = MISSING
451
    max_video_channel_users: APINullable[int] = MISSING
452
    members: APINullable[List[GuildMember]] = MISSING
453
    member_count: APINullable[bool] = MISSING
454
    nsfw: APINullable[bool] = MISSING
455
    # Note: This is missing from discord's docs but in the api
456
    owner: APINullable[bool] = MISSING
457
    permissions: APINullable[str] = MISSING
458
    premium_subscription_count: APINullable[int] = MISSING
459
    presences: APINullable[List[PresenceUpdateEvent]] = MISSING
460
    stage_instances: APINullable[List[StageInstance]] = MISSING
461
    stickers: APINullable[List[Sticker]] = MISSING
462
    region: APINullable[Optional[str]] = MISSING
463
    threads: APINullable[List[Channel]] = MISSING
464
    # Guilds are considered available unless otherwise specified
465
    unavailable: APINullable[bool] = False
466
    voice_states: APINullable[List[VoiceState]] = MISSING
467
    widget_enabled: APINullable[bool] = MISSING
468
    widget_channel_id: APINullable[Optional[Snowflake]] = MISSING
469
    welcome_screen: APINullable[WelcomeScreen] = MISSING
470
471
    @classmethod
472
    async def from_id(cls, client: Client, _id: int) -> Guild:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
473
        data = await client.http.get(f"/guilds/{_id}")
474
        channel_data = await client.http.get(f"/guilds/{_id}/channels")
475
476
        channels: List[Channel] = [
477
            Channel.from_dict({**i, "_client": client, "_http": client.http})
478
            for i in (channel_data or [])
479
        ]
480
481
        data.update(
482
            {
483
                "_client": client,
484
                "_http": client.http,
485
                "channels": channels
486
            }
487
        )
488
489
        # Once below is fixed. Change this to Guild.from_dict
490
        return Guild(**data)
491
492
    async def get_member(self, _id: int):
493
        """
494
        Fetches a GuildMember from its identifier
495
496
        :param _id:
497
            The id of the guild member which should be fetched from the Discord
498
            gateway.
499
500
        :returns:
501
            A GuildMember objects.
502
503
        """
504
        return await GuildMember.from_id(self._client, self.id, _id)
505
506
    @overload
507
    async def modify_member(
508
            self, *,
509
            _id: int,
510
            nick: Optional[str] = None,
511
            roles: Optional[List[Snowflake]] = None,
512
            mute: Optional[bool] = None,
513
            deaf: Optional[bool] = None,
514
            channel_id: Optional[Snowflake] = None
515
    ) -> GuildMember:
516
        """
517
        Modifies a member in the guild from its identifier and based on the
518
        keyword arguments provided.
519
520
        :returns:
521
            The GuildMember that has been modified.
522
        """
523
        ...
524
525
    async def modify_member(self, _id: int, **kwargs) -> GuildMember:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
526
        data = await self._http.patch(f"guilds/{self.id}/members/{_id}", kwargs)
527
        return GuildMember.from_dict(
528
            {**data, "_client": self._client, "_http": self._http}
529
        )
530
531
    @classmethod
532
    def from_dict(cls, data) -> Guild:
533
        """
534
        Instantiate a new guild from a dictionary.
535
536
        Also handles it if the guild isn't available.
537
538
        :raises UnavailableGuildError:
539
            Exception gets raised when guild is unavailable.
540
        """
541
        if data.get("unavailable", False):
542
            raise UnavailableGuildError(
543
                f"Guild \"{data['id']}\" is unavailable due"
544
                " to a discord outage."
545
            )
546
547
        return super().from_dict(data)
548