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

pincer.objects.guild.channel.TextChannel.mention()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 4
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 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 ...utils.types import APINullable
23
    from ...utils.snowflake import Snowflake
24
    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...
25
26
27
class ChannelType(IntEnum):
28
    """Represents a channel its type.
29
30
    Attributes
31
    ----------
32
    GUILD_TEXT:
33
        A text channel.
34
    DM:
35
        A DM channel.
36
    GUILD_VOICE:
37
        A voice channel.
38
    GROUP_DM:
39
        A group DM channel.
40
    GUILD_CATEGORY:
41
        A category channel.
42
    GUILD_NEWS:
43
        A news channel.
44
    GUILD_STORE:
45
        A store channel.
46
    GUILD_NEWS_THREAD:
47
        A news thread.
48
    GUILD_PUBLIC_THREAD:
49
        A public thread.
50
    GUILD_PRIVATE_THREAD:
51
        A private thread.
52
    GUILD_STAGE_VOICE:
53
        A stage channel.
54
    """
55
    GUILD_TEXT = 0
56
    DM = 1
57
    GUILD_VOICE = 2
58
    GROUP_DM = 3
59
    GUILD_CATEGORY = 4
60
    GUILD_NEWS = 5
61
    GUILD_STORE = 6
62
63
    if GatewayConfig.version >= 9:
64
        GUILD_NEWS_THREAD = 10
65
        GUILD_PUBLIC_THREAD = 11
66
        GUILD_PRIVATE_THREAD = 12
67
68
    GUILD_STAGE_VOICE = 13
69
70
71
@dataclass
0 ignored issues
show
best-practice introduced by
Too many instance attributes (26/7)
Loading history...
72
class Channel(APIObject):  # noqa E501
73
    """Represents a Discord Channel Mention object
74
75
    Attributes
76
    ----------
77
    id: :class:`~pincer.utils.snowflake.Snowflake`
78
        The id of this channel
79
    type: :class:`~pincer.objects.guild.channel.ChannelType`
80
        The type of channel
81
    application_id: APInullable[:class:`~pincer.utils.snowflake.Snowflake`]
82
        Application id of the group DM creator if it is bot-created
83
    bitrate: APINullable[:class:`int`]
84
        The bitrate (in bits) of the voice channel
85
    default_auto_archive_duration: APINullable[:class:`int`]
86
        Default duration for newly created threads, in minutes, to
87
        automatically archive the thread after recent activity, can be set to:
88
        60, 1440, 4320, 10080
89
    guild_id: APINullable[:class:`~pincer.utils.snowflake.Snowflake`]
90
        The id of the guild (may be missing for some channel objects received
91
        over gateway guild dispatches)
92
    icon: APINullable[Optional[:class:`str`]]
93
        Icon hash
94
    last_message_id: APINullable[Optional[:class:`~pincer.utils.snowflake.Snowflake`]]
95
        The id of the last message sent in this channel (may not point to an
96
        existing or valid message)
97
    last_pin_timestamp: APINullable[Optional[:class:`~pincer.utils.timestamp.Timestamp`]]
98
        When the last pinned message was pinned. This may be null in events
99
        such as GUILD_CREATE when a message is not pinned.
100
    member: APINullable[:class:`~pincer.objects.guild.member.GuildMember`]
101
        Thread member object for the current user, if they have joined the
102
        thread, only included on certain API endpoints
103
    member_count: APINullable[:class:`int`]
104
        An approximate count of users in a thread, stops counting at 50
105
    message_count: :class:`int`
106
        An approximate count of messages in a thread, stops counting at 50
107
    name: APINullable[:class:`str`]
108
        The name of the channel (1-100 characters)
109
    nsfw: APINullable[:class:`bool`]
110
        Whether the channel is nsfw
111
    owner_id: APINullable[:class:`~pincer.utils.snowflake.Snowflake`]
112
        Id of the creator of the group DM or thread
113
    parent_id: APInullable[Optional[:class:`~pincer.utils.snowflake.Snowflake`]]
114
        For guild channels: id of the parent category for a channel (each
115
        parent category can contain up to 50 channels), for threads: id of the
116
        text channel this thread was created
117
    permissions: APINullable[:class:`str`]
118
        Computed permissions for the invoking user in the channel, including
119
        overwrites, only included when part of the resolved data received on a
120
        slash command interaction
121
    permission_overwrites: APINullable[List[:class:`~pincer.obects.guild.overwrite.Overwrite`]]
122
        Explicit permission overwrites for members and roles
123
    position: APINullable[:class:`int`]
124
        Sorting position of the channel
125
    rate_limit_per_user: APINullable[:class:`int`]
126
        Amount of seconds a user has to wait before sending another message
127
        (0-21600); bots, as well as users with the permission manage_messages
128
        or manage_channel, are unaffected
129
    recipients: APINullable[List[:class:`~pincer.objects.user.user.User`]]
130
        The recipients of the DM
131
    rtc_region: APINullable[Optional[:class:`str`]]
132
        Voice region id for the voice channel, automatic when set to null
133
    thread_metadata: APINullable[:class:`~pincer.objects.guild.thread.ThreadMetadata`]
134
        Thread-specific fields not needed by other channels
135
    topic: APINullable[Optional[:class:`str`]]
136
        The channel topic (0-1024 characters)
137
    user_limit: APINullable[:class:`int`]
138
        The user limit of the voice channel
139
    video_quality_mode: APINullable[:class:`int`]
140
        The camera video quality mode of the voice channel, 1 when not present
141
    """  # noqa: E501
142
    id: Snowflake
143
    type: ChannelType
144
145
    application_id: APINullable[Snowflake] = MISSING
146
    bitrate: APINullable[int] = MISSING
147
    default_auto_archive_duration: APINullable[int] = MISSING
148
    guild_id: APINullable[Snowflake] = MISSING
149
    icon: APINullable[Optional[str]] = MISSING
150
151
    last_message_id: APINullable[Optional[Snowflake]] = MISSING
152
    last_pin_timestamp: APINullable[Optional[Timestamp]] = MISSING
153
    member: APINullable[GuildMember] = MISSING
154
155
    member_count: APINullable[int] = MISSING
156
157
    message_count: APINullable[int] = MISSING
158
159
    name: APINullable[str] = MISSING
160
    nsfw: APINullable[bool] = MISSING
161
    owner_id: APINullable[Snowflake] = MISSING
162
    parent_id: APINullable[Optional[Snowflake]] = MISSING
163
    permissions: APINullable[str] = MISSING
164
    permission_overwrites: APINullable[List[Overwrite]] = MISSING
165
    position: APINullable[int] = MISSING
166
    rate_limit_per_user: APINullable[int] = MISSING
167
    recipients: APINullable[List[User]] = MISSING
168
    rtc_region: APINullable[Optional[str]] = MISSING
169
    thread_metadata: APINullable[ThreadMetadata] = MISSING
170
    topic: APINullable[Optional[str]] = MISSING
171
    user_limit: APINullable[int] = MISSING
172
    video_quality_mode: APINullable[int] = MISSING
173
174
    @property
175
    def mention(self):
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
176
        return f"<#{self.id}>"
177
178
    @classmethod
179
    async def from_id(cls, client: Client, channel_id: int) -> Channel:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
180
        data = (await client.http.get(f"channels/{channel_id}")) or {}
181
        data.update(
182
            {
183
                "_client": client,
184
                "_http": client.http,
185
                "type": ChannelType(data.pop("type"))
186
            }
187
        )
188
189
        channel_cls = _channel_type_map.get(data["type"], Channel)
190
        return channel_cls.from_dict(data)
191
192
    @overload
193
    async def edit(
194
            self, *, name: str = None,
195
            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...
196
            position: int = None, topic: str = None, nsfw: bool = None,
197
            rate_limit_per_user: int = None, bitrate: int = None,
198
            user_limit: int = None,
199
            permissions_overwrites: List[Overwrite] = None,
200
            parent_id: Snowflake = None, rtc_region: str = None,
201
            video_quality_mod: int = None,
202
            default_auto_archive_duration: int = None
203
    ) -> Channel:
204
        ...
205
206
    async def edit(self, **kwargs):
207
        """Edit a channel with the given keyword arguments.
208
209
        Parameters
210
        ----------
211
        \\*\\*kwargs :
212
            The keyword arguments to edit the channel with.
213
214
        Returns
215
        -------
216
        :class:`~pincer.objects.guild.channel.Channel`
217
            The updated channel object.
218
        """
219
        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...
220
        data.update(
221
            {
222
                "_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...
223
                "_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...
224
                "type": ChannelType(data.pop("type"))
225
            }
226
        )
227
        channel_cls = _channel_type_map.get(data["type"], Channel)
228
        return channel_cls.from_dict(data)
229
230
231
def __str__(self):
232
    """return the discord tag when object gets used as a string."""
233
    return self.name or str(self.id)
234
235
236
class TextChannel(Channel):
237
    """A subclass of ``Channel`` for text channels with all the same attributes.
238
    """
239
240
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
241
        super().__init__(*args, **kwargs)
242
243
    @overload
244
    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...
245
            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...
246
            position: int = None, topic: str = None, nsfw: bool = None,
247
            rate_limit_per_user: int = None,
248
            permissions_overwrites: List[Overwrite] = None,
249
            parent_id: Snowflake = None,
250
            default_auto_archive_duration: int = None
251
    ) -> Union[TextChannel, NewsChannel]:
252
        ...
253
254
    async def edit(self, **kwargs):
255
        """Edit a text channel with the given keyword arguments.
256
257
        Parameters
258
        ----------
259
        \\*\\*kwargs :
260
            The keyword arguments to edit the channel with.
261
262
        Returns
263
        -------
264
        :class:`~pincer.objects.guild.channel.Channel`
265
            The updated channel object.
266
        """
267
        return await super().edit(**kwargs)
268
269
270
class VoiceChannel(Channel):
271
    """A subclass of ``Channel`` for voice channels with all the same attributes.
272
    """
273
274
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
275
        super().__init__(*args, **kwargs)
276
277
    @overload
278
    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...
279
            self, name: str = None, position: int = None, bitrate: int = None,
280
            user_limit: int = None,
281
            permissions_overwrites: List[Overwrite] = None,
282
            rtc_region: str = None, video_quality_mod: int = None
283
    ) -> VoiceChannel:
284
        ...
285
286
    async def edit(self, **kwargs):
287
        """Edit a text channel with the given keyword arguments.
288
289
        Parameters
290
        ----------
291
        \\*\\*kwargs :
292
            The keyword arguments to edit the channel with.
293
294
        Returns
295
        -------
296
        :class:`~pincer.objects.guild.channel.Channel`
297
            The updated channel object.
298
        """
299
        return await super().edit(**kwargs)
300
301
302
class CategoryChannel(Channel):
303
    """A subclass of ``Channel`` for categories channels
304
    with all the same attributes.
305
    """
306
307
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
308
        super().__init__(*args, **kwargs)
309
310
311
class NewsChannel(Channel):
312
    """A subclass of ``Channel`` for news channels with all the same attributes.
313
    """
314
315
    def __init__(self, *args, **kwargs):
0 ignored issues
show
introduced by
Useless super delegation in method '__init__'
Loading history...
316
        super().__init__(*args, **kwargs)
317
318
    @overload
319
    async def edit(
0 ignored issues
show
Bug introduced by
Parameters differ from overridden 'edit' method
Loading history...
best-practice introduced by
Too many arguments (9/5)
Loading history...
320
            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...
321
            position: int = None, topic: str = None, nsfw: bool = None,
322
            permissions_overwrites: List[Overwrite] = None,
323
            parent_id: Snowflake = None,
324
            default_auto_archive_duration: int = None
325
    ) -> Union[TextChannel, NewsChannel]:
326
        ...
327
328
    async def edit(self, **kwargs):
329
        """Edit a text channel with the given keyword arguments.
330
331
        Parameters
332
        ----------
333
        \\*\\*kwargs :
334
            The keyword arguments to edit the channel with.
335
336
        Returns
337
        -------
338
        :class:`~pincer.objects.guild.channel.Channel`
339
            The updated channel object.
340
        """
341
        return await super().edit(**kwargs)
342
343
344
@dataclass
345
class ChannelMention(APIObject):
346
    """Represents a Discord Channel Mention object
347
348
    Attributes
349
    ----------
350
    id: :class:`~pincer.utils.snowflake.Snowflake`
351
        Id of the channel
352
    guild_id: :class:`~pincer.utils.snowflake.Snowflake`
353
        Id of the guild containing the channel
354
    type: :class:`~pincer.objects.guild.channel.ChannelType`
355
        The type of channel
356
    name: :class:`str`
357
        The name of the channel
358
    """
359
    id: Snowflake
360
    guild_id: Snowflake
361
    type: ChannelType
362
    name: str
363
364
365
_channel_type_map: Dict[ChannelType, Channel] = {
366
    ChannelType.GUILD_TEXT: TextChannel,
367
    ChannelType.GUILD_VOICE: VoiceChannel,
368
    ChannelType.GUILD_CATEGORY: CategoryChannel,
369
    ChannelType.GUILD_NEWS: NewsChannel
370
}
371