From cb8117c269a3342ea6aa81b3a551534b783c4f97 Mon Sep 17 00:00:00 2001 From: Sabi <120003982+cyanogus@users.noreply.github.com> Date: Sat, 7 Oct 2023 10:31:12 +0530 Subject: [PATCH 1/2] Add framework library for managing the weather database --- framework/isobot/db/weather.py | 53 ++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 framework/isobot/db/weather.py diff --git a/framework/isobot/db/weather.py b/framework/isobot/db/weather.py new file mode 100644 index 00000000..964d2082 --- /dev/null +++ b/framework/isobot/db/weather.py @@ -0,0 +1,53 @@ +# Imports +import json +from discord import User + +# Classes +class Colors: + """Contains general stdout colors.""" + cyan = '\033[96m' + red = '\033[91m' + green = '\033[92m' + end = '\033[0m' + +# Functions +class Weather(Colors): + """Class to manage the weather db""" + def __init__(self): + print(f"[Framework/Loader] {Colors.green}Weather database initialized.{Colors.end}") + + def load(self) -> dict: + """Fetches and returns the latest data from the levelling database.""" + with open("database/weather.json", 'r', encoding="utf-8") as f: db = json.load(f) + return db + + def save(self, data: dict) -> int: + """Dumps all cached data to your local machine.""" + with open("database/weather.json", 'w+', encoding="utf-8") as f: json.dump(data, f, indent=4) + return 0 + + def new(self, user_id: User): + user_db = self.load() + if str(user_id) not in user_db: user_db[str(user_id)] = {"location": None, "scale": "Celsius"} + self.save(user_db) + return 0 + + def set_scale(self, user_id: User, scale: str) -> int: + user_db = self.load() + user_db[str(user_id)]["scale"] = scale + self.save(user_db) + return 0 + + def set_default_location(self, user_id: User, location: str) -> int: + user_db = self.load() + user_db[str(user_id)]["location"] = location + self.save(user_db) + return 0 + + def get_scale(self, user_id: User): + user_db = self.load() + return user_db[str(user_id)]["scale"] + + def get_default_location(self, user_id: User): + user_db = self.load() + return user_db[str(user_id)]["location"] From 817d0f2690df53c2401760aa302b353850f1e19b Mon Sep 17 00:00:00 2001 From: Sabi <120003982+cyanogus@users.noreply.github.com> Date: Sat, 7 Oct 2023 10:33:48 +0530 Subject: [PATCH 2/2] Update weather cog to work with weather db library Very fun fr --- cogs/weather.py | 32 +++++++++++++------------------- 1 file changed, 13 insertions(+), 19 deletions(-) diff --git a/cogs/weather.py b/cogs/weather.py index 5f94b64e..8ca3c075 100644 --- a/cogs/weather.py +++ b/cogs/weather.py @@ -3,17 +3,13 @@ import json import requests import os +from framework.isobot.db import weather from discord import ApplicationContext, option from discord.ext import commands # Variables api_key = os.environ['openweathermap_API_KEY'] -with open("database/weather.json", 'r', encoding="utf-8") as f: user_db = json.load(f) - -# Functions -def save(): - """Dumps all cached databases to storage.""" - with open("database/weather.json", 'w+', encoding="utf-8") as f: json.dump(user_db, f, indent=4) +weather = weather.Weather() # Commands class Weather(commands.Cog): @@ -26,13 +22,12 @@ def __init__(self, bot): ) @option(name="location", description="What location do you want to set?", type=str) async def weather_set_location(self, ctx: ApplicationContext, location: str): - if str(ctx.author.id) not in user_db: user_db[str(ctx.author.id)] = {"location": None, "scale": "Celsius"} + weather.new(ctx.author.id) test_ping = requests.get(f"https://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}").content test_ping_json = json.loads(test_ping) if test_ping_json["cod"] == '404': return await ctx.respond(":warning: This location does not exist.", ephemeral=True) else: - user_db[str(ctx.author.id)]["location"] = location.lower() - save() + weather.set_default_location(ctx.author.id, location.lower()) localembed = discord.Embed(description="Your default location has been updated.", color=discord.Color.green()) await ctx.respond(embed=localembed) @@ -42,10 +37,9 @@ async def weather_set_location(self, ctx: ApplicationContext, location: str): ) @option(name="scale", description="Which scale do you want to use?", type=str, choices=["Celsius", "Fahrenheit", "Kelvin"]) async def weather_set_scale(self, ctx: ApplicationContext, scale: str): - if str(ctx.author.id) not in user_db: user_db[str(ctx.author.id)] = {"location": None, "scale": "Celsius"} + weather.new(ctx.author.id) if scale not in ["Celsius", "Fahrenheit", "Kelvin"]: return 1 - user_db[str(ctx.author.id)]["scale"] = scale - save() + weather.set_scale(ctx.author.id, scale) localembed = discord.Embed(description="Your preferred unit scale has been updated.", color=discord.Color.green()) await ctx.respond(embed=localembed) @@ -55,10 +49,10 @@ async def weather_set_scale(self, ctx: ApplicationContext, scale: str): ) @option(name="location", description="The location you want weather info about (leave empty for set location)", type=str, default=None) async def weather(self, ctx: ApplicationContext, location: str = None): - if str(ctx.author.id) not in user_db: user_db[str(ctx.author.id)] = {"location": None, "scale": "Celsius"} + weather.new(ctx.author.id) if location == None: - if user_db[str(ctx.author.id)]["location"] == None: return await ctx.respond("You do not have a default location set yet.\nEnter a location name and try again.", ephemeral=True) - else: location = user_db[str(ctx.author.id)]["location"] + if weather.get_default_location(ctx.author.id) == None: return await ctx.respond("You do not have a default location set yet.\nEnter a location name and try again.", ephemeral=True) + else: location = weather.get_default_location(ctx.author.id) location = location.replace(" ", "%20") api_request = requests.get(f"https://api.openweathermap.org/data/2.5/weather?q={location}&appid={api_key}").content req: dict = json.loads(api_request) @@ -71,11 +65,11 @@ async def weather(self, ctx: ApplicationContext, location: str = None): # Stripped API request data loc_name = req["name"] - if user_db[str(ctx.author.id)]["scale"] == "Celsius": + if weather.get_scale(ctx.author.id) == "Celsius": temp = round(req["main"]["temp"] - 273) temp_max = round(req["main"]["temp_max"] - 273) temp_min = round(req["main"]["temp_min"] - 273) - elif user_db[str(ctx.author.id)]["scale"] == "Fahrenheit": + elif weather.get_scale(ctx.author.id) == "Fahrenheit": temp = round(((req["main"]["temp"] - 273) * 9/5) + 32) temp_max = round(((req["main"]["temp_max"] - 273) * 9/5) + 32) temp_min = round(((req["main"]["temp_min"] - 273) * 9/5) + 32) @@ -94,8 +88,8 @@ async def weather(self, ctx: ApplicationContext, location: str = None): description=f"**{forcast}**\n{forcast_description}", color=discord.Color.blue() ) - if user_db[str(ctx.author.id)]["scale"] == "Celsius": localembed.add_field(name="Temperature", value=f"**{temp}C** (max: {temp_max}C, min: {temp_min}C)") - elif user_db[str(ctx.author.id)]["scale"] == "Fahrenheit": localembed.add_field(name="Temperature", value=f"**{temp}F** (max: {temp_max}F, min: {temp_min}F)") + if weather.get_scale(ctx.author.id) == "Celsius": localembed.add_field(name="Temperature", value=f"**{temp}C** (max: {temp_max}C, min: {temp_min}C)") + elif weather.get_scale(ctx.author.id) == "Fahrenheit": localembed.add_field(name="Temperature", value=f"**{temp}F** (max: {temp_max}F, min: {temp_min}F)") else: localembed.add_field(name="Temperature", value=f"**{temp}K** (max: {temp_max}K, min: {temp_min}K)") localembed.add_field(name="Humidity", value=f"{humidity}%") localembed.add_field(name="Sunrise", value=f"", inline=False)