Passed
Push — main ( fdd10b...6849a6 )
by Yohann
01:28
created

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

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nop 3
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 enum import IntEnum
7
from dataclasses import dataclass, field
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 249)'
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
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
    NONE = 0
49
    TIER_1 = 1
50
    TIER_2 = 2
51
    TIER_3 = 3
52
53
54
class GuildNSFWLevel(IntEnum):
55
    """Represents the NSFW level of a guild.
56
57
    Attributes
58
    ----------
59
    DEFAULT:
60
        Default NSFW level.
61
    EXPLICIT:
62
        Explicit NSFW level.
63
    SAFE:
64
        SAFE NSFW level.
65
    AGE_RESTRICTED:
66
        Age restricted NSFW level.
67
    """
68
    DEFAULT = 0
69
    EXPLICIT = 1
70
    SAFE = 2
71
    AGE_RESTRICTED = 3
72
73
74
class ExplicitContentFilterLevel(IntEnum):
75
    """Represents the filter content level of a guild.
76
77
    Attributes
78
    ----------
79
    DISABLED:
80
        Media content will not be scanned.
81
    MEMBERS_WITHOUT_ROLES:
82
        Media content sent by members without roles will be scanned.
83
    ALL_MEMBERS:
84
        Media content sent by all members will be scanned.
85
    """
86
    DISABLED = 0
87
    MEMBERS_WITHOUT_ROLES = 1
88
    ALL_MEMBERS = 2
89
90
91
class MFALevel(IntEnum):
92
    """Represents the multi factor authentication level of a guild.
93
94
    Attributes
95
    ----------
96
    NONE:
97
        Guild has no MFA/2FA requirement for moderation actions.
98
    ELEVATED:
99
        Guild has a 2FA requirement for moderation actions
100
    """
101
    NONE = 0
102
    ELEVATED = 1
103
104
105
class VerificationLevel(IntEnum):
106
    """Represents the verification level of a guild.
107
108
    Attributes
109
    ----------
110
    NONE:
111
        Unrestricted.
112
    LOW:
113
        Must have verified email on account.
114
    MEDIUM:
115
        Must be registered on Discord for longer than 5 minutes.
116
    HIGH:
117
        Must be a member of the server for longer than 10 minutes.
118
    VERY_HIGH:
119
        Must have a verified phone number.
120
    """
121
    NONE = 0
122
    LOW = 1
123
    MEDIUM = 2
124
    HIGH = 3
125
    VERY_HIGH = 4
126
127
128
class DefaultMessageNotificationLevel(IntEnum):
129
    """Represents the default message notification level of a guild.
130
131
    Attributes
132
    ----------
133
    ALL_MESSAGES:
134
        Members will receive notifications for all messages by default.
135
    ONLY_MENTIONS:
136
        Members will receive notifications only for messages that @mention them by default.
137
    """
138
    # noqa: E501
139
    ALL_MESSAGES = 0
140
    ONLY_MENTIONS = 1
141
142
143
class SystemChannelFlags(IntEnum):
144
    """Represents the system channel flags of a guild.
145
146
    Attributes
147
    ----------
148
    SUPPRESS_JOIN_NOTIFICATIONS:
149
        Suppress member join notifications.
150
    SUPPRESS_PREMIUM_SUBSCRIPTIONS:
151
        Suppress server boost notifications.
152
    SUPPRESS_GUILD_REMINDER_NOTIFICATIONS:
153
        Suppress server setup tips.
154
    SUPPRESS_JOIN_NOTIFICATION_REPLIES:
155
        Hide member join sticker reply buttons
156
    """
157
    SUPPRESS_JOIN_NOTIFICATIONS = 1 << 0
158
    SUPPRESS_PREMIUM_SUBSCRIPTIONS = 1 << 1
159
    SUPPRESS_GUILD_REMINDER_NOTIFICATIONS = 1 << 2
160
    SUPPRESS_JOIN_NOTIFICATION_REPLIES = 1 << 3
161
162
163
@dataclass
0 ignored issues
show
best-practice introduced by
Too many instance attributes (59/7)
Loading history...
164
class Guild(APIObject):
165
    """Represents a Discord guild/server in which your client resides.
166
167
    Attributes
168
    ----------
169
    afk_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
170
        Id of afk channel
171
    afk_timeout: :class:`int`
172
        Afk timeout in seconds
173
    application_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
174
        Application id of the guild creator if it is bot-created
175
    banner: Optional[:class:`str`]
176
        Banner hash
177
    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...
178
        Default message notifications level
179
    description: Optional[:class:`str`]
180
        The description of a Community guild
181
    discovery_splash: Optional[:class:`str`]
182
        Discovery splash hash;
183
        only present for guilds with the "DISCOVERABLE" feature
184
    emojis: List[:class:`~pincer.objects.message.emoji.Emoji`]
185
        Custom guild emojis
186
    explicit_content_filter: :class:`~pincer.objects.guild.guild.ExplicitContentFilterLevel`
187
        Explicit content filter level
188
    features: List[:class:`~pincer.objects.guild.features.GuildFeature`]
189
        Enabled guild features
190
    id: :class:`~pincer.utils.snowflake.Snowflake`
191
        Guild id
192
    icon: Optional[:class:`str`]
193
        Icon hash
194
    mfa_level: :class:`~pincer.objects.guild.guild.MFALevel`
195
        Required MFA level for the guild
196
    name: :class:`str`
197
        Guild name (2-100 characters, excluding trailing and leading
198
        whitespace)
199
    nsfw_level: :class:`~pincer.objects.guild.guild.NSFWLevel`
200
        Guild NSFW level
201
    owner_id: :class:`~pincer.utils.snowflake.Snowflake`
202
        Id of owner
203
    preferred_locale: :class:`str`
204
        The preferred locale of a Community guild;
205
        used in server discovery and notices from Discord;
206
        defaults to "en-US"
207
    premium_tier: :class:`~pincer.objects.guild.guild.PremiumTier`
208
        Premium tier (Server Boost level)
209
    public_updates_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
210
        The id of the channel where admins
211
        and moderators of Community guilds receive notices from Discord
212
    roles: List[:class:`~pincer.objects.guild.role.Role`]
213
        Roles in the guild
214
    rules_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
215
        The id of the channel where Community guilds can display rules
216
        and/or guidelines
217
    splash: Optional[:class:`str`]
218
        Splash hash
219
    system_channel_flags: :class:`~pincer.objects.guild.guild.SystemChannelFlags`
220
        System channel flags
221
    system_channel_id: Optional[:class:`~pincer.utils.snowflake.Snowflake`]
222
        The id of the channel where guild notices
223
        such as welcome messages and boost events are posted
224
    vanity_url_code: Optional[:class:`str`]
225
        The vanity url code for the guild
226
    verification_level: :class:`~pincer.objects.guild.guild.VerificationLevel`
227
        Verification level required for the guild
228
    approximate_member_count: APINullable[:class:`int`]
229
        Approximate number of members in this guild, returned from the
230
        `GET /guilds/<id>` endpoint when with_counts is true
231
    approximate_presence_count: APINullable[:class:`int`]
232
        Approximate number of non-offline members in this guild,
233
        returned from the `GET /guilds/<id>`
234
        endpoint when with_counts is true
235
    channels: APINullable[List[:class:`~pincer.objects.guild.channel.Channel`]]
236
        Channels in the guild
237
    icon_hash: APINullable[Optional[:class:`str`]]
238
        Icon hash, returned when in the template object
239
    joined_at: APINullable[:class:`~pincer.utils.timestamp.Timestamp`]
240
        When this guild was joined at
241
    large: APINullable[:class:`bool`]
242
        True if this is considered a large guild
243
    max_members: APINullable[:class:`int`]
244
        The maximum number of members for the guild
245
    max_presences: APINullable[Optional[:class:`int`]]
246
        The maximum number of presences for the guild
247
        (null is always returned, apart from the largest of guilds)
248
    max_video_channel_users: APINullable[:class:`int`]
249
        The maximum amount of users in a video channel
250
    members: APINullable[List[:class:`~pincer.objects.guild.member.GuildMember`]]
251
        Users in the guild
252
    member_count: APINullable[:class:`bool`]
253
        Total number of members in this guild
254
    nsfw: APINullable[:class:`bool`]
255
        Boolean if the server is NSFW
256
    owner: APINullable[:class:`bool`]
257
        True if the user is the owner of the guild
258
    permissions: APINullable[:class:`str`]
259
        Total permissions for the user in the guild
260
        (excludes overwrites)
261
    premium_subscription_count: APINullable[:class:`int`]
262
        The number of boosts this guild currently has
263
    presences: APINullable[List[:class:`~pincer.objects.events.presence.PresenceUpdateEvent`]]
264
        Presences of the members in the guild,
265
        will only include non-offline members if the size is greater
266
        than large threshold
267
    stage_instances: APINullable[List[:class:`~pincer.objects.guild.stage.StageInstance`]]
268
        Stage instances in the guild
269
    stickers: Optional[List[:class:`~pincer.objects.message.sticker.Sticker`]]
270
        Custom guild stickers
271
    region: APINullable[Optional[:class:`str`]]
272
        Voice region id for the guild (deprecated)
273
    threads: APINullable[List[:class:`~pincer.objects.guild.channel.Channel`]]
274
        All active threads in the guild that current user
275
        has permission to view
276
    unavailable: APINullable[:class:`bool`]
277
        True if this guild is unavailable due to an outage
278
    voice_states: APINullable[List[:class:`~pincer.objects.user.voice_state.VoiceState`]]
279
        States of members currently in voice channels;
280
        lacks the guild_id key
281
    widget_enabled: APINullable[:class:`bool`]
282
        True if the server widget is enabled
283
    widget_channel_id: APINullable[Optional[:class:`~pincer.utils.snowflake.Snowflake`]]
284
        The channel id that the widget will generate an invite to,
285
        or null if set to no invite
286
    welcome_screen: APINullable[:class:`~pincer.objects.guild.welcome_screen.WelcomeScreen`]
287
        The welcome screen of a Community guild, shown to new members,
288
        returned in an Invite's guild object
289
    """
290
    # noqa: E501
291
    afk_timeout: int
292
    default_message_notifications: DefaultMessageNotificationLevel
293
    emojis: List[Emoji]
294
    explicit_content_filter: ExplicitContentFilterLevel
295
    features: List[GuildFeature]
296
    id: Snowflake
297
    mfa_level: MFALevel
298
    name: str
299
    nsfw_level: GuildNSFWLevel
300
    owner_id: Snowflake
301
    preferred_locale: str
302
    premium_tier: PremiumTier
303
    roles: List[Role]
304
    system_channel_flags: SystemChannelFlags
305
    verification_level: VerificationLevel
306
307
    guild_scheduled_events: APINullable[List] = MISSING
308
    lazy: APINullable[bool] = MISSING
309
    premium_progress_bar_enabled: APINullable[bool] = MISSING
310
    guild_hashes: APINullable[Dict] = MISSING
311
    afk_channel_id: APINullable[Snowflake] = MISSING
312
    application_id: APINullable[Snowflake] = MISSING
313
    embedded_activities: APINullable[List] = MISSING
314
    banner: APINullable[str] = MISSING
315
    description: APINullable[str] = MISSING
316
    discovery_splash: APINullable[str] = MISSING
317
    icon: APINullable[str] = MISSING
318
    public_updates_channel_id: APINullable[Snowflake] = MISSING
319
    rules_channel_id: APINullable[Snowflake] = MISSING
320
    splash: APINullable[str] = MISSING
321
    system_channel_id: APINullable[Snowflake] = MISSING
322
    vanity_url_code: APINullable[str] = MISSING
323
324
    application_command_counts: APINullable[Dict] = MISSING
325
    application_command_count: APINullable[int] = MISSING
326
    approximate_member_count: APINullable[int] = MISSING
327
    approximate_presence_count: APINullable[int] = MISSING
328
    channels: APINullable[List[Channel]] = field(default_factory=list)
329
    # 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...
330
    hub_type: APINullable[Any] = MISSING
331
    icon_hash: APINullable[Optional[str]] = MISSING
332
    joined_at: APINullable[Timestamp] = MISSING
333
    large: APINullable[bool] = MISSING
334
    max_members: APINullable[int] = MISSING
335
    max_presences: APINullable[Optional[int]] = MISSING
336
    max_video_channel_users: APINullable[int] = MISSING
337
    members: APINullable[List[GuildMember]] = MISSING
338
    member_count: APINullable[bool] = MISSING
339
    nsfw: APINullable[bool] = MISSING
340
    # Note: This is missing from discord's docs but in the api
341
    owner: APINullable[bool] = MISSING
342
    permissions: APINullable[str] = MISSING
343
    premium_subscription_count: APINullable[int] = MISSING
344
    presences: APINullable[List[PresenceUpdateEvent]] = MISSING
345
    stage_instances: APINullable[List[StageInstance]] = MISSING
346
    stickers: APINullable[List[Sticker]] = MISSING
347
    region: APINullable[Optional[str]] = MISSING
348
    threads: APINullable[List[Channel]] = MISSING
349
    # Guilds are considered available unless otherwise specified
350
    unavailable: APINullable[bool] = False
351
    voice_states: APINullable[List[VoiceState]] = MISSING
352
    widget_enabled: APINullable[bool] = MISSING
353
    widget_channel_id: APINullable[Optional[Snowflake]] = MISSING
354
    welcome_screen: APINullable[WelcomeScreen] = MISSING
355
356
    @classmethod
357
    async def from_id(cls, client: Client, _id: Union[int, Snowflake]) -> Guild:
0 ignored issues
show
Comprehensibility Best Practice introduced by
Undefined variable 'Union'
Loading history...
358
        """
359
        Parameters
360
        ----------
361
        client : `~pincer.Client`
362
            Client object to use the http gateway from.
363
        _id : :class: `pincer.utils.snowflake.Snowflake`
364
            Guild ID.
365
366
        Returns
367
        -------
368
        :class: `~pincer.objects.guild.guild.Guild`
369
            The new guild object.
370
        """
371
        data = await client.http.get(f"/guilds/{_id}")
372
        channel_data = await client.http.get(f"/guilds/{_id}/channels")
373
374
        data["channels"]: List[Channel] = [
375
            Channel.from_dict({**i, "_client": client, "_http": client.http})
376
            for i in (channel_data or [])
377
        ]
378
379
        return Guild.from_dict(construct_client_dict(client, data))
380
381
    async def get_member(self, _id: int) -> GuildMember:
382
        """|coro|
383
384
        Fetches a GuildMember from its identifier
385
386
        Parameters
387
        ----------
388
        _id:
389
            The id of the guild member which should be fetched from the Discord
390
            gateway.
391
392
        Returns
393
        -------
394
        :class:`~pincer.objects.guild.member.GuildMember`
395
            A GuildMember object.
396
        """
397
        return await GuildMember.from_id(self._client, self.id, _id)
398
399
    @overload
400
    async def modify_member(
401
            self, *,
402
            _id: int,
403
            nick: Optional[str] = None,
404
            roles: Optional[List[Snowflake]] = None,
405
            mute: Optional[bool] = None,
406
            deaf: Optional[bool] = None,
407
            channel_id: Optional[Snowflake] = None
408
    ) -> GuildMember:
409
        """|coro|
410
411
        Modifies a member in the guild from its identifier and based on the
412
        keyword arguments provided.
413
414
        Parameters
415
        ----------
416
        _id : int
417
            Id of the member to modify
418
        nick : Optional[:class:`str`]
419
            New nickname for the member |default| :data:`None`
420
        roles : Optional[List[:class:`~pincer.utils.snowflake.Snowflake]]
421
            New roles for the member |default| :data:`None`
422
        mute : Optional[:class:`bool`]
423
            Whether the member is muted |default| :data:`None`
424
        deaf : Optional[:class:`bool`]
425
            Whether the member is deafened |default| :data:`None`
426
        channel_id : Optional[:class:`~pincer.utils.snowflake.Snowflake]
427
            Voice channel id to move to |default| :data:`None`
428
429
        Returns
430
        -------
431
        :class:`~pincer.objects.guild.member.GuildMember`
432
            The new member object.
433
        """
434
        ...
435
436
    async def modify_member(self, _id: int, **kwargs) -> GuildMember:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
437
        data = await self._http.patch(
438
            f"guilds/{self.id}/members/{_id}",
439
            data=kwargs
440
        )
441
        return GuildMember.from_dict(construct_client_dict(self._client, data))
442
443
    async def kick(self, member_id: int, **kwargs):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
444
        # TODO: docs
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
445
        await self._http.put(f"/guilds/{self.id}/bans/{member_id}", data=kwargs)
446
447
    async def ban(self, member_id: int):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
448
        # TODO: docs
0 ignored issues
show
Coding Style introduced by
TODO and FIXME comments should generally be avoided.
Loading history...
449
        await self._http.delete(f"/guilds/{self.id}/members/{member_id}")
450
451
    @classmethod
452
    def from_dict(cls, data) -> Guild:
453
        """
454
        Parameters
455
        ----------
456
        data : :class: Dict
457
            Guild data received from the discord API.
458
459
        Returns
460
        -------
461
        :class: `~pincer.objects.guild.guild.Guild`
462
            The new guild object.
463
464
        Raises
465
        :class: `~pincer.exceptions.UnavailableGuildError`
466
            The guild is unavailable due to a discord outage.
467
        """
468
        if data.get("unavailable", False):
469
            raise UnavailableGuildError(
470
                f"Guild \"{data['id']}\" is unavailable due to a discord"
471
                " outage."
472
            )
473
474
        return super().from_dict(data)
475
476
477
@dataclass
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
478
class UnavailableGuild(APIObject):
479
    id: Snowflake
480
    unavailable: bool = True
481