Skip to content

Commit

Permalink
Merge pull request #310 from cyanogus/weather-db-library
Browse files Browse the repository at this point in the history
Migrate weather db commands from weather cog to the framework
  • Loading branch information
notsniped authored Oct 8, 2023
2 parents 4e13811 + f454a0d commit 8856933
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 19 deletions.
32 changes: 13 additions & 19 deletions cogs/weather.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand All @@ -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)

Expand All @@ -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)

Expand All @@ -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)
Expand All @@ -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)
Expand All @@ -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"<t:{sunrise}:f>", inline=False)
Expand Down
53 changes: 53 additions & 0 deletions framework/isobot/db/weather.py
Original file line number Diff line number Diff line change
@@ -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"]

0 comments on commit 8856933

Please sign in to comment.