diff --git a/disagreement/models.py b/disagreement/models.py index 0c0c64e..83e06b6 100644 --- a/disagreement/models.py +++ b/disagreement/models.py @@ -2,11 +2,12 @@ Data models for Discord objects. """ -import asyncio -import io -import json -import os -import re +import asyncio +import datetime +import io +import json +import os +import re from dataclasses import dataclass from typing import ( Any, @@ -122,7 +123,8 @@ class Message: self.guild_id: Optional[str] = data.get("guild_id") self.author: User = User(data["author"], client_instance) self.content: str = data["content"] - self.timestamp: str = data["timestamp"] + self.timestamp: str = data["timestamp"] + self.edited_timestamp: Optional[str] = data.get("edited_timestamp") if data.get("components"): self.components: Optional[List[ActionRow]] = [ ActionRow.from_dict(c, client_instance) @@ -147,12 +149,26 @@ class Message: return f"https://discord.com/channels/{guild_or_dm}/{self.channel_id}/{self.id}" @property - def clean_content(self) -> str: - """Returns message content without user, role, or channel mentions.""" - - pattern = re.compile(r"<@!?\d+>|<#\d+>|<@&\d+>") - cleaned = pattern.sub("", self.content) - return " ".join(cleaned.split()) + def clean_content(self) -> str: + """Returns message content without user, role, or channel mentions.""" + + pattern = re.compile(r"<@!?\d+>|<#\d+>|<@&\d+>") + cleaned = pattern.sub("", self.content) + return " ".join(cleaned.split()) + + @property + def created_at(self) -> datetime.datetime: + """Return message timestamp as a :class:`~datetime.datetime`.""" + + return datetime.datetime.fromisoformat(self.timestamp) + + @property + def edited_at(self) -> Optional[datetime.datetime]: + """Return edited timestamp as :class:`~datetime.datetime` if present.""" + + if self.edited_timestamp is None: + return None + return datetime.datetime.fromisoformat(self.edited_timestamp) async def pin(self) -> None: """|coro| diff --git a/tests/test_message_clean_content.py b/tests/test_message_clean_content.py index 83b1b91..e857f99 100644 --- a/tests/test_message_clean_content.py +++ b/tests/test_message_clean_content.py @@ -21,3 +21,19 @@ def test_clean_content_removes_mentions(): def test_clean_content_no_mentions(): msg = make_message("Just text") assert msg.clean_content == "Just text" + + +def test_created_at_parses_timestamp(): + ts = "2024-05-04T12:34:56+00:00" + msg = make_message("hi") + msg.timestamp = ts + assert msg.created_at.isoformat() == ts + + +def test_edited_at_parses_timestamp_or_none(): + ts = "2024-05-04T12:35:56+00:00" + msg = make_message("hi") + msg.timestamp = ts + assert msg.edited_at is None + msg.edited_timestamp = ts + assert msg.edited_at.isoformat() == ts