Stash currency beginning

Stijn De Clercq 2021-09-26 20:41:24 +02:00
parent cb72774a7a
commit ea2a25d1fc
6 changed files with 67 additions and 79 deletions

View File

@ -25,7 +25,7 @@ class Bitcoin(commands.Cog):
:param ctx: Discord Context :param ctx: Discord Context
""" """
price = self.getPrice() 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() currentTime = timeFormatters.dateTimeNow()
currentTimeFormatted = currentTime.strftime('%m/%d/%Y om %H:%M:%S') currentTimeFormatted = currentTime.strftime('%m/%d/%Y om %H:%M:%S')
@ -78,9 +78,9 @@ class Bitcoin(commands.Cog):
purchased = round(float(amount) / price, 8) purchased = round(float(amount) / price, 8)
# Update the db # 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", 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{}!" await ctx.send("**{}** heeft **{:,}** Bitcoin{} gekocht voor **{:,}** Didier Dink{}!"
.format(ctx.author.display_name, purchased, checks.pluralS(purchased), .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 :param amount: the amount of Bitcoins the user wants to sell
""" """
if str(amount).lower() == "all": 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: try:
amount = float(amount) amount = float(amount)
if amount <= 0: if amount <= 0:
raise ValueError 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: if bc == 0.0:
# User has no Bitcoins # User has no Bitcoins
@ -112,7 +112,7 @@ class Bitcoin(commands.Cog):
.format(ctx.author.display_name)) .format(ctx.author.display_name))
else: else:
price = self.getPrice() 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, "bitcoins", bc - amount)
currency.update(ctx.author.id, "dinks", dinks + (price * amount)) currency.update(ctx.author.id, "dinks", dinks + (price * amount))

View File

@ -66,7 +66,7 @@ class Dinks(commands.Cog):
Command that shows the user's Didier Dinks & Platinum Dinks Command that shows the user's Didier Dinks & Platinum Dinks
:param ctx: Discord Context :param ctx: Discord Context
""" """
dinks = currency.dinksAll(ctx.author.id) dinks = currency.dinks_all(ctx.author.id)
answer = "**{}** heeft **{:,}** Didier Dink{}"\ answer = "**{}** heeft **{:,}** Didier Dink{}"\
.format(ctx.author.display_name, math.floor(dinks["dinks"]), checks.pluralS(dinks["dinks"])) .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 # 0 1 2 3 4 5 6 7 8 9 10
# ID dinks level investedamount investeddays profit defense offense bc nightly streak # 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 # Calculate the cost to level your bank
interestLevelPrice = round(math.pow(1.28, int(response[2])) * 300) 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. Command that shows the user's bank stats.
:param ctx: Discord Context :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 # Calculate the prices to level stats up
defense = int(response[6]) defense = int(response[6])
@ -213,7 +213,7 @@ class Dinks(commands.Cog):
increasing interest. increasing interest.
:param ctx: Discord Context :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) interestLevelPrice = float(math.pow(1.28, int(response[2])) * 300)
# Check if user has enough Didier Dinks to do this # Check if user has enough Didier Dinks to do this
@ -233,7 +233,7 @@ class Dinks(commands.Cog):
increasing capacity & rob chances. increasing capacity & rob chances.
:param ctx: Discord Context :param ctx: Discord Context
""" """
response = currency.getOrAddUser(ctx.author.id) response = currency.get_or_add_user(ctx.author.id)
offense = int(response[7]) offense = int(response[7])
capacity = calcCapacity(offense) capacity = calcCapacity(offense)
@ -256,7 +256,7 @@ class Dinks(commands.Cog):
increasing chance of failed robs by others. increasing chance of failed robs by others.
:param ctx: Discord Context :param ctx: Discord Context
""" """
response = currency.getOrAddUser(ctx.author.id) response = currency.get_or_add_user(ctx.author.id)
defense = int(response[6]) defense = int(response[6])
defenseLevelPrice = math.floor(math.pow(1.4, defense) * 365) if defense < 38 else 5 * calcCapacity(defense - 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]: elif not checks.isValidAmount(ctx, amount[0])[0]:
await ctx.send(checks.isValidAmount(ctx, amount[0])[1]) await ctx.send(checks.isValidAmount(ctx, amount[0])[1])
else: else:
user = currency.getOrAddUser(ctx.author.id) user = currency.get_or_add_user(ctx.author.id)
if str(amount[0]).lower() == "all": if str(amount[0]).lower() == "all":
amount[0] = user[1] amount[0] = user[1]
@ -307,7 +307,7 @@ class Dinks(commands.Cog):
:param args: :param args:
:return: :return:
""" """
user = currency.getOrAddUser(ctx.author.id) user = currency.get_or_add_user(ctx.author.id)
args = list(args) args = list(args)
claimAll = False claimAll = False
@ -546,8 +546,8 @@ class Dinks(commands.Cog):
return False, None, None return False, None, None
# Check the database for these users # Check the database for these users
user1 = currency.getOrAddUser(ctx.author.id) user1 = currency.get_or_add_user(ctx.author.id)
user2 = currency.getOrAddUser(target.id) user2 = currency.get_or_add_user(target.id)
# Can't rob without Didier Dinks # Can't rob without Didier Dinks
if float(user1[1]) < 1.0: if float(user1[1]) < 1.0:

View File

@ -34,8 +34,8 @@ class Leaderboards(commands.Cog):
@leaderboard.command(name="Dinks", aliases=["Cash"], hidden=True) @leaderboard.command(name="Dinks", aliases=["Cash"], hidden=True)
async def dinks(self, ctx): async def dinks(self, ctx):
entries = currency.getAllRows() entries = currency.get_all_rows()
platDinks = currency.getAllPlatDinks() platDinks = currency.get_all_plat_dinks()
# Take platinum dinks into account # Take platinum dinks into account
for i, user in enumerate(entries): for i, user in enumerate(entries):
@ -77,7 +77,7 @@ class Leaderboards(commands.Cog):
@leaderboard.command(name="Bitcoin", aliases=["Bc"], hidden=True) @leaderboard.command(name="Bitcoin", aliases=["Bc"], hidden=True)
async def bitcoin(self, ctx): async def bitcoin(self, ctx):
users = currency.getAllRows() users = currency.get_all_rows()
boardTop = [] boardTop = []
for i, user in enumerate(sorted(users, key=lambda x: x[8], reverse=True)): for i, user in enumerate(sorted(users, key=lambda x: x[8], reverse=True)):
# Don't create an empty leaderboard # Don't create an empty leaderboard

View File

@ -36,7 +36,7 @@ class Tasks(commands.Cog):
with open("files/lastTasks.json", "r") as fp: with open("files/lastTasks.json", "r") as fp:
lastTasks = json.load(fp) lastTasks = json.load(fp)
if int(self.getCurrentHour()) == 4 and int(time.time()) - int(lastTasks["interest"]) > 10000: if int(self.getCurrentHour()) == 4 and int(time.time()) - int(lastTasks["interest"]) > 10000:
users = currency.getAllRows() users = currency.get_all_rows()
bitcoinPrice = self.getCurrentBitcoinPrice() bitcoinPrice = self.getCurrentBitcoinPrice()
for user in users: for user in users:
# People in prison don't get interest # People in prison don't get interest

View File

@ -1,103 +1,90 @@
import datetime import datetime
from typing import List, Dict
from database.db import session
from database.models import BankAccount, Inventory
from functions.database import utils, stats from functions.database import utils, stats
import time import time
def dinks(userid): def dinks(userid) -> float:
return getOrAddUser(userid)[1] return float(get_or_add_user(userid).dinks)
def dinksAll(userid): def dinks_all(userid) -> Dict:
platinumDinks = 0 platinum_dinks = 0
connection = utils.connect() inventory = session.query(Inventory).filter(Inventory.userid == userid and Inventory.itemid == 1).scalar()
cursor = connection.cursor()
cursor.execute("SELECT amount FROM inventory WHERE userid = %s AND itemid = %s", (int(userid), 1,))
result = cursor.fetchall()
if result: # Don't add to db if not present, doesn't matter
platinumDinks = result[0][0] if inventory is not None:
platinum_dinks = inventory.amount
return {"dinks": dinks(userid), "platinum": platinumDinks} return {"dinks": dinks(userid), "platinum": platinum_dinks}
def getAllRows(): def get_all_rows() -> List[BankAccount]:
connection = utils.connect() return session.query(BankAccount).all()
cursor = connection.cursor()
cursor.execute(
"""SELECT * FROM currencytable"""
)
return cursor.fetchall()
def getAllPlatDinks(): def get_all_plat_dinks() -> Dict[str, int]:
connection = utils.connect() users: List[Inventory] = session.query(Inventory).filter(Inventory.itemid == 1).all()
cursor = connection.cursor()
cursor.execute("SELECT userid, amount FROM inventory WHERE itemid = 1")
result = cursor.fetchall()
dic = {} dic = {}
for user in result: for user in users:
dic[str(user[0])] = user[1] dic[str(user.userid)] = user.amount
return dic return dic
def getOrAddUser(userid): def get_or_add_user(userid: int) -> BankAccount:
connection = utils.connect() user = session.query(BankAccount).filter(BankAccount.userid == userid).scalar()
cursor = connection.cursor()
query = "SELECT * FROM currencytable WHERE userid = %s" # User doesn't exist yet, add them
cursor.execute( if user is None:
query, (int(userid),) session.add(BankAccount(userid=userid))
) session.commit()
result = cursor.fetchall()
# User didn't exist yet, so create a new default file return user
if len(result) == 0:
createNewUser(userid, connection)
return getOrAddUser(userid)
return result[0]
# TODO check for nightly bonus & add+return that instead of 420 # TODO check for nightly bonus & add+return that instead of 420
def nightly(userid): def nightly(userid):
user = getOrAddUser(userid) user = get_or_add_user(userid)
today = datetime.datetime.today().date() today = datetime.datetime.today().date()
lastNightly = datetime.datetime.fromtimestamp(user[9]).date() last_nightly = datetime.datetime.fromtimestamp(user.nightly).date()
streak = int(user[10]) streak = user.nightly_streak
if lastNightly < today:
update(userid, "dinks", float(user[1]) + 420.0) if last_nightly < today:
update(userid, "nightly", int(time.time())) user.dinks = float(user.dinks) + 420.0
user.nightly = int(time.time())
# Update the streak # Update the streak
if (today - lastNightly).days > 1: if (today - last_nightly).days > 1:
update(userid, "nightly_streak", 1) user.nightly_streak = 1
streak = 1 streak = 1
else: else:
update(userid, "nightly_streak", streak + 1) user.nightly_streak += 1
streak += 1 streak += 1
s = stats.getOrAddUser(userid) s = stats.getOrAddUser(userid)
# TODO when stats is done
if streak > int(s[5]): if streak > int(s[5]):
stats.update(userid, "longest_streak", streak) stats.update(userid, "longest_streak", streak)
stats.update(userid, "nightlies_count", int(s[6]) + 1) stats.update(userid, "nightlies_count", int(s[6]) + 1)
session.commit()
return [True, 420, streak] return [True, 420, streak]
return [False, 0, -1] return [False, 0, -1]
def createNewUser(userid, connection=None): # TODO fix usages first
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()
def update(userid, column, value): def update(userid, column, value):
_ = getOrAddUser(userid) _ = get_or_add_user(userid)
connection = utils.connect() connection = utils.connect()
cursor = connection.cursor() cursor = connection.cursor()
query = "UPDATE currencytable " \ query = "UPDATE currencytable " \

View File

@ -5,6 +5,7 @@ import random
import time import time
# TODO Fix currency/nightly when this is done
def getOrAddUser(userid): def getOrAddUser(userid):
connection = utils.connect() connection = utils.connect()
cursor = connection.cursor() cursor = connection.cursor()