aboutsummaryrefslogtreecommitdiff
path: root/discord/emoji.py
blob: 7b966c3d70f4570ccc8cf438548285f35c346ba9 (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
# -*- 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
from collections import namedtuple

import discord.utils
from .mixins import Hashable

PartialEmoji = namedtuple('PartialEmoji', 'id name')

class Emoji(Hashable):
    """Represents a custom emoji.

    Depending on the way this object was created, some of the attributes can
    have a value of ``None``.

    Supported Operations:

    +-----------+-----------------------------------------+
    | Operation |               Description               |
    +===========+=========================================+
    | x == y    | Checks if two emoji are the same.       |
    +-----------+-----------------------------------------+
    | x != y    | Checks if two emoji are not the same.   |
    +-----------+-----------------------------------------+
    | hash(x)   | Return the emoji's hash.                |
    +-----------+-----------------------------------------+
    | iter(x)   | Returns an iterator of (field, value)   |
    |           | pairs. This allows this class to be     |
    |           | used as an iterable in list/dict/etc.   |
    |           | constructions.                          |
    +-----------+-----------------------------------------+
    | str(x)    | Returns the emoji rendered for discord. |
    +-----------+-----------------------------------------+

    Attributes
    -----------
    name: str
        The name of the emoji.
    id: int
        The emoji's ID.
    require_colons: bool
        If colons are required to use this emoji in the client (:PJSalt: vs PJSalt).
    managed: bool
        If this emoji is managed by a Twitch integration.
    guild: :class:`Guild`
        The guild the emoji belongs to.
    roles: List[:class:`Role`]
        A list of :class:`Role` that is allowed to use this emoji. If roles is empty,
        the emoji is unrestricted.
    """
    __slots__ = ('require_colons', 'managed', 'id', 'name', 'roles', 'guild', '_state')

    def __init__(self, *, guild, state, data):
        self.guild = guild
        self._state = state
        self._from_data(data)

    def _from_data(self, emoji):
        self.require_colons = emoji['require_colons']
        self.managed = emoji['managed']
        self.id = int(emoji['id'])
        self.name = emoji['name']
        self.roles = emoji.get('roles', [])
        if self.roles:
            roles = set(self.roles)
            self.roles = [role for role in self.guild.roles if role.id in roles]

    def _iterator(self):
        for attr in self.__slots__:
            if attr[0] != '_':
                value = getattr(self, attr, None)
                if value is not None:
                    yield (attr, value)

    def __iter__(self):
        return self._iterator()

    def __str__(self):
        return "<:{0.name}:{0.id}>".format(self)

    @property
    def created_at(self):
        """Returns the emoji's creation time in UTC."""
        return discord.utils.snowflake_time(self.id)

    @property
    def url(self):
        """Returns a URL version of the emoji."""
        return "https://discordapp.com/api/emojis/{0.id}.png".format(self)


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

        Deletes the custom emoji.

        You must have :attr:`Permissions.manage_emojis` permission to
        do this.

        Guild local emotes can only be deleted by user bots.

        Raises
        -------
        Forbidden
            You are not allowed to delete emojis.
        HTTPException
            An error occurred deleting the emoji.
        """

        yield from self._state.http.delete_custom_emoji(self.guild.id, self.id)

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

        Edits the custom emoji.

        You must have :attr:`Permissions.manage_emojis` permission to
        do this.

        Guild local emotes can only be edited by user bots.

        Parameters
        -----------
        name: str
            The new emoji name.

        Raises
        -------
        Forbidden
            You are not allowed to edit emojis.
        HTTPException
            An error occurred editing the emoji.
        """

        yield from self._state.http.edit_custom_emoji(self.guild.id, self.id, name=name)