From 205cc46a9cfd47560d8a860e24e9c34de3ead1b2 Mon Sep 17 00:00:00 2001 From: NikolajDanger Date: Thu, 6 Aug 2020 23:05:20 +0200 Subject: [PATCH 1/2] :dollar: --- .gitignore | 1 + cogs/GamesCog.py | 8 ++- funcs/games/invest.py | 116 +++++++++++++++++++++++++++++++-- resources/help/help-invest.txt | 3 + resources/help/help.txt | 2 + resources/startingFiles.json | 1 + 6 files changed, 126 insertions(+), 5 deletions(-) create mode 100644 resources/help/help-invest.txt diff --git a/.gitignore b/.gitignore index f1f852f..938c7e8 100644 --- a/.gitignore +++ b/.gitignore @@ -161,6 +161,7 @@ resources/games/blackjackTables/ resources/games/oldImages/ resources/games/4InARowBoards/ resources/games/monopolyBoards/ +resources/games/investments.json resources/lookup/monsters.json resources/lookup/spells.json resources/movies.txt diff --git a/cogs/GamesCog.py b/cogs/GamesCog.py index 33254c7..0850d3e 100644 --- a/cogs/GamesCog.py +++ b/cogs/GamesCog.py @@ -37,7 +37,13 @@ class GamesCog(commands.Cog): # Invest GwendoBucks in the stock market @commands.command(aliases=["i"]) async def invest(self, ctx, *, content = "check"): - await ctx.send(parseInvest(content,str(ctx.message.author.id))) + response = parseInvest(content,"#"+str(ctx.message.author.id)) + 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) # Runs a game of trivia @commands.command() diff --git a/funcs/games/invest.py b/funcs/games/invest.py index 0a2f535..032493d 100644 --- a/funcs/games/invest.py +++ b/funcs/games/invest.py @@ -1,4 +1,7 @@ -import finnhub +import finnhub, json + +from funcs import getName +from .money import checkBalance, addMoney finnhubClient = finnhub.Client(api_key = "bsm16nvrh5rdb4ara3j0") @@ -7,11 +10,95 @@ def getPrice(symbol : str): if res == {}: return 0 else: - print(res) return int(res["c"] * 100) def getPortfolio(user : str): - return None + with open("resources/games/investments.json") as f: + data = json.load(f) + + if user not in data or data[user] == {}: + return f"{getName(user)} does not have a stock portfolio." + else: + portfolio = f"**Stock portfolio for {getName(user)}**" + + for key, value in list(data[user].items()): + purchaseValue = value["purchased for"] + currentValue = int((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(user : str, stock : str, buyAmount : int): + if buyAmount >= 100: + if checkBalance(user) >= buyAmount: + stockPrice = getPrice(stock) + if stockPrice > 0: + with open("resources/games/investments.json", "r") as f: + data = json.load(f) + + addMoney(user,-1*buyAmount) + stock = stock.upper() + + if user in data: + if stock in data[user]: + value = data[user][stock] + newAmount = int((stockPrice / value["value at purchase"]) * value["purchased"]) + buyAmount + + data[user][stock]["value at purchase"] = stockPrice + data[user][stock]["purchased"] = newAmount + if value["purchased for"] != "?": + data[user][stock]["purchased for"] += buyAmount + else: + data[user][stock] = {"purchased" : buyAmount, "value at purchase" : stockPrice, "purchased for" : buyAmount} + else: + data[user] = {stock : {"purchased" : buyAmount, "value at purchase" : stockPrice, "purchased for" : buyAmount}} + + with open("resources/games/investments.json", "w") as f: + json.dump(data,f,indent=4) + + return f"{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(user : str, stock : str, sellAmount : int): + if sellAmount > 0: + with open("resources/games/investments.json", "r") as f: + data = json.load(f) + + stock = stock.upper() + + if user in data and stock in data[user]: + value = data[user][stock] + stockPrice = getPrice(stock) + data[user][stock]["purchased"] = int((stockPrice / value["value at purchase"]) * value["purchased"]) + data[user][stock]["value at purchase"] = stockPrice + if value["purchased"] >= sellAmount: + + addMoney(user,sellAmount) + if sellAmount < value["purchased"]: + data[user][stock]["purchased"] -= sellAmount + data[user][stock]["purchased for"] = "?" + else: + del data[user][stock] + + with open("resources/games/investments.json", "w") as f: + json.dump(data,f,indent=4) + + return f"{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" def parseInvest(content: str, user : str): if content.startswith("check"): @@ -23,4 +110,25 @@ def parseInvest(content: str, user : str): if price == 0: return f"{commands[1].upper()} is not traded on the american market." else: - return "The current "+commands[1].upper()+" stock is valued at **"+str(price)+"** GwendoBucks" \ No newline at end of file + price = f"{price:,}".replace(",",".") + return f"The current {commands[1].upper()} stock is valued at **{price}** GwendoBucks" + + elif content.startswith("buy"): + commands = content.split(" ") + if len(commands) == 3: + try: + return buyStock(user,commands[1],int(commands[2])) + except: + return "The command must be given as \"!invest buy [stock] [amount of GwendoBucks to purchase with]\"" + else: + return "You must give both a stock name and an amount of gwendobucks you wish to spend." + + elif content.startswith("sell"): + commands = content.split(" ") + if len(commands) == 3: + try: + return sellStock(user,commands[1],int(commands[2])) + except: + return "The command must be given as \"!invest sell [stock] [amount of GwendoBucks to sell stocks for]\"" + else: + return "You must give both a stock name and an amount of GwendoBucks you wish to sell stocks for." diff --git a/resources/help/help-invest.txt b/resources/help/help-invest.txt new file mode 100644 index 0000000..b5ceae5 --- /dev/null +++ b/resources/help/help-invest.txt @@ -0,0 +1,3 @@ +`!invest` vil vise dig hvilke aktier du har. `!invest check [symbol]` viser dig en akties nuværende pris, hvor [symbol] er forkortelsen for firmaet. GwendoBucks er lig med 1 amerikans cent. +`!invest buy [symbol] [pris]` lader dig købe aktier. [pris] er mængden af GwendoBucks du bruger på at købe. Du kan købe for færre GwendoBucks end en enkelt akties pris, men ikke for mindre end 100 GwendoBucks. +`!invest buy [symbol] [pris]` lader dig sælge dine aktier. Du kan godt sælge for mindre end 100 GwendoBucks. \ No newline at end of file diff --git a/resources/help/help.txt b/resources/help/help.txt index 1010e01..561a0d4 100644 --- a/resources/help/help.txt +++ b/resources/help/help.txt @@ -24,6 +24,8 @@ `!balance` - Viser dig hvor mange GwendoBucks du har. +`!invest` - Lader dig investere dine GwendoBucks i aktiemarkedet. + `!blackjack` - Lader dig spille et spil blackjack. `!trivia` - Lader dig spille et spil trivia, hvor du kan tjene GwendoBucks. diff --git a/resources/startingFiles.json b/resources/startingFiles.json index 85537f4..57d50b3 100644 --- a/resources/startingFiles.json +++ b/resources/startingFiles.json @@ -4,6 +4,7 @@ "resources/games/hexGames.json": {}, "resources/games/monopolyGames.json": {}, "resources/users.json" : {}, + "resources/games/investments.json" : {}, "resources/games/games.json" : { "trivia questions":{}, "blackjack games":{}, From 05fe12277781e4e44c13326af7489c00377e30fa Mon Sep 17 00:00:00 2001 From: NikolajDanger Date: Thu, 6 Aug 2020 23:38:14 +0200 Subject: [PATCH 2/2] :card_file_box: Moves gameLoops.py --- cogs/GamesCog.py | 4 +--- cogs/ReactionCog.py | 3 +-- funcs/__init__.py | 4 ++-- funcs/games/__init__.py | 6 ++---- gameLoops.py => funcs/games/gameLoops.py | 7 ++++++- 5 files changed, 12 insertions(+), 12 deletions(-) rename gameLoops.py => funcs/games/gameLoops.py (97%) diff --git a/cogs/GamesCog.py b/cogs/GamesCog.py index 0850d3e..6dcd593 100644 --- a/cogs/GamesCog.py +++ b/cogs/GamesCog.py @@ -1,9 +1,7 @@ import discord, asyncio, os, json from discord.ext import commands -from funcs import logThis, triviaAnswer, triviaCountPoints, triviaStart, deleteGame, checkBalance, giveMoney, blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackHit, blackjackDouble, blackjackFinish, blackjackSplit, blackjackStand, parseInvest - -from gameLoops import blackjackLoop, fiar, runMonopoly, runHex +from funcs import logThis, triviaAnswer, triviaCountPoints, triviaStart, deleteGame, checkBalance, giveMoney, blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackHit, blackjackDouble, blackjackFinish, blackjackSplit, blackjackStand, parseInvest, blackjackLoop, fiar, runMonopoly, runHex class GamesCog(commands.Cog): diff --git a/cogs/ReactionCog.py b/cogs/ReactionCog.py index a210757..0e88fff 100644 --- a/cogs/ReactionCog.py +++ b/cogs/ReactionCog.py @@ -1,7 +1,6 @@ from discord.ext import commands -from funcs import logThis, fiarReactionTest, monopolyReactionTest, emojiToCommand -from gameLoops import fiar, runMonopoly +from funcs import logThis, fiarReactionTest, monopolyReactionTest, emojiToCommand, fiar, runMonopoly class ReactionCog(commands.Cog): def __init__(self, client): diff --git a/funcs/__init__.py b/funcs/__init__.py index 85b7e9f..9decccb 100644 --- a/funcs/__init__.py +++ b/funcs/__init__.py @@ -1,10 +1,10 @@ """A collection of all Gwendolyn functions.""" -__all__ = ["helloFunc", "cap", "imageFunc", "logThis", "findWikiPage", "makeFiles", "emojiToCommand", "fiarReactionTest", "deleteGame", "stopServer", "checkBalance", "giveMoney", "addMoney", "triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "parseFourInARow", "fourInARowAI", "spellFunc", "monsterFunc", "nameGen", "tavernGen", "movieFunc", "roll_dice", "parseChar", "parseRoll", "critRoll", "parseDestiny", "parseHex", "addToDict", "getName", "getID", "replaceMultiple", "hexAI", "parseMonopoly", "monopolyContinue", "monopolyReactionTest","parseInvest"] +__all__ = ["helloFunc", "cap", "imageFunc", "logThis", "findWikiPage", "makeFiles", "emojiToCommand", "fiarReactionTest", "deleteGame", "stopServer", "checkBalance", "giveMoney", "addMoney", "triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "spellFunc", "monsterFunc", "nameGen", "tavernGen", "movieFunc", "roll_dice", "parseChar", "parseRoll", "critRoll", "parseDestiny", "addToDict", "getName", "getID", "replaceMultiple", "monopolyReactionTest","parseInvest", "blackjackLoop", "fiar", "runMonopoly", "runHex"] from .miscFuncs import helloFunc, cap, imageFunc, logThis, findWikiPage, makeFiles, replaceMultiple, emojiToCommand, fiarReactionTest, deleteGame, stopServer, addToDict, getName, getID, monopolyReactionTest -from .games import checkBalance, giveMoney, addMoney, triviaCountPoints, triviaStart, triviaAnswer, blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackContinue, blackjackFinish, blackjackHit, blackjackStand, blackjackDouble, blackjackSplit, parseFourInARow, fourInARowAI, parseHex, hexAI, parseMonopoly, monopolyContinue, parseInvest +from .games import checkBalance, giveMoney, addMoney, triviaCountPoints, triviaStart, triviaAnswer, blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackContinue, blackjackFinish, blackjackHit, blackjackStand, blackjackDouble, blackjackSplit, parseInvest, blackjackLoop, fiar, runMonopoly, runHex from .lookup import spellFunc, monsterFunc diff --git a/funcs/games/__init__.py b/funcs/games/__init__.py index 897fd1d..f116ce3 100644 --- a/funcs/games/__init__.py +++ b/funcs/games/__init__.py @@ -1,11 +1,9 @@ """Functions for games Gwendolyn can play.""" -__all__ = ["checkBalance", "giveMoney", "addMoney","triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "parseFourInARow", "fourInARowAI", "parseHex", "hexAI", "parseMonopoly", "monopolyContinue","parseInvest"] +__all__ = ["checkBalance", "giveMoney", "addMoney","triviaCountPoints", "triviaStart", "triviaAnswer", "blackjackShuffle", "blackjackStart", "blackjackPlayerDrawHand", "blackjackContinue", "blackjackFinish", "blackjackHit", "blackjackStand", "blackjackDouble", "blackjackSplit", "parseInvest", "blackjackLoop", "fiar", "runMonopoly", "runHex"] from .money import checkBalance, giveMoney, addMoney from .trivia import triviaCountPoints, triviaStart, triviaAnswer from .blackjack import blackjackShuffle, blackjackStart, blackjackPlayerDrawHand, blackjackContinue, blackjackFinish, blackjackHit, blackjackStand, blackjackDouble, blackjackSplit -from .fourInARow import parseFourInARow, fourInARowAI -from .hex import parseHex, hexAI -from .monopoly import parseMonopoly, monopolyContinue from .invest import parseInvest +from .gameLoops import blackjackLoop, fiar, runMonopoly, runHex diff --git a/gameLoops.py b/funcs/games/gameLoops.py similarity index 97% rename from gameLoops.py rename to funcs/games/gameLoops.py index ac400be..ca89987 100644 --- a/gameLoops.py +++ b/funcs/games/gameLoops.py @@ -2,7 +2,12 @@ import asyncio import discord import json -from funcs import logThis, addMoney, deleteGame, parseFourInARow, fourInARowAI, blackjackContinue, blackjackFinish, parseHex, hexAI, parseMonopoly, monopolyContinue +from funcs import logThis, deleteGame +from .money import addMoney +from .fourInARow import parseFourInARow, fourInARowAI +from .blackjack import blackjackContinue, blackjackFinish +from .hex import parseHex, hexAI +from .monopoly import parseMonopoly, monopolyContinue # Deletes a message async def deleteMessage(imageLocation,channel):