Code cleanup involving enums and message replies

This commit is contained in:
Rapptz
2020-11-27 00:32:08 -05:00
parent d1cb30cccf
commit bd6ab93348
4 changed files with 80 additions and 101 deletions

View File

@@ -44,7 +44,6 @@ from .utils import escape_mentions
from .guild import Guild
from .mixins import Hashable
from .mentions import AllowedMentions
from .message_reference import _MessageType, MessageReference
from .sticker import Sticker
@@ -213,6 +212,64 @@ class Attachment:
return File(io.BytesIO(data), filename=self.filename, spoiler=spoiler)
class MessageReference:
"""Represents a reference to a :class:`~discord.Message`.
.. versionadded:: 1.5
Attributes
-----------
message_id: Optional[:class:`int`]
The id of the message referenced.
channel_id: :class:`int`
The channel id of the message referenced.
guild_id: Optional[:class:`int`]
The guild id of the message referenced.
"""
__slots__ = ('message_id', 'channel_id', 'guild_id', '_state')
def __init__(self, state, **kwargs):
self.message_id = utils._get_as_snowflake(kwargs, 'message_id')
self.channel_id = int(kwargs.pop('channel_id'))
self.guild_id = utils._get_as_snowflake(kwargs, 'guild_id')
self._state = state
@classmethod
def from_message(cls, message):
"""Creates a :class:`MessageReference` from an existing :class:`~discord.Message`.
.. versionadded:: 1.6
Parameters
----------
message: :class:`~discord.Message`
The message to be converted into a reference.
Returns
-------
:class:`MessageReference`
A reference to the message.
"""
return cls(message._state, message_id=message.id, channel_id=message.channel.id, guild_id=getattr(message.guild, 'id', None))
@property
def cached_message(self):
"""Optional[:class:`~discord.Message`]: The cached message, if found in the internal message cache."""
return self._state._get_message(self.message_id)
def __repr__(self):
return '<MessageReference message_id={0.message_id!r} channel_id={0.channel_id!r} guild_id={0.guild_id!r}>'.format(self)
def to_dict(self):
result = {'message_id': self.message_id} if self.message_id is not None else {}
result['channel_id'] = self.channel_id
if self.guild_id is not None:
result['guild_id'] = self.guild_id
return result
to_message_reference_dict = to_dict
def flatten_handlers(cls):
prefix = len('_handle_')
handlers = [
@@ -230,7 +287,7 @@ def flatten_handlers(cls):
return cls
@flatten_handlers
class Message(Hashable, _MessageType):
class Message(Hashable):
r"""Represents a message from Discord.
There should be no need to create one of these manually.
@@ -1158,3 +1215,14 @@ class Message(Hashable, _MessageType):
"""
return MessageReference.from_message(self)
def to_message_reference_dict(self):
data = {
'message_id': self.id,
'channel_id': self.channel.id,
}
if self.guild is not None:
data['guild_id'] = self.guild.id
return data