Add timestamp datetime properties (#96)

This commit is contained in:
Slipstream 2025-06-15 18:50:03 -06:00 committed by GitHub
parent 2008dd33d1
commit 9c10ab0f70
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 44 additions and 12 deletions

View File

@ -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|

View File

@ -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