From 25a0d7fd9b34252fd0b9f4b50369231b47a9536a Mon Sep 17 00:00:00 2001 From: snipe <72265661+notsniped@users.noreply.github.com> Date: Sun, 21 Apr 2024 22:59:44 +0530 Subject: [PATCH] Move all IsoCard database functions from cog to a separate framework module --- cogs/isocard.py | 33 ++++++---------------- framework/isobot/db/isocard.py | 51 ++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 25 deletions(-) create mode 100644 framework/isobot/db/isocard.py diff --git a/cogs/isocard.py b/cogs/isocard.py index 38302e15..89e6f4ba 100644 --- a/cogs/isocard.py +++ b/cogs/isocard.py @@ -2,17 +2,13 @@ # Imports import discord -import json import random -import time +from framework.isobot.db.isocard import IsoCard from discord import option, ApplicationContext, SlashCommandGroup from discord.ext import commands -# Variables -with open("database/isocard.json", 'r', encoding="utf-8") as f: isocard_db = json.load(f) - -def save(): - with open("database/isocard.json", 'w+', encoding="utf-8") as f: json.dump(isocard_db, f, indent=4) +# Variables and Functions +isocard_db = IsoCard() def generate_card_id() -> int: # Generate 16 random digits and append to a str variable @@ -38,24 +34,12 @@ def __init__(self, bot): @option(name="ssc", description="The Special Security Code for your new card. (aka. CVV)", type=int) async def register(self, ctx: ApplicationContext, ssc: int): new_card_id = generate_card_id() - isocard_db[str(new_card_id)] = { - "cardholder_user_id": ctx.author.id, - "cardholder_name": ctx.author.name, - "ssc": ssc, # Special Security Code - "card_registration_timestamp": round(time.time()), - "type": "standard", # Card type - "config" : { - "spend_limit": 100000, # Daily spending limit for IsoCard - "shared_cardholder_ids": [], # Other users who can use this card - "card_label": None - } - } - save() + new_card_data = isocard_db.generate(new_card_id, ctx.author.id, ctx.author.name, ssc) localembed = discord.Embed(title=":tada: Congratulations!", description="Your new IsoCard has successfully been registered!", color=discord.Color.green()) localembed.add_field(name="Cardholder name", value=ctx.author.name, inline=False) localembed.add_field(name="Card number", value=new_card_id, inline=False) localembed.add_field(name="SSC", value=f"`{ssc}`", inline=True) - localembed.add_field(name="Card registration date", value=f"", inline=False) + localembed.add_field(name="Card registration date", value=f"", inline=False) localembed.set_footer(text="Always remember, NEVER share your card info to anyone!") await ctx.respond(embed=localembed, ephemeral=True) @@ -66,7 +50,7 @@ async def register(self, ctx: ApplicationContext, ssc: int): @option(name="card_number", description="Enter your card number of the card you want to view.", type=int) async def info(self, ctx: ApplicationContext, card_number: int): try: - try: card_data = isocard_db[str(card_number)] + try: card_data = isocard_db.fetch_card_data(card_number) except KeyError: return await ctx.respond("There was a problem with your card number. Please check it and try again.", ephemeral=True) if card_data["cardholder_user_id"] != ctx.author.id: return await ctx.respond("You do not have permission to access this IsoCard.\n If you think this is an error, please contact the devs.", ephemeral=True) localembed = discord.Embed( @@ -117,11 +101,10 @@ async def my_card(self, ctx: ApplicationContext): @option(name="card_number", description="Enter your card number that you want to work with.", type=int) @option(name="new_label", description="What do you want your new card label to be?", type=str, default=None) async def options_label(self, ctx: ApplicationContext, card_number: int, new_label: str): - try: card_data = isocard_db[str(card_number)] + try: card_data = isocard_db.fetch_card_data(card_number) except KeyError: return await ctx.respond("There was a problem with your card number. Please check it and try again.", ephemeral=True) if card_data["cardholder_user_id"] != ctx.author.id: return await ctx.respond("You do not have permission to access this IsoCard.\n If you think this is an error, please contact the devs.", ephemeral=True) - isocard_db[str(card_number)]["config"]["card_label"] = new_label - save() + isocard_db.set_card_label(card_number, new_label) if new_label == None: return await ctx.respond(embed=discord.Embed(description=":white_check_mark: Your card label has been reset.", color=discord.Color.green()), ephemeral=True) else: return await ctx.respond(embed=discord.Embed(description=":white_check_mark: Your card label has been edited.", color=discord.Color.green()), ephemeral=True) diff --git a/framework/isobot/db/isocard.py b/framework/isobot/db/isocard.py new file mode 100644 index 00000000..bf03ae0c --- /dev/null +++ b/framework/isobot/db/isocard.py @@ -0,0 +1,51 @@ +"""The framework database module for handling IsoCard data.""" + +# Imports +import json +import time +from colors import Colors as colors + +# Functions +class IsoCard: + def __init__(self): + print(f"[framework/db/IsoCard] {colors.green}IsoCard db library initialized.{colors.end}") + + def load(self) -> dict: + """Loads the latest IsoCard database content from local storage.""" + with open("database/isocard.json", "r", encoding="utf-8") as f: data = json.load(f) + return data + + def save(self, data: dict) -> int: + """Saves the latest cached database to local storage.""" + with open("database/isocard.json", 'w+', encoding="utf-8") as f: json.dump(data, f, indent=4) + return 0 + + def fetch_card_data(self, card_id: int) -> dict: + """Fetches the raw `dict` data related to the given IsoCard id.\n\nReturns data as `dict` if successful, returns `KeyError` if card id does not exist.""" + isocard_db = self.load() + return isocard_db[str(card_id)] + + def generate(self, new_card_id: int, user_id: int, user_name: str, ssc: int) -> dict: + """Generates a new IsoCard with the given data, and returns that IsoCard data as a `dict` through the function.""" + isocard_db = self.load() + isocard_db[str(new_card_id)] = { + "cardholder_user_id": user_id, + "cardholder_name": user_name, + "ssc": ssc, # Special Security Code + "card_registration_timestamp": round(time.time()), + "type": "standard", # Card type + "config" : { + "spend_limit": 100000, # Daily spending limit for IsoCard + "shared_cardholder_ids": [], # Other users who can use this card + "card_label": None + } + } + self.save(isocard_db) + return isocard_db[str(new_card_id)] + + def set_card_label(self, card_id: int, label: str) -> int: + """Changes the display label for a specific IsoCard.""" + isocard_db = self.load() + isocard_db[str(card_id)]["config"]["card_label"] = label + self.save() + return 0