Passed
Pull Request — main (#155)
by Oliver
01:52
created

NewsChannel.__init__()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 2
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
8
from typing import overload, TYPE_CHECKING
9
10
from ...utils.types import MISSING
11
from ..._config import GatewayConfig
12
from ...utils.api_object import APIObject
13
14
if TYPE_CHECKING:
15
    from typing import Dict, List, Optional, Union
16
17
    from ...client import Client
0 ignored issues
show
introduced by
Cannot import 'client' due to syntax error 'invalid syntax (<unknown>, line 342)'
Loading history...
18
    from ..user.user import User
19
    from .member import GuildMember
20
    from .overwrite import Overwrite
21
    from .thread import ThreadMetadata
22
    from ...core.http import HTTPClient
23
    from ...utils.types import APINullable
24
    from ...utils.snowflake import Snowflake
25
    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 99)'
Loading history...
26
27
28
class ChannelType(IntEnum):
29
    """Represents a channel its type.
30
31
    Attributes
32
    ----------
33
    GUILD_TEXT:
34
        A text channel.
35
    DM:
36
        A DM channel.
37
    GUILD_VOICE:
38
        A voice channel.
39
    GROUP_DM:
40
        A group DM channel.
41
    GUILD_CATEGORY:
42
        A category channel.
43
    GUILD_NEWS:
44
        A news channel.
45
    GUILD_STORE:
46
        A store channel.
47
    GUILD_NEWS_THREAD:
48
        A news thread.
49
    GUILD_PUBLIC_THREAD:
50
        A public thread.
51
    GUILD_PRIVATE_THREAD:
52
        A private thread.
53
    GUILD_STAGE_VOICE:
54
        A stage channel.
55
    """
56
    GUILD_TEXT = 0
57
    DM = 1
58
    GUILD_VOICE = 2
59
    GROUP_DM = 3
60
    GUILD_CATEGORY = 4
61
    GUILD_NEWS = 5
62
    GUILD_STORE = 6
63
64
    if GatewayConfig.version >= 9:
65
        GUILD_NEWS_THREAD = 10
66
        GUILD_PUBLIC_THREAD = 11
67
        GUILD_PRIVATE_THREAD = 12
68
69
    GUILD_STAGE_VOICE = 13
70
71
72
@dataclass
0 ignored issues
show
best-practice introduced by
Too many instance attributes (26/7)
Loading history...
73
class Channel(APIObject):  # noqa E501
74
    """Represents a Discord Channel Mention object
75
76
    Attributes
77
    ----------
78
    id: :class:`~pincer.utils.snowflake.Snowflake`
79
        The id of this channel
80
    type: :class:`~pincer.objects.guild.channel.ChannelType`
81
        The type of channel
82
    application_id: APInullable[:class:`~pincer.utils.snowflake.Snowflake`]
83
        Application id of the group DM creator if it is bot-created
84
    bitrate: APINullable[:class:`int`]
85
        The bitrate (in bits) of the voice channel
86
    default_auto_archive_duration: APINullable[:class:`int`]
87
        Default duration for newly created threads, in minutes, to
88
        automatically archive the thread after recent activity, can be set to:
89
        60, 1440, 4320, 10080
90
    guild_id: APINullable[:class:`~pincer.utils.snowflake.Snowflake`]
91
        The id of the guild (may be missing for some channel objects received
92
        over gateway guild dispatches)
93
    icon: APINullable[Optional[:class:`str`]]
94
        Icon hash
95
    last_message_id: APINullable[Optional[:class:`~pincer.utils.snowflake.Snowflake`]]
96
        The id of the last message sent in this channel (may not point to an
97
        existing or valid message)
98
    last_pin_timestamp: APINullable[Optional[:class:`~pincer.utils.timestamp.Timestamp`]]
99
        When the last pinned message was pinned. This may be null in events
100
        such as GUILD_CREATE when a message is not pinned.
101
    member: APINullable[:class:`~pincer.objects.guild.member.GuildMember`]
102
        Thread member object for the current user, if they have joined the
103
        thread, only included on certain API endpoints
104
    member_count: APINullable[:class:`int`]
105
        An approximate count of users in a thread, stops counting at 50
106
    message_count: :class:`int`
107
        An approximate count of messages in a thread, stops counting at 50
108
    name: APINullable[:class:`str`]
109
        The name of the channel (1-100 characters)
110
    nsfw: APINullable[:class:`bool`]
111
        Whether the channel is nsfw
112
    owner_id: APINullable[:class:`~pincer.utils.snowflake.Snowflake`]
113
        Id of the creator of the group DM or thread
114
    parent_id: APInullable[Optional[:class:`~pincer.utils.snowflake.Snowflake`]]
115
        For guild channels: id of the parent category for a channel (each
116
        parent category can contain up to 50 channels), for threads: id of the
117
        text channel this thread was created
118
    permissions: APINullable[:class:`str`]
119
        Computed permissions for the invoking user in the channel, including
120
        overwrites, only included when part of the resolved data received on a
121
        slash command interaction
122
    permission_overwrites: APINullable[List[:class:`~pincer.obects.guild.overwrite.Overwrite`]]
123
        Explicit permission overwrites for members and roles
124
    position: APINullable[:class:`int`]
125
        Sorting position of the channel
126
    rate_limit_per_user: APINullable[:class:`int`]
127
        Amount of seconds a user has to wait before sending another message
128
        (0-21600); bots, as well as users with the permission manage_messages
129
        or manage_channel, are unaffected
130
    recipients: APINullable[List[:class:`~pincer.objects.user.user.User`]]
131
        The recipients of the DM
132
    rtc_region: APINullable[Optional[:class:`str`]]
133
        Voice region id for the voice channel, automatic when set to null
134
    thread_metadata: APINullable[:class:`~pincer.objects.guild.thread.ThreadMetadata`]
135
        Thread-specific fields not needed by other channels
136
    topic: APINullable[Optional[:class:`str`]]
137
        The channel topic (0-1024 characters)
138
    user_limit: APINullable[:class:`int`]
139
        The user limit of the voice channel
140
    video_quality_mode: APINullable[:class:`int`]
141
        The camera video quality mode of the voice channel, 1 when not present
142
    """  # noqa: E501
143
    id: Snowflake
144
    type: ChannelType
145
146
    application_id: APINullable[Snowflake] = MISSING
147
    bitrate: APINullable[int] = MISSING
148
    default_auto_archive_duration: APINullable[int] = MISSING
149
    guild_id: APINullable[Snowflake] = MISSING
150
    icon: APINullable[Optional[str]] = MISSING
151
152
    last_message_id: APINullable[Optional[Snowflake]] = MISSING
153
    last_pin_timestamp: APINullable[Optional[Timestamp]] = MISSING
154
    member: APINullable[GuildMember] = MISSING
155
156
    member_count: APINullable[int] = MISSING
157
158
    message_count: APINullable[int] = MISSING
159
160
    name: APINullable[str] = MISSING
161
    nsfw: APINullable[bool] = MISSING
162
    owner_id: APINullable[Snowflake] = MISSING
163
    parent_id: APINullable[Optional[Snowflake]] = MISSING
164
    permissions: APINullable[str] = MISSING
165
    permission_overwrites: APINullable[List[Overwrite]] = MISSING
166
    position: APINullable[int] = MISSING
167
    rate_limit_per_user: APINullable[int] = MISSING
168
    recipients: APINullable[List[User]] = MISSING
169
    rtc_region: APINullable[Optional[str]] = MISSING
170
    thread_metadata: APINullable[ThreadMetadata] = MISSING
171
    topic: APINullable[Optional[str]] = MISSING
172
    user_limit: APINullable[int] = MISSING
173
    video_quality_mode: APINullable[int] = MISSING
174
175
    @property
176
    def mention(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
177
        return f"<#{self.id}>"
178
179
    @classmethod
180
    async def from_id(cls, client: Client, channel_id: int) -> Channel:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
181
        data = (await client.http.get(f"channels/{channel_id}")) or {}
182
        data.update(
183
            {
184
                "_client": client,
185
                "_http": client.http,
186
                "type": ChannelType(data.pop("type"))
187
            }
188
        )
189
190
        channel_cls = _channel_type_map.get(data["type"], Channel)
191
        return channel_cls.from_dict(data)
192
193
    @overload
194
    async def edit(
195
            self, *, name: str = None,
196
            type: ChannelType = None,
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in type.

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

Loading history...
197
            position: int = None, topic: str = None, nsfw: bool = None,
198
            rate_limit_per_user: int = None, bitrate: int = None,
199
            user_limit: int = None,
200
            permissions_overwrites: List[Overwrite] = None,
201
            parent_id: Snowflake = None, rtc_region: str = None,
202
            video_quality_mod: int = None,
203
            default_auto_archive_duration: int = None
204
    ) -> Channel:
205
        ...
206
207
    async def edit(self, **kwargs):
208
        """Edit a channel with the given keyword arguments.
209
210
        Parameters
211
        ----------
212
        \\*\\*kwargs :
213
            The keyword arguments to edit the channel with.
214
215
        Returns
216
        -------
217
        :class:`~pincer.objects.guild.channel.Channel`
218
            The updated channel object.
219
        """
220
        data = await self._http.patch(f"channels/{self.id}", kwargs)
0 ignored issues
show
Bug introduced by
The Instance of Channel does not seem to have a member named _http.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
221
        data.update(
222
            {
223
                "_client": self.client,
0 ignored issues
show
Bug introduced by
The Instance of Channel does not seem to have a member named client.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
224
                "_http": self._http,
0 ignored issues
show
Bug introduced by
The Instance of Channel does not seem to have a member named _http.

This check looks for calls to members that are non-existent. These calls will fail.

The member could have been renamed or removed.

Loading history...
225
                "type": ChannelType(data.pop("type"))
226
            }
227
        )
228
        channel_cls = _channel_type_map.get(data["type"], Channel)
229
        return channel_cls.from_dict(data)
230
231
232
def __str__(self):
233
    """return the discord tag when object gets used as a string."""
234
    return self.name or str(self.id)
235
236
237
class TextChannel(Channel):
238
    """A subclass of ``Channel`` for text channels with all the same attributes.
239
    """
240
241
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
242
        super().__init__(*args, **kwargs)
243
244
    @overload
245
    async def edit(
0 ignored issues
show
best-practice introduced by
Too many arguments (10/5)
Loading history...
Bug introduced by
Parameters differ from overridden 'edit' method
Loading history...
246
            self, name: str = None, type: ChannelType = None,
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in type.

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

Loading history...
247
            position: int = None, topic: str = None, nsfw: bool = None,
248
            rate_limit_per_user: int = None,
249
            permissions_overwrites: List[Overwrite] = None,
250
            parent_id: Snowflake = None,
251
            default_auto_archive_duration: int = None
252
    ) -> Union[TextChannel, NewsChannel]:
253
        ...
254
255
    async def edit(self, **kwargs):
256
        """Edit a text channel with the given keyword arguments.
257
258
        Parameters
259
        ----------
260
        \\*\\*kwargs :
261
            The keyword arguments to edit the channel with.
262
263
        Returns
264
        -------
265
        :class:`~pincer.objects.guild.channel.Channel`
266
            The updated channel object.
267
        """
268
        return await super().edit(**kwargs)
269
270
271
class VoiceChannel(Channel):
272
    """A subclass of ``Channel`` for voice channels with all the same attributes.
273
    """
274
275
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
276
        super().__init__(*args, **kwargs)
277
278
    @overload
279
    async def edit(
0 ignored issues
show
best-practice introduced by
Too many arguments (8/5)
Loading history...
Bug introduced by
Parameters differ from overridden 'edit' method
Loading history...
280
            self, name: str = None, position: int = None, bitrate: int = None,
281
            user_limit: int = None,
282
            permissions_overwrites: List[Overwrite] = None,
283
            rtc_region: str = None, video_quality_mod: int = None
284
    ) -> VoiceChannel:
285
        ...
286
287
    async def edit(self, **kwargs):
288
        """Edit a text channel with the given keyword arguments.
289
290
        Parameters
291
        ----------
292
        \\*\\*kwargs :
293
            The keyword arguments to edit the channel with.
294
295
        Returns
296
        -------
297
        :class:`~pincer.objects.guild.channel.Channel`
298
            The updated channel object.
299
        """
300
        return await super().edit(**kwargs)
301
302
303
class CategoryChannel(Channel):
304
    """A subclass of ``Channel`` for categories channels
305
    with all the same attributes.
306
    """
307
308
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
309
        super().__init__(*args, **kwargs)
310
311
312
class NewsChannel(Channel):
313
    """A subclass of ``Channel`` for news channels with all the same attributes.
314
    """
315
316
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
317
        super().__init__(*args, **kwargs)
318
319
    @overload
320
    async def edit(
0 ignored issues
show
best-practice introduced by
Too many arguments (9/5)
Loading history...
Bug introduced by
Parameters differ from overridden 'edit' method
Loading history...
321
            self, name: str = None, type: ChannelType = None,
0 ignored issues
show
Bug Best Practice introduced by
This seems to re-define the built-in type.

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

Loading history...
322
            position: int = None, topic: str = None, nsfw: bool = None,
323
            permissions_overwrites: List[Overwrite] = None,
324
            parent_id: Snowflake = None,
325
            default_auto_archive_duration: int = None
326
    ) -> Union[TextChannel, NewsChannel]:
327
        ...
328
329
    async def edit(self, **kwargs):
330
        """Edit a text channel with the given keyword arguments.
331
332
        Parameters
333
        ----------
334
        \\*\\*kwargs :
335
            The keyword arguments to edit the channel with.
336
337
        Returns
338
        -------
339
        :class:`~pincer.objects.guild.channel.Channel`
340
            The updated channel object.
341
        """
342
        return await super().edit(**kwargs)
343
344
345
@dataclass
346
class ChannelMention(APIObject):
347
    """Represents a Discord Channel Mention object
348
349
    Attributes
350
    ----------
351
    id: :class:`~pincer.utils.snowflake.Snowflake`
352
        Id of the channel
353
    guild_id: :class:`~pincer.utils.snowflake.Snowflake`
354
        Id of the guild containing the channel
355
    type: :class:`~pincer.objects.guild.channel.ChannelType`
356
        The type of channel
357
    name: :class:`str`
358
        The name of the channel
359
    """
360
    id: Snowflake
361
    guild_id: Snowflake
362
    type: ChannelType
363
    name: str
364
365
366
_channel_type_map: Dict[ChannelType, Channel] = {
367
    ChannelType.GUILD_TEXT: TextChannel,
368
    ChannelType.GUILD_VOICE: VoiceChannel,
369
    ChannelType.GUILD_CATEGORY: CategoryChannel,
370
    ChannelType.GUILD_NEWS: NewsChannel
371
}
372