Skip to content

Commit 392b7be

Browse files
committed
refactor: use timezone-aware datetime objects
1 parent 810dfdd commit 392b7be

7 files changed

Lines changed: 18 additions & 22 deletions

File tree

guild_profiles/guild_profiles.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import logging
22
import re
33
from dataclasses import asdict, dataclass
4-
from datetime import datetime, timezone
54
from pathlib import Path
65
from typing import Type
76

@@ -251,7 +250,7 @@ async def create_profile_cmd(self, ctx: commands.GuildContext, name: str, icon_i
251250
# Create the profile
252251
profiles[profile_name] = {
253252
"creator": ctx.author.id,
254-
"created": int(datetime.now(timezone.utc).timestamp()),
253+
"created": int(discord.utils.utcnow().timestamp()),
255254
"icon_id": icon_id,
256255
"banner_id": banner_id,
257256
}
@@ -541,7 +540,7 @@ async def create_asset_cmd(self, ctx: commands.GuildContext, name: str | None):
541540
asset = GuildAsset(
542541
name=name.lower(),
543542
creator=ctx.author.id,
544-
created=int(datetime.now(timezone.utc).timestamp()),
543+
created=int(discord.utils.utcnow().timestamp()),
545544
path=file_path,
546545
)
547546

jail/jail.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import uuid
2-
from datetime import datetime
32
from io import BytesIO
43
from os import path
54
from typing import Optional
@@ -28,7 +27,7 @@ def __init__(self, bot: Red, *args, **kwargs):
2827
@commands.group("jail", pass_context=True, invoke_without_command=True)
2928
async def _jail(self, ctx: commands.Context, member: discord.Member):
3029
"""Jails the specified user."""
31-
jail = await self.config.create_jail(ctx, int(datetime.utcnow().timestamp()), member)
30+
jail = await self.config.create_jail(ctx, int(discord.utils.utcnow().timestamp()), member)
3231
if jail is None:
3332
await ctx.send("Sorry, there was an error with jail category. Make sure things are setup correctly!")
3433
return

notes/utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from datetime import datetime
21
from typing import Callable, Iterable, List, Union
32

43
import discord
@@ -23,7 +22,7 @@ def new(cls, ctx: commands.Context, note_id: int, member_id: int, message: str,
2322
message=message,
2423
reporter_id=ctx.author.id,
2524
reporter_name=ctx.author.name,
26-
created_at=int(datetime.utcnow().timestamp()),
25+
created_at=int(discord.utils.utcnow().timestamp()),
2726
deleted=False,
2827
is_warning=is_warning,
2928
_guild=ctx.guild,

purge/purge.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""discord red-bot purge"""
22

33
import asyncio
4-
from datetime import datetime, timedelta
4+
from datetime import datetime, timedelta, timezone
55

66
import discord
77
from croniter import croniter
@@ -50,7 +50,7 @@ async def check_purgeable_users(self):
5050
continue
5151

5252
# Is it time to run?
53-
cur_epoch = datetime.utcnow()
53+
cur_epoch = discord.utils.utcnow()
5454
last_run = await self.config.guild(guild).lastrun()
5555
last_run = last_run or 0
5656
crontab = await self.config.guild(guild).schedule()
@@ -104,7 +104,7 @@ async def _purge_users(self, guild: discord.Guild, title: str):
104104
break
105105
users_kicked = new_list
106106

107-
data = discord.Embed(colour=discord.Colour.orange(), timestamp=datetime.utcnow())
107+
data = discord.Embed(colour=discord.Colour.orange(), timestamp=discord.utils.utcnow())
108108
data.title = f"{title} Purge - Purged {len(users)}"
109109
data.description = users_kicked
110110

@@ -141,7 +141,7 @@ async def get_purgeable_users(self, guild):
141141

142142
# If user is not older than the minimum age, they're safe
143143
timelimit = await self.config.guild(guild).minage()
144-
cutoff_date = datetime.utcnow() - timedelta(days=timelimit)
144+
cutoff_date = discord.utils.utcnow() - timedelta(days=timelimit)
145145
if member.joined_at > cutoff_date:
146146
continue
147147

@@ -339,12 +339,12 @@ async def purge_status(self, ctx: commands.GuildContext):
339339

340340
last_run_friendly = "Never"
341341
if purge_last_run is not None:
342-
last_run = datetime.utcfromtimestamp(purge_last_run)
342+
last_run = datetime.fromtimestamp(purge_last_run, tz=timezone.utc)
343343
last_run_friendly = last_run.strftime("%Y-%m-%d %H:%M:%SZ")
344344
data.add_field(name="Last Run", value=f"{last_run_friendly}")
345345

346346
if (purge_last_run is not None or purge_enabled) and purge_schedule is not None:
347-
next_date = croniter(purge_schedule, purge_last_run or datetime.utcnow()).get_next(datetime)
347+
next_date = croniter(purge_schedule, purge_last_run or discord.utils.utcnow()).get_next(datetime)
348348
next_run_friendly = next_date.strftime("%Y-%m-%d %H:%M:%SZ")
349349

350350
data.add_field(name="Next Run", value=f"{next_run_friendly}")

tags/tags.py

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

43
import discord
@@ -54,7 +53,7 @@ async def _tag(self, ctx: commands.Context, trigger: str):
5453
"""Manage tags and aliases."""
5554
tag, alias = await self.config.get_tag_or_alias(ctx, trigger)
5655

57-
time = int(datetime.utcnow().timestamp())
56+
time = int(discord.utils.utcnow().timestamp())
5857

5958
if tag is None and alias is None:
6059
await ctx.send("That's not a valid tag or alias!")
@@ -162,7 +161,9 @@ async def _claim(self, ctx: commands.Context, trigger: str):
162161
f"wants to transfer it to you."
163162
)
164163
else:
165-
await self.config.transfer_tag(ctx, trigger, ctx.author.id, "Claim", int(datetime.utcnow().timestamp()))
164+
await self.config.transfer_tag(
165+
ctx, trigger, ctx.author.id, "Claim", int(discord.utils.utcnow().timestamp())
166+
)
166167
await ctx.send("Tag successfully claimed!")
167168
else:
168169
await ctx.send("Sorry, that isn't a valid tag so you can't claim it. Good news! You can create it!")
@@ -182,7 +183,7 @@ async def _transfer(self, ctx: commands.Context, trigger: str, member: discord.M
182183
reason = f"Mod-initiated by {ctx.author.mention}"
183184
if allowable:
184185
await self.config.transfer_tag(
185-
ctx, trigger, member.id, f"Transfer: {reason}", int(datetime.utcnow().timestamp())
186+
ctx, trigger, member.id, f"Transfer: {reason}", int(discord.utils.utcnow().timestamp())
186187
)
187188
await ctx.send("Tag successfully transferred!")
188189
else:
@@ -253,7 +254,7 @@ async def _alias_create(self, ctx: commands.Context, alias: str, tag: str):
253254
await ctx.send("You can't alias to another alias! That gets messy.")
254255
return
255256

256-
await self.config.create_alias(ctx, alias, tag, ctx.author.id, int(datetime.utcnow().timestamp()))
257+
await self.config.create_alias(ctx, alias, tag, ctx.author.id, int(discord.utils.utcnow().timestamp()))
257258
await ctx.send("Alias created!")
258259

259260
@_alias.command("delete")

tags/utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
from datetime import datetime
21
from typing import List, Optional
32

43
import discord
@@ -93,7 +92,7 @@ async def set_log_transfers(self, ctx: commands.Context, log: bool):
9392
return self.config.guild(ctx.guild).log().uses.transfers(log)
9493

9594
async def create_tag(self, ctx: commands.Context, trigger: str, content: str) -> Tag:
96-
time = int(datetime.utcnow().timestamp())
95+
time = int(discord.utils.utcnow().timestamp())
9796
tag = Tag.new(ctx, ctx.author.id, ctx.author.id, time, trigger, content)
9897
async with self.config.guild(ctx.guild).tags() as tags:
9998
tags[trigger] = tag.to_dict()

timeout/timeout.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import datetime
21
import logging
32
from typing import Optional
43

@@ -36,7 +35,7 @@ async def report_handler(self, ctx: commands.GuildContext, user: discord.Member,
3635

3736
# Build embed
3837
embed = discord.Embed(
39-
description=f"{user.mention} ({user.id})", color=(await ctx.embed_colour()), timestamp=datetime.datetime.utcnow()
38+
description=f"{user.mention} ({user.id})", color=(await ctx.embed_colour()), timestamp=discord.utils.utcnow()
4039
)
4140
embed.add_field(name="Moderator", value=ctx.author.mention, inline=False)
4241
embed.add_field(name="Reason", value=action_info["reason"], inline=False)

0 commit comments

Comments
 (0)