Fix code style issues with Black

This commit is contained in:
Lint Action
2021-09-05 21:34:20 +00:00
parent a23dae8604
commit 7513c2138f
108 changed files with 5369 additions and 4858 deletions

View File

@ -29,7 +29,21 @@ import datetime
import re
import io
from os import PathLike
from typing import Dict, TYPE_CHECKING, Union, List, Optional, Any, Callable, Tuple, ClassVar, Optional, overload, TypeVar, Type
from typing import (
Dict,
TYPE_CHECKING,
Union,
List,
Optional,
Any,
Callable,
Tuple,
ClassVar,
Optional,
overload,
TypeVar,
Type,
)
from . import utils
from .reaction import Reaction
@ -76,15 +90,15 @@ if TYPE_CHECKING:
from .role import Role
from .ui.view import View
MR = TypeVar('MR', bound='MessageReference')
MR = TypeVar("MR", bound="MessageReference")
EmojiInputType = Union[Emoji, PartialEmoji, str]
__all__ = (
'Attachment',
'Message',
'PartialMessage',
'MessageReference',
'DeletedReferencedMessage',
"Attachment",
"Message",
"PartialMessage",
"MessageReference",
"DeletedReferencedMessage",
)
@ -93,15 +107,15 @@ def convert_emoji_reaction(emoji):
emoji = emoji.emoji
if isinstance(emoji, Emoji):
return f'{emoji.name}:{emoji.id}'
return f"{emoji.name}:{emoji.id}"
if isinstance(emoji, PartialEmoji):
return emoji._as_reaction()
if isinstance(emoji, str):
# Reactions can be in :name:id format, but not <:name:id>.
# No existing emojis have <> in them, so this should be okay.
return emoji.strip('<>')
return emoji.strip("<>")
raise InvalidArgument(f'emoji argument must be str, Emoji, or Reaction not {emoji.__class__.__name__}.')
raise InvalidArgument(f"emoji argument must be str, Emoji, or Reaction not {emoji.__class__.__name__}.")
class Attachment(Hashable):
@ -157,28 +171,28 @@ class Attachment(Hashable):
.. versionadded:: 1.7
"""
__slots__ = ('id', 'size', 'height', 'width', 'filename', 'url', 'proxy_url', '_http', 'content_type')
__slots__ = ("id", "size", "height", "width", "filename", "url", "proxy_url", "_http", "content_type")
def __init__(self, *, data: AttachmentPayload, state: ConnectionState):
self.id: int = int(data['id'])
self.size: int = data['size']
self.height: Optional[int] = data.get('height')
self.width: Optional[int] = data.get('width')
self.filename: str = data['filename']
self.url: str = data.get('url')
self.proxy_url: str = data.get('proxy_url')
self.id: int = int(data["id"])
self.size: int = data["size"]
self.height: Optional[int] = data.get("height")
self.width: Optional[int] = data.get("width")
self.filename: str = data["filename"]
self.url: str = data.get("url")
self.proxy_url: str = data.get("proxy_url")
self._http = state.http
self.content_type: Optional[str] = data.get('content_type')
self.content_type: Optional[str] = data.get("content_type")
def is_spoiler(self) -> bool:
""":class:`bool`: Whether this attachment contains a spoiler."""
return self.filename.startswith('SPOILER_')
return self.filename.startswith("SPOILER_")
def __repr__(self) -> str:
return f'<Attachment id={self.id} filename={self.filename!r} url={self.url!r}>'
return f"<Attachment id={self.id} filename={self.filename!r} url={self.url!r}>"
def __str__(self) -> str:
return self.url or ''
return self.url or ""
async def save(
self,
@ -227,7 +241,7 @@ class Attachment(Hashable):
fp.seek(0)
return written
else:
with open(fp, 'wb') as f:
with open(fp, "wb") as f:
return f.write(data)
async def read(self, *, use_cached: bool = False) -> bytes:
@ -309,19 +323,19 @@ class Attachment(Hashable):
def to_dict(self) -> AttachmentPayload:
result: AttachmentPayload = {
'filename': self.filename,
'id': self.id,
'proxy_url': self.proxy_url,
'size': self.size,
'url': self.url,
'spoiler': self.is_spoiler(),
"filename": self.filename,
"id": self.id,
"proxy_url": self.proxy_url,
"size": self.size,
"url": self.url,
"spoiler": self.is_spoiler(),
}
if self.height:
result['height'] = self.height
result["height"] = self.height
if self.width:
result['width'] = self.width
result["width"] = self.width
if self.content_type:
result['content_type'] = self.content_type
result["content_type"] = self.content_type
return result
@ -335,7 +349,7 @@ class DeletedReferencedMessage:
.. versionadded:: 1.6
"""
__slots__ = ('_parent',)
__slots__ = ("_parent",)
def __init__(self, parent: MessageReference):
self._parent: MessageReference = parent
@ -347,7 +361,7 @@ class DeletedReferencedMessage:
def id(self) -> int:
""":class:`int`: The message ID of the deleted referenced message."""
# the parent's message id won't be None here
return self._parent.message_id # type: ignore
return self._parent.message_id # type: ignore
@property
def channel_id(self) -> int:
@ -394,9 +408,11 @@ class MessageReference:
.. versionadded:: 1.6
"""
__slots__ = ('message_id', 'channel_id', 'guild_id', 'fail_if_not_exists', 'resolved', '_state')
__slots__ = ("message_id", "channel_id", "guild_id", "fail_if_not_exists", "resolved", "_state")
def __init__(self, *, message_id: int, channel_id: int, guild_id: Optional[int] = None, fail_if_not_exists: bool = True):
def __init__(
self, *, message_id: int, channel_id: int, guild_id: Optional[int] = None, fail_if_not_exists: bool = True
):
self._state: Optional[ConnectionState] = None
self.resolved: Optional[Union[Message, DeletedReferencedMessage]] = None
self.message_id: Optional[int] = message_id
@ -407,10 +423,10 @@ class MessageReference:
@classmethod
def with_state(cls: Type[MR], state: ConnectionState, data: MessageReferencePayload) -> MR:
self = cls.__new__(cls)
self.message_id = utils._get_as_snowflake(data, 'message_id')
self.channel_id = int(data.pop('channel_id'))
self.guild_id = utils._get_as_snowflake(data, 'guild_id')
self.fail_if_not_exists = data.get('fail_if_not_exists', True)
self.message_id = utils._get_as_snowflake(data, "message_id")
self.channel_id = int(data.pop("channel_id"))
self.guild_id = utils._get_as_snowflake(data, "guild_id")
self.fail_if_not_exists = data.get("fail_if_not_exists", True)
self._state = state
self.resolved = None
return self
@ -439,7 +455,7 @@ class MessageReference:
self = cls(
message_id=message.id,
channel_id=message.channel.id,
guild_id=getattr(message.guild, 'id', None),
guild_id=getattr(message.guild, "id", None),
fail_if_not_exists=fail_if_not_exists,
)
self._state = message._state
@ -456,36 +472,36 @@ class MessageReference:
.. versionadded:: 1.7
"""
guild_id = self.guild_id if self.guild_id is not None else '@me'
return f'https://discord.com/channels/{guild_id}/{self.channel_id}/{self.message_id}'
guild_id = self.guild_id if self.guild_id is not None else "@me"
return f"https://discord.com/channels/{guild_id}/{self.channel_id}/{self.message_id}"
def __repr__(self) -> str:
return f'<MessageReference message_id={self.message_id!r} channel_id={self.channel_id!r} guild_id={self.guild_id!r}>'
return f"<MessageReference message_id={self.message_id!r} channel_id={self.channel_id!r} guild_id={self.guild_id!r}>"
def to_dict(self) -> MessageReferencePayload:
result: MessageReferencePayload = {'message_id': self.message_id} if self.message_id is not None else {}
result['channel_id'] = self.channel_id
result: MessageReferencePayload = {"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
result["guild_id"] = self.guild_id
if self.fail_if_not_exists is not None:
result['fail_if_not_exists'] = self.fail_if_not_exists
result["fail_if_not_exists"] = self.fail_if_not_exists
return result
to_message_reference_dict = to_dict
def flatten_handlers(cls):
prefix = len('_handle_')
prefix = len("_handle_")
handlers = [
(key[prefix:], value)
for key, value in cls.__dict__.items()
if key.startswith('_handle_') and key != '_handle_member'
if key.startswith("_handle_") and key != "_handle_member"
]
# store _handle_member last
handlers.append(('member', cls._handle_member))
handlers.append(("member", cls._handle_member))
cls._HANDLERS = handlers
cls._CACHED_SLOTS = [attr for attr in cls.__slots__ if attr.startswith('_cs_')]
cls._CACHED_SLOTS = [attr for attr in cls.__slots__ if attr.startswith("_cs_")]
return cls
@ -615,36 +631,36 @@ class Message(Hashable):
"""
__slots__ = (
'_state',
'_edited_timestamp',
'_cs_channel_mentions',
'_cs_raw_mentions',
'_cs_clean_content',
'_cs_raw_channel_mentions',
'_cs_raw_role_mentions',
'_cs_system_content',
'tts',
'content',
'channel',
'webhook_id',
'mention_everyone',
'embeds',
'id',
'mentions',
'author',
'attachments',
'nonce',
'pinned',
'role_mentions',
'type',
'flags',
'reactions',
'reference',
'application',
'activity',
'stickers',
'components',
'guild',
"_state",
"_edited_timestamp",
"_cs_channel_mentions",
"_cs_raw_mentions",
"_cs_clean_content",
"_cs_raw_channel_mentions",
"_cs_raw_role_mentions",
"_cs_system_content",
"tts",
"content",
"channel",
"webhook_id",
"mention_everyone",
"embeds",
"id",
"mentions",
"author",
"attachments",
"nonce",
"pinned",
"role_mentions",
"type",
"flags",
"reactions",
"reference",
"application",
"activity",
"stickers",
"components",
"guild",
)
if TYPE_CHECKING:
@ -664,39 +680,39 @@ class Message(Hashable):
data: MessagePayload,
):
self._state: ConnectionState = state
self.id: int = int(data['id'])
self.webhook_id: Optional[int] = utils._get_as_snowflake(data, 'webhook_id')
self.reactions: List[Reaction] = [Reaction(message=self, data=d) for d in data.get('reactions', [])]
self.attachments: List[Attachment] = [Attachment(data=a, state=self._state) for a in data['attachments']]
self.embeds: List[Embed] = [Embed.from_dict(a) for a in data['embeds']]
self.application: Optional[MessageApplicationPayload] = data.get('application')
self.activity: Optional[MessageActivityPayload] = data.get('activity')
self.id: int = int(data["id"])
self.webhook_id: Optional[int] = utils._get_as_snowflake(data, "webhook_id")
self.reactions: List[Reaction] = [Reaction(message=self, data=d) for d in data.get("reactions", [])]
self.attachments: List[Attachment] = [Attachment(data=a, state=self._state) for a in data["attachments"]]
self.embeds: List[Embed] = [Embed.from_dict(a) for a in data["embeds"]]
self.application: Optional[MessageApplicationPayload] = data.get("application")
self.activity: Optional[MessageActivityPayload] = data.get("activity")
self.channel: MessageableChannel = channel
self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(data['edited_timestamp'])
self.type: MessageType = try_enum(MessageType, data['type'])
self.pinned: bool = data['pinned']
self.flags: MessageFlags = MessageFlags._from_value(data.get('flags', 0))
self.mention_everyone: bool = data['mention_everyone']
self.tts: bool = data['tts']
self.content: str = data['content']
self.nonce: Optional[Union[int, str]] = data.get('nonce')
self.stickers: List[StickerItem] = [StickerItem(data=d, state=state) for d in data.get('sticker_items', [])]
self.components: List[Component] = [_component_factory(d) for d in data.get('components', [])]
self._edited_timestamp: Optional[datetime.datetime] = utils.parse_time(data["edited_timestamp"])
self.type: MessageType = try_enum(MessageType, data["type"])
self.pinned: bool = data["pinned"]
self.flags: MessageFlags = MessageFlags._from_value(data.get("flags", 0))
self.mention_everyone: bool = data["mention_everyone"]
self.tts: bool = data["tts"]
self.content: str = data["content"]
self.nonce: Optional[Union[int, str]] = data.get("nonce")
self.stickers: List[StickerItem] = [StickerItem(data=d, state=state) for d in data.get("sticker_items", [])]
self.components: List[Component] = [_component_factory(d) for d in data.get("components", [])]
try:
# if the channel doesn't have a guild attribute, we handle that
self.guild = channel.guild # type: ignore
except AttributeError:
self.guild = state._get_guild(utils._get_as_snowflake(data, 'guild_id'))
self.guild = state._get_guild(utils._get_as_snowflake(data, "guild_id"))
try:
ref = data['message_reference']
ref = data["message_reference"]
except KeyError:
self.reference = None
else:
self.reference = ref = MessageReference.with_state(state, ref)
try:
resolved = data['referenced_message']
resolved = data["referenced_message"]
except KeyError:
pass
else:
@ -712,18 +728,15 @@ class Message(Hashable):
# the channel will be the correct type here
ref.resolved = self.__class__(channel=chan, data=resolved, state=state) # type: ignore
for handler in ('author', 'member', 'mentions', 'mention_roles'):
for handler in ("author", "member", "mentions", "mention_roles"):
try:
getattr(self, f'_handle_{handler}')(data[handler])
getattr(self, f"_handle_{handler}")(data[handler])
except KeyError:
continue
def __repr__(self) -> str:
name = self.__class__.__name__
return (
f'<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>'
)
return f"<{name} id={self.id} channel={self.channel!r} type={self.type!r} author={self.author!r} flags={self.flags!r}>"
def __str__(self) -> Optional[str]:
return self.content
@ -741,7 +754,7 @@ class Message(Hashable):
def _add_reaction(self, data, emoji, user_id) -> Reaction:
reaction = utils.find(lambda r: r.emoji == emoji, self.reactions)
is_me = data['me'] = user_id == self._state.self_id
is_me = data["me"] = user_id == self._state.self_id
if reaction is None:
reaction = Reaction(message=self, data=data, emoji=emoji)
@ -758,7 +771,7 @@ class Message(Hashable):
if reaction is None:
# already removed?
raise ValueError('Emoji already removed?')
raise ValueError("Emoji already removed?")
# if reaction isn't in the list, we crash. This means discord
# sent bad data, or we stored improperly
@ -872,7 +885,7 @@ class Message(Hashable):
return
for mention in filter(None, mentions):
id_search = int(mention['id'])
id_search = int(mention["id"])
member = guild.get_member(id_search)
if member is not None:
r.append(member)
@ -894,7 +907,7 @@ class Message(Hashable):
self.guild = new_guild
self.channel = new_channel
@utils.cached_slot_property('_cs_raw_mentions')
@utils.cached_slot_property("_cs_raw_mentions")
def raw_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of user IDs matched with
the syntax of ``<@user_id>`` in the message content.
@ -902,30 +915,30 @@ class Message(Hashable):
This allows you to receive the user IDs of mentioned users
even in a private message context.
"""
return [int(x) for x in re.findall(r'<@!?([0-9]{15,20})>', self.content)]
return [int(x) for x in re.findall(r"<@!?([0-9]{15,20})>", self.content)]
@utils.cached_slot_property('_cs_raw_channel_mentions')
@utils.cached_slot_property("_cs_raw_channel_mentions")
def raw_channel_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of channel IDs matched with
the syntax of ``<#channel_id>`` in the message content.
"""
return [int(x) for x in re.findall(r'<#([0-9]{15,20})>', self.content)]
return [int(x) for x in re.findall(r"<#([0-9]{15,20})>", self.content)]
@utils.cached_slot_property('_cs_raw_role_mentions')
@utils.cached_slot_property("_cs_raw_role_mentions")
def raw_role_mentions(self) -> List[int]:
"""List[:class:`int`]: A property that returns an array of role IDs matched with
the syntax of ``<@&role_id>`` in the message content.
"""
return [int(x) for x in re.findall(r'<@&([0-9]{15,20})>', self.content)]
return [int(x) for x in re.findall(r"<@&([0-9]{15,20})>", self.content)]
@utils.cached_slot_property('_cs_channel_mentions')
@utils.cached_slot_property("_cs_channel_mentions")
def channel_mentions(self) -> List[GuildChannel]:
if self.guild is None:
return []
it = filter(None, map(self.guild.get_channel, self.raw_channel_mentions))
return utils._unique(it)
@utils.cached_slot_property('_cs_clean_content')
@utils.cached_slot_property("_cs_clean_content")
def clean_content(self) -> str:
""":class:`str`: A property that returns the content in a "cleaned up"
manner. This basically means that mentions are transformed
@ -972,9 +985,9 @@ class Message(Hashable):
# fmt: on
def repl(obj):
return transformations.get(re.escape(obj.group(0)), '')
return transformations.get(re.escape(obj.group(0)), "")
pattern = re.compile('|'.join(transformations.keys()))
pattern = re.compile("|".join(transformations.keys()))
result = pattern.sub(repl, self.content)
return escape_mentions(result)
@ -991,8 +1004,8 @@ class Message(Hashable):
@property
def jump_url(self) -> str:
""":class:`str`: Returns a URL that allows the client to jump to this message."""
guild_id = getattr(self.guild, 'id', '@me')
return f'https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}'
guild_id = getattr(self.guild, "id", "@me")
return f"https://discord.com/channels/{guild_id}/{self.channel.id}/{self.id}"
def is_system(self) -> bool:
""":class:`bool`: Whether the message is a system message.
@ -1009,7 +1022,7 @@ class Message(Hashable):
MessageType.thread_starter_message,
)
@utils.cached_slot_property('_cs_system_content')
@utils.cached_slot_property("_cs_system_content")
def system_content(self):
r""":class:`str`: A property that returns the content that is rendered
regardless of the :attr:`Message.type`.
@ -1024,24 +1037,24 @@ class Message(Hashable):
if self.type is MessageType.recipient_add:
if self.channel.type is ChannelType.group:
return f'{self.author.name} added {self.mentions[0].name} to the group.'
return f"{self.author.name} added {self.mentions[0].name} to the group."
else:
return f'{self.author.name} added {self.mentions[0].name} to the thread.'
return f"{self.author.name} added {self.mentions[0].name} to the thread."
if self.type is MessageType.recipient_remove:
if self.channel.type is ChannelType.group:
return f'{self.author.name} removed {self.mentions[0].name} from the group.'
return f"{self.author.name} removed {self.mentions[0].name} from the group."
else:
return f'{self.author.name} removed {self.mentions[0].name} from the thread.'
return f"{self.author.name} removed {self.mentions[0].name} from the thread."
if self.type is MessageType.channel_name_change:
return f'{self.author.name} changed the channel name: **{self.content}**'
return f"{self.author.name} changed the channel name: **{self.content}**"
if self.type is MessageType.channel_icon_change:
return f'{self.author.name} changed the channel icon.'
return f"{self.author.name} changed the channel icon."
if self.type is MessageType.pins_add:
return f'{self.author.name} pinned a message to this channel.'
return f"{self.author.name} pinned a message to this channel."
if self.type is MessageType.new_member:
formats = [
@ -1065,62 +1078,62 @@ class Message(Hashable):
if self.type is MessageType.premium_guild_subscription:
if not self.content:
return f'{self.author.name} just boosted the server!'
return f"{self.author.name} just boosted the server!"
else:
return f'{self.author.name} just boosted the server **{self.content}** times!'
return f"{self.author.name} just boosted the server **{self.content}** times!"
if self.type is MessageType.premium_guild_tier_1:
if not self.content:
return f'{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**'
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 1!**"
else:
return f'{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**'
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 1!**"
if self.type is MessageType.premium_guild_tier_2:
if not self.content:
return f'{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**'
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 2!**"
else:
return f'{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**'
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 2!**"
if self.type is MessageType.premium_guild_tier_3:
if not self.content:
return f'{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**'
return f"{self.author.name} just boosted the server! {self.guild} has achieved **Level 3!**"
else:
return f'{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**'
return f"{self.author.name} just boosted the server **{self.content}** times! {self.guild} has achieved **Level 3!**"
if self.type is MessageType.channel_follow_add:
return f'{self.author.name} has added {self.content} to this channel'
return f"{self.author.name} has added {self.content} to this channel"
if self.type is MessageType.guild_stream:
# the author will be a Member
return f'{self.author.name} is live! Now streaming {self.author.activity.name}' # type: ignore
return f"{self.author.name} is live! Now streaming {self.author.activity.name}" # type: ignore
if self.type is MessageType.guild_discovery_disqualified:
return 'This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details.'
return "This server has been removed from Server Discovery because it no longer passes all the requirements. Check Server Settings for more details."
if self.type is MessageType.guild_discovery_requalified:
return 'This server is eligible for Server Discovery again and has been automatically relisted!'
return "This server is eligible for Server Discovery again and has been automatically relisted!"
if self.type is MessageType.guild_discovery_grace_period_initial_warning:
return 'This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery.'
return "This server has failed Discovery activity requirements for 1 week. If this server fails for 4 weeks in a row, it will be automatically removed from Discovery."
if self.type is MessageType.guild_discovery_grace_period_final_warning:
return 'This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery.'
return "This server has failed Discovery activity requirements for 3 weeks in a row. If this server fails for 1 more week, it will be removed from Discovery."
if self.type is MessageType.thread_created:
return f'{self.author.name} started a thread: **{self.content}**. See all **threads**.'
return f"{self.author.name} started a thread: **{self.content}**. See all **threads**."
if self.type is MessageType.reply:
return self.content
if self.type is MessageType.thread_starter_message:
if self.reference is None or self.reference.resolved is None:
return 'Sorry, we couldn\'t load the first message in this thread'
return "Sorry, we couldn't load the first message in this thread"
# the resolved message for the reference will be a Message
return self.reference.resolved.content # type: ignore
if self.type is MessageType.guild_invite_reminder:
return 'Wondering who to invite?\nStart by inviting anyone who can help you build the server!'
return "Wondering who to invite?\nStart by inviting anyone who can help you build the server!"
async def delete(self, *, delay: Optional[float] = None, silent: bool = False) -> None:
"""|coro|
@ -1271,45 +1284,45 @@ class Message(Hashable):
payload: Dict[str, Any] = {}
if content is not MISSING:
if content is not None:
payload['content'] = str(content)
payload["content"] = str(content)
else:
payload['content'] = None
payload["content"] = None
if embed is not MISSING and embeds is not MISSING:
raise InvalidArgument('cannot pass both embed and embeds parameter to edit()')
raise InvalidArgument("cannot pass both embed and embeds parameter to edit()")
if embed is not MISSING:
if embed is None:
payload['embeds'] = []
payload["embeds"] = []
else:
payload['embeds'] = [embed.to_dict()]
payload["embeds"] = [embed.to_dict()]
elif embeds is not MISSING:
payload['embeds'] = [e.to_dict() for e in embeds]
payload["embeds"] = [e.to_dict() for e in embeds]
if suppress is not MISSING:
flags = MessageFlags._from_value(self.flags.value)
flags.suppress_embeds = suppress
payload['flags'] = flags.value
payload["flags"] = flags.value
if allowed_mentions is MISSING:
if self._state.allowed_mentions is not None and self.author.id == self._state.self_id:
payload['allowed_mentions'] = self._state.allowed_mentions.to_dict()
payload["allowed_mentions"] = self._state.allowed_mentions.to_dict()
else:
if allowed_mentions is not None:
if self._state.allowed_mentions is not None:
payload['allowed_mentions'] = self._state.allowed_mentions.merge(allowed_mentions).to_dict()
payload["allowed_mentions"] = self._state.allowed_mentions.merge(allowed_mentions).to_dict()
else:
payload['allowed_mentions'] = allowed_mentions.to_dict()
payload["allowed_mentions"] = allowed_mentions.to_dict()
if attachments is not MISSING:
payload['attachments'] = [a.to_dict() for a in attachments]
payload["attachments"] = [a.to_dict() for a in attachments]
if view is not MISSING:
self._state.prevent_view_updates_for(self.id)
if view:
payload['components'] = view.to_components()
payload["components"] = view.to_components()
else:
payload['components'] = []
payload["components"] = []
data = await self._state.http.edit_message(self.channel.id, self.id, **payload)
message = Message(state=self._state, channel=self.channel, data=data)
@ -1551,9 +1564,11 @@ class Message(Hashable):
The created thread.
"""
if self.guild is None:
raise InvalidArgument('This message does not have guild info attached.')
raise InvalidArgument("This message does not have guild info attached.")
default_auto_archive_duration: ThreadArchiveDuration = getattr(self.channel, 'default_auto_archive_duration', 1440)
default_auto_archive_duration: ThreadArchiveDuration = getattr(
self.channel, "default_auto_archive_duration", 1440
)
data = await self._state.http.start_thread_with_message(
self.channel.id,
self.id,
@ -1611,12 +1626,12 @@ class Message(Hashable):
def to_message_reference_dict(self) -> MessageReferencePayload:
data: MessageReferencePayload = {
'message_id': self.id,
'channel_id': self.channel.id,
"message_id": self.id,
"channel_id": self.channel.id,
}
if self.guild is not None:
data['guild_id'] = self.guild.id
data["guild_id"] = self.guild.id
return data
@ -1662,7 +1677,7 @@ class PartialMessage(Hashable):
The message ID.
"""
__slots__ = ('channel', 'id', '_cs_guild', '_state')
__slots__ = ("channel", "id", "_cs_guild", "_state")
jump_url: str = Message.jump_url # type: ignore
delete = Message.delete
@ -1686,7 +1701,7 @@ class PartialMessage(Hashable):
ChannelType.public_thread,
ChannelType.private_thread,
):
raise TypeError(f'Expected TextChannel, DMChannel or Thread not {type(channel)!r}')
raise TypeError(f"Expected TextChannel, DMChannel or Thread not {type(channel)!r}")
self.channel: PartialMessageableChannel = channel
self._state: ConnectionState = channel._state
@ -1702,17 +1717,17 @@ class PartialMessage(Hashable):
pinned = property(None, lambda x, y: None)
def __repr__(self) -> str:
return f'<PartialMessage id={self.id} channel={self.channel!r}>'
return f"<PartialMessage id={self.id} channel={self.channel!r}>"
@property
def created_at(self) -> datetime.datetime:
""":class:`datetime.datetime`: The partial message's creation time in UTC."""
return utils.snowflake_time(self.id)
@utils.cached_slot_property('_cs_guild')
@utils.cached_slot_property("_cs_guild")
def guild(self) -> Optional[Guild]:
"""Optional[:class:`Guild`]: The guild that the partial message belongs to, if applicable."""
return getattr(self.channel, 'guild', None)
return getattr(self.channel, "guild", None)
async def fetch(self) -> Message:
"""|coro|
@ -1794,34 +1809,34 @@ class PartialMessage(Hashable):
"""
try:
content = fields['content']
content = fields["content"]
except KeyError:
pass
else:
if content is not None:
fields['content'] = str(content)
fields["content"] = str(content)
try:
embed = fields['embed']
embed = fields["embed"]
except KeyError:
pass
else:
if embed is not None:
fields['embed'] = embed.to_dict()
fields["embed"] = embed.to_dict()
try:
suppress: bool = fields.pop('suppress')
suppress: bool = fields.pop("suppress")
except KeyError:
pass
else:
flags = MessageFlags._from_value(0)
flags.suppress_embeds = suppress
fields['flags'] = flags.value
fields["flags"] = flags.value
delete_after = fields.pop('delete_after', None)
delete_after = fields.pop("delete_after", None)
try:
allowed_mentions = fields.pop('allowed_mentions')
allowed_mentions = fields.pop("allowed_mentions")
except KeyError:
pass
else:
@ -1830,19 +1845,19 @@ class PartialMessage(Hashable):
allowed_mentions = self._state.allowed_mentions.merge(allowed_mentions).to_dict()
else:
allowed_mentions = allowed_mentions.to_dict()
fields['allowed_mentions'] = allowed_mentions
fields["allowed_mentions"] = allowed_mentions
try:
view = fields.pop('view')
view = fields.pop("view")
except KeyError:
# To check for the view afterwards
view = None
else:
self._state.prevent_view_updates_for(self.id)
if view:
fields['components'] = view.to_components()
fields["components"] = view.to_components()
else:
fields['components'] = []
fields["components"] = []
if fields:
data = await self._state.http.edit_message(self.channel.id, self.id, **fields)