Files
Gwendolyn/funcs/games/invest.py

150 lines
7.1 KiB
Python

import discord
class Invest():
def __init__(self, bot):
self.bot = bot
def getPrice(self, symbol : str):
res = self.bot.finnhubClient.quote(symbol.upper())
if res == {}:
return 0
else:
return int(res["c"] * 100)
def getPortfolio(self, user : str):
userInvestments = self.bot.database["investments"].find_one({"_id":user})
if userInvestments in [None,{}]:
return f"{self.bot.databaseFuncs.getName(user)} does not have a stock portfolio."
else:
portfolio = f"**Stock portfolio for {self.bot.databaseFuncs.getName(user)}**"
for key, value in list(userInvestments["investments"].items()):
purchaseValue = value["purchased for"]
currentValue = int((self.getPrice(key) / value["value at purchase"]) * value["purchased"])
if purchaseValue == "?":
portfolio += f"\n**{key}**: ___{str(currentValue)} GwendoBucks___"
else:
portfolio += f"\n**{key}**: ___{str(currentValue)} GwendoBucks___ (purchased for {str(purchaseValue)})"
return portfolio
def buyStock(self, user : str, stock : str, buyAmount : int):
if buyAmount >= 100:
if self.bot.money.checkBalance(user) >= buyAmount:
stockPrice = self.getPrice(stock)
if stockPrice > 0:
userInvestments = self.bot.database["investments"].find_one({"_id":user})
self.bot.money.addMoney(user,-1*buyAmount)
stock = stock.upper()
if userInvestments != None:
userInvestments = userInvestments["investments"]
if stock in userInvestments:
value = userInvestments[stock]
newAmount = int((stockPrice / value["value at purchase"]) * value["purchased"]) + buyAmount
self.bot.database["investments"].update_one({"_id":user},
{"$set":{"investments."+stock+".value at purchase" : stockPrice}})
self.bot.database["investments"].update_one({"_id":user},
{"$set":{"investments."+stock+".purchased" : newAmount}})
if value["purchased for"] != "?":
self.bot.database["investments"].update_one({"_id":user},
{"$set":{"investments."+stock+".purchased for" : buyAmount}})
else:
self.bot.database["investments"].update_one({"_id":user},
{"$set":{"investments."+stock : {"purchased" : buyAmount, "value at purchase" : stockPrice,
"purchased for" : buyAmount}}})
else:
newUser = {"_id":user,"investments":{stock : {"purchased" : buyAmount, "value at purchase" : stockPrice, "purchased for" : buyAmount}}}
self.bot.database["investments"].insert_one(newUser)
return f"{self.bot.databaseFuncs.getName(user)} bought {buyAmount} GwendoBucks worth of {stock} stock"
else:
return f"{stock} is not traded on the american market."
else:
return "You don't have enough money for that"
else:
return "You cannot buy stocks for less than 100 GwendoBucks"
def sellStock(self, user : str, stock : str, sellAmount : int):
if sellAmount > 0:
userInvestments = self.bot.database["investments"].find_one({"_id":user})["investments"]
stock = stock.upper()
if userInvestments != None and stock in userInvestments:
value = userInvestments[stock]
stockPrice = self.getPrice(stock)
self.bot.database["investments"].update_one({"_id":user},
{"$set":{"investments."+stock+".purchased" :
int((stockPrice / value["value at purchase"]) * value["purchased"])}})
self.bot.database["investments"].update_one({"_id":user},
{"$set":{"investments."+stock+".value at purchase" : stockPrice}})
if value["purchased"] >= sellAmount:
self.bot.money.addMoney(user,sellAmount)
if sellAmount < value["purchased"]:
self.bot.database["investments"].update_one({"_id":user},
{"$inc":{"investments."+stock+".purchased" : -sellAmount}})
self.bot.database["investments"].update_one({"_id":user},
{"$set":{"investments."+stock+".purchased for" : "?"}})
else:
self.bot.database["investments"].update_one({"_id":user},
{"$unset":{"investments."+stock:""}})
return f"{self.bot.databaseFuncs.getName(user)} sold {sellAmount} GwendoBucks worth of {stock} stock"
else:
return f"You don't have enough {stock} stocks to do that"
else:
return f"You don't have any {stock} stock"
else:
return "no"
async def parseInvest(self, ctx, parameters):
await self.bot.defer(ctx)
user = f"#{ctx.author.id}"
if parameters.startswith("check"):
commands = parameters.split(" ")
if len(commands) == 1:
response = self.getPortfolio(user)
else:
price = self.getPrice(commands[1])
if price == 0:
response = f"{commands[1].upper()} is not traded on the american market."
else:
price = f"{price:,}".replace(",",".")
response = f"The current {commands[1].upper()} stock is valued at **{price}** GwendoBucks"
elif parameters.startswith("buy"):
commands = parameters.split(" ")
if len(commands) == 3:
response = self.buyStock(user,commands[1],int(commands[2]))
else:
response = "You must give both a stock name and an amount of gwendobucks you wish to spend."
elif parameters.startswith("sell"):
commands = parameters.split(" ")
if len(commands) == 3:
try:
response = self.sellStock(user,commands[1],int(commands[2]))
except:
response = "The command must be given as \"/invest sell [stock] [amount of GwendoBucks to sell stocks for]\""
else:
response = "You must give both a stock name and an amount of GwendoBucks you wish to sell stocks for."
else:
response = "Incorrect parameters"
if response.startswith("**"):
responses = response.split("\n")
em = discord.Embed(title=responses[0],description="\n".join(responses[1:]),colour=0x00FF00)
await ctx.send(embed=em)
else:
await ctx.send(response)