diff --git a/changelog/1118.feature.rst b/changelog/1118.feature.rst new file mode 100644 index 0000000000..ce4dcb3a05 --- /dev/null +++ b/changelog/1118.feature.rst @@ -0,0 +1 @@ +Add :attr:`.Attachment.expires_at` and :attr:`.Attachment.is_expired` properties to :class:`.Attachment`. diff --git a/disnake/message.py b/disnake/message.py index 21f59e269e..5620a1b349 100644 --- a/disnake/message.py +++ b/disnake/message.py @@ -21,6 +21,7 @@ cast, overload, ) +from urllib.parse import parse_qs, urlparse from . import utils from .components import ActionRow, MessageComponent, _component_factory @@ -302,6 +303,7 @@ class Attachment(Hashable): "description", "duration", "waveform", + "_ex", "_flags", ) @@ -321,8 +323,33 @@ def __init__(self, *, data: AttachmentPayload, state: ConnectionState) -> None: self.waveform: Optional[bytes] = ( b64decode(waveform_data) if (waveform_data := data.get("waveform")) else None ) + _params = urlparse(self.url) + self._ex = parse_qs(_params.query).get("ex") self._flags: int = data.get("flags", 0) + def expires_at(self) -> Optional[datetime.datetime]: + """The date when this attachment will expire. + ``None`` if the ``ex`` param is not present in :attr:`.Attachment.url`. + + :return type: Optional[:class:`datetime.datetime`] + """ + if not self._ex: + return + + timestamp = int(self._ex[0], 16) + return datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc) + + def is_expired(self) -> bool: + """Whether this attachment expired or not. + + :return type: :class:`bool` + """ + ex = self.expires_at() + if not ex: + return False + + return utils.utcnow() >= ex + def is_spoiler(self) -> bool: """Whether this attachment contains a spoiler.