Skip to content
This repository was archived by the owner on Feb 7, 2026. It is now read-only.

Commit f9d40aa

Browse files
authored
Merge pull request #314 from PyBotDevs/user-data-library
Migrate UserData system completely to a framework module
2 parents 3a3303e + 19501c9 commit f9d40aa

3 files changed

Lines changed: 60 additions & 32 deletions

File tree

cogs/economy.py

Lines changed: 15 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,13 @@
22

33
# Imports
44
import discord
5-
import json
65
import random
76
import math
87
import utils.logger
98
import asyncio
109
import framework.isobot.currency
1110
from framework.isobot.shop import ShopData
12-
from framework.isobot.db import levelling, items
11+
from framework.isobot.db import levelling, items, userdata
1312
from random import randint
1413
from discord import option, ApplicationContext
1514
from discord.ext import commands
@@ -19,6 +18,7 @@
1918
currency = framework.isobot.currency.CurrencyAPI("database/currency.json", "logs/currency.log")
2019
levelling = levelling.Levelling()
2120
items = items.Items()
21+
userdata = userdata.UserData()
2222
shop_data = ShopData("config/shop.json")
2323
all_item_ids = shop_data.get_item_ids()
2424
shopitem = shop_data.get_raw_data()
@@ -32,19 +32,6 @@
3232
"Doctor"
3333
]
3434

35-
with open("database/user_data.json", 'r') as f: userdat = json.load(f)
36-
37-
def save():
38-
with open("database/user_data.json", 'w+') as f: json.dump(userdat, f, indent=4)
39-
40-
# Functions
41-
def new_userdat(id: int):
42-
if str(id) not in userdat.keys():
43-
userdat[str(id)] = {"work_job": None}
44-
save()
45-
return 0
46-
else: return 1
47-
4835
# Commands
4936
class Economy(commands.Cog):
5037
def __init__(self, bot):
@@ -410,16 +397,17 @@ async def give(self, ctx: ApplicationContext, user:discord.User, amount:int):
410397
)
411398
@commands.cooldown(1, 1800, commands.BucketType.user)
412399
async def work(self, ctx: ApplicationContext):
413-
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)
414-
if userdat[str(ctx.author.id)]["work_job"] == "Discord mod": i = randint(5000, 10000)
415-
elif userdat[str(ctx.author.id)]["work_job"] == "YouTuber": i = randint(10000, 15000)
416-
elif userdat[str(ctx.author.id)]["work_job"] == "Streamer": i = randint(12000, 18000)
417-
elif userdat[str(ctx.author.id)]["work_job"] == "Developer": i = randint(20000, 40000)
418-
elif userdat[str(ctx.author.id)]["work_job"] == "Scientist": i = randint(50000, 100000)
419-
elif userdat[str(ctx.author.id)]["work_job"] == "Engineer": i = randint(100000, 175000)
420-
elif userdat[str(ctx.author.id)]["work_job"] == "Doctor": i = randint(200000, 300000)
400+
job_name = userdata.fetch(ctx.author.id, "work_job")
401+
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)
402+
if job_name == "Discord mod": i = randint(5000, 10000)
403+
elif job_name == "YouTuber": i = randint(10000, 15000)
404+
elif job_name == "Streamer": i = randint(12000, 18000)
405+
elif job_name == "Developer": i = randint(20000, 40000)
406+
elif job_name == "Scientist": i = randint(50000, 100000)
407+
elif job_name == "Engineer": i = randint(100000, 175000)
408+
elif job_name == "Doctor": i = randint(200000, 300000)
421409
currency.add(ctx.author.id, i)
422-
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.')
410+
await ctx.respond(f'{ctx.author.mention} worked for a 30-minute shift as a {job_name} and earned {i} coins.')
423411

424412
@commands.slash_command(
425413
name="work_list",
@@ -447,8 +435,7 @@ async def work_select(self, ctx: ApplicationContext, job: str):
447435
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)
448436
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)
449437
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)
450-
userdat[str(ctx.author.id)]["work_job"] = job
451-
save()
438+
userdata.set(ctx.author.id, "work_job", job)
452439
localembed = discord.Embed(title="New job!", description=f"You are now working as a {job}!")
453440
await ctx.respond(embed=localembed)
454441

@@ -457,9 +444,8 @@ async def work_select(self, ctx: ApplicationContext, job: str):
457444
description="Quit your job."
458445
)
459446
async def work_resign(self, ctx: ApplicationContext):
460-
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)
461-
userdat[str(ctx.author.id)]["work_job"] = None
462-
save()
447+
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)
448+
userdata.set(ctx.author.id, "work_job", None)
463449
localembed = discord.Embed(title="Resignation", description="You have successfully resigned from your job.")
464450
await ctx.respond(embed=localembed)
465451

framework/isobot/db/userdata.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
"""The framework module library used for managing general user data."""
2+
3+
# Imports
4+
import json
5+
6+
# Functions
7+
class UserData():
8+
"""Used to initialize the UserData system."""
9+
def __init__(self):
10+
print("[framework/db/UserData] UserData library initialized.")
11+
12+
def load(self) -> dict:
13+
"""Fetches and returns the latest data from the levelling database."""
14+
with open("database/user_data.json", 'r', encoding="utf8") as f: db = json.load(f)
15+
return db
16+
17+
def save(self, data: dict) -> int:
18+
"""Dumps all cached data to your local machine."""
19+
with open("database/user_data.json", 'w+', encoding="utf8") as f: json.dump(data, f, indent=4)
20+
return 0
21+
22+
def generate(self, user_id: int) -> int:
23+
"""Generates a new data key for the specified user.\n
24+
Returns `0` if the request was successful, returns `1` if the data key already exists."""
25+
userdat = self.load()
26+
if str(user_id) not in userdat.keys():
27+
userdat[str(user_id)] = {"work_job": None}
28+
self.save(userdat)
29+
return 0
30+
else: return 1
31+
32+
def fetch(self, user_id: int, key: str) -> str:
33+
"""Fetches the vakue of a data key, from a specific user."""
34+
userdat = self.load()
35+
return userdat[str(user_id)][key]
36+
37+
def set(self, user_id: int, key: str, value) -> int:
38+
"""Sets a new value for a data key, for a specific user."""
39+
userdat = self.load()
40+
userdat[str(user_id)][key] = value
41+
self.save(userdat)
42+
return 0

main.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,9 @@
1111
from math import floor
1212
from random import randint
1313
from framework.isobot import currency, colors, settings
14-
from framework.isobot.db import levelling, items
14+
from framework.isobot.db import levelling, items, userdata
1515
from discord import ApplicationContext, option
1616
from discord.ext import commands
17-
from cogs.economy import new_userdat
1817
from cogs.isocoin import create_isocoin_key
1918

2019
# Slash option types:
@@ -57,6 +56,7 @@ def save():
5756
settings = settings.Configurator()
5857
levelling = levelling.Levelling()
5958
items = items.Items()
59+
userdata = userdata.UserData()
6060

6161
# Theme Loader
6262
themes = False # True: enables themes; False: disables themes;
@@ -96,7 +96,7 @@ async def on_message(ctx):
9696
currency.new_wallet(ctx.author.id)
9797
currency.new_bank(ctx.author.id)
9898
create_isocoin_key(ctx.author.id)
99-
new_userdat(ctx.author.id)
99+
userdata.generate(ctx.author.id)
100100
settings.generate(ctx.author.id)
101101
items.generate(ctx.author.id)
102102
levelling.generate(ctx.author.id)

0 commit comments

Comments
 (0)