Redesign asset retrieval in the library.

Most assets now return a new class named `Asset`. This allows for the
assets to be consistently saved via a `save` method instead of special
casing for `Attachment`.

`AppInfo` is no longer a namedtuple it is a fully documented dataclass,
as well as having the state attached to it.

Fixes #1997
This commit is contained in:
NCPlayz
2019-03-21 19:59:58 +00:00
committed by Rapptz
parent dea3ba5eb7
commit be227ebcf0
16 changed files with 332 additions and 155 deletions

View File

@ -24,11 +24,10 @@ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from collections import namedtuple
from .asset import Asset
from . import utils
class PartialEmoji(namedtuple('PartialEmoji', 'animated name id')):
class PartialEmoji:
"""Represents a "partial" emoji.
This model will be given in two scenarios:
@ -65,7 +64,19 @@ class PartialEmoji(namedtuple('PartialEmoji', 'animated name id')):
The ID of the custom emoji, if applicable.
"""
__slots__ = ()
__slots__ = ('animated', 'name', 'id', '_state')
def __init__(self, *, animated, name, id=None):
self.animated = animated
self.name = name
self.id = id
self._state = None
@classmethod
def with_state(cls, state, *, animated, name, id=None):
self = cls(animated=animated, name=name, id=id)
self._state = state
return self
def __str__(self):
if self.id is None:
@ -81,6 +92,9 @@ class PartialEmoji(namedtuple('PartialEmoji', 'animated name id')):
if isinstance(other, (PartialEmoji, Emoji)):
return self.id == other.id
def __ne__(self, other):
return not self == other
def __hash__(self):
return hash((self.id, self.name))
@ -99,12 +113,13 @@ class PartialEmoji(namedtuple('PartialEmoji', 'animated name id')):
@property
def url(self):
"""Returns a URL version of the emoji, if it is custom."""
""":class:`Asset`:Returns an asset of the emoji, if it is custom."""
if self.is_unicode_emoji():
return None
return Asset(self._state)
_format = 'gif' if self.animated else 'png'
return "https://cdn.discordapp.com/emojis/{0.id}.{1}".format(self, _format)
url = "https://cdn.discordapp.com/emojis/{0.id}.{1}".format(self, _format)
return Asset(self._state, url)
class Emoji:
"""Represents a custom emoji.
@ -186,6 +201,9 @@ class Emoji:
def __eq__(self, other):
return isinstance(other, (PartialEmoji, Emoji)) and self.id == other.id
def __ne__(self, other):
return not self == other
def __hash__(self):
return self.id >> 22
@ -198,7 +216,8 @@ class Emoji:
def url(self):
"""Returns a URL version of the emoji."""
_format = 'gif' if self.animated else 'png'
return "https://cdn.discordapp.com/emojis/{0.id}.{1}".format(self, _format)
url = "https://cdn.discordapp.com/emojis/{0.id}.{1}".format(self, _format)
return Asset(self._state, url)
@property
def roles(self):