Completed
Push — main ( 95099e...48f12d )
by Yohann
16s queued 12s
created

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

Complexity

Conditions 1

Size

Total Lines 20
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 13
dl 0
loc 20
rs 9.75
c 0
b 0
f 0
cc 1
nop 3
1
# -*- coding: utf-8 -*-
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# MIT License
3
#
4
# Copyright (c) 2021 Pincer
5
#
6
# Permission is hereby granted, free of charge, to any person obtaining
7
# a copy of this software and associated documentation files
8
# (the "Software"), to deal in the Software without restriction,
9
# including without limitation the rights to use, copy, modify, merge,
10
# publish, distribute, sublicense, and/or sell copies of the Software,
11
# and to permit persons to whom the Software is furnished to do so,
12
# subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice shall be
15
# included in all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
from __future__ import annotations
25
26
from dataclasses import dataclass, InitVar, field
27
from enum import Enum, auto, IntEnum
28
from typing import Optional, List, TYPE_CHECKING
29
30
from pincer.objects.events.presence import PresenceUpdateEvent
31
from ..exceptions import UnavailableGuildError
32
from .channel import Channel
33
from .emoji import Emoji
34
from .guild_member import GuildMember
35
from .role import Role
36
from .stage import StageInstance
37
from .sticker import Sticker
38
from .voice_state import VoiceState
39
from .welcome_screen import WelcomeScreen
40
from ..utils import APIObject, APINullable, MISSING, Snowflake, Timestamp
41
42
if TYPE_CHECKING:
43
    from pincer import Client
44
    from pincer.core.http import HTTPClient
45
46
class PremiumTier(IntEnum):
47
    """
48
    :param NONE:
49
        guild has not unlocked any Server Boost perks
50
51
    :param TIER_1:
52
        guild has unlocked Server Boost level 1 perks
53
54
    :param TIER_2:
55
        guild has unlocked Server Boost level 2 perks
56
57
    :param TIER_3:
58
        guild has unlocked Server Boost level 3 perks
59
    """
60
    NONE = 0
61
    TIER_1 = 1
62
    TIER_2 = 2
63
    TIER_3 = 3
64
65
66
class GuildNSFWLevel(IntEnum):
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
67
    DEFAULT = 0
68
    EXPLICIT = 1
69
    SAFE = 2
70
    AGE_RESTRICTED = 3
71
72
73
class ExplicitContentFilterLevel(IntEnum):
74
    """
75
    :param DISABLED:
76
        media content will not be scanned
77
78
    :param MEMBERS_WITHOUT_ROLES:
79
        media content sent by members without roles will be scanned
80
81
    :param ALL_MEMBERS:
82
        media content sent by all members will be scanned
83
    """
84
    DISABLED = 0
85
    MEMBERS_WITHOUT_ROLES = 1
86
    ALL_MEMBERS = 2
87
88
89
class MFALevel(IntEnum):
90
    """
91
    :param NONE:
92
        guild has no MFA/2FA requirement for moderation actions
93
94
    :param ELEVATED:
95
        guild has a 2FA requirement for moderation actions
96
    """
97
    NONE = 0
98
    ELEVATED = 1
99
100
101
class VerificationLevel(IntEnum):
102
    """
103
    :param NONE:
104
        unrestricted
105
106
    :param LOW:
107
        must have verified email on account
108
109
    :param MEDIUM:
110
        must be registered on Discord for longer than 5 minutes
111
112
    :param HIGH:
113
        must be a member of the server for longer than 10 minutes
114
115
    :param VERY_HIGH:
116
        must have a verified phone number
117
    """
118
    NONE = 0
119
    LOW = 1
120
    MEDIUM = 2
121
    HIGH = 3
122
    VERY_HIGH = 4
123
124
125
class DefaultMessageNotificationLevel(IntEnum):
126
    """
127
    :param ALL_MESSAGES:
128
        members will receive notifications for all messages by default
129
130
    :param ONLY_MENTIONS:
131
        members will receive notifications only
132
        for messages that @mention them by default
133
    """
134
    ALL_MESSAGES = 0
135
    ONLY_MENTIONS = 1
136
137
138
class SystemChannelFlags(IntEnum):
139
    """
140
    :param SUPPRESS_JOIN_NOTIFICATIONS:
141
        Suppress member join notifications
142
143
    :param SUPPRESS_PREMIUM_SUBSCRIPTIONS:
144
        Suppress server boost notifications
145
146
    :param SUPPRESS_GUILD_REMINDER_NOTIFICATIONS:
147
        Suppress server setup tips
148
    """
149
    SUPPRESS_JOIN_NOTIFICATIONS = 1 << 0
150
    SUPPRESS_PREMIUM_SUBSCRIPTIONS = 1 << 1
151
    SUPPRESS_GUILD_REMINDER_NOTIFICATIONS = 1 << 2
152
153
154 View Code Duplication
class GuildFeature(Enum):
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
155
    """
156
    :param ANIMATED_ICON:
157
        guild has access to set an animated guild icon
158
159
    :param BANNER:
160
        guild has access to set a guild banner image
161
162
    :param COMMERCE:
163
        guild has access to use commerce features (i.e. create store channels)
164
165
    :param COMMUNITY:
166
        guild can enable welcome screen, Membership Screening, stage channels
167
        and discovery, and receives community updates
168
169
    :param DISCOVERABLE:
170
        guild is able to be discovered in the directory
171
172
    :param FEATURABLE:
173
        guild is able to be featured in the directory
174
175
    :param INVITE_SPLASH:
176
        guild has access to set an invite splash background
177
178
    :param MEMBER_VERIFICATION_GATE_ENABLED:
179
        guild has enabled Membership Screening
180
181
    :param NEWS:
182
        guild has access to create news channels
183
184
    :param PARTNERED:
185
        guild is partnered
186
187
    :param PREVIEW_ENABLED:
188
        guild can be previewed before joining via Membership Screening
189
        or the directory
190
191
    :param VANITY_URL:
192
        guild has access to set a vanity URL
193
194
    :param VERIFIED:
195
        guild is verified
196
197
    :param VIP_REGIONS:
198
        guild has access to set 384kbps bitrate in voice
199
        (previously VIP voice servers)
200
201
    :param WELCOME_SCREEN_ENABLED:
202
        guild has enabled the welcome screen
203
204
    :param TICKETED_EVENTS_ENABLED:
205
        guild has enabled ticketed events
206
207
    :param MONETIZATION_ENABLED:
208
        guild has enabled monetization
209
210
    :param MORE_STICKERS:
211
        guild has increased custom sticker slots
212
213
    :param THREE_DAY_THREAD_ARCHIVE:
214
        guild has access to the three day archive time for threads
215
216
    :param SEVEN_DAY_THREAD_ARCHIVE:
217
        guild has access to the seven day archive time for threads
218
219
    :param PRIVATE_THREADS:
220
        guild has access to create private threads
221
    """
222
    ANIMATED_ICON = auto()
223
    BANNER = auto()
224
    COMMERCE = auto()
225
    COMMUNITY = auto()
226
    DISCOVERABLE = auto()
227
    FEATURABLE = auto()
228
    INVITE_SPLASH = auto()
229
    MEMBER_VERIFICATION_GATE_ENABLED = auto()
230
    NEWS = auto()
231
    PARTNERED = auto()
232
    PREVIEW_ENABLED = auto()
233
    VANITY_URL = auto()
234
    VERIFIED = auto()
235
    VIP_REGIONS = auto()
236
    WELCOME_SCREEN_ENABLED = auto()
237
    TICKETED_EVENTS_ENABLED = auto()
238
    MONETIZATION_ENABLED = auto()
239
    MORE_STICKERS = auto()
240
    THREE_DAY_THREAD_ARCHIVE = auto()
241
    SEVEN_DAY_THREAD_ARCHIVE = auto()
242
    PRIVATE_THREADS = auto()
243
244
245
@dataclass
0 ignored issues
show
best-practice introduced by
Too many instance attributes (53/7)
Loading history...
246
class Guild(APIObject):
247
    """
248
    Represents a Discord guild/server in which your client resides.
249
250
    :param afk_channel_id:
251
        id of afk channel
252
253
    :param afk_timeout:
254
        afk timeout in seconds
255
256
    :param application_id:
257
        application id of the guild creator if it is bot-created
258
259
    :param banner:
260
        banner hash
261
262
    :param default_message_notifications:
263
        default message notifications level
264
265
    :param description:
266
        the description of a Community guild
267
268
    :param discovery_splash:
269
        discovery splash hash;
270
        only present for guilds with the "DISCOVERABLE" feature
271
272
    :param emojis:
273
        custom guild emojis
274
275
    :param explicit_content_filter:
276
        explicit content filter level
277
278
    :param features:
279
        enabled guild features
280
281
    :param id:
282
        guild id
283
284
    :param icon:
285
        icon hash
286
287
    :param mfa_level:
288
        required MFA level for the guild
289
290
    :param name:
291
        guild name (2-100 characters, excluding trailing and leading
292
        whitespace)
293
294
    :param nsfw_level:
295
        guild NSFW level
296
297
    :param owner_id:
298
        id of owner
299
300
    :param preferred_locale:
301
        the preferred locale of a Community guild;
302
        used in server discovery and notices from Discord;
303
        defaults to "en-US"
304
305
    :param premium_tier:
306
        premium tier (Server Boost level)
307
308
    :param public_updates_channel_id:
309
        the id of the channel where admins
310
        and moderators of Community guilds receive notices from Discord
311
312
    :param roles:
313
        roles in the guild
314
315
    :param rules_channel_id:
316
        the id of the channel where Community guilds can display rules
317
        and/or guidelines
318
319
    :param splash:
320
        splash hash
321
322
    :param system_channel_flags:
323
        system channel flags
324
325
    :param system_channel_id:
326
        the id of the channel where guild notices
327
        such as welcome messages and boost events are posted
328
329
    :param vanity_url_code:
330
        the vanity url code for the guild
331
332
    :param verification_level:
333
        verification level required for the guild
334
335
    :param approximate_member_count:
336
        approximate number of members in this guild, returned from the
337
        `GET /guilds/<id>` endpoint when with_counts is true
338
339
    :param approximate_presence_count:
340
        approximate number of non-offline members in this guild,
341
        returned from the `GET /guilds/<id>`
342
        endpoint when with_counts is true
343
344
    :param channels:
345
        channels in the guild
346
347
    :param icon_hash:
348
        icon hash, returned when in the template object
349
350
    :param joined_at:
351
        when this guild was joined at
352
353
    :param large:
354
        true if this is considered a large guild
355
356
    :param max_members:
357
        the maximum number of members for the guild
358
359
    :param max_presences:
360
        the maximum number of presences for the guild
361
        (null is always returned, apart from the largest of guilds)
362
363
    :param max_video_channel_users:
364
        the maximum amount of users in a video channel
365
366
    :param members:
367
        users in the guild
368
369
    :param member_count:
370
        total number of members in this guild
371
372
    :param nsfw:
373
        boolean if the server is NSFW
374
375
    :param owner:
376
        true if the user is the owner of the guild
377
378
    :param permissions:
379
        total permissions for the user in the guild
380
        (excludes overwrites)
381
382
    :param premium_subscription_count:
383
        the number of boosts this guild currently has
384
385
    :param presences:
386
        presences of the members in the guild,
387
        will only include non-offline members if the size is greater
388
        than large threshold
389
390
    :param stage_instances:
391
        Stage instances in the guild
392
393
    :param stickers:
394
        custom guild stickers
395
396
    :param region:
397
        voice region id for the guild (deprecated)
398
399
    :param threads:
400
        all active threads in the guild that current user
401
        has permission to view
402
403
    :param unavailable:
404
        true if this guild is unavailable due to an outage
405
406
    :param voice_states:
407
        states of members currently in voice channels;
408
        lacks the guild_id key
409
410
    :param widget_enabled:
411
        true if the server widget is enabled
412
413
    :param widget_channel_id:
414
        the channel id that the widget will generate an invite to,
415
        or null if set to no invite
416
417
    :param welcome_screen:
418
        the welcome screen of a Community guild, shown to new members,
419
        returned in an Invite's guild object
420
    """
421
422
    _client: Client
0 ignored issues
show
introduced by
The variable Client does not seem to be defined in case TYPE_CHECKING on line 42 is False. Are you sure this can never be the case?
Loading history...
423
    _http: HTTPClient
0 ignored issues
show
introduced by
The variable HTTPClient does not seem to be defined in case TYPE_CHECKING on line 42 is False. Are you sure this can never be the case?
Loading history...
424
425
    afk_channel_id: Optional[Snowflake]
426
    afk_timeout: int
427
    application_id: Optional[Snowflake]
428
    banner: Optional[str]
429
    default_message_notifications: DefaultMessageNotificationLevel
430
    description: Optional[str]
431
    discovery_splash: Optional[str]
432
    emojis: List[Emoji]
433
    explicit_content_filter: ExplicitContentFilterLevel
434
    features: List[GuildFeature]
435
    id: Snowflake
436
    icon: Optional[str]
437
    mfa_level: MFALevel
438
    name: str
439
    nsfw_level: GuildNSFWLevel
440
    owner_id: Snowflake
441
    preferred_locale: str
442
    premium_tier: InitVar[PremiumTier]
443
    public_updates_channel_id: Optional[Snowflake]
444
    roles: List[Role]
445
    rules_channel_id: Optional[Snowflake]
446
    splash: Optional[str]
447
    system_channel_flags: SystemChannelFlags
448
    system_channel_id: Optional[Snowflake]
449
    vanity_url_code: Optional[str]
450
    verification_level: VerificationLevel
451
452
    approximate_member_count: APINullable[int] = MISSING
453
    approximate_presence_count: APINullable[int] = MISSING
454
    channels: APINullable[List[Channel]] = field(default_factory=list)
455
    icon_hash: APINullable[Optional[str]] = MISSING
456
    joined_at: APINullable[Timestamp] = MISSING
457
    large: APINullable[bool] = MISSING
458
    max_members: APINullable[int] = MISSING
459
    max_presences: APINullable[Optional[int]] = MISSING
460
    max_video_channel_users: APINullable[int] = MISSING
461
    members: APINullable[List[GuildMember]] = MISSING
462
    member_count: APINullable[bool] = MISSING
463
    nsfw: APINullable[bool] = MISSING 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
464
    # Note: This is missing from discord's docs but in the api
465
    owner: APINullable[bool] = MISSING
466
    permissions: APINullable[str] = MISSING
467
    premium_subscription_count: APINullable[int] = MISSING
468
    presences: APINullable[List[PresenceUpdateEvent]] = MISSING
469
    stage_instances: APINullable[List[StageInstance]] = MISSING
470
    stickers: APINullable[List[Sticker]] = MISSING
471
    region: APINullable[Optional[str]] = MISSING
472
    threads: APINullable[List[Channel]] = MISSING
473
    # Guilds are considered available unless otherwise specified
474
    unavailable: APINullable[bool] = False
475
    voice_states: APINullable[List[VoiceState]] = MISSING
476
    widget_enabled: APINullable[bool] = MISSING
477
    widget_channel_id: APINullable[Optional[Snowflake]] = MISSING
478
    welcome_screen: APINullable[WelcomeScreen] = MISSING
479
480
481
    @classmethod
482
    async def from_id(cls, client: Client, id: int) -> Guild:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
Bug Best Practice introduced by
This seems to re-define the built-in id.

It is generally discouraged to redefine built-ins as this makes code very hard to read.

Loading history...
483
        data = await client.http.get(f"/guilds/{id}")
484
        channel_data = await client.http.get(f"/guilds/{id}/channels")
485
486
        channels: List[Channel] = [
487
            Channel.from_dict(i | {"_client": client, "_http": client.http})
488
            for i in (channel_data or [])
489
        ]
490
491
        data.update(
492
            {
493
                "_client": client, 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
494
                "_http": client.http, 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
495
                "channels": channels
496
            }
497
        )
498
499
        # Once below is fixed. Change this to Guild.from_dict
500
        return Guild(**data) 
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
501
502
    # TODO: Fix this function. 
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
Coding Style introduced by
Trailing whitespace
Loading history...
503
    # It causes a RecursionError because ot keeps calling itself
504
    @classmethod
505
    def from_dict(cls, data) -> Guild:
506
        """
507
        Instantiate a new guild from a dictionary.
508
509
        Also handles it if the guild isn't available.
510
511
        :raises UnavailableGuildError:
512
            Exception gets raised when guild is unavailable.
513
        """
514
        if data.get("unavailable", False):
515
            raise UnavailableGuildError(
516
                f"Guild \"{data['id']}\" is unavailable due"
517
                " to a discord outage."
518
            )
519
520
        return cls.from_dict(data)
521