Skip to content

Commit 49ceef9

Browse files
authored
Merge pull request #312 from PyBotDevs/items-db-library
Add base implementation for items db framework module
2 parents 541b66b + c904b9d commit 49ceef9

File tree

4 files changed

+87
-27
lines changed

4 files changed

+87
-27
lines changed

cogs/economy.py

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,33 +8,19 @@
88
import utils.logger
99
import asyncio
1010
import framework.isobot.currency
11+
from framework.isobot.shop import ShopData
1112
from framework.isobot.db import levelling
1213
from random import randint
1314
from discord import option, ApplicationContext
1415
from discord.ext import commands
1516

16-
# Classes
17-
class ShopData:
18-
def __init__(self, db_path: str):
19-
self.db_path = db_path
20-
with open(db_path, 'r') as f: self.config = json.load(f)
21-
22-
def get_item_ids(self) -> list:
23-
json_list = list()
24-
for h in self.config: json_list.append(str(h))
25-
return json_list
26-
27-
def get_item_names(self) -> list:
28-
json_list = list()
29-
for h in self.config: json_list.append(str(h["stylized name"]))
30-
return json_list
31-
3217
# Variables
3318
color = discord.Color.random()
3419
currency = framework.isobot.currency.CurrencyAPI("database/currency.json", "logs/currency.log")
3520
levelling = levelling.Levelling()
3621
shop_data = ShopData("config/shop.json")
3722
all_item_ids = shop_data.get_item_ids()
23+
shopitem = shop_data.get_raw_data()
3824
jobs = [
3925
"Discord mod",
4026
"YouTuber",
@@ -46,7 +32,6 @@ def get_item_names(self) -> list:
4632
]
4733

4834
with open("database/items.json", 'r') as f: items = json.load(f)
49-
with open("config/shop.json", 'r') as f: shopitem = json.load(f)
5035
with open("database/user_data.json", 'r') as f: userdat = json.load(f)
5136

5237
def save():
@@ -563,7 +548,7 @@ async def deposit(self, ctx: ApplicationContext, amount):
563548
elif int(amount) > currency.get_wallet(ctx.author.id): return await ctx.respond('The amount to deposit must not be more than what you have in your wallet!', ephemeral=True)
564549
currency.deposit(ctx.author.id, int(amount))
565550
localembed = discord.Embed(title="Deposit successful", description=f"You deposited `{amount}` coin(s) to your bank account.", color=color)
566-
localembed.add_field(name="You previously had", value=f"`{currency.get_bank(ctx.author.id) - amount} coins` in your bank account")
551+
localembed.add_field(name="You previously had", value=f"`{currency.get_bank(ctx.author.id) - int(amount)} coins` in your bank account")
567552
localembed.add_field(name="Now you have", value=f"`{currency.get_bank(ctx.author.id)} coins` in your bank account")
568553
await ctx.respond(embed=localembed)
569554

@@ -581,7 +566,7 @@ async def withdraw(self, ctx: ApplicationContext, amount):
581566
elif int(amount) > currency.get_bank(ctx.author.id): return await ctx.respond('The amount to withdraw must not be more than what you have in your bank account!', ephemeral=True)
582567
currency.withdraw(ctx.author.id, int(amount))
583568
localembed = discord.Embed(title="Withdraw successful", description=f"You withdrew `{amount}` coin(s) from your bank account.", color=color)
584-
localembed.add_field(name="You previously had", value=f"`{currency.get_wallet(ctx.author.id) - amount} coins` in your wallet")
569+
localembed.add_field(name="You previously had", value=f"`{currency.get_wallet(ctx.author.id) - int(amount)} coins` in your wallet")
585570
localembed.add_field(name="Now you have", value=f"`{currency.get_wallet(ctx.author.id)} coins` in your wallet")
586571
await ctx.respond(embed=localembed)
587572

framework/isobot/db/items.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""The framework module library used for managing isobot's items database."""
2+
# Imports
3+
import json
4+
from framework.isobot.shop import ShopData
5+
6+
# Variables
7+
shop = ShopData("config/shop.json")
8+
shopitem = shop.get_item_ids()
9+
10+
# Functions
11+
class Items():
12+
"""Used to initialize the items database."""
13+
def __init__(self):
14+
print("[framework/db/Levelling] Items db library initialized.")
15+
16+
def load(self) -> dict:
17+
"""Fetches and returns the latest data from the items database."""
18+
with open("database/items.json", 'r', encoding="utf8") as f: db = json.load(f)
19+
return db
20+
21+
def save(self, data: dict) -> int:
22+
"""Dumps all cached data to your local machine."""
23+
with open("database/items.json", 'w+', encoding="utf8") as f: json.dump(data, f, indent=4)
24+
return 0
25+
26+
def generate(self, user_id: int) -> int:
27+
"""Generates a new database key for the specified user id in the items database."""
28+
items = self.load()
29+
if str(user_id) not in items: items[str(user_id)] = {}
30+
for z in shopitem:
31+
if z not in items[str(user_id)]:
32+
items[str(user_id)][str(z)] = 0
33+
self.save(items)
34+
return 0
35+
36+
def add_item(self, user_id: int, item: str, *, quantity: int = 1) -> int:
37+
"""Adds an item of choice to a specific user id."""
38+
items = self.load()
39+
items[str(user_id)][item] += quantity
40+
self.save()
41+
return 0
42+
43+
def remove_item(self, user_id: int, item: str, *, quantity: int = 1) -> int:
44+
"""Removes an item of choice from a specific user id."""
45+
items = self.load()
46+
items[str(user_id)][item] += quantity
47+
self.save()
48+
return 0
49+
50+
def fetch_item_count(self, user_id: int, item: str) -> int:
51+
"""Fetches and returns the amount of a specific item owned by the user."""
52+
items = self.load()
53+
return items[str(user_id)][item]

framework/isobot/shop.py

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
"""Framework module used to fetch information on isobot's item shop."""
2+
3+
# Imports
4+
import json
5+
6+
# Functions
7+
class ShopData:
8+
"""Initializes the isobot shop."""
9+
def __init__(self, db_path: str):
10+
self.db_path = db_path
11+
with open(db_path, 'r') as f: self.db = json.load(f)
12+
13+
def get_item_ids(self) -> list:
14+
"""Fetches and returns all of the shop item ids."""
15+
json_list = list()
16+
for h in self.db: json_list.append(str(h))
17+
return json_list
18+
19+
def get_item_names(self) -> list:
20+
"""Fetches and returns all of the shop item names."""
21+
json_list = list()
22+
for h in self.db: json_list.append(str(h["stylized name"]))
23+
return json_list
24+
25+
def get_raw_data(self) -> dict:
26+
"""Fetches the entire raw shop data, in a `dict` format."""
27+
return self.db

main.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
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
14+
from framework.isobot.db import levelling, items
1515
from discord import ApplicationContext, option
1616
from discord.ext import commands
1717
from cogs.economy import new_userdat
@@ -25,7 +25,6 @@
2525
#Variables
2626
client = discord.Bot()
2727
color = discord.Color.random()
28-
with open('database/items.json', 'r', encoding="utf-8") as f: items = json.load(f)
2928
with open('config/shop.json', 'r', encoding="utf-8") as f: shopitem = json.load(f)
3029
with open('database/presence.json', 'r', encoding="utf-8") as f: presence = json.load(f)
3130
with open('config/commands.json', 'r', encoding="utf-8") as f: commandsdb = json.load(f)
@@ -35,7 +34,6 @@
3534
#Pre-Initialization Commands
3635
def save():
3736
"""Dumps all cached data to the local databases."""
38-
with open('database/items.json', 'w+', encoding="utf-8") as e: json.dump(items, e, indent=4)
3937
with open('database/presence.json', 'w+', encoding="utf-8") as e: json.dump(presence, e, indent=4)
4038
with open('database/automod.json', 'w+', encoding="utf-8") as e: json.dump(automod_config, e, indent=4)
4139

@@ -58,6 +56,7 @@ def save():
5856
currency = currency.CurrencyAPI("database/currency.json", "logs/currency.log")
5957
settings = settings.Configurator()
6058
levelling = levelling.Levelling()
59+
items = items.Items()
6160

6261
# Theme Loader
6362
themes = False # True: enables themes; False: disables themes;
@@ -99,8 +98,7 @@ async def on_message(ctx):
9998
create_isocoin_key(ctx.author.id)
10099
new_userdat(ctx.author.id)
101100
settings.generate(ctx.author.id)
102-
if str(ctx.author.id) not in items:
103-
items[str(ctx.author.id)] = {}
101+
items.generate(ctx.author.id)
104102
levelling.generate(ctx.author.id)
105103
if str(ctx.guild.id) not in automod_config:
106104
automod_config[str(ctx.guild.id)] = {
@@ -113,9 +111,6 @@ async def on_message(ctx):
113111
}
114112
}
115113
}
116-
for z in shopitem:
117-
if z in items[str(ctx.author.id)]: pass
118-
else: items[str(ctx.author.id)][str(z)] = 0
119114
save()
120115
uList = list()
121116
if str(ctx.guild.id) in presence:

0 commit comments

Comments
 (0)