Skip to content

Commit

Permalink
fix: fix the loading of daily weather data
Browse files Browse the repository at this point in the history
  • Loading branch information
clement-pages committed Dec 5, 2023
1 parent 8c23db4 commit 8633de3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 15 deletions.
5 changes: 5 additions & 0 deletions sunbot/SunController.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ async def on_ready(self) -> None:
if user.id not in self.usr_dict:
self.usr_dict[user.id] = current_usr
self.srv_dict[server.id].addUser(current_usr)
# load daily weather data
await self.daily_weather_handler.load_locations_subscribers(
self.bot.get_user,
self.bot.get_channel,
)
loop = asyncio.get_running_loop()
# setup signal handlers:
loop.add_signal_handler(signal.SIGINT,
Expand Down
30 changes: 15 additions & 15 deletions sunbot/weather_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import json
import logging
import os
from typing import Dict, Literal, Union
from typing import Dict, List, Literal, Union

import discord
from sunbot.location import Location
Expand Down Expand Up @@ -144,8 +144,7 @@ async def add_sub2location(self, subscriber : Union[discord.TextChannel, discord
sub_id = subscriber.guild.id
sub_type = SERVER_SUB_TYPE
else:
logging.error("Unknown subscriber type %s", sub_type)
raise ValueError("Unknown subscriber type")
raise ValueError(f"Unknown subscriber type {type(subscriber)}")
# It is not needed to check if entity was already added, the corresponding
# discord interaction will just be updated
await self.__mutex_access_dict.acquire()
Expand Down Expand Up @@ -217,18 +216,19 @@ async def save_locations_subscribers(self) -> None:
copy_dict[sub_type] = []
for location, location_subs_dict in sub_dict.items():
# Replace location by their name and tz to allow serialization:
location_dict = {'name': location.name, 'tz': location.tz, 'subscribers': []}
location_dict = {'name': location.name, 'tz': str(location.tz), 'subscribers': []}
# Only subsribers' id need to be saved:
for subscriber_id in location_subs_dict.keys():
location_dict['subscribers'].append(subscriber_id)
for sub_id, entity in location_subs_dict.items():
subscriber_dict = {"sub_id": sub_id, "entity_id": entity.id}
location_dict['subscribers'].append(subscriber_dict)
copy_dict[sub_type].append(location_dict)
self.__mutex_access_dict.release()
with open(self.save_file_path, 'w', encoding='UTF-8') as json_file:
json.dump(copy_dict, json_file, ensure_ascii=False, indent=2)
os.chmod(self.save_file_path, mode=0o777)
logging.info("Location's subscribers data saved into %s", self.save_file_path)

async def load_locations_subscribers(self, usr_loader, srv_loader) -> None:
async def load_locations_subscribers(self, usr_loader, channel_loader) -> None:
"""Load data from a JSON save file into the structure that contains
entities that subscribe to each location
## Parameters:
Expand All @@ -251,18 +251,19 @@ async def load_locations_subscribers(self, usr_loader, srv_loader) -> None:
for sub_type, locations_dict_list in loaded_dict.items():
for location_dict in locations_dict_list:
location = Location(location_dict['name'], location_dict['tz'])
for subscriber_id in location_dict['subscribers']:
for sub_dict in location_dict['subscribers']:
if sub_type == USER_SUB_TYPE:
subscriber = usr_loader(subscriber_id)
subscriber = usr_loader(sub_dict["sub_id"])
else:
subscriber = srv_loader(subscriber_id)
subscriber = channel_loader(sub_dict["entity_id"])
# subscriber is None if current subscriber is not linked to an
# existent discord entity:
if subscriber is None:
logging.error("ID %d does not correspond to any discord entity",
subscriber_id)
logging.error("Subscriber %d does not correspond to any discord entity",
sub_dict["sub_id"]
)
continue # Do not add a None subscriber, as it can broke the bot
await self.add_sub2location(subscriber, location.name, location.tz)
await self.add_sub2location(subscriber, location.name, str(location.tz))
logging.info("Subscribers data was successfully loaded")

@abstractmethod
Expand Down Expand Up @@ -353,8 +354,7 @@ async def add_sub2location(self, subscriber : Union[discord.TextChannel, discord
elif isinstance(subscriber, discord.TextChannel):
sub_type = SERVER_SUB_TYPE
else:
logging.error("Unknown subscriber type %s", sub_type)
raise ValueError("Unknown subscriber type")
raise ValueError(f"Unknown subscriber type: {type(subscriber)}")
# Only add specified location if there is not already known by the task:
location = Location(location_name, location_tz)
if location not in self.__dict_weather_sent_flag[sub_type]:
Expand Down

0 comments on commit 8633de3

Please sign in to comment.