Skip to content

Commit

Permalink
more refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
tylovejoy committed May 19, 2024
1 parent 1011674 commit 4068a21
Show file tree
Hide file tree
Showing 15 changed files with 198 additions and 78 deletions.
4 changes: 2 additions & 2 deletions cogs/mod.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
import typing

import discord
import utils
from discord import app_commands
from discord.ext import commands

import utils
import views
from config import CONFIG

Expand All @@ -21,7 +21,7 @@ def __init__(self, bot: core.Doom):

async def cog_check(self, ctx: DoomCtx) -> bool:
return True
# return bool(ctx.author.get_role(utils.STAFF))
# return bool(ctx.author.get_role(utils-old.STAFF))

mod = app_commands.Group(
**utils.mod_,
Expand Down
87 changes: 39 additions & 48 deletions cogs/records.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
import typing

import discord
import utils
from discord import app_commands
from discord.ext import commands

import utils
import utilities
import views
from config import CONFIG
from utilities import translations, errors
import utilities
from utilities import ConfirmationBaseView, Record, errors, translations

if typing.TYPE_CHECKING:
import core
Expand Down Expand Up @@ -41,7 +41,6 @@ def __init__(self, bot: core.Doom):
@app_commands.command(**translations.submit_record)
@app_commands.describe(**translations.submit_record_args)
@app_commands.guilds(CONFIG["GUILD_ID"])
# @app_commands.choices(rating=utils.ALL_STARS_CHOICES)
async def submit_record(
self,
itx: DoomItx,
Expand All @@ -53,60 +52,52 @@ async def submit_record(
rating: int | None,
) -> None:
await itx.response.defer(ephemeral=False)
if map_code not in itx.client.map_cache.keys():
raise errors.InvalidMapCodeError

if level_name not in itx.client.map_cache[map_code]["levels"]:
raise errors.InvalidMapLevelError
previous_record = await self.bot.database.fetch_previous_record_submission(map_code, level_name, itx.user.id)
if previous_record and previous_record["record"] < record:
raise errors.RecordNotFasterError

query = """
SELECT record, hidden_id FROM records r
LEFT OUTER JOIN maps m on r.map_code = m.map_code
WHERE r.map_code = $1 AND level_name = $2 AND user_id = $3
ORDER BY inserted_at DESC
"""
old_row = await itx.client.database.fetchrow(
query,
user_nickname = await self.bot.database.fetch_user_nickname(itx.user.id)
confirmation_image = await screenshot.to_file(filename="image.png")
data = Record(
self.bot,
map_code,
level_name,
itx.user.id,
)
if old_row and old_row["record"] < record:
raise errors.RecordNotFasterError

user = itx.client.all_users[itx.user.id]

view = views.Confirm(
itx,
"⌛ Waiting for verification...\n",
record,
"",
video,
nickname=user_nickname,
user_image=itx.user.display_avatar.url,
)
new_screenshot = await screenshot.to_file(filename="image.png")
# embed = utils.record_embed(
# {
# "map_code": map_code,
# "map_level": level_name,
# "record": utils.pretty_record(record),
# "video": video,
# "user_name": user_nickname,
# "user_url": itx.user.display_avatar.url,
# }
# )
embed = data.build_embed()

embed = utils.record_embed(
{
"map_code": map_code,
"map_level": level_name,
"record": utils.pretty_record(record),
"video": video,
"user_name": user["nickname"],
"user_url": itx.user.display_avatar.url,
}
)
channel_msg = await itx.edit_original_response(
content=f"{itx.user.mention}, is this correct?",
embed=embed,
view=view,
attachments=[new_screenshot],
)
await view.wait()
view = ConfirmationBaseView(itx, f"{itx.user.mention}, is this correct?", embed=embed, attachment=confirmation_image)
await view.start()
if not view.value:
return
new_screenshot2 = await screenshot.to_file(filename="image.png")
verification_msg = await itx.client.get_channel(CONFIG["VERIFICATION_QUEUE"]).send(embed=embed, file=new_screenshot2)

if old_row and old_row["hidden_id"]:
channel_image = await screenshot.to_file(filename="image.png")
await itx.channel.send("Waiting for verification...", embed=embed, file=channel_image)
# TODO: Send message to channel and use it as 'channel_msg'

verification_image = await screenshot.to_file(filename="image.png")
verification_queue = itx.client.get_channel(CONFIG["VERIFICATION_QUEUE"])
verification_msg = await verification_queue.send(embed=embed, file=verification_image)

if previous_record and previous_record["hidden_id"]:
with contextlib.suppress(discord.NotFound):
await itx.guild.get_channel(CONFIG["VERIFICATION_QUEUE"]).get_partial_message(old_row["hidden_id"]).delete()
await verification_queue.get_partial_message(previous_record["hidden_id"]).delete()
# TODO: Delete Hidden ID from previous record

view = views.VerificationView()
await verification_msg.edit(view=view)
Expand Down
8 changes: 4 additions & 4 deletions cogs/tournament/org_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@
from typing import TYPE_CHECKING

import discord
import utils
from discord import app_commands
from discord.ext import commands
from utils import DoomEmbed

import utils
import views
from cogs.tournament.utils import Categories_NoGen, Ranks
from cogs.tournament.utils.errors import ModalError
Expand All @@ -16,7 +17,6 @@
from cogs.tournament.views.info import TournamentInfoView, all_info_embeds
from cogs.tournament.views.seasons import SeasonManager
from config import CONFIG
from utils import DoomEmbed

if TYPE_CHECKING:
import core
Expand Down Expand Up @@ -112,11 +112,11 @@ async def announcement(
raise ModalError

if not thumbnail:
thumbnail = "https://bkan0n.com/assets/images/icons/gold_cup.png"
thumbnail = "https://doom.pk/assets/images/icons/gold_cup.png"
else:
thumbnail = thumbnail.url
if not image:
image = "https://bkan0n.com/assets/images/icons/tournament_announcement_banner.png"
image = "https://doom.pk/assets/images/icons/tournament_announcement_banner.png"
else:
image = image.url

Expand Down
11 changes: 6 additions & 5 deletions cogs/tournament/utils/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@
from typing import Literal

import discord.utils
from utils import make_ordinal, pretty_record

from config import CONFIG
from utils import make_ordinal, pretty_record

if typing.TYPE_CHECKING:
import core

import utils

from cogs.tournament.utils import Categories, Category, CategoryData, Rank
from cogs.tournament.utils.utils import role_map

Expand Down Expand Up @@ -49,8 +50,8 @@ def base_embed(
embed = utils.DoomEmbed(
title="Doomfist Parkour Tournament",
description=description,
thumbnail="https://bkan0n.com/assets/images/icons/gold_cup.png",
image=f"https://bkan0n.com/assets/images/icons/tournament_{embed_type}_banner.png",
thumbnail="https://doom.pk/assets/images/icons/gold_cup.png",
image=f"https://doom.pk/assets/images/icons/tournament_{embed_type}_banner.png",
color=discord.Color.gold(),
)
return embed
Expand All @@ -59,8 +60,8 @@ def base_embed(
def leaderboard_embed(description: str, category: Categories, rank: Rank | None):
embed = base_embed(description=description, embed_type="leaderboard")
if rank:
embed.set_thumbnail(url=f"https://bkan0n.com/assets/images/icons/{rank.lower()}.png")
embed.set_image(url=f"https://bkan0n.com/assets/images/tournament/{category.lower().replace(' ', '_')}.png")
embed.set_thumbnail(url=f"https://doom.pk/assets/images/icons/{rank.lower()}.png")
embed.set_image(url=f"https://doom.pk/assets/images/tournament/{category.lower().replace(' ', '_')}.png")

embed.colour = discord.Color.from_str(category_color[category])
return embed
Expand Down
2 changes: 1 addition & 1 deletion database/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from database.database import *
from .database import *
14 changes: 14 additions & 0 deletions database/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,17 @@ async def insert_map_data(
description,
image_url,
)

async def fetch_previous_record_submission(self, map_code: str, level_name: str, user_id: int) -> asyncpg.Record | None:
query = """
SELECT record, hidden_id FROM records r
LEFT OUTER JOIN maps m on r.map_code = m.map_code
WHERE r.map_code = $1 AND level_name = $2 AND user_id = $3
ORDER BY inserted_at DESC
"""
return await self.fetchrow(
query,
map_code,
level_name,
user_id,
)
2 changes: 1 addition & 1 deletion utilities/confirmation.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ async def reject(self, itx: DoomItx, button: discord.ui.Button):
await itx.response.send_message("Rejected.", ephemeral=True)
self.stop()

async def start(self):
async def start(self) -> discord.InteractionMessage | None:
if self.itx.response.is_done():
send = functools.partial(self.itx.edit_original_response, attachments=self.attachments)
else:
Expand Down
2 changes: 1 addition & 1 deletion utilities/embeds.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def __init__(
description=description,
color=discord.Color.red(),
)
self.set_thumbnail(url="http://bkan0n.com/assets/images/icons/error.png")
self.set_thumbnail(url="http://doom.pk/assets/images/icons/error.png")
else:
super().__init__(
title="What happened?",
Expand Down
70 changes: 69 additions & 1 deletion utilities/models.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import datetime
from dataclasses import dataclass, field
from typing import TYPE_CHECKING

Expand All @@ -13,7 +14,7 @@
from core import Doom


_MAPS_BASE_URL = "https://bkan0n.com/assets/images/map_banners/"
_MAPS_BASE_URL = "https://doom.pk/assets/images/map_banners/"


@dataclass
Expand Down Expand Up @@ -120,3 +121,70 @@ async def commit(self):
)
await self.bot.database.add_creator_to_map_code(self.primary_creator, self.map_code, connection=conn)
await self.bot.database.add_multiple_map_levels(self.map_code, self.levels, connection=conn)


@dataclass
class Record:
bot: Doom
map_code: str
level_name: str
record: float
screenshot: str = ""
video: str | None = None
nickname: str | None = None
user_image: str | None = None
tournament: bool = False
verified: bool = False
map_name: str = ""
rank_num: int | None = None

@property
def pretty_record(self):
"""
The pretty_record property takes the record time for a given
document and returns a string representation of that time.
The function is used to display the record times in an easily
readable format on the leaderboard page.
Returns:
A string
"""
record = float(self.record)
negative = "-" if record < 0 else ""
dt = datetime.datetime.min + datetime.timedelta(seconds=abs(record))
hour_remove = 0
seconds_remove = -4

if dt.hour == 0 and dt.minute == 0:
hour_remove = 6
if dt.second < 10:
hour_remove += 1

elif dt.hour == 0:
hour_remove = 3
if dt.minute < 10:
hour_remove = 4

if dt.microsecond == 0:
seconds_remove = -4

return negative + dt.strftime("%H:%M:%S.%f")[hour_remove:seconds_remove]

def build_embed(self):
if not self.video:
description = f"` Code ` {self.map_code}\n` Level ` {self.level_name}\n` Record ` {self.pretty_record}\n"
else:
description = (
f"` Code ` {self.map_code}\n"
f"` Level ` {self.level_name}\n"
f"` Record ` {self.pretty_record}\n"
f"` Video ` [Link]({self.video})\n"
)

embed = discord.Embed(
title="New Personal Record!",
description=description,
)
embed.set_author(name=self.nickname, icon_url=self.user_image)
embed.set_image(url="attachment://image.png")
return embed
Loading

0 comments on commit 4068a21

Please sign in to comment.