Skip to content
This repository was archived by the owner on Oct 2, 2023. It is now read-only.

Commit 2c1acfa

Browse files
committed
Made all datetime objects timezone aware
1 parent 6c5ccf4 commit 2c1acfa

File tree

16 files changed

+99
-88
lines changed

16 files changed

+99
-88
lines changed

general/polls/cog.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
import re
22
import string
3-
from datetime import datetime
43
from typing import Optional, Tuple
54

65
from discord import Embed, Message, PartialEmoji, Member, Forbidden, Guild
76
from discord.ext import commands
87
from discord.ext.commands import Context, guild_only, CommandError
8+
from discord.utils import utcnow
99

1010
from PyDrocsid.cog import Cog
1111
from PyDrocsid.embeds import EmbedLimits
@@ -53,7 +53,7 @@ async def send_poll(
5353
if any(len(str(option)) > EmbedLimits.FIELD_VALUE for option in options):
5454
raise CommandError(t.option_too_long(EmbedLimits.FIELD_VALUE))
5555

56-
embed = Embed(title=title, description=question, color=Colors.Polls, timestamp=datetime.utcnow())
56+
embed = Embed(title=title, description=question, color=Colors.Polls, timestamp=utcnow())
5757
embed.set_author(name=str(ctx.author), icon_url=ctx.author.avatar_url)
5858
if allow_delete:
5959
embed.set_footer(text=t.created_by(ctx.author, ctx.author.id), icon_url=ctx.author.avatar_url)
@@ -216,7 +216,7 @@ async def team_yesno(self, ctx: Context, *, text: str):
216216
Starts a yes/no poll and shows, which teamler has not voted yet.
217217
"""
218218

219-
embed = Embed(title=t.team_poll, description=text, color=Colors.Polls, timestamp=datetime.utcnow())
219+
embed = Embed(title=t.team_poll, description=text, color=Colors.Polls, timestamp=utcnow())
220220
embed.set_author(name=str(ctx.author), icon_url=ctx.author.avatar_url)
221221

222222
embed.add_field(name=tg.status, value=await self.get_reacted_teamlers(), inline=False)

general/voice_channel/cog.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import asyncio
22
import random
3-
from datetime import datetime
43
from os import getenv
54
from pathlib import Path
65
from typing import Optional, Union
@@ -25,6 +24,7 @@
2524
from discord.abc import Messageable
2625
from discord.ext import commands, tasks
2726
from discord.ext.commands import guild_only, Context, UserInputError, CommandError, Greedy
27+
from discord.utils import utcnow
2828

2929
from PyDrocsid.async_thread import gather_any, GatherAnyException
3030
from PyDrocsid.cog import Cog
@@ -213,7 +213,7 @@ def prepare(self) -> bool:
213213
return bool(self.names)
214214

215215
def _get_name_list(self, guild_id: int) -> str:
216-
r = random.Random(f"{guild_id}{datetime.utcnow().date().isoformat()}")
216+
r = random.Random(f"{guild_id}{utcnow().date().isoformat()}")
217217
return r.choice(sorted(self.names))
218218

219219
def _random_channel_name(self, guild_id: int, avoid: set[str]) -> Optional[str]:
@@ -277,7 +277,7 @@ async def send_voice_msg(self, channel: DynChannel, title: str, msg: str, force_
277277
text_channel,
278278
title,
279279
"",
280-
datetime.utcnow().strftime("%d.%m.%Y %H:%M:%S"),
280+
utcnow().strftime("%d.%m.%Y %H:%M:%S"),
281281
msg,
282282
colour=color,
283283
force_new_embed=force_new_embed,

general/voice_channel/models.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,11 @@
44
from typing import Union, Optional
55
from uuid import uuid4
66

7-
from sqlalchemy import Column, BigInteger, Boolean, DateTime, ForeignKey, String
7+
from discord.utils import utcnow
8+
from sqlalchemy import Column, BigInteger, Boolean, ForeignKey, String
89
from sqlalchemy.orm import relationship
910

10-
from PyDrocsid.database import db
11+
from PyDrocsid.database import db, UTCDateTime
1112

1213

1314
class DynGroup(db.Base):
@@ -65,15 +66,15 @@ class DynChannelMember(db.Base):
6566
member_id: Union[Column, int] = Column(BigInteger)
6667
channel_id: Union[Column, int] = Column(BigInteger, ForeignKey("dynvoice_channel.channel_id"))
6768
channel: DynChannel = relationship("DynChannel", back_populates="members")
68-
timestamp: Union[Column, datetime] = Column(DateTime)
69+
timestamp: Union[Column, datetime] = Column(UTCDateTime)
6970

7071
@staticmethod
7172
async def create(member_id: int, channel_id: int) -> DynChannelMember:
7273
member = DynChannelMember(
7374
id=str(uuid4()),
7475
member_id=member_id,
7576
channel_id=channel_id,
76-
timestamp=datetime.utcnow(),
77+
timestamp=utcnow(),
7778
)
7879
await db.add(member)
7980
return member

information/heartbeat/cog.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
from datetime import datetime
21
from typing import Optional
32

43
from discord import User, Forbidden
54
from discord.ext import tasks
5+
from discord.utils import utcnow
66

77
from PyDrocsid.cog import Cog
88
from PyDrocsid.config import Config
@@ -36,7 +36,7 @@ async def status_loop(self):
3636
t.online_status,
3737
t.status_description(Config.NAME, Config.VERSION),
3838
t.heartbeat,
39-
datetime.utcnow().strftime("%d.%m.%Y %H:%M:%S UTC"),
39+
utcnow().strftime("%d.%m.%Y %H:%M:%S UTC"),
4040
)
4141
except Forbidden:
4242
pass
@@ -49,7 +49,7 @@ async def on_ready(self):
4949
t.online_status,
5050
t.status_description(Config.NAME, Config.VERSION),
5151
t.logged_in,
52-
datetime.utcnow().strftime("%d.%m.%Y %H:%M:%S UTC"),
52+
utcnow().strftime("%d.%m.%Y %H:%M:%S UTC"),
5353
force_resend=True,
5454
force_new_embed=not self.initialized,
5555
)

information/inactivity/cog.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
from PyDrocsid.database import db, db_wrapper
1414
from PyDrocsid.embeds import send_long_embed
1515
from PyDrocsid.translations import t
16+
from discord.utils import utcnow
17+
1618
from .models import Activity
1719
from .permissions import InactivityPermission
1820
from .settings import InactivitySettings
@@ -35,15 +37,15 @@ def status_icon(status: Status) -> str:
3537
async def scan(ctx: Context, days: int):
3638
async def update_msg(m: Message, content):
3739
embed.description = content
38-
embed.timestamp = datetime.utcnow()
40+
embed.timestamp = utcnow()
3941
await ignore_message_edit(m)
4042
try:
4143
await m.edit(embed=embed)
4244
except NotFound:
4345
return await reply(ctx, embed=embed)
4446
return m
4547

46-
embed = Embed(title=t.scanning, timestamp=datetime.utcnow())
48+
embed = Embed(title=t.scanning, timestamp=utcnow())
4749
message: list[Message] = [await reply(ctx, embed=embed)]
4850
guild: Guild = ctx.guild
4951
members: dict[Member, datetime] = {}
@@ -54,7 +56,7 @@ async def update_progress_message():
5456
while len(completed) < len(channels):
5557
content = t.scanning_channel(len(completed), len(channels), cnt=len(active))
5658
for a, d in active.items():
57-
channel_age = (datetime.utcnow() - a.created_at).days
59+
channel_age = (utcnow() - a.created_at).days
5860
content += f"\n:small_orange_diamond: {a.mention} ({d} / {min(channel_age, days)})"
5961
message[0] = await update_msg(message[0], content)
6062
await asyncio.sleep(2)
@@ -63,7 +65,7 @@ async def update_members(c: TextChannel):
6365
active[c] = 0
6466

6567
async for msg in c.history(limit=None, oldest_first=False):
66-
s = (datetime.utcnow() - msg.created_at).total_seconds()
68+
s = (utcnow() - msg.created_at).total_seconds()
6769
if s > days * 24 * 60 * 60:
6870
break
6971
members[msg.author] = max(members.get(msg.author, msg.created_at), msg.created_at)
@@ -129,7 +131,7 @@ async def handle_get_user_status_entries(self, user_id) -> list[tuple[str, str]]
129131

130132
if activity is None:
131133
status = t.status.inactive
132-
elif (days := (datetime.utcnow() - activity.timestamp).days) >= inactive_days:
134+
elif (days := (utcnow() - activity.timestamp).days) >= inactive_days:
133135
status = t.status.inactive_since(activity.timestamp.strftime("%d.%m.%Y %H:%M:%S"))
134136
else:
135137
status = t.status.active(cnt=days)
@@ -153,7 +155,7 @@ async def inactive(self, ctx: Context, days: Optional[int], *roles: Optional[Rol
153155
elif days not in range(1, 10001):
154156
raise CommandError(tg.invalid_duration)
155157

156-
now = datetime.utcnow()
158+
now = utcnow()
157159

158160
@db_wrapper
159161
async def load_member(m: Member) -> tuple[Member, Optional[datetime]]:

information/inactivity/models.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,15 @@
33
from datetime import datetime
44
from typing import Union
55

6-
from PyDrocsid.database import db, db_wrapper
7-
from sqlalchemy import Column, BigInteger, DateTime
6+
from PyDrocsid.database import db, db_wrapper, UTCDateTime
7+
from sqlalchemy import Column, BigInteger
88

99

1010
class Activity(db.Base):
1111
__tablename__ = "activity"
1212

1313
id: Union[Column, int] = Column(BigInteger, primary_key=True, unique=True)
14-
timestamp: Union[Column, datetime] = Column(DateTime)
14+
timestamp: Union[Column, datetime] = Column(UTCDateTime)
1515

1616
@staticmethod
1717
async def create(object_id: int, timestamp: datetime) -> Activity:

information/user_info/models.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,24 @@
33
from datetime import datetime, timedelta
44
from typing import Union, Optional
55

6-
from sqlalchemy import Column, Integer, BigInteger, DateTime, Text, Boolean
6+
from discord.utils import utcnow
7+
from sqlalchemy import Column, Integer, BigInteger, Text, Boolean
78

8-
from PyDrocsid.database import db, filter_by
9+
from PyDrocsid.database import db, filter_by, UTCDateTime
910

1011

1112
class Join(db.Base):
1213
__tablename__ = "join"
1314
id: Union[Column, int] = Column(Integer, primary_key=True, unique=True, autoincrement=True)
1415
member: Union[Column, int] = Column(BigInteger)
1516
member_name: Union[Column, str] = Column(Text(collation="utf8mb4_bin"))
16-
timestamp: Union[Column, datetime] = Column(DateTime)
17+
timestamp: Union[Column, datetime] = Column(UTCDateTime)
1718
join_msg_channel_id: Union[Column, int] = Column(BigInteger, nullable=True)
1819
join_msg_id: Union[Column, int] = Column(BigInteger, nullable=True)
1920

2021
@staticmethod
2122
async def create(member: int, member_name: str, timestamp: Optional[datetime] = None) -> Join:
22-
row = Join(member=member, member_name=member_name, timestamp=timestamp or datetime.utcnow())
23+
row = Join(member=member, member_name=member_name, timestamp=timestamp or utcnow())
2324
await db.add(row)
2425
await db.session.flush()
2526
return row
@@ -37,11 +38,11 @@ class Leave(db.Base):
3738
id: Union[Column, int] = Column(Integer, primary_key=True, unique=True, autoincrement=True)
3839
member: Union[Column, int] = Column(BigInteger)
3940
member_name: Union[Column, str] = Column(Text(collation="utf8mb4_bin"))
40-
timestamp: Union[Column, datetime] = Column(DateTime)
41+
timestamp: Union[Column, datetime] = Column(UTCDateTime)
4142

4243
@staticmethod
4344
async def create(member: int, member_name: str) -> Leave:
44-
row = Leave(member=member, member_name=member_name, timestamp=datetime.utcnow())
45+
row = Leave(member=member, member_name=member_name, timestamp=utcnow())
4546
await db.add(row)
4647
return row
4748

@@ -54,7 +55,7 @@ class UsernameUpdate(db.Base):
5455
member_name: Union[Column, str] = Column(Text(collation="utf8mb4_bin"))
5556
new_name: Union[Column, str] = Column(Text(collation="utf8mb4_bin"))
5657
nick: Union[Column, bool] = Column(Boolean)
57-
timestamp: Union[Column, datetime] = Column(DateTime)
58+
timestamp: Union[Column, datetime] = Column(UTCDateTime)
5859

5960
@staticmethod
6061
async def create(member: int, member_name: str, new_name: str, nick: bool) -> UsernameUpdate:
@@ -63,7 +64,7 @@ async def create(member: int, member_name: str, new_name: str, nick: bool) -> Us
6364
member_name=member_name,
6465
new_name=new_name,
6566
nick=nick,
66-
timestamp=datetime.utcnow(),
67+
timestamp=utcnow(),
6768
)
6869
await db.add(row)
6970
return row
@@ -76,10 +77,10 @@ class Verification(db.Base):
7677
member: Union[Column, int] = Column(BigInteger)
7778
member_name: Union[Column, str] = Column(Text(collation="utf8mb4_bin"))
7879
accepted: Union[Column, bool] = Column(Boolean)
79-
timestamp: Union[Column, datetime] = Column(DateTime)
80+
timestamp: Union[Column, datetime] = Column(UTCDateTime)
8081

8182
@staticmethod
8283
async def create(member: int, member_name: str, accepted: bool) -> Verification:
83-
row = Verification(member=member, member_name=member_name, accepted=accepted, timestamp=datetime.utcnow())
84+
row = Verification(member=member, member_name=member_name, accepted=accepted, timestamp=utcnow())
8485
await db.add(row)
8586
return row

integrations/reddit/models.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
from datetime import datetime, timedelta
44
from typing import Union
55

6-
from sqlalchemy import Column, String, BigInteger, DateTime
6+
from discord.utils import utcnow
7+
from sqlalchemy import Column, String, BigInteger
78

8-
from PyDrocsid.database import db, delete, filter_by
9+
from PyDrocsid.database import db, delete, filter_by, UTCDateTime
910

1011

1112
class RedditChannel(db.Base):
@@ -25,17 +26,17 @@ class RedditPost(db.Base):
2526
__tablename__ = "reddit_post"
2627

2728
post_id: Union[Column, str] = Column(String(16), primary_key=True, unique=True)
28-
timestamp: Union[Column, datetime] = Column(DateTime)
29+
timestamp: Union[Column, datetime] = Column(UTCDateTime)
2930

3031
@staticmethod
3132
async def create(post_id: str) -> RedditPost:
32-
row = RedditPost(post_id=post_id, timestamp=datetime.utcnow())
33+
row = RedditPost(post_id=post_id, timestamp=utcnow())
3334
await db.add(row)
3435
return row
3536

3637
@staticmethod
3738
async def clean():
38-
drop_before_timestamp = datetime.utcnow() - timedelta(weeks=1)
39+
drop_before_timestamp = utcnow() - timedelta(weeks=1)
3940
await db.exec(delete(RedditPost).filter(RedditPost.timestamp < drop_before_timestamp))
4041

4142
@staticmethod

moderation/autoclear/cog.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
import asyncio
2-
from datetime import datetime, timedelta
2+
from datetime import timedelta
33
from typing import Optional
44

55
from discord import TextChannel, Forbidden, Embed, Message, NotFound
66
from discord.ext import commands, tasks
77
from discord.ext.commands import Context, UserInputError, guild_only, CommandError
8+
from discord.utils import utcnow
89

910
from PyDrocsid.cog import Cog
1011
from PyDrocsid.command import docs
@@ -29,7 +30,7 @@ async def clear_channel(channel: TextChannel, minutes: int, limit: Optional[int]
2930

3031
message: Message
3132
async for message in channel.history(
32-
before=datetime.utcnow() - timedelta(minutes=minutes),
33+
before=utcnow() - timedelta(minutes=minutes),
3334
limit=limit,
3435
oldest_first=True,
3536
):

0 commit comments

Comments
 (0)