aboutsummaryrefslogtreecommitdiff
path: root/discord/member.py
blob: bd6f40510b5f67d6ceed8be5583edd5c772d359c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# -*- coding: utf-8 -*-

"""
The MIT License (MIT)

Copyright (c) 2015-2016 Rapptz

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""

import asyncio

import discord.utils
from .user import User
from .game import Game
from .permissions import Permissions
from .enums import Status, ChannelType, try_enum
from .colour import Colour

class VoiceState:
    """Represents a Discord user's voice state.

    Attributes
    ------------
    deaf: bool
        Indicates if the user is currently deafened by the guild.
    mute: bool
        Indicates if the user is currently muted by the guild.
    self_mute: bool
        Indicates if the user is currently muted by their own accord.
    self_deaf: bool
        Indicates if the user is currently deafened by their own accord.
    is_afk: bool
        Indicates if the user is currently in the AFK channel in the guild.
    channel: Optional[Union[:class:`Channel`, :class:`PrivateChannel`]]
        The voice channel that the user is currently connected to. None if the user
        is not currently in a voice channel.
    """

    __slots__ = ( 'session_id', 'deaf', 'mute', 'self_mute',
                  'self_deaf', 'is_afk', 'channel' )

    def __init__(self, *, data, channel=None):
        self.session_id = data.get('session_id')
        self._update(data, channel)

    def _update(self, data, channel):
        self.self_mute = data.get('self_mute', False)
        self.self_deaf = data.get('self_deaf', False)
        self.is_afk = data.get('suppress', False)
        self.mute = data.get('mute', False)
        self.deaf = data.get('deaf', False)
        self.channel = channel

def flatten_user(cls):
    for attr, value in User.__dict__.items():
        # ignore private/special methods
        if attr.startswith('_'):
            continue

        # don't override what we already have
        if attr in cls.__dict__:
            continue

        # if it's a slotted attribute or a property, redirect it
        # slotted members are implemented as member_descriptors in Type.__dict__
        if hasattr(value, '__get__'):
            def getter(self, x=attr):
                return getattr(self._user, x)
            setattr(cls, attr, property(getter, doc='Equivalent to :attr:`User.%s`' % attr))
        else:
            # probably a member function by now
            def generate_function(x):
                def general(self, *args, **kwargs):
                    return getattr(self._user, x)(*args, **kwargs)

                general.__name__ = x
                return general

            func = generate_function(attr)
            func.__doc__ = value.__doc__
            setattr(cls, attr, func)

    return cls

@flatten_user
class Member:
    """Represents a Discord member to a :class:`Guild`.

    This implements a lot of the functionality of :class:`User`.

    Supported Operations:

    +-----------+-----------------------------------------------+
    | Operation |                  Description                  |
    +===========+===============================================+
    | x == y    | Checks if two members are equal.              |
    +-----------+-----------------------------------------------+
    | x != y    | Checks if two members are not equal.          |
    +-----------+-----------------------------------------------+
    | hash(x)   | Return the member's hash.                     |
    +-----------+-----------------------------------------------+
    | str(x)    | Returns the member's name with discriminator. |
    +-----------+-----------------------------------------------+

    Attributes
    ----------
    roles
        A list of :class:`Role` that the member belongs to. Note that the first element of this
        list is always the default '@everyone' role.
    joined_at : `datetime.datetime`
        A datetime object that specifies the date and time in UTC that the member joined the guild for
        the first time.
    status : :class:`Status`
        The member's status. There is a chance that the status will be a ``str``
        if it is a value that is not recognised by the enumerator.
    game : :class:`Game`
        The game that the user is currently playing. Could be None if no game is being played.
    guild : :class:`Guild`
        The guild that the member belongs to.
    nick : Optional[str]
        The guild specific nickname of the user.
    """

    __slots__ = ('roles', 'joined_at', 'status', 'game', 'guild', 'nick', '_user', '_state')

    def __init__(self, *, data, guild, state):
        self._state = state
        self._user = state.store_user(data['user'])
        self.joined_at = discord.utils.parse_time(data.get('joined_at'))
        self.roles = data.get('roles', [])
        self.status = Status.offline
        game = data.get('game', {})
        self.game = Game(**game) if game else None
        self.guild = guild
        self.nick = data.get('nick', None)

    def __str__(self):
        return str(self._user)

    def __repr__(self):
        return '<Member id={1.id} name={1.name!r} discriminator={1.discriminator!r}' \
               ' bot={1.bot} nick={0.nick!r} guild={0.guild!r}>'.format(self, self._user)

    def __eq__(self, other):
        return isinstance(other, Member) and other._user.id == self._user.id and self.guild.id == other.guild.id

    def __ne__(self, other):
        return not self.__eq__(other)

    def __hash__(self):
        return hash(self._user.id)

    def _update(self, data, user=None):
        if user:
            self._user.name = user['username']
            self._user.discriminator = user['discriminator']
            self._user.avatar = user['avatar']
            self._user.bot = user.get('bot', False)

        # the nickname change is optional,
        # if it isn't in the payload then it didn't change
        try:
            self.nick = data['nick']
        except KeyError:
            pass

        # update the roles
        self.roles = [self.guild.default_role]
        for role in self.guild.roles:
            if role.id in data['roles']:
                self.roles.append(role)

        # sort the roles by ID since they can be "randomised"
        self.roles.sort(key=lambda r: int(r.id))

    def _presence_update(self, data, user):
        self.status = try_enum(Status, data['status'])
        game = data.get('game', {})
        self.game = Game(**game) if game else None
        u = self._user
        u.name = user.get('username', u.name)
        u.avatar = user.get('avatar', u.avatar)
        u.discriminator = user.get('discriminator', u.discriminator)

    @property
    def colour(self):
        """A property that returns a :class:`Colour` denoting the rendered colour
        for the member. If the default colour is the one rendered then an instance
        of :meth:`Colour.default` is returned.

        There is an alias for this under ``color``.
        """

        default_colour = Colour.default()
        # highest order of the colour is the one that gets rendered.
        # if the highest is the default colour then the next one with a colour
        # is chosen instead
        if self.roles:
            roles = sorted(self.roles, key=lambda r: r.position, reverse=True)
            for role in roles:
                if role.colour == default_colour:
                    continue
                else:
                    return role.colour

        return default_colour

    color = colour

    @property
    def mention(self):
        """Returns a string that mentions the member."""
        if self.nick:
            return '<@!{}>'.format(self.id)
        return '<@{}>'.format(self.id)

    def mentioned_in(self, message):
        """Checks if the member is mentioned in the specified message.

        Parameters
        -----------
        message: :class:`Message`
            The message to check if you're mentioned in.
        """
        if self._user.mentioned_in(message):
            return True

        for role in message.role_mentions:
            has_role = discord.utils.get(self.roles, id=role.id) is not None
            if has_role:
                return True

        return False

    @property
    def top_role(self):
        """Returns the member's highest role.

        This is useful for figuring where a member stands in the role
        hierarchy chain.
        """

        if self.roles:
            roles = sorted(self.roles, reverse=True)
            return roles[0]
        return None

    @property
    def guild_permissions(self):
        """Returns the member's guild permissions.

        This only takes into consideration the guild permissions
        and not most of the implied permissions or any of the
        channel permission overwrites. For 100% accurate permission
        calculation, please use either :meth:`permissions_in` or
        :meth:`Channel.permissions_for`.

        This does take into consideration guild ownership and the
        administrator implication.
        """

        if self.guild.owner == self:
            return Permissions.all()

        base = Permissions.none()
        for r in self.roles:
            base.value |= r.permissions.value

        if base.administrator:
            return Permissions.all()

        return base

    @property
    def voice(self):
        """Optional[:class:`VoiceState`]: Returns the member's current voice state."""
        return self.guild._voice_state_for(self._user.id)

    @asyncio.coroutine
    def ban(self):
        """|coro|

        Bans this member. Equivalent to :meth:`Guild.ban`
        """
        yield from self.guild.ban(self)

    @asyncio.coroutine
    def unban(self):
        """|coro|

        Unbans this member. Equivalent to :meth:`Guild.unban`
        """
        yield from self.guild.unban(self)

    @asyncio.coroutine
    def kick(self):
        """|coro|

        Kicks this member. Equivalent to :meth:`Guild.kick`
        """
        yield from self.guild.kick(self)

    @asyncio.coroutine
    def edit(self, **fields):
        """|coro|

        Edits the member's data.

        Depending on the parameter passed, this requires different permissions listed below:

        +---------------+--------------------------------------+
        |   Parameter   |              Permission              |
        +---------------+--------------------------------------+
        | nick          | :attr:`Permissions.manage_nicknames` |
        +---------------+--------------------------------------+
        | mute          | :attr:`Permissions.mute_members`     |
        +---------------+--------------------------------------+
        | deafen        | :attr:`Permissions.deafen_members`   |
        +---------------+--------------------------------------+
        | roles         | :attr:`Permissions.manage_roles`     |
        +---------------+--------------------------------------+
        | voice_channel | :attr:`Permissions.move_members`     |
        +---------------+--------------------------------------+

        All parameters are optional.

        Parameters
        -----------
        nick: str
            The member's new nickname. Use ``None`` to remove the nickname.
        mute: bool
            Indicates if the member should be guild muted or un-muted.
        deafen: bool
            Indicates if the member should be guild deafened or un-deafened.
        roles: List[:class:`Roles`]
            The member's new list of roles. This *replaces* the roles.
        voice_channel: :class:`VoiceChannel`
            The voice channel to move the member to.

        Raises
        -------
        Forbidden
            You do not have the proper permissions to the action requested.
        HTTPException
            The operation failed.
        """
        http = self._state.http
        guild_id = self.guild.id
        payload = {}

        try:
            nick = fields['nick']
        except KeyError:
            # nick not present so...
            pass
        else:
            nick = nick if nick else ''
            if self._state.self_id == self.id:
                yield from http.change_my_nickname(guild_id, nick)
            else:
                payload['nick'] = nick

        deafen = fields.get('deafen')
        if deafen is not None:
            payload['deaf'] = deafen

        mute = fields.get('mute')
        if mute is not None:
            payload['mute'] = mute

        try:
            vc = fields['voice_channel']
        except KeyError:
            pass
        else:
            payload['channel_id'] = vc.id

        try:
            roles = fields['roles']
        except KeyError:
            pass
        else:
            payload['roles'] = tuple(r.id for r in roles)

        yield from http.edit_member(guild_id, self.id, **payload)

        # TODO: wait for WS event for modify-in-place behaviour

    @asyncio.coroutine
    def move_to(self, channel):
        """|coro|

        Moves a member to a new voice channel (they must be connected first).

        You must have the :attr:`Permissions.move_members` permission to
        use this.

        This raises the same exceptions as :meth:`edit`.

        Parameters
        -----------
        channel: :class:`VoiceChannel`
            The new voice channel to move the member to.
        """
        yield from self.edit(voice_channel=channel)

    @asyncio.coroutine
    def add_roles(self, *roles):
        """|coro|

        Gives the member a number of :class:`Role`\s.

        You must have the :attr:`Permissions.manage_roles` permission to
        use this.

        Parameters
        -----------
        \*roles
            An argument list of :class:`Role`\s to give the member.

        Raises
        -------
        Forbidden
            You do not have permissions to add these roles.
        HTTPException
            Adding roles failed.
        """

        new_roles = discord.utils._unique(r for s in (self.roles[1:], roles) for r in s)
        yield from self.edit(roles=new_roles)

    @asyncio.coroutine
    def remove_roles(self, *roles):
        """|coro|

        Removes :class:`Role`\s from this member.

        You must have the :attr:`Permissions.manage_roles` permission to
        use this.

        Parameters
        -----------
        \*roles
            An argument list of :class:`Role`\s to remove from the member.

        Raises
        -------
        Forbidden
            You do not have permissions to remove these roles.
        HTTPException
            Removing the roles failed.
        """

        new_roles = self.roles[1:] # remove @everyone
        for role in roles:
            try:
                new_roles.remove(role)
            except ValueError:
                pass

        yield from self.edit(roles=new_roles)