fix: Handle empty giveaway data file and improve async directory creation

This commit is contained in:
Slipstream 2025-05-30 16:23:56 -06:00
parent 4579d5f9c8
commit bd3a1c031a
Signed by: slipstream
GPG Key ID: 13E498CE010AC6FD

View File

@ -183,7 +183,11 @@ class GiveawaysCog(commands.Cog, name="Giveaways"):
try:
async with aiofiles.open(GIVEAWAY_DATA_FILE, mode='r') as f:
content = await f.read()
giveaways_data_for_views = json.loads(content)
if not content: # Handle empty file case
giveaways_data_for_views = []
else:
giveaways_data_for_views = await self.bot.loop.run_in_executor(None, json.loads, content)
for gw_data in giveaways_data_for_views:
# We only need to re-add views for messages that should have them
is_ended = gw_data.get("ended", False)
@ -206,8 +210,10 @@ class GiveawaysCog(commands.Cog, name="Giveaways"):
async def _ensure_data_dir_exists(self):
if not os.path.exists(DATA_DIR): # os.path.exists is synchronous, but fine for checking existence
await aiofiles.os.makedirs(DATA_DIR) # Use aiofiles.os for async mkdir
try:
await aiofiles.os.makedirs(DATA_DIR, exist_ok=True) # Use aiofiles.os for async mkdir, exist_ok handles if it already exists
except Exception as e:
print(f"Error ensuring data directory {DATA_DIR} exists: {e}")
def cog_unload(self):
self.check_giveaways_loop.cancel()
@ -218,7 +224,11 @@ class GiveawaysCog(commands.Cog, name="Giveaways"):
try:
async with aiofiles.open(GIVEAWAY_DATA_FILE, mode='r') as f:
content = await f.read()
giveaways_data = json.loads(content)
if not content: # Handle empty file case
giveaways_data = []
else:
giveaways_data = await self.bot.loop.run_in_executor(None, json.loads, content)
now = datetime.datetime.now(datetime.timezone.utc)
for gw_data in giveaways_data:
gw_data["end_time"] = datetime.datetime.fromisoformat(gw_data["end_time"])
@ -275,12 +285,13 @@ class GiveawaysCog(commands.Cog, name="Giveaways"):
new_gw_to_save["end_time"] = new_gw_to_save["end_time"].isoformat()
new_gw_to_save["participants"] = list(new_gw_to_save["participants"])
giveaways_to_save.append(new_gw_to_save)
# Also add to all_loaded_giveaways for next time
self.all_loaded_giveaways.append(gw_active.copy())
# Also add to all_loaded_giveaways for next time
self.all_loaded_giveaways.append(gw_active.copy())
# Offload json.dumps to executor
json_string_to_save = await self.bot.loop.run_in_executor(None, json.dumps, giveaways_to_save, indent=4)
async with aiofiles.open(GIVEAWAY_DATA_FILE, mode='w') as f:
await f.write(json.dumps(giveaways_to_save, indent=4))
await f.write(json_string_to_save)
# print(f"Saved {len(giveaways_to_save)} giveaways to disk.")
except Exception as e:
print(f"Error saving giveaways: {e}")