Skip to content

Commit

Permalink
Manual ruff fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisLovering committed Aug 29, 2023
1 parent 3d0ce8e commit 3f79871
Show file tree
Hide file tree
Showing 16 changed files with 128 additions and 129 deletions.
4 changes: 2 additions & 2 deletions bot/constants.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import dataclasses
import enum
import logging
from datetime import datetime
from datetime import UTC, datetime
from os import environ
from typing import NamedTuple

Expand Down Expand Up @@ -69,7 +69,7 @@ class AdventOfCode:
leaderboard_displayed_members = 10
leaderboard_cache_expiry_seconds = 1800
max_day_and_star_results = 15
year = int(environ.get("AOC_YEAR", datetime.utcnow().year))
year = int(environ.get("AOC_YEAR", datetime.now(tz=UTC).year))
role_id = int(environ.get("AOC_ROLE_ID", 518565788744024082))


Expand Down
20 changes: 11 additions & 9 deletions bot/exts/advent_of_code/_cog.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import json
import logging
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from pathlib import Path

import arrow
Expand Down Expand Up @@ -177,8 +177,8 @@ async def aoc_countdown(self, ctx: commands.Context) -> None:

datetime_now = arrow.now(_helpers.EST)
# Calculate the delta to this & next year's December 1st to see which one is closest and not in the past
this_year = arrow.get(datetime(datetime_now.year, 12, 1), _helpers.EST)
next_year = arrow.get(datetime(datetime_now.year + 1, 12, 1), _helpers.EST)
this_year = arrow.get(datetime(datetime_now.year, 12, 1, tzinfo=UTC), _helpers.EST)
next_year = arrow.get(datetime(datetime_now.year + 1, 12, 1, tzinfo=UTC), _helpers.EST)
deltas = (dec_first - datetime_now for dec_first in (this_year, next_year))
delta = min(delta for delta in deltas if delta >= timedelta()) # timedelta() gives 0 duration delta

Expand All @@ -200,7 +200,7 @@ async def about_aoc(self, ctx: commands.Context) -> None:
@app_commands.guild_only()
async def join_leaderboard(self, interaction: discord.Interaction) -> None:
"""Send the user an ephemeral message with the information for joining the Python Discord leaderboard."""
current_date = datetime.now()
current_date = datetime.now(tz=UTC)
allowed_months = (Month.NOVEMBER.value, Month.DECEMBER.value)
if not (
current_date.month in allowed_months and current_date.year == AocConfig.year
Expand Down Expand Up @@ -267,7 +267,7 @@ async def aoc_link_account(self, ctx: commands.Context, *, aoc_name: str | None
if aoc_name == await self.account_links.get(ctx.author.id):
await ctx.reply(f"{aoc_name} is already tied to your account.")
return
elif aoc_name in cache_aoc_names:
if aoc_name in cache_aoc_names:
log.info(
f"{ctx.author} ({ctx.author.id}) tried to connect their account to {aoc_name},"
" but it's already connected to another user."
Expand Down Expand Up @@ -394,9 +394,11 @@ async def aoc_leaderboard(self, ctx: commands.Context, *, aoc_name: str | None =
top_count = min(AocConfig.leaderboard_displayed_members, number_of_participants)
self_placement_header = " (and your personal stats compared to the top 10)" if aoc_name else ""
header = f"Here's our current top {top_count}{self_placement_header}! {Emojis.christmas_tree * 3}"
table = "```\n" \
f"{leaderboard['placement_leaderboard'] if aoc_name else leaderboard['top_leaderboard']}" \
"\n```"
table = (
"```\n"
f"{leaderboard['placement_leaderboard'] if aoc_name else leaderboard['top_leaderboard']}"
"\n```"
)
info_embed = _helpers.get_summary_embed(leaderboard)

await ctx.send(content=f"{header}\n\n{table}", embed=info_embed)
Expand Down Expand Up @@ -485,7 +487,7 @@ def _build_about_embed(self) -> discord.Embed:
title=self._base_url,
colour=Colours.soft_green,
url=self._base_url,
timestamp=datetime.utcnow()
timestamp=datetime.now(tz=UTC)
)
about_embed.set_author(name="Advent of Code", url=self._base_url)
for field in embed_fields:
Expand Down
8 changes: 4 additions & 4 deletions bot/exts/advent_of_code/_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def _parse_raw_leaderboard_data(raw_leaderboard_data: dict) -> dict:
leaderboard[member_id][f"star_{star}"] += 1

# Record completion datetime for this participant for this day/star
completion_time = datetime.datetime.fromtimestamp(int(data["get_star_ts"]))
completion_time = datetime.datetime.fromtimestamp(int(data["get_star_ts"]), tz=datetime.UTC)
star_results[(day, star)].append(
StarResult(member_id=member_id, completion_time=completion_time)
)
Expand Down Expand Up @@ -492,7 +492,7 @@ async def wait_for_advent_of_code(*, hours_before: int = 1) -> None:
if we're already past the Advent of Code edition the bot is currently
configured for.
"""
start = arrow.get(datetime.datetime(AdventOfCode.year, 12, 1), EST)
start = arrow.get(datetime.datetime(AdventOfCode.year, 12, 1, tzinfo=datetime.UTC), EST)
target = start - datetime.timedelta(hours=hours_before)
now = arrow.now(EST)

Expand Down Expand Up @@ -529,7 +529,7 @@ async def countdown_status(bot: SirRobin) -> None:
# sleeping for the entire year, it will only wait in the currently
# configured year. This means that the task will only start hibernating once
# we start preparing the next event by changing environment variables.
last_challenge = arrow.get(datetime.datetime(AdventOfCode.year, 12, 25), EST)
last_challenge = arrow.get(datetime.datetime(AdventOfCode.year, 12, 25, tzinfo=datetime.UTC), EST)
end = last_challenge + datetime.timedelta(hours=1)

while arrow.now(EST) < end:
Expand Down Expand Up @@ -586,7 +586,7 @@ async def new_puzzle_notification(bot: SirRobin) -> None:

# The last event day is 25 December, so we only have to schedule
# a reminder if the current day is before 25 December.
end = arrow.get(datetime.datetime(AdventOfCode.year, 12, 25), EST)
end = arrow.get(datetime.datetime(AdventOfCode.year, 12, 25, tzinfo=datetime.UTC), EST)
while arrow.now(EST) < end:
log.trace("Started puzzle notification loop.")
tomorrow, time_left = time_left_to_est_midnight()
Expand Down
4 changes: 2 additions & 2 deletions bot/exts/advent_of_code/views/dayandstarview.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import UTC, datetime

import discord

Expand Down Expand Up @@ -30,7 +30,7 @@ def generate_output(self) -> str:
if not (day_and_star_data := self.data.get(f"{self.day}-{self.star}")):
return ":x: The requested data for the specified day and star does not exist yet."
for rank, scorer in enumerate(day_and_star_data[:self.maximum_scorers]):
time_data = datetime.fromtimestamp(scorer["completion_time"]).strftime("%I:%M:%S %p")
time_data = datetime.fromtimestamp(scorer["completion_time"], tz=UTC).strftime("%I:%M:%S %p")
lines.append(AOC_DAY_AND_STAR_TEMPLATE.format(
datastamp="",
rank=rank + 1,
Expand Down
6 changes: 3 additions & 3 deletions bot/exts/code_jams/_flows.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime
from datetime import UTC, datetime
from urllib.parse import quote as quote_url

import discord
Expand Down Expand Up @@ -33,7 +33,7 @@ async def creation_flow(
"""
team_leaders = await ctx.guild.create_role(name=TEAM_LEADER_ROLE_NAME, colour=TEAM_LEADERS_COLOUR)
await _creation_utils.create_team_leader_channel(ctx.guild, team_leaders)
jam_api_format = {"name": f"Summer Code Jam {datetime.now().year}", "ongoing": True, "teams": []}
jam_api_format = {"name": f"Summer Code Jam {datetime.now(tz=UTC).year}", "ongoing": True, "teams": []}
for team_name, team_members in teams.items():
team_role = await _creation_utils.create_team_role(
ctx.guild,
Expand Down Expand Up @@ -320,7 +320,7 @@ async def pin_flow(
if referenced_message.pinned and not unpin:
await ctx.reply(":x: The message has already been pinned!")
return
elif not referenced_message.pinned and unpin:
if not referenced_message.pinned and unpin:
await ctx.reply(":x: The message has already been unpinned!")
return

Expand Down
84 changes: 42 additions & 42 deletions bot/exts/code_jams/_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,33 +226,33 @@ async def on_submit(self, interaction: discord.Interaction) -> None:
)
):
return
else:
jam_id = user["team"]["jam_id"]
try:
await self.mgmt_client.post(
"infractions",
json={
"user_id": self.member.id,
"jam_id": jam_id, "reason": self.note.value,
"infraction_type": "note"
},
raise_for_status=True

jam_id = user["team"]["jam_id"]
try:
await self.mgmt_client.post(
"infractions",
json={
"user_id": self.member.id,
"jam_id": jam_id, "reason": self.note.value,
"infraction_type": "note"
},
raise_for_status=True
)
except ResponseCodeError as err:
if err.response.status == 404:
await interaction.response.send_message(
":x: The user could not be found!",
ephemeral=True
)
except ResponseCodeError as err:
if err.response.status == 404:
await interaction.response.send_message(
":x: The user could not be found!",
ephemeral=True
)
else:
await interaction.response.send_message(
":x: Something went wrong! Full details have been logged.",
ephemeral=True
)
log.error(f"Something went wrong: {err}")
return
else:
await interaction.response.send_message("Your note has been saved!", ephemeral=True)
await interaction.response.send_message(
":x: Something went wrong! Full details have been logged.",
ephemeral=True
)
log.error(f"Something went wrong: {err}")
return
else:
await interaction.response.send_message("Your note has been saved!", ephemeral=True)

async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
"""Discord.py default to handle modal error."""
Expand Down Expand Up @@ -282,24 +282,24 @@ async def view_notes(self, interaction: discord.Interaction, button: discord.ui.
"""A button to view the notes of a participant."""
if not (user := await interaction_fetch_user_data(f"users/{self.member.id}", self.mgmt_client, interaction)):
return

part_history = user["participation_history"]
notes = []
for entry in part_history:
for infraction in entry["infractions"]:
notes.append(infraction)
if not notes:
await interaction.response.send_message(
f":x: {self.member.mention} doesn't have any notes yet.",
ephemeral=True
)
else:
part_history = user["participation_history"]
notes = []
for entry in part_history:
for infraction in entry["infractions"]:
notes.append(infraction)
if not notes:
await interaction.response.send_message(
f":x: {self.member.mention} doesn't have any notes yet.",
ephemeral=True
)
else:
if len(notes) > 25:
notes = notes[:25]
notes_embed = discord.Embed(title=f"Notes on {self.member.name}", colour=discord.Colour.orange())
for note in notes:
notes_embed.add_field(name=f"Jam - (ID: {note['jam_id']})", value=note["reason"])
await interaction.response.send_message(embed=notes_embed, ephemeral=True)
if len(notes) > 25:
notes = notes[:25]
notes_embed = discord.Embed(title=f"Notes on {self.member.name}", colour=discord.Colour.orange())
for note in notes:
notes_embed.add_field(name=f"Jam - (ID: {note['jam_id']})", value=note["reason"])
await interaction.response.send_message(embed=notes_embed, ephemeral=True)

async def interaction_check(self, interaction: discord.Interaction) -> bool:
"""Global check to ensure the interacting user is an admin."""
Expand Down
8 changes: 4 additions & 4 deletions bot/exts/error_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,19 @@ async def on_command_error(self, ctx: Context, error: CommandError) -> None:
embed = self._get_error_embed("Bad argument", str(error))
await ctx.send(embed=embed)
return
elif isinstance(error, CommandNotFound):
if isinstance(error, CommandNotFound):
embed = self._get_error_embed("Command not found", str(error))
await ctx.send(embed=embed)
return
elif isinstance(error, MissingRequiredArgument):
if isinstance(error, MissingRequiredArgument):
embed = self._get_error_embed("Missing required argument", str(error))
await ctx.send(embed=embed)
return
elif isinstance(error, MissingAnyRole):
if isinstance(error, MissingAnyRole):
embed = self._get_error_embed("Permission error", "You are not allowed to use this command!")
await ctx.send(embed=embed)
return
elif isinstance(error, CodeJamCategoryCheckFailure):
if isinstance(error, CodeJamCategoryCheckFailure):
# Silently fail, as SirRobin should not respond
# to any of the CJ related commands outside of the CJ categories.
log.error(exc_info=error)
Expand Down
26 changes: 13 additions & 13 deletions bot/exts/pep.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from datetime import datetime, timedelta
from datetime import UTC, datetime, timedelta
from email.parser import HeaderParser
from io import StringIO

Expand Down Expand Up @@ -26,15 +26,15 @@ def __init__(self, bot: SirRobin):
self.bot = bot
self.peps: dict[int, str] = {}
# To avoid situations where we don't have last datetime, set this to now.
self.last_refreshed_peps: datetime = datetime.now()
self.last_refreshed_peps: datetime = datetime.now(tz=UTC)
scheduling.create_task(self.refresh_peps_urls())

async def refresh_peps_urls(self) -> None:
"""Refresh PEP URLs listing in every 3 hours."""
# Wait until HTTP client is available
await self.bot.wait_until_ready()
log.trace("Started refreshing PEP URLs.")
self.last_refreshed_peps = datetime.now()
self.last_refreshed_peps = datetime.now(tz=UTC)

async with self.bot.http_session.get(
PEPS_LISTING_API_URL
Expand Down Expand Up @@ -73,7 +73,7 @@ async def validate_pep_number(self, pep_nr: int) -> Embed | None:
"""Validate is PEP number valid. When it isn't, return error embed, otherwise None."""
if (
pep_nr not in self.peps
and (self.last_refreshed_peps + timedelta(minutes=30)) <= datetime.now()
and (self.last_refreshed_peps + timedelta(minutes=30)) <= datetime.now(tz=UTC)
and len(str(pep_nr)) < 5
):
await self.refresh_peps_urls()
Expand Down Expand Up @@ -125,15 +125,15 @@ async def get_pep_embed(self, pep_nr: int) -> tuple[Embed, bool]:
pep_header = HeaderParser().parse(StringIO(pep_content))

return self.generate_pep_embed(pep_header, pep_nr), True
else:
log.trace(
f"The user requested PEP {pep_nr}, but the response had an unexpected status code: {response.status}."
)
return Embed(
title="Unexpected error",
description="Unexpected HTTP error during PEP search. Please let us know.",
colour=Colour.red()
), False

log.trace(
f"The user requested PEP {pep_nr}, but the response had an unexpected status code: {response.status}."
)
return Embed(
title="Unexpected error",
description="Unexpected HTTP error during PEP search. Please let us know.",
colour=Colour.red()
), False

@command(name="pep", aliases=("get_pep", "p"))
async def pep_command(self, ctx: Context, pep_number: int) -> None:
Expand Down
9 changes: 4 additions & 5 deletions bot/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,15 +43,14 @@ async def send_to_paste_service(contents: str, *, extension: str = "") -> str |
f"trying again ({attempt}/{FAILED_REQUEST_ATTEMPTS})."
)
continue
elif "key" in response_json:
if "key" in response_json:
log.info(f"Successfully uploaded contents to paste service behind key {response_json['key']}.")

paste_link = f"{PASTE_URL}/{response_json['key']}{extension}"

if extension == ".py":
return paste_link
if extension == ".py":
return paste_link

return paste_link + "?noredirect"
return paste_link + "?noredirect"

log.warning(
f"Got unexpected JSON response from paste service: {response_json}\n"
Expand Down
10 changes: 4 additions & 6 deletions bot/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import re
import string
from collections.abc import Iterable
from datetime import datetime
from datetime import UTC, datetime

import discord
from discord.ext.commands import BadArgument, Context
Expand All @@ -26,8 +26,7 @@ def resolve_current_month() -> Month:
"""
if Client.month_override is not None:
return Month(Client.month_override)
else:
return Month(datetime.utcnow().month)
return Month(datetime.now(tz=UTC).month)


async def disambiguate(
Expand Down Expand Up @@ -151,10 +150,9 @@ def _repl(match: re.Match) -> str:
cleaned_word = word.translate(str.maketrans("", "", string.punctuation))
if cleaned_word.isupper():
return replacement.upper()
elif cleaned_word[0].isupper():
if cleaned_word[0].isupper():
return replacement.capitalize()
else:
return replacement.lower()
return replacement.lower()

return regex.sub(_repl, sentence)

Expand Down
Loading

0 comments on commit 3f79871

Please sign in to comment.