Skip to content

Commit

Permalink
refact(xp): move cards deletion loop from events + fix xp comparison
Browse files Browse the repository at this point in the history
  • Loading branch information
ZRunner committed Dec 17, 2024
1 parent 7fc46af commit 36eb475
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
3 changes: 0 additions & 3 deletions modules/events/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,9 +223,6 @@ async def loop(self):
# Timed tasks - every 20s
if now.second%20 == 0 and self.bot.database_online:
await self.bot.task_handler.check_tasks()
# Clear old rank cards - every 20min
elif now.minute%20 == 0 and self.bot.database_online:
await self.bot.get_cog("Xp").clear_cards()
# Bots lists updates - every day
elif now.hour == 0 and now.day != self.dbl_last_sending.day:
await self.dbl_send_data()
Expand Down
33 changes: 23 additions & 10 deletions modules/xp/xp.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import datetime
import logging
import operator
import os
import random
import re
Expand Down Expand Up @@ -623,22 +622,36 @@ async def before_xp_decay_loop(self):
async def on_xp_decay_loop_error(self, error: Exception):
self.bot.dispatch("error", error, "XP decay loop has stopped <@279568324260528128>")

@tasks.loop(hours=1)
async def clear_cards_loop(self, delete_all: bool=False):
"""Delete outdated rank cards
A card is 'outdated' if the user generated another card with more total xp,
so we sort the files list by total xp (descending) and keep only the first card of each user"""
folder_path = "./assets/cards/"
files = os.listdir(folder_path)
done: set[str] = set()
for f in sorted([f.split('-') for f in files], key=lambda f: int(f[1]), reverse=True):
if delete_all or f[0] in done:
os.remove(folder_path + "-".join(f))
else:
done.add(f[0])

@clear_cards_loop.before_loop
async def before_clear_cards_loop(self):
await self.bot.wait_until_ready()

@clear_cards_loop.error
async def on_clear_cards_loop_error(self, error: Exception):
self.bot.dispatch("error", error, "XP decay loop has stopped <@279568324260528128>")


async def get_image_from_url(self, url: str):
"Download an image from an url"
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return Image.open(BytesIO(await response.read()))

async def clear_cards(self, delete_all: bool=False):
"""Delete outdated rank cards"""
files = os.listdir("./assets/cards/")
done: set[str] = set()
for f in sorted([f.split('-')+["./assets/cards/"+f] for f in files], key=operator.itemgetter(1), reverse=True):
if delete_all or f[0] in done:
os.remove(f[3])
else:
done.add(f[0])

@app_commands.command(name="rank")
@app_commands.describe(user="The user to get the rank of. If not specified, it will be you.")
Expand Down

0 comments on commit 36eb475

Please sign in to comment.