From 3ec360b6fe5c374c00012cdce573a35482088d36 Mon Sep 17 00:00:00 2001 From: snipe <72265661+notsniped@users.noreply.github.com> Date: Mon, 23 Oct 2023 22:23:52 +0530 Subject: [PATCH 1/3] Migrate UserData system completely to a framework module --- cogs/economy.py | 43 ++++++++++++--------------------- framework/isobot/db/userdata.py | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 28 deletions(-) create mode 100644 framework/isobot/db/userdata.py diff --git a/cogs/economy.py b/cogs/economy.py index 0b11f090..1f4111e2 100644 --- a/cogs/economy.py +++ b/cogs/economy.py @@ -9,7 +9,7 @@ import asyncio import framework.isobot.currency from framework.isobot.shop import ShopData -from framework.isobot.db import levelling, items +from framework.isobot.db import levelling, items, userdata from random import randint from discord import option, ApplicationContext from discord.ext import commands @@ -19,6 +19,7 @@ currency = framework.isobot.currency.CurrencyAPI("database/currency.json", "logs/currency.log") levelling = levelling.Levelling() items = items.Items() +userdata = userdata.UserData() shop_data = ShopData("config/shop.json") all_item_ids = shop_data.get_item_ids() shopitem = shop_data.get_raw_data() @@ -32,19 +33,6 @@ "Doctor" ] -with open("database/user_data.json", 'r') as f: userdat = json.load(f) - -def save(): - with open("database/user_data.json", 'w+') as f: json.dump(userdat, f, indent=4) - -# Functions -def new_userdat(id: int): - if str(id) not in userdat.keys(): - userdat[str(id)] = {"work_job": None} - save() - return 0 - else: return 1 - # Commands class Economy(commands.Cog): def __init__(self, bot): @@ -410,16 +398,17 @@ async def give(self, ctx: ApplicationContext, user:discord.User, amount:int): ) @commands.cooldown(1, 1800, commands.BucketType.user) async def work(self, ctx: ApplicationContext): - if userdat[str(ctx.author.id)]["work_job"] == None: return await ctx.respond("You don't currently have a job! Join one by using the `/work_select` command.", ephemeral=True) - if userdat[str(ctx.author.id)]["work_job"] == "Discord mod": i = randint(5000, 10000) - elif userdat[str(ctx.author.id)]["work_job"] == "YouTuber": i = randint(10000, 15000) - elif userdat[str(ctx.author.id)]["work_job"] == "Streamer": i = randint(12000, 18000) - elif userdat[str(ctx.author.id)]["work_job"] == "Developer": i = randint(20000, 40000) - elif userdat[str(ctx.author.id)]["work_job"] == "Scientist": i = randint(50000, 100000) - elif userdat[str(ctx.author.id)]["work_job"] == "Engineer": i = randint(100000, 175000) - elif userdat[str(ctx.author.id)]["work_job"] == "Doctor": i = randint(200000, 300000) + job_name = userdata.fetch(ctx.author.id, "work_job") + if job_name == None: return await ctx.respond("You don't currently have a job! Join one by using the `/work_select` command.", ephemeral=True) + if job_name == "Discord mod": i = randint(5000, 10000) + elif job_name == "YouTuber": i = randint(10000, 15000) + elif job_name == "Streamer": i = randint(12000, 18000) + elif job_name == "Developer": i = randint(20000, 40000) + elif job_name == "Scientist": i = randint(50000, 100000) + elif job_name == "Engineer": i = randint(100000, 175000) + elif job_name == "Doctor": i = randint(200000, 300000) currency.add(ctx.author.id, i) - await ctx.respond(f'{ctx.author.mention} worked for a 30-minute shift as a {userdat[str(ctx.author.id)]["work_job"]} and earned {i} coins.') + await ctx.respond(f'{ctx.author.mention} worked for a 30-minute shift as a {job_name} and earned {i} coins.') @commands.slash_command( name="work_list", @@ -447,8 +436,7 @@ async def work_select(self, ctx: ApplicationContext, job: str): elif job == "Scientist" and levelling.get_level(ctx.author.id) < 20: return await ctx.respond("You currently do not have the required level to perform this job!", ephemeral=True) elif job == "Engineer" and levelling.get_level(ctx.author.id) < 25: return await ctx.respond("You currently do not have the required level to perform this job!", ephemeral=True) elif job == "Doctor" and levelling.get_level(ctx.author.id) < 40: return await ctx.respond("You currently do not have the required level to perform this job!", ephemeral=True) - userdat[str(ctx.author.id)]["work_job"] = job - save() + userdata.set(ctx.author.id, "work_job", job) localembed = discord.Embed(title="New job!", description=f"You are now working as a {job}!") await ctx.respond(embed=localembed) @@ -457,9 +445,8 @@ async def work_select(self, ctx: ApplicationContext, job: str): description="Quit your job." ) async def work_resign(self, ctx: ApplicationContext): - if userdat[str(ctx.author.id)]["work_job"] is None: return await ctx.respond("You can't quit your job if you don't already have one!", ephemeral=True) - userdat[str(ctx.author.id)]["work_job"] = None - save() + if userdata.fetch(ctx.author.id, "work_job") is None: return await ctx.respond("You can't quit your job if you don't already have one!", ephemeral=True) + userdata.set(ctx.author.id, "work_job", None) localembed = discord.Embed(title="Resignation", description="You have successfully resigned from your job.") await ctx.respond(embed=localembed) diff --git a/framework/isobot/db/userdata.py b/framework/isobot/db/userdata.py new file mode 100644 index 00000000..b63fcce7 --- /dev/null +++ b/framework/isobot/db/userdata.py @@ -0,0 +1,42 @@ +"""The framework module library used for managing general user data.""" + +# Imports +import json + +# Functions +class UserData(): + """Used to initialize the UserData system.""" + def __init__(self): + print("[framework/db/UserData] UserData library initialized.") + + def load(self) -> dict: + """Fetches and returns the latest data from the levelling database.""" + with open("database/user_data.json", 'r', encoding="utf8") 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/user_data.json", 'w+', encoding="utf8") as f: json.dump(data, f, indent=4) + return 0 + + def generate(self, user_id: int) -> int: + """Generates a new data key for the specified user.\n + Returns `0` if the request was successful, returns `1` if the data key already exists.""" + userdat = self.load() + if str(user_id) not in userdat.keys(): + userdat[str(user_id)] = {"work_job": None} + self.save(userdat) + return 0 + else: return 1 + + def fetch(self, user_id: int, key: str) -> str: + """Fetches the vakue of a data key, from a specific user.""" + userdat = self.load() + return userdat[str(user_id)][key] + + def set(self, user_id: int, key: str, value) -> int: + """Sets a new value for a data key, for a specific user.""" + userdat = self.load() + userdat[str(user_id)][key] = value + self.save(userdat) + return 0 From 6ad9acc9266d5fcff92b4205a3319b1b64700ce4 Mon Sep 17 00:00:00 2001 From: snipe <72265661+notsniped@users.noreply.github.com> Date: Mon, 23 Oct 2023 22:28:31 +0530 Subject: [PATCH 2/3] Remove unused `json` import Omg how did I come to this :joy: --- cogs/economy.py | 1 - 1 file changed, 1 deletion(-) diff --git a/cogs/economy.py b/cogs/economy.py index 1f4111e2..e3c73e36 100644 --- a/cogs/economy.py +++ b/cogs/economy.py @@ -2,7 +2,6 @@ # Imports import discord -import json import random import math import utils.logger From 19501c9f15805351862e3465f8eca15fc05c9716 Mon Sep 17 00:00:00 2001 From: snipe <72265661+notsniped@users.noreply.github.com> Date: Mon, 23 Oct 2023 23:19:04 +0530 Subject: [PATCH 3/3] Add UserData framework module support --- main.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/main.py b/main.py index 3e5c78ee..304e5c86 100644 --- a/main.py +++ b/main.py @@ -11,10 +11,9 @@ from math import floor from random import randint from framework.isobot import currency, colors, settings -from framework.isobot.db import levelling, items +from framework.isobot.db import levelling, items, userdata from discord import ApplicationContext, option from discord.ext import commands -from cogs.economy import new_userdat from cogs.isocoin import create_isocoin_key # Slash option types: @@ -57,6 +56,7 @@ def save(): settings = settings.Configurator() levelling = levelling.Levelling() items = items.Items() +userdata = userdata.UserData() # Theme Loader themes = False # True: enables themes; False: disables themes; @@ -96,7 +96,7 @@ async def on_message(ctx): currency.new_wallet(ctx.author.id) currency.new_bank(ctx.author.id) create_isocoin_key(ctx.author.id) - new_userdat(ctx.author.id) + userdata.generate(ctx.author.id) settings.generate(ctx.author.id) items.generate(ctx.author.id) levelling.generate(ctx.author.id)