diff --git a/cogs/economy.py b/cogs/economy.py index 00290759..7fb7654a 100644 --- a/cogs/economy.py +++ b/cogs/economy.py @@ -8,6 +8,7 @@ import math import utils.logger import asyncio +import framework.isobot.currency from random import randint from discord import option, ApplicationContext from discord.ext import commands @@ -32,6 +33,7 @@ def get_item_names(self) -> list: # Variables wdir = os.getcwd() color = discord.Color.random() +currency = framework.isobot.currency.CurrencyAPI("database/currency.json", "logs/currency.log") shop_data = ShopData(f"{wdir}/config/shop.json") all_item_ids = shop_data.get_item_ids() jobs = [ @@ -44,47 +46,15 @@ def get_item_names(self) -> list: "Doctor" ] -with open(f"{wdir}/database/currency.json", 'r') as f: currency = json.load(f) with open(f"{wdir}/database/items.json", 'r') as f: items = json.load(f) with open(f"{wdir}/config/shop.json", 'r') as f: shopitem = json.load(f) with open(f"{wdir}/database/user_data.json", 'r') as f: userdat = json.load(f) def save(): - with open(f"{wdir}/database/currency.json", 'w+') as f: json.dump(currency, f, indent=4) with open(f"{wdir}/database/items.json", 'w+') as f: json.dump(items, f, indent=4) with open(f"{wdir}/database/user_data.json", 'w+') as f: json.dump(userdat, f, indent=4) # Functions -def get_user_networth(user_id:int): - nw = currency["wallet"][str(user_id)] + currency["bank"][str(user_id)] - #for e in items[str(user_id)]: - # if e != 0: nw += shopitem[e]["sell price"] - return nw - -def get_wallet(id: int) -> int: - return currency['wallet'][str(id)] - -def get_bank(id: int) -> int: - return currency['bank'][str(id)] - -def new_wallet(id: int): - if str(id) not in currency['wallet']: - currency['wallet'][str(id)] = 5000 - return 0 - else: return 1 - -def new_bank(id: int): - if str(id) not in currency['bank']: - currency['bank'][str(id)] = 0 - return 0 - else: return 1 - -def get_user_count(): - users = 0 - for x in currency["wallet"].keys(): - users += 1 - return users - def new_userdat(id: int): if str(id) not in userdat.keys(): userdat[str(id)] = {"work_job": None} @@ -129,20 +99,20 @@ async def openlootbox(self, ctx: ApplicationContext, lootbox:str, amount:int): ] localembed = discord.Embed(title="You opened a lootbox!", description=f"The amazing rewards of your {lootbox} lootbox behold you...", color=discord.Color.gold()) if lootbox == "normal lootbox": - currency["wallet"][str(ctx.author.id)] += normal_loot[0] + currency.add(ctx.author.id, normal_loot[0]) items[str(ctx.author.id)][normal_loot[1]] += 1 items[str(ctx.author.id)][normal_loot[2]] += 1 localembed.add_field(name="Coins gained", value=f"**{normal_loot[0]}** coins", inline=False) localembed.add_field(name="Items recieved", value=f"You got **1 {normal_loot[1]}**!\nYou got **1 {normal_loot[2]}**!", inline=False) if lootbox == "large lootbox": - currency["wallet"][str(ctx.author.id)] += large_loot[0] + currency.add(ctx.author.id, large_loot[0]) items[str(ctx.author.id)][large_loot[1]] += 1 items[str(ctx.author.id)][large_loot[2]] += 1 items[str(ctx.author.id)][large_loot[3]] += 1 localembed.add_field(name="Coins gained", value=f"**{large_loot[0]}** coins", inline=False) localembed.add_field(name="Items recieved", value=f"You got **1 {large_loot[1]}**!\nYou got **1 {large_loot[2]}**!\nYou got **1 {large_loot[3]}**!", inline=False) if lootbox == "special lootbox": - currency["wallet"][str(ctx.author.id)] += special_loot[0] + currency.add(ctx.author.id, special_loot[0]) items[str(ctx.author.id)][special_loot[1]] += 1 items[str(ctx.author.id)][special_loot[2]] += 1 items[str(ctx.author.id)][special_loot[3]] += 1 @@ -195,8 +165,8 @@ async def beg(self, ctx: ApplicationContext): ] if (randint(1, 100) >= 50): x = randint(10, 100) - currency["wallet"][str(ctx.author.id)] += x - save() + currency.get_wallet(ctx.author.id) += x + currency.add(ctx.author.id, x) await ctx.respond(embed=discord.Embed(title=random.choice(names), description=f"Oh you poor beggar, here's {x} coin(s) for you. Hope it helps!")) else: await ctx.respond(embed=discord.Embed(title=random.choice(names), description=f'"{random.choice(fail_responses)}"')) @@ -206,8 +176,7 @@ async def beg(self, ctx: ApplicationContext): ) @commands.cooldown(1, 43200, commands.BucketType.user) async def daily(self, ctx: ApplicationContext): - currency['wallet'][str(ctx.author.id)] += 10000 - save() + currency.add(ctx.author.id, 10000) await ctx.respond('You claimed 10000 coins from the daily reward. Check back in 24 hours for your next one!') @commands.slash_command( @@ -216,8 +185,7 @@ async def daily(self, ctx: ApplicationContext): ) @commands.cooldown(1, 302400, commands.BucketType.user) async def weekly(self, ctx: ApplicationContext): - currency['wallet'][str(ctx.author.id)] += 45000 - save() + currency.add(ctx.author.id, 45000) await ctx.respond('You claimed 45000 coins from the weekly reward. Check back in 7 days for your next one!') @commands.slash_command( @@ -226,8 +194,7 @@ async def weekly(self, ctx: ApplicationContext): ) @commands.cooldown(1, 1339200, commands.BucketType.user) async def monthly(self, ctx: ApplicationContext): - currency['wallet'][str(ctx.author.id)] += 1000000 - save() + currency.add(ctx.author.id, 1000000) await ctx.respond('You claimed 1000000 coins from the monthly reward. Check back in 1 month for your next one!') @commands.slash_command( @@ -237,19 +204,18 @@ async def monthly(self, ctx: ApplicationContext): @option(name="user", description="Who do you want to rob?", type=discord.User) @commands.cooldown(1, 60, commands.BucketType.user) async def rob(self, ctx: ApplicationContext, user:discord.User): - if currency['wallet'][str(user.id)] < 5000: return await ctx.respond('They has less than 5000 coins on them. Don\'t waste your time...') - elif currency['wallet'][str(ctx.author.id)] < 5000: return await ctx.respond('You have less than 5k coins in your wallet. Play fair dude.') + if currency.get_wallet(user.id) < 5000: return await ctx.respond('They has less than 5000 coins on them. Don\'t waste your time...') + elif currency.get_wallet(ctx.author.id) < 5000: return await ctx.respond('You have less than 5k coins in your wallet. Play fair dude.') if randint(1, 100) <= 50: - x = randint(5000, currency['wallet'][str(user.id)]) - currency['wallet'][str(ctx.author.id)] += x - currency['wallet'][str(user.id)] -= x + x = randint(5000, currency.get_wallet(user.id)) + currency.add(ctx.author.id, x) + currency.remove(user.id, x) await ctx.respond(f"You just stole {x} coins from {user.display_name}! Feels good, doesn't it?") else: - x = randint(5000, currency['wallet'][str(ctx.author.id)]) - currency['wallet'][str(ctx.author.id)] -= x - currency['wallet'][str(user.id)] += x + x = randint(5000, currency.get_wallet(ctx.author.id)) + currency.remove(ctx.author.id, x) + currency.add(user.id, x) await ctx.respond(f"LOL YOU GOT CAUGHT! You paid {user.display_name} {x} coins as compensation for your action.") - save() @commands.slash_command( name='bankrob', @@ -258,16 +224,16 @@ async def rob(self, ctx: ApplicationContext, user:discord.User): @option(name="user", description="Whose bank account do you want to raid?", type=discord.User) @commands.cooldown(1, (60*5), commands.BucketType.user) async def bankrob(self, ctx: ApplicationContext, user:discord.User): - if currency['wallet'][str(user.id)] < 10000: return await ctx.respond('You really want to risk losing your life to a poor person? (imagine robbing someone with < 10k net worth)') - elif currency['wallet'][str(ctx.author.id)] < 10000: return await ctx.respond('You have less than 10k in your wallet. Don\'t be greedy.') + if currency.get_wallet(user.id) < 10000: return await ctx.respond('You really want to risk losing your life to a poor person? (imagine robbing someone with < 10k net worth)') + elif currency.get_wallet(ctx.author.id) < 10000: return await ctx.respond('You have less than 10k in your wallet. Don\'t be greedy.') if randint(1, 100) <= 20: - x = randint(10000, currency['wallet'][str(user.id)]) - currency['wallet'][str(ctx.author.id)] += x - currency['bank'][str(user.id)] -= x + x = randint(10000, currency.get_wallet(user.id)) + currency.add(ctx.author.id, x) + currency.bank_remove(user.id, x) await ctx.respond(f"You raided {user.display_name}'s bank and ended up looting {x} coins from them! Now thats what I like to call *success*.") else: x = 10000 - currency['wallet'][str(ctx.author.id)] -= x + currency.remove(ctx.author.id, x) await ctx.respond(f"Have you ever thought of this as the outcome? You failed AND ended up getting caught by the police. You just lost {x} coins, you absolute loser.") @commands.slash_command( @@ -285,8 +251,7 @@ async def hunt(self, ctx: ApplicationContext): save() elif (choice == "nothing"): await ctx.respond('You found absolutely **nothing** while hunting.') elif (choice == "died"): - currency['wallet'][str(ctx.author.id)] -= 1000 - save() + currency.remove(ctx.author.id, 1000) await ctx.respond("Stupid, you died while hunting and lost 1000 coins...") @commands.slash_command( @@ -325,8 +290,7 @@ async def dig(self, ctx: ApplicationContext): ] choice = random.choice(loot) if (choice == "coins"): - currency['wallet'][str(ctx.author.id)] += random.randint('1000', '5000') - save() + currency.add(ctx.author.id, random.randint('1000', '5000')) await ctx.respond('You went digging and found a bunch of coins. Nice!') elif choice != "nothing" and choice != "died": items[str(ctx.author.id)][choice] += 1 @@ -334,8 +298,7 @@ async def dig(self, ctx: ApplicationContext): await ctx.respond(f'You found a {choice} while digging ') elif (choice == "nothing"): await ctx.respond('After some time of digging you eventually gave up. You got nothing.') elif (choice == "died"): - currency['wallet'][str(ctx.author.id)] -= 2000 - save() + currency.remove(ctx.author.id, 2000) await ctx.respond('YOU FELL INTO YOUR OWN TRAP AND DIED LMFAO\nYou lost 2000 coins in the process.') @commands.slash_command( @@ -373,16 +336,16 @@ async def shop(self, ctx: ApplicationContext, item:str=None): async def buy(self, ctx: ApplicationContext, name: str, quantity: int=1): try: amt = shopitem[name]['buy price'] * quantity - if (currency['wallet'][str(ctx.author.id)] < amt): return await ctx.respond('You don\'t have enough balance to buy this.') + if (currency.get_wallet(ctx.author.id) < amt): return await ctx.respond('You don\'t have enough balance to buy this.') if (shopitem[name]['available'] == False): return await ctx.respond('You can\'t buy this item **dood**') if (quantity <= 0): return await ctx.respond('The specified quantity cannot be less than `1`!') tax = 3 taxable_amount = (amt / 100) * tax rounded_taxable_amount = math.floor(taxable_amount) total_amount = amt + rounded_taxable_amount - currency['wallet'][str(ctx.author.id)] -= int(total_amount) + currency.remove(ctx.author.id, total_amount) items[str(ctx.author.id)][str(name)] += quantity - currency["treasury"] += rounded_taxable_amount + currency.treasury_add(rounded_taxable_amount) save() localembed = discord.Embed( title=f'You just bought {quantity} {shopitem[name]["stylized name"]}!', @@ -405,7 +368,7 @@ async def sell(self, ctx: ApplicationContext, name: str, quantity: int=1): if quantity > items[str(ctx.author.id)][str(name)]: return await ctx.respond('You can\'t sell more than you have.') items[str(ctx.author.id)][str(name)] -= quantity ttl = shopitem[name]["sell price"]*quantity - currency["wallet"][str(ctx.author.id)] += int(ttl) + currency.add(ctx.author.id, int(ttl)) save() localembed = discord.Embed(title='Item sold', description=f'You successfully sold {quantity} {name} for {ttl} coins!', color=color) localembed.set_footer(text='Thank you for your business.') @@ -449,9 +412,8 @@ async def gift(self, ctx: ApplicationContext, user:discord.User, item:str, amoun async def modify_balance(self, ctx: ApplicationContext, user:discord.User, modifier:int): if ctx.author.id != 738290097170153472: return ctx.respond("Sorry, but this command is only for my developer's use.", ephemeral=True) try: - currency["wallet"][str(user.id)] += modifier - save() - await ctx.respond(f"{user.name}\'s balance has been modified by {modifier} coins.\n\n**New Balance:** {currency['wallet'][str(user.id)]} coins", ephemeral=True) + currency.add(user.id, modifier) + await ctx.respond(f"{user.name}\'s balance has been modified by {modifier} coins.\n\n**New Balance:** {currency.get_wallet(user.id)} coins", ephemeral=True) except KeyError: await ctx.respond("That user doesn't exist in the database.", ephemeral=True) @commands.slash_command( @@ -462,11 +424,10 @@ async def modify_balance(self, ctx: ApplicationContext, user:discord.User, modif @option(name="amount", description="How much do you want to give?", type=int) async def give(self, ctx: ApplicationContext, user:discord.User, amount:int): if amount <= 0: return await ctx.respond('The amount you want to give must be greater than `0` coins!', ephemeral=True) - if amount > int(currency['wallet'][str(ctx.author.id)]): return await ctx.respond('You don\'t have enough coins in your wallet to do this.', ephemeral=True) + if amount > int(currency.get_wallet(ctx.author.id)): return await ctx.respond('You don\'t have enough coins in your wallet to do this.', ephemeral=True) else: - currency['wallet'][str(ctx.author.id)] -= amount - currency['wallet'][str(user.id)] += amount - save() + currency.remove(ctx.author.id, amount) + currency.add(user.id, amount) await ctx.respond(f':gift: {ctx.author.mention} just gifted {amount} coin(s) to {user.display_name}!') @commands.slash_command( @@ -483,8 +444,7 @@ async def work(self, ctx: ApplicationContext): 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) - currency['wallet'][str(ctx.author.id)] += i - save() + 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.') @commands.slash_command( @@ -537,18 +497,17 @@ async def work_resign(self, ctx: ApplicationContext): @option(name="amount", description="How much do you want to donate?", type=int) async def donate(self, ctx: ApplicationContext, id:str, amount): reciever_info = self.bot.get_user(int(id)) - if id not in currency["wallet"]: return await ctx.respond("Unfortunately, we couldn't find that user in our server. Try double-checking the ID you've provided.", ephemeral=True) # Prevent self-donations if id == ctx.author.id: return await ctx.respond("You can't donate to yourself stupid.", ephemeral=True) # Check for improper amount argument values if amount < 1: return await ctx.respond("The amount has to be greater than `1`!", ephemeral=True) elif amount > 1000000000: return await ctx.respond("You can only donate less than 1 billion coins!", ephemeral=True) - elif amount > currency["wallet"][str(ctx.author.id)]: return await ctx.respond("You're too poor to be donating that much money lmao") + elif amount > currency.get_wallet(ctx.author.id): return await ctx.respond("You're too poor to be donating that much money lmao") # If no improper values, proceed with donation try: - currency["wallet"][str(id)] += amount - currency["wallet"][str(ctx.author.id)] -= amount - save() + currency.add(id, amount) + currency.remove(ctx.author.id, amount) + except KeyError: return await ctx.respond("Unfortunately, we couldn't find that user in our database. Try double-checking the ID you've provided.", ephemeral=True) except Exception as e: return await ctx.respond(e) localembed = discord.Embed(title="Donation Successful", description=f"You successfully donated {amount} coins to {reciever_info.name}!", color=discord.Color.green()) localembed.add_field(name="Your ID", value=ctx.author.id, inline=True) @@ -571,8 +530,7 @@ async def scout(self, ctx: ApplicationContext): x *= 1.425 x = math.floor(x) else: pass - currency["wallet"][str(ctx.author.id)] += x - save() + currency.add(ctx.author.id, x) await ctx.respond(embed=discord.Embed(title='What you found', description=f'You searched your area and found {x} coin(s)!')) else: await ctx.respond(embed=discord.Embed(title='What you found', description='Unfortunately no coins for you :(')) @@ -587,7 +545,7 @@ async def autogrind(self, ctx: ApplicationContext): coins_reward = randint(10000, 35000) ie = shopitem.keys() items_reward = [random.choice(list(ie)), random.choice(list(ie)), random.choice(list(ie))] - currency["wallet"][str(ctx.author.id)] += coins_reward + currency.add(ctx.author.id, coins_reward) items[str(ctx.author.id)][items_reward[0]] += 1 items[str(ctx.author.id)][items_reward[1]] += 1 items[str(ctx.author.id)][items_reward[2]] += 1 @@ -602,18 +560,16 @@ async def autogrind(self, ctx: ApplicationContext): @option(name="amount", description="Specify an amount to deposit (use 'max' for everything)", type=str) async def deposit(self, ctx: ApplicationContext, amount): if not amount.isdigit(): - if str(amount) == "max": amount = currency["wallet"][str(ctx.author.id)] + if str(amount) == "max": amount = currency.get_wallet(ctx.author.id) else: return await ctx.respond("The amount must be a number, or `max`.", ephemeral=True) - elif currency['bank'] == 0: return await ctx.respond('You don\'t have anything in your bank account.', ephemeral=True) + elif currency.get_wallet(ctx.author.id) == 0: return await ctx.respond('You don\'t have anything in your wallet.', ephemeral=True) elif int(amount) <= 0: return await ctx.respond('The amount to deposit must be more than `0` coins!', ephemeral=True) - elif int(amount) > currency["wallet"][str(ctx.author.id)]: return await ctx.respond('The amount to deposit must not be more than what you have in your wallet!', ephemeral=True) - currency["wallet"][str(ctx.author.id)] -= int(amount) - currency["bank"][str(ctx.author.id)] += int(amount) + 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) + currency.deposit(ctx.author.id, int(amount)) localembed = discord.Embed(title="Deposit successful", description=f"You deposited `{amount}` coin(s) to your bank account.", color=color) - localembed.add_field(name="You previously had", value=f"`{currency['bank'][str(ctx.author.id)] - amount} coins` in your bank account") - localembed.add_field(name="Now you have", value=f"`{currency['bank'][str(ctx.author.id)]} coins` in your bank account") + localembed.add_field(name="You previously had", value=f"`{currency.get_bank(ctx.author.id) - amount} coins` in your bank account") + localembed.add_field(name="Now you have", value=f"`{currency.get_bank(ctx.author.id)} coins` in your bank account") await ctx.respond(embed=localembed) - save() @commands.slash_command( name='withdraw', @@ -622,18 +578,16 @@ async def deposit(self, ctx: ApplicationContext, amount): @option(name="amount", description="Specify an amount to withdraw (use 'max' for everything)", type=str) async def withdraw(self, ctx: ApplicationContext, amount): if not amount.isdigit(): - if str(amount) == "max": amount = currency["bank"][str(ctx.author.id)] + if str(amount) == "max": amount = currency.get_bank(ctx.author.id) else: return await ctx.respond("The amount must be a number, or `max`.", ephemeral=True) - elif currency['bank'][str(ctx.author.id)] == 0: return await ctx.respond('You don\'t have anything in your bank account.', ephemeral=True) + elif currency.get_bank(ctx.author.id) == 0: return await ctx.respond('You don\'t have anything in your bank account.', ephemeral=True) elif int(amount) <= 0: return await ctx.respond('The amount to withdraw must be more than `0` coins!', ephemeral=True) - elif int(amount) > currency["bank"][str(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) - currency["wallet"][str(ctx.author.id)] += int(amount) - currency["bank"][str(ctx.author.id)] -= int(amount) + 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) + currency.withdraw(ctx.author.id, int(amount)) localembed = discord.Embed(title="Withdraw successful", description=f"You withdrew `{amount}` coin(s) from your bank account.", color=color) - localembed.add_field(name="You previously had", value=f"`{currency['wallet'][str(ctx.author.id)] - amount} coins` in your wallet") - localembed.add_field(name="Now you have", value=f"`{currency['wallet'][str(ctx.author.id)]} coins` in your wallet") + localembed.add_field(name="You previously had", value=f"`{currency.get_wallet(ctx.author.id) - amount} coins` in your wallet") + localembed.add_field(name="Now you have", value=f"`{currency.get_wallet(ctx.author.id)} coins` in your wallet") await ctx.respond(embed=localembed) - save() @commands.slash_command( name="networth", @@ -697,9 +651,9 @@ async def balance(self, ctx: ApplicationContext, user=None): if user == None: user = ctx.author try: e = discord.Embed(title=f"{user.display_name}'s balance", color=color) - e.add_field(name='Cash in wallet', value=f'{currency["wallet"][str(user.id)]} coin(s)', inline=True) - e.add_field(name='Cash in bank account', value=f'{currency["bank"][str(user.id)]} coin(s)', inline=True) - e.add_field(name="Networth", value=f"{get_user_networth(user.id)} coin(s)", inline=True) + e.add_field(name='Cash in wallet', value=f'{currency.get_wallet(user.id)} coin(s)', inline=True) + e.add_field(name='Cash in bank account', value=f'{currency.get_bank(user.id)} coin(s)', inline=True) + e.add_field(name="Networth", value=f"{currency.get_user_networth(user.id)} coin(s)", inline=True) await ctx.respond(embed=e) except: await ctx.respond('Looks like that user is not indexed in our server. Try again later.', ephemeral=True) except Exception as e: await ctx.respond(f'An error occured: `{e}`. This has automatically been reported to the devs.') @@ -709,7 +663,7 @@ async def balance(self, ctx: ApplicationContext, user=None): description="See the amount of coins in the isobot treasury." ) async def treasury(self, ctx: ApplicationContext): - localembed = discord.Embed(description="There are currently {currency['treasury']} coins in the isobot treasury.") + localembed = discord.Embed(description=f"There are currently {currency.get_treasury()} coins in the isobot treasury.") await ctx.respond(embed=localembed) @commands.slash_command( diff --git a/cogs/minigames.py b/cogs/minigames.py index 298b0292..f68ec03d 100644 --- a/cogs/minigames.py +++ b/cogs/minigames.py @@ -4,6 +4,7 @@ import discord import json import os.path +import framework.isobot.currency from random import randint from discord import option, ApplicationContext from discord.ext import commands @@ -11,11 +12,7 @@ # Variables wdir = os.getcwd() color = discord.Color.random() - -with open(f"{wdir}/database/currency.json", 'r', encoding="utf-8") as f: currency = json.load(f) - -def save(): - with open(f"{wdir}/database/currency.json", 'w+', encoding="utf-8") as f: json.dump(currency, f) +currency = framework.isobot.currency.CurrencyAPI("database/currency.json", "logs/currency.log") # Commands class Minigames(commands.Cog): @@ -36,8 +33,7 @@ def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel a msg = await commands.wait_for("message", check=check) if int(msg.content) == number: randcoins = randint(500, 1000) - currency["wallet"][str(ctx.author.id)] += randcoins - save() + currency.add(ctx.author.id, randcoins) await ctx.respond(f"Correct! You've just won **{randcoins} coins** by guessing the correct number.") else: return await ctx.respond("Too bad bozo, you guessed the number wrong and you won nothing.") @@ -58,21 +54,18 @@ def check(msg): return msg.author == ctx.author and msg.channel == ctx.channel a if msg.content == 'low': if numb > numb2: await ctx.respond(f'Congrats! Your number was {numb2} and you won **{coins} coins**.') - currency["wallet"][ctx.author.id] += coins - save() + currency.add(ctx.author.id, coins) elif numb < numb2: await ctx.respond(f"Wrong! The number was **{numb2}**.") elif numb == numb2: await ctx.respond("Rip bozo, you just missed your chance of winning 5 million coins because you didn't choose `jackpot` XD") if msg.content == 'jackpot': if numb == numb2: await ctx.respond(f'Congrats! Your luck did you good because your number was {numb2} and you earned **5 million coins**. GG!') - currency["wallet"][ctx.author.id] += 5000000 - save() + currency.add(ctx.author.id, 5000000) else: await ctx.respond(f'Wrong! The number was {numb2}.') if msg.content == 'high': if numb < numb2: await ctx.respond(f'Congrats! Your number was {numb2} and you earned **{coins} coins**.') - currency["wallet"][ctx.author.id] += coins - save() + currency.add(ctx.author.id, coins) else: return await ctx.respond(f'Wrong! The number was {numb2}.') else: await ctx.respond(f'wtf is {msg.content}?') diff --git a/cogs/utils.py b/cogs/utils.py index f34ef640..08f6a60e 100644 --- a/cogs/utils.py +++ b/cogs/utils.py @@ -7,14 +7,15 @@ import math import openai import framework.isobot.embedengine +import framework.isobot.currency from discord import option, ApplicationContext from discord.ext import commands -from cogs.economy import get_wallet, get_bank, get_user_networth, get_user_count from cogs.levelling import get_level, get_xp from cogs.afk import get_presence # Variables color = discord.Color.random() +currency = framework.isobot.currency.CurrencyAPI("database/currency.json", "logs/currency.log") openai.api_key = os.getenv("chatgpt_API_KEY") chatgpt_conversation = dict() @@ -82,7 +83,7 @@ async def whoami(self, ctx: ApplicationContext, user: discord.User=None): for p in user.roles: if p != user.roles[0]: role_render += f"<@&{p.id}> " localembed.add_field(name='Roles', value=role_render, inline=False) - localembed.add_field(name="Net worth", value=f"{get_user_networth(user.id)} coins", inline=False) + localembed.add_field(name="Net worth", value=f"{currency.get_user_networth(user.id)} coins", inline=False) await ctx.respond(embed=localembed) @commands.slash_command( @@ -95,9 +96,9 @@ async def profile(self, ctx: ApplicationContext, user: discord.User = None): localembed = discord.Embed(title=f"{user.display_name}'s isobot stats", color=color) localembed.set_thumbnail(url=user.avatar) localembed.add_field(name="Level", value=f"Level {get_level(user.id)} ({get_xp(user.id)} XP)", inline=False) - localembed.add_field(name="Balance in Wallet", value=f"{get_wallet(user.id)} coins", inline=True) - localembed.add_field(name="Balance in Bank Account", value=f"{get_bank(user.id)} coins", inline=True) - localembed.add_field(name="Net-Worth", value=f"{get_user_networth(user.id)} coins", inline=True) + localembed.add_field(name="Balance in Wallet", value=f"{currency.get_wallet(user.id)} coins", inline=True) + localembed.add_field(name="Balance in Bank Account", value=f"{currency.get_bank(user.id)} coins", inline=True) + localembed.add_field(name="Net-Worth", value=f"{currency.get_user_networth(user.id)} coins", inline=True) # More stats will be added later # Maybe I should make a userdat system for collecting statistical data to process and display here, coming in a future update. await ctx.respond(embed=localembed) @@ -110,7 +111,7 @@ async def status(self, ctx: ApplicationContext): os_name = os.name sys_ram = str(f"{psutil.virtual_memory()[2]}GiB") sys_cpu = str(f"{psutil.cpu_percent(1)}%") - bot_users = get_user_count() + bot_users = currency.get_user_count() localembed = discord.Embed(title="Client Info") localembed.add_field(name="OS Name", value=os_name) localembed.add_field(name="RAM Available", value=sys_ram) diff --git a/framework/isobot/currency.py b/framework/isobot/currency.py index 5c2f893c..cbb6c228 100644 --- a/framework/isobot/currency.py +++ b/framework/isobot/currency.py @@ -1,4 +1,6 @@ -import json, discord, datetime +import json +import discord +import datetime class Colors: """Contains general stdout colors.""" @@ -13,73 +15,161 @@ class CurrencyAPI(Colors): Valid commands: - add(user, amount) - remove(user, amount) + - bank_add(user, amount) + - bank_remove(user, amount) - reset(user) - deposit(user, amount) - - withdraw(user, amount)""" + - withdraw(user, amount) + - treasury_add(amount) + - treasury_remove(amount) + - get_wallet(user) + - get_bank(user) + - get_treasury() + - get_user_networth(user) + - get_user_count + - new_wallet(user) + - new_bank(user)""" + def __init__(self, db_path: str, log_path: str): self.db_path = db_path self.log_path = log_path - with open(self.db_path, 'r') as f: - global currency - currency = json.load(f) print(f"[Framework/Loader] {Colors.green}CurrencyAPI initialized.{Colors.end}") - def get_time(self): return datetime.datetime.now().strftime("%H:%M:%S") - - def save(self): - """Saves databases cached on memory.""" - with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) + def get_time(self): + return datetime.datetime.now().strftime("%H:%M:%S") - def add(self, user: discord.User, amount: int): + def add(self, user: discord.User, amount: int) -> int: """Adds balance to the specified user.""" + with open(self.db_path, 'r') as f: currency = json.load(f) currency["wallet"][str(user)] += int(amount) - self.save() + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) with open(self.log_path, 'a') as f: f.write(f'{self.get_time()} framework.isobot.currency User({user}): Added {amount} coins to wallet\n') f.close() + return 0 + + def bank_add(self, user: discord.User, amount: int) -> int: + """Adds balance to the specified user's bank account.""" + with open(self.db_path, 'r') as f: currency = json.load(f) + currency["bank"][str(user)] += int(amount) + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) + with open(self.log_path, 'a') as f: + f.write(f'{self.get_time()} framework.isobot.currency User({user}): Added {amount} coins to bank\n') + f.close() + return 0 - def remove(self, user: discord.User, amount: int): + def remove(self, user: discord.User, amount: int) -> int: """Removes balance from the specified user.""" + with open(self.db_path, 'r') as f: currency = json.load(f) currency["wallet"][str(user)] -= int(amount) - self.save() + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) with open(self.log_path, 'a') as f: f.write(f'{self.get_time()} framework.isobot.currency User({user}): Removed {amount} coins from wallet\n') f.close() + return 0 + + def bank_remove(self, user: discord.User, amount: int) -> int: + """Removes balance from the specified user's bank account.""" + with open(self.db_path, 'r') as f: currency = json.load(f) + currency["bank"][str(user)] -= int(amount) + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) + with open(self.log_path, 'a') as f: + f.write(f'{self.get_time()} framework.isobot.currency User({user}): Removed {amount} coins from bank\n') + f.close() + return 0 - def reset(self, user: discord.User): + def reset(self, user: discord.User) -> int: """Resets the specified user's balance.""" + with open(self.db_path, 'r') as f: currency = json.load(f) currency["wallet"][str(user)] = 0 currency["bank"][str(user)] = 0 - self.save() + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) print(f"[Framework/CurrencyAPI] Currency data for \"{user}\" has been wiped") with open(self.log_path, 'a') as f: f.write(f'{self.get_time()} framework.isobot.currency User({user}): Wiped all currency data\n') f.close() + return 0 - def deposit(self, user: discord.User, amount: int): + def deposit(self, user: discord.User, amount: int) -> int: """Moves a specified amount of coins to the user's bank.""" + with open(self.db_path, 'r') as f: currency = json.load(f) currency["bank"][str(user)] += int(amount) currency["wallet"][str(user)] -= int(amount) - self.save() + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) print(f"[Framework/CurrencyAPI] Moved {amount} coins to bank. User: {user} [{user}]") with open(self.log_path, 'a') as f: f.write(f'{self.get_time()} framework.isobot.currency User({user}): Moved {amount} coins from wallet to bank\n') f.close() + return 0 - def withdraw(self, user: discord.User, amount: int): + def withdraw(self, user: discord.User, amount: int) -> int: """Moves a specified amount of coins to the user's wallet.""" + with open(self.db_path, 'r') as f: currency = json.load(f) currency["wallet"][str(user)] += int(amount) currency["bank"][str(user)] -= int(amount) - self.save() + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) print(f"[Framework/CurrencyAPI] Moved {amount} coins to wallet. User: {user} [{user}]") with open(self.log_path, 'a') as f: f.write(f'{self.get_time()} framework.isobot.currency User({user}): Moved {amount} coins from bank to wallet\n') f.close() + return 0 + + def treasury_add(self, amount: int) -> int: + with open(self.db_path, 'r') as f: currency = json.load(f) + currency["treasury"] += int(amount) + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) + with open(self.log_path, 'a') as f: + f.write(f'{self.get_time()} framework.isobot.currency Treasury: Added {amount} coins to treasury\n') + f.close() + return 0 + + def treasury_remove(self, amount: int) -> int: + with open(self.db_path, 'r') as f: currency = json.load(f) + currency["treasury"] -= int(amount) + with open(self.db_path, 'w+') as f: json.dump(currency, f, indent=4) + with open(self.log_path, 'a') as f: + f.write(f'{self.get_time()} framework.isobot.currency Treasury: Removed {amount} coins from treasury\n') + f.close() + return 0 - def wallet(self, user: discord.User): + def get_wallet(self, user: discord.User) -> int: """Returns the amount of coins in the user's wallet.""" + with open(self.db_path, 'r') as f: currency = json.load(f) return int(currency["wallet"][str(user)]) - def bank(self, user: discord.User): + def get_bank(self, user: discord.User) -> int: """Returns the amount of coins in the user's bank account.""" + with open(self.db_path, 'r') as f: currency = json.load(f) return int(currency["bank"][str(user)]) + + def get_treasury(self) -> int: + """Returns the amount of coins in the treasury.""" + with open(self.db_path, 'r') as f: currency = json.load(f) + return int(currency["treasury"]) + + def get_user_networth(self, user: discord.User) -> int: + """Returns the net-worth of the user.""" + with open(self.db_path, 'r') as f: currency = json.load(f) + nw = int(currency["wallet"][str(user)]) + int(currency["bank"][str(user)]) + return nw + + def get_user_count(self) -> int: + """Returns the total number of users cached in the currency database.""" + with open(self.db_path, 'r') as f: currency = json.load(f) + users = 0 + for x in currency["wallet"].keys(): users += 1 + return users + + def new_wallet(self, user: int) -> int: + """Makes a new key for a user wallet in the currency database.""" + with open(self.db_path, 'r') as f: currency = json.load(f) + if str(id) not in currency['wallet']: + currency['wallet'][str(id)] = 5000 + return 0 + + def new_bank(self, user: int) -> int: + """Makes a new key for a user bank account in the currency database.""" + with open(self.db_path, 'r') as f: currency = json.load(f) + if str(id) not in currency['bank']: + currency['bank'][str(id)] = 0 + return 0 diff --git a/main.py b/main.py index dcc7b95c..ef293b9a 100644 --- a/main.py +++ b/main.py @@ -21,7 +21,7 @@ from discord import ApplicationContext, option from discord.ext import commands from discord.ext.commands import * -from cogs.economy import new_bank, new_wallet, new_userdat +from cogs.economy import new_userdat from cogs.isocoin import create_isocoin_key # Slash option types: @@ -63,7 +63,7 @@ def save(): #Framework Module Loader colors = framework.isobot.colors.Colors() -currency_unused = framework.isobot.currency.CurrencyAPI(f"{wdir}/database/currency.json", f"{wdir}/logs/currency.log") # Initialize part of the framework (Currency) +currency = framework.isobot.currency.CurrencyAPI("database/currency.json", "logs/currency.log") # isobank = framework.isobank.manager.IsoBankManager(f"{wdir}/database/isobank/accounts.json", f"{wdir}/database/isobank/auth.json") # isobankauth = framework.isobank.authorize.IsobankAuth(f"{wdir}/database/isobank/auth.json", f"{wdir}/database/isobank/accounts.json") @@ -97,8 +97,8 @@ async def on_ready(): @client.event async def on_message(ctx): - new_wallet(ctx.author.id) - new_bank(ctx.author.id) + currency.new_wallet(ctx.author.id) + currency.new_bank(ctx.author.id) create_isocoin_key(ctx.author.id) new_userdat(ctx.author.id) if str(ctx.author.id) not in items: items[str(ctx.author.id)] = {}