From ea2a25d1fc48d9af21cc811b991ebe07d318a171 Mon Sep 17 00:00:00 2001 From: Stijn De Clercq Date: Sun, 26 Sep 2021 20:41:24 +0200 Subject: [PATCH] Stash currency beginning --- cogs/bitcoin.py | 12 ++-- cogs/dinks.py | 20 +++---- cogs/leaderboards.py | 6 +- cogs/tasks.py | 2 +- functions/database/currency.py | 105 +++++++++++++++------------------ functions/database/stats.py | 1 + 6 files changed, 67 insertions(+), 79 deletions(-) diff --git a/cogs/bitcoin.py b/cogs/bitcoin.py index 1a8bda2..8994822 100644 --- a/cogs/bitcoin.py +++ b/cogs/bitcoin.py @@ -25,7 +25,7 @@ class Bitcoin(commands.Cog): :param ctx: Discord Context """ price = self.getPrice() - bc = float(currency.getOrAddUser(ctx.author.id)[8]) + bc = float(currency.get_or_add_user(ctx.author.id)[8]) currentTime = timeFormatters.dateTimeNow() currentTimeFormatted = currentTime.strftime('%m/%d/%Y om %H:%M:%S') @@ -78,9 +78,9 @@ class Bitcoin(commands.Cog): purchased = round(float(amount) / price, 8) # Update the db - currency.update(ctx.author.id, "dinks", float(currency.dinks(ctx.author.id)) - float(amount)) + currency.update(ctx.author.id, "dinks", currency.dinks(ctx.author.id) - float(amount)) currency.update(ctx.author.id, "bitcoins", - float(currency.getOrAddUser(ctx.author.id)[8]) + float(purchased)) + float(currency.get_or_add_user(ctx.author.id).bitcoins) + float(purchased)) await ctx.send("**{}** heeft **{:,}** Bitcoin{} gekocht voor **{:,}** Didier Dink{}!" .format(ctx.author.display_name, purchased, checks.pluralS(purchased), @@ -94,14 +94,14 @@ class Bitcoin(commands.Cog): :param amount: the amount of Bitcoins the user wants to sell """ if str(amount).lower() == "all": - amount = float(currency.getOrAddUser(ctx.author.id)[8]) + amount = float(currency.get_or_add_user(ctx.author.id)[8]) try: amount = float(amount) if amount <= 0: raise ValueError - bc = float(currency.getOrAddUser(ctx.author.id)[8]) + bc = float(currency.get_or_add_user(ctx.author.id)[8]) if bc == 0.0: # User has no Bitcoins @@ -112,7 +112,7 @@ class Bitcoin(commands.Cog): .format(ctx.author.display_name)) else: price = self.getPrice() - dinks = float(currency.dinks(ctx.author.id)) + dinks = currency.dinks(ctx.author.id) currency.update(ctx.author.id, "bitcoins", bc - amount) currency.update(ctx.author.id, "dinks", dinks + (price * amount)) diff --git a/cogs/dinks.py b/cogs/dinks.py index b1a2beb..1f7ec8e 100644 --- a/cogs/dinks.py +++ b/cogs/dinks.py @@ -66,7 +66,7 @@ class Dinks(commands.Cog): Command that shows the user's Didier Dinks & Platinum Dinks :param ctx: Discord Context """ - dinks = currency.dinksAll(ctx.author.id) + dinks = currency.dinks_all(ctx.author.id) answer = "**{}** heeft **{:,}** Didier Dink{}"\ .format(ctx.author.display_name, math.floor(dinks["dinks"]), checks.pluralS(dinks["dinks"])) @@ -148,7 +148,7 @@ class Dinks(commands.Cog): """ # 0 1 2 3 4 5 6 7 8 9 10 # ID dinks level investedamount investeddays profit defense offense bc nightly streak - response = currency.getOrAddUser(ctx.author.id) + response = currency.get_or_add_user(ctx.author.id) # Calculate the cost to level your bank interestLevelPrice = round(math.pow(1.28, int(response[2])) * 300) @@ -179,7 +179,7 @@ class Dinks(commands.Cog): Command that shows the user's bank stats. :param ctx: Discord Context """ - response = currency.getOrAddUser(ctx.author.id) + response = currency.get_or_add_user(ctx.author.id) # Calculate the prices to level stats up defense = int(response[6]) @@ -213,7 +213,7 @@ class Dinks(commands.Cog): increasing interest. :param ctx: Discord Context """ - response = currency.getOrAddUser(ctx.author.id) + response = currency.get_or_add_user(ctx.author.id) interestLevelPrice = float(math.pow(1.28, int(response[2])) * 300) # Check if user has enough Didier Dinks to do this @@ -233,7 +233,7 @@ class Dinks(commands.Cog): increasing capacity & rob chances. :param ctx: Discord Context """ - response = currency.getOrAddUser(ctx.author.id) + response = currency.get_or_add_user(ctx.author.id) offense = int(response[7]) capacity = calcCapacity(offense) @@ -256,7 +256,7 @@ class Dinks(commands.Cog): increasing chance of failed robs by others. :param ctx: Discord Context """ - response = currency.getOrAddUser(ctx.author.id) + response = currency.get_or_add_user(ctx.author.id) defense = int(response[6]) defenseLevelPrice = math.floor(math.pow(1.4, defense) * 365) if defense < 38 else 5 * calcCapacity(defense - 6) @@ -287,7 +287,7 @@ class Dinks(commands.Cog): elif not checks.isValidAmount(ctx, amount[0])[0]: await ctx.send(checks.isValidAmount(ctx, amount[0])[1]) else: - user = currency.getOrAddUser(ctx.author.id) + user = currency.get_or_add_user(ctx.author.id) if str(amount[0]).lower() == "all": amount[0] = user[1] @@ -307,7 +307,7 @@ class Dinks(commands.Cog): :param args: :return: """ - user = currency.getOrAddUser(ctx.author.id) + user = currency.get_or_add_user(ctx.author.id) args = list(args) claimAll = False @@ -546,8 +546,8 @@ class Dinks(commands.Cog): return False, None, None # Check the database for these users - user1 = currency.getOrAddUser(ctx.author.id) - user2 = currency.getOrAddUser(target.id) + user1 = currency.get_or_add_user(ctx.author.id) + user2 = currency.get_or_add_user(target.id) # Can't rob without Didier Dinks if float(user1[1]) < 1.0: diff --git a/cogs/leaderboards.py b/cogs/leaderboards.py index 724bf54..d860633 100644 --- a/cogs/leaderboards.py +++ b/cogs/leaderboards.py @@ -34,8 +34,8 @@ class Leaderboards(commands.Cog): @leaderboard.command(name="Dinks", aliases=["Cash"], hidden=True) async def dinks(self, ctx): - entries = currency.getAllRows() - platDinks = currency.getAllPlatDinks() + entries = currency.get_all_rows() + platDinks = currency.get_all_plat_dinks() # Take platinum dinks into account for i, user in enumerate(entries): @@ -77,7 +77,7 @@ class Leaderboards(commands.Cog): @leaderboard.command(name="Bitcoin", aliases=["Bc"], hidden=True) async def bitcoin(self, ctx): - users = currency.getAllRows() + users = currency.get_all_rows() boardTop = [] for i, user in enumerate(sorted(users, key=lambda x: x[8], reverse=True)): # Don't create an empty leaderboard diff --git a/cogs/tasks.py b/cogs/tasks.py index 8209d19..5248ae3 100644 --- a/cogs/tasks.py +++ b/cogs/tasks.py @@ -36,7 +36,7 @@ class Tasks(commands.Cog): with open("files/lastTasks.json", "r") as fp: lastTasks = json.load(fp) if int(self.getCurrentHour()) == 4 and int(time.time()) - int(lastTasks["interest"]) > 10000: - users = currency.getAllRows() + users = currency.get_all_rows() bitcoinPrice = self.getCurrentBitcoinPrice() for user in users: # People in prison don't get interest diff --git a/functions/database/currency.py b/functions/database/currency.py index b1d7232..086babb 100644 --- a/functions/database/currency.py +++ b/functions/database/currency.py @@ -1,103 +1,90 @@ import datetime +from typing import List, Dict + +from database.db import session +from database.models import BankAccount, Inventory from functions.database import utils, stats import time -def dinks(userid): - return getOrAddUser(userid)[1] +def dinks(userid) -> float: + return float(get_or_add_user(userid).dinks) -def dinksAll(userid): - platinumDinks = 0 +def dinks_all(userid) -> Dict: + platinum_dinks = 0 - connection = utils.connect() - cursor = connection.cursor() - cursor.execute("SELECT amount FROM inventory WHERE userid = %s AND itemid = %s", (int(userid), 1,)) - result = cursor.fetchall() + inventory = session.query(Inventory).filter(Inventory.userid == userid and Inventory.itemid == 1).scalar() - if result: - platinumDinks = result[0][0] + # Don't add to db if not present, doesn't matter + if inventory is not None: + platinum_dinks = inventory.amount - return {"dinks": dinks(userid), "platinum": platinumDinks} + return {"dinks": dinks(userid), "platinum": platinum_dinks} -def getAllRows(): - connection = utils.connect() - cursor = connection.cursor() - cursor.execute( - """SELECT * FROM currencytable""" - ) - - return cursor.fetchall() +def get_all_rows() -> List[BankAccount]: + return session.query(BankAccount).all() -def getAllPlatDinks(): - connection = utils.connect() - cursor = connection.cursor() - cursor.execute("SELECT userid, amount FROM inventory WHERE itemid = 1") - result = cursor.fetchall() +def get_all_plat_dinks() -> Dict[str, int]: + users: List[Inventory] = session.query(Inventory).filter(Inventory.itemid == 1).all() + dic = {} - for user in result: - dic[str(user[0])] = user[1] + for user in users: + dic[str(user.userid)] = user.amount + return dic -def getOrAddUser(userid): - connection = utils.connect() - cursor = connection.cursor() - query = "SELECT * FROM currencytable WHERE userid = %s" - cursor.execute( - query, (int(userid),) - ) - result = cursor.fetchall() - # User didn't exist yet, so create a new default file - if len(result) == 0: - createNewUser(userid, connection) - return getOrAddUser(userid) - return result[0] +def get_or_add_user(userid: int) -> BankAccount: + user = session.query(BankAccount).filter(BankAccount.userid == userid).scalar() + + # User doesn't exist yet, add them + if user is None: + session.add(BankAccount(userid=userid)) + session.commit() + + return user # TODO check for nightly bonus & add+return that instead of 420 def nightly(userid): - user = getOrAddUser(userid) + user = get_or_add_user(userid) + today = datetime.datetime.today().date() - lastNightly = datetime.datetime.fromtimestamp(user[9]).date() - streak = int(user[10]) - if lastNightly < today: - update(userid, "dinks", float(user[1]) + 420.0) - update(userid, "nightly", int(time.time())) + last_nightly = datetime.datetime.fromtimestamp(user.nightly).date() + streak = user.nightly_streak + + if last_nightly < today: + user.dinks = float(user.dinks) + 420.0 + user.nightly = int(time.time()) # Update the streak - if (today - lastNightly).days > 1: - update(userid, "nightly_streak", 1) + if (today - last_nightly).days > 1: + user.nightly_streak = 1 streak = 1 else: - update(userid, "nightly_streak", streak + 1) + user.nightly_streak += 1 streak += 1 s = stats.getOrAddUser(userid) + # TODO when stats is done if streak > int(s[5]): stats.update(userid, "longest_streak", streak) stats.update(userid, "nightlies_count", int(s[6]) + 1) + session.commit() + return [True, 420, streak] return [False, 0, -1] -def createNewUser(userid, connection=None): - if connection is None: - connection = utils.connect() - cursor = connection.cursor() - query = "INSERT INTO currencytable(userid, dinks, banklevel, investedamount, investeddays, profit, defense, offense, bitcoins, nightly) " \ - "VALUES (%s, 0.0, 1, 0.0, 0, 0, 1, 1, 0.0, 0)" - cursor.execute(query, (int(userid),)) - connection.commit() - - +# TODO fix usages first def update(userid, column, value): - _ = getOrAddUser(userid) + _ = get_or_add_user(userid) connection = utils.connect() cursor = connection.cursor() query = "UPDATE currencytable " \ diff --git a/functions/database/stats.py b/functions/database/stats.py index 60d4685..986ee0a 100644 --- a/functions/database/stats.py +++ b/functions/database/stats.py @@ -5,6 +5,7 @@ import random import time +# TODO Fix currency/nightly when this is done def getOrAddUser(userid): connection = utils.connect() cursor = connection.cursor()