Passed
Pull Request — main (#225)
by Yohann
01:48
created

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

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nop 1
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 IntEnum
8
from typing import overload, TYPE_CHECKING
9
10
from .channel import Channel
0 ignored issues
show
introduced by
Cannot import 'channel' due to syntax error 'invalid syntax (<unknown>, line 251)'
Loading history...
11
from .member import GuildMember
12
from ...exceptions import UnavailableGuildError
13
from ...utils.api_object import APIObject
0 ignored issues
show
introduced by
Cannot import 'utils.api_object' due to syntax error 'invalid syntax (<unknown>, line 80)'
Loading history...
Bug introduced by
The name api_object does not seem to exist in module pincer.utils.
Loading history...
14
from ...utils.conversion import construct_client_dict
15
from ...utils.types import MISSING
16
17
if TYPE_CHECKING:
18
    from typing import Any, Dict, List, Optional, Union
19
20
    from .features import GuildFeature
21
    from .role import Role
22
    from .stage import StageInstance
23
    from .welcome_screen import WelcomeScreen
24
    from ..events.presence import PresenceUpdateEvent
25
    from ..message.emoji import Emoji
26
    from ..message.sticker import Sticker
27
    from ..user.voice_state import VoiceState
28
    from ...client import Client
0 ignored issues
show
introduced by
Cannot import 'client' due to syntax error 'invalid syntax (<unknown>, line 351)'
Loading history...
29
    from ...utils.timestamp import Timestamp
0 ignored issues
show
Bug introduced by
The name timestamp does not seem to exist in module pincer.utils.
Loading history...
introduced by
Cannot import 'utils.timestamp' due to syntax error 'invalid syntax (<unknown>, line 103)'
Loading history...
30
    from ...utils.types import APINullable
31
    from ...utils.snowflake import Snowflake
32
33
34
class PremiumTier(IntEnum):
35
    """Represents the boost tier of a guild.
36
37
    Attributes
38
    ----------
39
    NONE:
40
        Guild has not unlocked any Server Boost perks.
41
    TIER_1:
42
        Guild has unlocked Server Boost level 1 perks.
43
    TIER_2:
44
        Guild has unlocked Server Boost level 2 perks.
45
    TIER_3:
46
        Guild has unlocked Server Boost level 3 perks.
47
    """
48
49
    NONE = 0
50
    TIER_1 = 1
51
    TIER_2 = 2
52
    TIER_3 = 3
53
54
55
class GuildNSFWLevel(IntEnum):
56
    """Represents the NSFW level of a guild.
57
58
    Attributes
59
    ----------
60
    DEFAULT:
61
        Default NSFW level.
62
    EXPLICIT:
63
        Explicit NSFW level.
64
    SAFE:
65
        SAFE NSFW level.
66
    AGE_RESTRICTED:
67
        Age restricted NSFW level.
68
    """
69
70
    DEFAULT = 0
71
    EXPLICIT = 1
72
    SAFE = 2
73
    AGE_RESTRICTED = 3
74
75
76
class ExplicitContentFilterLevel(IntEnum):
77
    """Represents the filter content level of a guild.
78
79
    Attributes
80
    ----------
81
    DISABLED:
82
        Media content will not be scanned.
83
    MEMBERS_WITHOUT_ROLES:
84
        Media content sent by members without roles will be scanned.
85
    ALL_MEMBERS:
86
        Media content sent by all members will be scanned.
87
    """
88
89
    DISABLED = 0
90
    MEMBERS_WITHOUT_ROLES = 1
91
    ALL_MEMBERS = 2
92
93
94
class MFALevel(IntEnum):
95
    """Represents the multi factor authentication level of a guild.
96
97
    Attributes
98
    ----------
99
    NONE:
100
        Guild has no MFA/2FA requirement for moderation actions.
101
    ELEVATED:
102
        Guild has a 2FA requirement for moderation actions
103
    """
104
105
    NONE = 0
106
    ELEVATED = 1
107
108
109
class VerificationLevel(IntEnum):
110
    """Represents the verification level of a guild.
111
112
    Attributes
113
    ----------
114
    NONE:
115
        Unrestricted.
116
    LOW:
117
        Must have verified email on account.
118
    MEDIUM:
119
        Must be registered on Discord for longer than 5 minutes.
120
    HIGH:
121
        Must be a member of the server for longer than 10 minutes.
122
    VERY_HIGH:
123
        Must have a verified phone number.
124
    """
125
126
    NONE = 0
127
    LOW = 1
128
    MEDIUM = 2
129
    HIGH = 3
130
    VERY_HIGH = 4
131
132
133
class DefaultMessageNotificationLevel(IntEnum):
134
    """Represents the default message notification level of a guild.
135
136
    Attributes
137
    ----------
138
    ALL_MESSAGES:
139
        Members will receive notifications for all messages by default.
140
    ONLY_MENTIONS:
141
        Members will receive notifications only for messages that @mention them by default.
142
    """
143
144
    # noqa: E501
145
    ALL_MESSAGES = 0
146
    ONLY_MENTIONS = 1
147
148
149
class SystemChannelFlags(IntEnum):
150
    """Represents the system channel flags of a guild.
151
152
    Attributes
153
    ----------
154
    SUPPRESS_JOIN_NOTIFICATIONS:
155
        Suppress member join notifications.
156
    SUPPRESS_PREMIUM_SUBSCRIPTIONS:
157
        Suppress server boost notifications.
158
    SUPPRESS_GUILD_REMINDER_NOTIFICATIONS:
159
        Suppress server setup tips.
160
    SUPPRESS_JOIN_NOTIFICATION_REPLIES:
161
        Hide member join sticker reply buttons
162
    """
163
164
    SUPPRESS_JOIN_NOTIFICATIONS = 1 << 0
165
    SUPPRESS_PREMIUM_SUBSCRIPTIONS = 1 << 1
166
    SUPPRESS_GUILD_REMINDER_NOTIFICATIONS = 1 << 2
167
    SUPPRESS_JOIN_NOTIFICATION_REPLIES = 1 << 3
168
169
@dataclass
0 ignored issues
show
best-practice introduced by
Too many instance attributes (10/7)
Loading history...
170
class GuildPreview(APIObject):
171
    """Represents a guild preview.
172
173
    Attributes
174
    ----------
175
    id: :class:`Snowflake`
176
        The guild ID.
177
    name: :class:`str`
178
        The guild name.
179
    icon: :class:`str`
180
        The guild icon hash.
181
    splash: :class:`str`
182
        The guild splash hash.
183
    discovery_splash: :class:`str`
184
        The guild discovery splash hash.
185
    emojis: :class:`List[Emoji]`
186
        The guild emojis.
187
    features: :class:`List[GuildFeature]`
188
        The guild features.
189
    approximate_member_count: :class:`int`
190
        The approximate member count.
191
    approximate_presence_count: :class:`int`
192
        The approximate number of online members in this guild
193
    description: :class:`str`
194
        The guild description.
195
    """
196
    id: Snowflake
197
    name: str
198
    emojis: List[Emoji]
199
    features: List[GuildFeature]
200
    approximate_member_count: int
201
    approximate_presence_count: int
202
203
    icon: APINullable[str] = MISSING
204
    splash: APINullable[str] = MISSING
205
    discovery_splash: APINullable[str] = MISSING
206
    description: APINullable[str] = MISSING
207
208
@dataclass
0 ignored issues
show
best-practice introduced by
Too many instance attributes (59/7)
Loading history...
209
class Guild(APIObject):
210
    """Represents a Discord guild/server in which your client resides.
211
212
    Attributes
213
    ----------
214
    afk_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
215
        Id of afk channel
216
    afk_timeout: :class:`int`
217
        Afk timeout in seconds
218
    application_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
219
        Application id of the guild creator if it is bot-created
220
    banner: Optional[:class:`str`]
221
        Banner hash
222
    default_message_notifications: :class:`~pincer.objects.guild.guild.DefaultMessageNotificationLevel`
0 ignored issues
show
Coding Style introduced by
This line is too long as per the coding-style (103/100).

This check looks for lines that are too long. You can specify the maximum line length.

Loading history...
223
        Default message notifications level
224
    description: Optional[:class:`str`]
225
        The description of a Community guild
226
    discovery_splash: Optional[:class:`str`]
227
        Discovery splash hash;
228
        only present for guilds with the "DISCOVERABLE" feature
229
    emojis: List[:class:`~pincer.objects.message.emoji.Emoji`]
230
        Custom guild emojis
231
    explicit_content_filter: :class:`~pincer.objects.guild.guild.ExplicitContentFilterLevel`
232
        Explicit content filter level
233
    features: List[:class:`~pincer.objects.guild.features.GuildFeature`]
234
        Enabled guild features
235
    id: :class:`~pincer.utils.snowflake.Snowflake`
236
        Guild id
237
    icon: Optional[:class:`str`]
238
        Icon hash
239
    mfa_level: :class:`~pincer.objects.guild.guild.MFALevel`
240
        Required MFA level for the guild
241
    name: :class:`str`
242
        Guild name (2-100 characters, excluding trailing and leading
243
        whitespace)
244
    nsfw_level: :class:`~pincer.objects.guild.guild.NSFWLevel`
245
        Guild NSFW level
246
    owner_id: :class:`~pincer.utils.snowflake.Snowflake`
247
        Id of owner
248
    preferred_locale: :class:`str`
249
        The preferred locale of a Community guild;
250
        used in server discovery and notices from Discord;
251
        defaults to "en-US"
252
    premium_tier: :class:`~pincer.objects.guild.guild.PremiumTier`
253
        Premium tier (Server Boost level)
254
    public_updates_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
255
        The id of the channel where admins
256
        and moderators of Community guilds receive notices from Discord
257
    roles: List[:class:`~pincer.objects.guild.role.Role`]
258
        Roles in the guild
259
    rules_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
260
        The id of the channel where Community guilds can display rules
261
        and/or guidelines
262
    splash: Optional[:class:`str`]
263
        Splash hash
264
    system_channel_flags: :class:`~pincer.objects.guild.guild.SystemChannelFlags`
265
        System channel flags
266
    system_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
267
        The id of the channel where guild notices
268
        such as welcome messages and boost events are posted
269
    vanity_url_code: Optional[:class:`str`]
270
        The vanity url code for the guild
271
    verification_level: :class:`~pincer.objects.guild.guild.VerificationLevel`
272
        Verification level required for the guild
273
    approximate_member_count: APINullable[:class:`int`]
274
        Approximate number of members in this guild, returned from the
275
        `GET /guilds/<id>` endpoint when with_counts is true
276
    approximate_presence_count: APINullable[:class:`int`]
277
        Approximate number of non-offline members in this guild,
278
        returned from the `GET /guilds/<id>`
279
        endpoint when with_counts is true
280
    channels: APINullable[List[:class:`~pincer.objects.guild.channel.Channel`]]
281
        Channels in the guild
282
    icon_hash: APINullable[Optional[:class:`str`]]
283
        Icon hash, returned when in the template object
284
    joined_at: APINullable[:class:`~pincer.utils.timestamp.Timestamp`]
285
        When this guild was joined at
286
    large: APINullable[:class:`bool`]
287
        True if this is considered a large guild
288
    max_members: APINullable[:class:`int`]
289
        The maximum number of members for the guild
290
    max_presences: APINullable[Optional[:class:`int`]]
291
        The maximum number of presences for the guild
292
        (null is always returned, apart from the largest of guilds)
293
    max_video_channel_users: APINullable[:class:`int`]
294
        The maximum amount of users in a video channel
295
    members: APINullable[List[:class:`~pincer.objects.guild.member.GuildMember`]]
296
        Users in the guild
297
    member_count: APINullable[:class:`bool`]
298
        Total number of members in this guild
299
    nsfw: APINullable[:class:`bool`]
300
        Boolean if the server is NSFW
301
    owner: APINullable[:class:`bool`]
302
        True if the user is the owner of the guild
303
    permissions: APINullable[:class:`str`]
304
        Total permissions for the user in the guild
305
        (excludes overwrites)
306
    premium_subscription_count: APINullable[:class:`int`]
307
        The number of boosts this guild currently has
308
    presences: APINullable[List[:class:`~pincer.objects.events.presence.PresenceUpdateEvent`]]
309
        Presences of the members in the guild,
310
        will only include non-offline members if the size is greater
311
        than large threshold
312
    stage_instances: APINullable[List[:class:`~pincer.objects.guild.stage.StageInstance`]]
313
        Stage instances in the guild
314
    stickers: Optional[List[:class:`~pincer.objects.message.sticker.Sticker`]]
315
        Custom guild stickers
316
    region: APINullable[Optional[:class:`str`]]
317
        Voice region id for the guild (deprecated)
318
    threads: APINullable[List[:class:`~pincer.objects.guild.channel.Channel`]]
319
        All active threads in the guild that current user
320
        has permission to view
321
    unavailable: APINullable[:class:`bool`]
322
        True if this guild is unavailable due to an outage
323
    voice_states: APINullable[List[:class:`~pincer.objects.user.voice_state.VoiceState`]]
324
        States of members currently in voice channels;
325
        lacks the guild_id key
326
    widget_enabled: APINullable[:class:`bool`]
327
        True if the server widget is enabled
328
    widget_channel_id: APINullable[Optional[:class:`~pincer.utils.snowflake.Snowflake`]]
329
        The channel id that the widget will generate an invite to,
330
        or null if set to no invite
331
    welcome_screen: APINullable[:class:`~pincer.objects.guild.welcome_screen.WelcomeScreen`]
332
        The welcome screen of a Community guild, shown to new members,
333
        returned in an Invite's guild object
334
    """
335
336
    # noqa: E501
337
    afk_timeout: int
338
    default_message_notifications: DefaultMessageNotificationLevel
339
    emojis: List[Emoji]
340
    explicit_content_filter: ExplicitContentFilterLevel
341
    features: List[GuildFeature]
342
    id: Snowflake
343
    mfa_level: MFALevel
344
    name: str
345
    nsfw_level: GuildNSFWLevel
346
    owner_id: Snowflake
347
    preferred_locale: str
348
    premium_tier: PremiumTier
349
    roles: List[Role]
350
    system_channel_flags: SystemChannelFlags
351
    verification_level: VerificationLevel
352
353
    guild_scheduled_events: APINullable[List] = MISSING
354
    lazy: APINullable[bool] = MISSING
355
    premium_progress_bar_enabled: APINullable[bool] = MISSING
356
    guild_hashes: APINullable[Dict] = MISSING
357
    afk_channel_id: APINullable[Snowflake] = MISSING
358
    application_id: APINullable[Snowflake] = MISSING
359
    embedded_activities: APINullable[List] = MISSING
360
    banner: APINullable[str] = MISSING
361
    description: APINullable[str] = MISSING
362
    discovery_splash: APINullable[str] = MISSING
363
    icon: APINullable[str] = MISSING
364
    public_updates_channel_id: APINullable[Snowflake] = MISSING
365
    rules_channel_id: APINullable[Snowflake] = MISSING
366
    splash: APINullable[str] = MISSING
367
    system_channel_id: APINullable[Snowflake] = MISSING
368
    vanity_url_code: APINullable[str] = MISSING
369
370
    application_command_counts: APINullable[Dict] = MISSING
371
    application_command_count: APINullable[int] = MISSING
372
    approximate_member_count: APINullable[int] = MISSING
373
    approximate_presence_count: APINullable[int] = MISSING
374
    channels: APINullable[List[Channel]] = field(default_factory=list)
375
    # 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...
376
    hub_type: APINullable[Any] = MISSING
377
    icon_hash: APINullable[Optional[str]] = MISSING
378
    joined_at: APINullable[Timestamp] = MISSING
379
    large: APINullable[bool] = MISSING
380
    max_members: APINullable[int] = MISSING
381
    max_presences: APINullable[Optional[int]] = MISSING
382
    max_video_channel_users: APINullable[int] = MISSING
383
    members: APINullable[List[GuildMember]] = MISSING
384
    member_count: APINullable[bool] = MISSING
385
    nsfw: APINullable[bool] = MISSING
386
    # Note: This is missing from discord's docs but in the api
387
    owner: APINullable[bool] = MISSING
388
    permissions: APINullable[str] = MISSING
389
    premium_subscription_count: APINullable[int] = MISSING
390
    presences: APINullable[List[PresenceUpdateEvent]] = MISSING
391
    stage_instances: APINullable[List[StageInstance]] = MISSING
392
    stickers: APINullable[List[Sticker]] = MISSING
393
    region: APINullable[Optional[str]] = MISSING
394
    threads: APINullable[List[Channel]] = MISSING
395
    # Guilds are considered available unless otherwise specified
396
    unavailable: APINullable[bool] = False
397
    voice_states: APINullable[List[VoiceState]] = MISSING
398
    widget_enabled: APINullable[bool] = MISSING
399
    widget_channel_id: APINullable[Optional[Snowflake]] = MISSING
400
    welcome_screen: APINullable[WelcomeScreen] = MISSING
401
402
    @classmethod
403
    async def from_id(cls, client: Client, _id: Union[int, Snowflake]) -> Guild:
404
        """
405
        Parameters
406
        ----------
407
        client : `~pincer.Client`
408
            Client object to use the http gateway from.
409
        _id : :class: `pincer.utils.snowflake.Snowflake`
410
            Guild ID.
411
412
        Returns
413
        -------
414
        :class: `~pincer.objects.guild.guild.Guild`
415
            The new guild object.
416
        """
417
        data = await client.http.get(f"/guilds/{_id}")
418
        channel_data = await client.http.get(f"/guilds/{_id}/channels")
419
420
        data["channels"]: List[Channel] = [
421
            Channel.from_dict({**i, "_client": client, "_http": client.http})
422
            for i in (channel_data or [])
423
        ]
424
425
        return Guild.from_dict(construct_client_dict(client, data))
426
427
    async def get_member(self, _id: int) -> GuildMember:
428
        """|coro|
429
430
        Fetches a GuildMember from its identifier
431
432
        Parameters
433
        ----------
434
        _id:
435
            The id of the guild member which should be fetched from the Discord
436
            gateway.
437
438
        Returns
439
        -------
440
        :class:`~pincer.objects.guild.member.GuildMember`
441
            A GuildMember object.
442
        """
443
        return await GuildMember.from_id(self._client, self.id, _id)
444
445
    @overload
446
    async def modify_member(
447
        self,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
448
        *,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
449
        _id: int,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
450
        nick: Optional[str] = None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
451
        roles: Optional[List[Snowflake]] = None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
452
        mute: Optional[bool] = None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
453
        deaf: Optional[bool] = None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
454
        channel_id: Optional[Snowflake] = None,
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation before block (add 4 spaces).
Loading history...
455
    ) -> GuildMember:
456
        """|coro|
457
458
        Modifies a member in the guild from its identifier and based on the
459
        keyword arguments provided.
460
461
        Parameters
462
        ----------
463
        _id : int
464
            Id of the member to modify
465
        nick : Optional[:class:`str`]
466
            New nickname for the member |default| :data:`None`
467
        roles : Optional[List[:class:`~pincer.utils.snowflake.Snowflake]]
468
            New roles for the member |default| :data:`None`
469
        mute : Optional[:class:`bool`]
470
            Whether the member is muted |default| :data:`None`
471
        deaf : Optional[:class:`bool`]
472
            Whether the member is deafened |default| :data:`None`
473
        channel_id : Optional[:class:`~pincer.utils.snowflake.Snowflake]
474
            Voice channel id to move to |default| :data:`None`
475
476
        Returns
477
        -------
478
        :class:`~pincer.objects.guild.member.GuildMember`
479
            The new member object.
480
        """
481
        ...
482
483
    async def modify_member(self, _id: int, **kwargs) -> GuildMember:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
484
        data = await self._http.patch(
485
            f"guilds/{self.id}/members/{_id}", data=kwargs
486
        )
487
        return GuildMember.from_dict(construct_client_dict(self._client, data))
488
489
    async def kick(self, member_id: int):
490
        """|coro|
491
        Bans a guild member.
492
493
        Parameters
494
        ----------
495
        member_id : :class: int
496
            ID of the guild member to kick.
497
        """
498
        await self._http.delete(f"/guilds/{self.id}/members/{member_id}")
499
500
    async def ban(self, member_id: int, **kwargs):
501
        """|coro|
502
        Kicks a guild member.
503
504
        Parameters
505
        ----------
506
        member_id : :class: int
507
            ID of the guild member to ban.
508
        \\*\\* kwargs
509
            Additional keyword arguments to kick the guild member with.
510
        """
511
        await self._http.put(f"/guilds/{self.id}/bans/{member_id}", data=kwargs)
512
513
    async def edit(self, **kwargs):
514
        """|coro|
515
        Modifies the guild.
516
517
        Parameters
518
        ----------
519
        \\*\\* kwargs
520
            Keyword arguments to modify the guild with.
521
        """
522
        await self._http.patch(f"/guilds/{self.id}", data=kwargs)
523
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
524
    async def preview(self) -> GuildPreview:
525
        """|coro|
526
        Previews the guild.
527
528
        Returns
529
        -------
530
        :class:`~pincer.objects.guild.guild.GuildPreview`
531
            The guild preview object.
532
        """
533
        data = await self._http.get(f"/guilds/{self.id}/preview")
534
        return GuildPreview.from_dict(data)
535
    
0 ignored issues
show
Coding Style introduced by
Trailing whitespace
Loading history...
536
    async def delete(self):
537
        """|coro|
538
        Deletes the guild. Returns `204 No Content` on success.
539
        """
540
        await self._http.delete(f"/guilds/{self.id}")
541
542
    @classmethod
543
    def from_dict(cls, data) -> Guild:
544
        """
545
        Parameters
546
        ----------
547
        data : :class: Dict
548
            Guild data received from the discord API.
549
550
        Returns
551
        -------
552
        :class: `~pincer.objects.guild.guild.Guild`
553
            The new guild object.
554
555
        Raises
556
        :class: `~pincer.exceptions.UnavailableGuildError`
557
            The guild is unavailable due to a discord outage.
558
        """
559
        if data.get("unavailable", False):
560
            raise UnavailableGuildError(
561
                f"Guild \"{data['id']}\" is unavailable due to a discord"
562
                " outage."
563
            )
564
565
        return super().from_dict(data)
566
567
568
@dataclass
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
569
class UnavailableGuild(APIObject):
570
    id: Snowflake
571
    unavailable: bool = True
572