Better credentials

This commit is contained in:
NikolajDanger
2020-08-09 13:02:04 +02:00
parent 9f683034c5
commit 84e332fa68
8 changed files with 56 additions and 49 deletions

1
.gitignore vendored
View File

@ -150,6 +150,7 @@ static
.vscode/
token.txt
credentials.txt
resources/starWars/swcharacters.json
resources/games/games.json
resources/games/hexGames.json

View File

@ -1,11 +1,32 @@
import discord, os
import discord, os, finnhub
from discord.ext import commands
from funcs import logThis, makeFiles
commandPrefix = "!"
client = commands.Bot(command_prefix=commandPrefix, case_insensitive=True)
class Credentials():
def __init__(self):
with open("credentials.txt","r") as f:
data = f.read().splitlines()
self.token = data[0][10:].replace(" ","")
self.finnhubKey = data[1][16:].replace(" ","")
self.wordnikKey = data[2][16:].replace(" ","")
class Gwendolyn(commands.Bot):
def __init__(self):
self.credentials = Credentials()
self.finnhubClient = finnhub.Client(api_key = self.credentials.finnhubKey)
super().__init__(command_prefix=commandPrefix, case_insensitive=True)
# Creates the required files
makeFiles()
# Creates the Bot
client = Gwendolyn()
# Logs in
@client.event
@ -14,16 +35,7 @@ async def on_ready():
game = discord.Game("Some weeb shit")
await client.change_presence(activity=game)
# Loads and unloads cogs
@client.command()
async def load(ctx,extension):
client.load_extension(f"cogs.{extension}")
@client.command()
async def unload(ctx,extension):
client.unload_extension(f"cogs.{extension}")
# Logs when user sends a command
@client.event
async def on_command(ctx):
logThis(f"{ctx.message.author.display_name} ran {ctx.message.content}")
@ -37,16 +49,13 @@ async def on_command_error(ctx, error):
logThis(f"Something went wrong, {error}",str(ctx.message.channel.id))
await ctx.send("Something went wrong (error code 000)")
#Loads cogs
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
# Creates the required files
makeFiles()
# Gets secret bot token
with open("token.txt","r") as f:
token = f.read().replace("\n","")
# Runs the whole shabang
client.run(token)
try:
# Runs the whole shabang
client.run(client.credentials.token)
except:
logThis("Could not log in. Remember to write your bot token in the credentials.txt file")

View File

@ -34,7 +34,7 @@ class GamesCog(commands.Cog):
# Invest GwendoBucks in the stock market
@commands.command(aliases=["i"])
async def invest(self, ctx, *, content = "check"):
response = parseInvest(content,"#"+str(ctx.message.author.id))
response = parseInvest(content,"#"+str(ctx.message.author.id),self.client.finnhubClient)
if response.startswith("**"):
responses = response.split("\n")
em = discord.Embed(title=responses[0],description="\n".join(responses[1:]),colour=0x00FF00)
@ -275,7 +275,7 @@ class GamesCog(commands.Cog):
# Runs a game of Hangman
@commands.command(aliases = ["hm"])
async def hangman(self, ctx, *, content = "start"):
await runHangman(ctx.message.channel,"#"+str(ctx.message.author.id),content)
await runHangman(ctx.message.channel,"#"+str(ctx.message.author.id),self.client.credentials.wordnikKey,content)
def setup(client):
client.add_cog(GamesCog(client))

View File

@ -25,6 +25,6 @@ class ReactionCog(commands.Cog):
await runMonopoly(channel,"roll","#"+str(user.id))
elif hangmanReactionTest(channel,message):
guess = chr(ord(reaction.emoji)-127397)
await runHangman(channel,"#"+str(user.id),"guess "+guess)
await runHangman(channel,"#"+str(user.id),command="guess "+guess)
def setup(client):
client.add_cog(ReactionCog(client))

View File

@ -234,9 +234,9 @@ async def runMonopoly(channel, command, user):
except:
logThis("Image deleted before I could react to all of them")
async def runHangman(channel,user,command = "start"):
async def runHangman(channel,user,apiKey = "",command = "start"):
try:
response, showImage, deleteImage, remainingLetters = parseHangman(str(channel.id),user,command)
response, showImage, deleteImage, remainingLetters = parseHangman(str(channel.id),user,command,apiKey)
except:
logThis("Error parsing command (error code 1701)")
if response != "":

View File

@ -3,16 +3,15 @@ import json, urllib, random, datetime, string
from . import hangmanDraw, money
from funcs import getName, logThis
def hangmanStart(channel,user):
apiUrl = "https://api.wordnik.com/v4/words.json/randomWords?hasDictionaryDef=true&minCorpusCount=10000&maxCorpusCount=-1&minDictionaryCount=1&maxDictionaryCount=-1&minLength=3&maxLength=11&limit=1&api_key="
def hangmanStart(channel,user,apiKey):
with open("resources/games/hangmanGames.json", "r") as f:
data = json.load(f)
if channel not in data:
with urllib.request.urlopen("https://random-word-api.herokuapp.com/word?number=20") as p:
words = json.load(p)
word = "disestablishmentarianism"
while len(word) > 11:
word = list(random.choice(words).upper())
with urllib.request.urlopen(apiUrl+apiKey) as p:
word = list(json.load(p)[0]["word"].upper())
logThis("Found the word \""+"".join(word)+"\"")
guessed = [False] * len(word)
gameID = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
@ -97,10 +96,10 @@ def hangmanGuess(channel,user,guess):
else:
return "There's no Hangman game going on in this channel", False, False, []
def parseHangman(channel,user,command):
def parseHangman(channel,user,command,apiKey):
if command == "start":
try:
return hangmanStart(channel,user)
return hangmanStart(channel,user,apiKey)
except:
logThis("Error starting game (error code 1730)")
elif command == "stop":

View File

@ -3,16 +3,14 @@ import finnhub, json
from funcs import getName
from .money import checkBalance, addMoney
finnhubClient = finnhub.Client(api_key = "bsm16nvrh5rdb4ara3j0")
def getPrice(symbol : str):
def getPrice(symbol : str,finnhubClient):
res = finnhubClient.quote(symbol.upper())
if res == {}:
return 0
else:
return int(res["c"] * 100)
def getPortfolio(user : str):
def getPortfolio(user : str,finnhubClient):
with open("resources/games/investments.json") as f:
data = json.load(f)
@ -23,7 +21,7 @@ def getPortfolio(user : str):
for key, value in list(data[user].items()):
purchaseValue = value["purchased for"]
currentValue = int((getPrice(key) / value["value at purchase"]) * value["purchased"])
currentValue = int((getPrice(key,finnhubClient) / value["value at purchase"]) * value["purchased"])
if purchaseValue == "?":
portfolio += f"\n**{key}**: ___{str(currentValue)} GwendoBucks___"
else:
@ -31,10 +29,10 @@ def getPortfolio(user : str):
return portfolio
def buyStock(user : str, stock : str, buyAmount : int):
def buyStock(user : str, stock : str, buyAmount : int,finnhubClient):
if buyAmount >= 100:
if checkBalance(user) >= buyAmount:
stockPrice = getPrice(stock)
stockPrice = getPrice(stock,finnhubClient)
if stockPrice > 0:
with open("resources/games/investments.json", "r") as f:
data = json.load(f)
@ -68,7 +66,7 @@ def buyStock(user : str, stock : str, buyAmount : int):
else:
return "You cannot buy stocks for less than 100 GwendoBucks"
def sellStock(user : str, stock : str, sellAmount : int):
def sellStock(user : str, stock : str, sellAmount : int,finnhubClient):
if sellAmount > 0:
with open("resources/games/investments.json", "r") as f:
data = json.load(f)
@ -77,7 +75,7 @@ def sellStock(user : str, stock : str, sellAmount : int):
if user in data and stock in data[user]:
value = data[user][stock]
stockPrice = getPrice(stock)
stockPrice = getPrice(stock,finnhubClient)
data[user][stock]["purchased"] = int((stockPrice / value["value at purchase"]) * value["purchased"])
data[user][stock]["value at purchase"] = stockPrice
if value["purchased"] >= sellAmount:
@ -100,13 +98,13 @@ def sellStock(user : str, stock : str, sellAmount : int):
else:
return "no"
def parseInvest(content: str, user : str):
def parseInvest(content: str, user : str,finnhubClient):
if content.startswith("check"):
commands = content.split(" ")
if len(commands) == 1:
return getPortfolio(user)
return getPortfolio(user,finnhubClient)
else:
price = getPrice(commands[1])
price = getPrice(commands[1],finnhubClient)
if price == 0:
return f"{commands[1].upper()} is not traded on the american market."
else:
@ -117,7 +115,7 @@ def parseInvest(content: str, user : str):
commands = content.split(" ")
if len(commands) == 3:
try:
return buyStock(user,commands[1],int(commands[2]))
return buyStock(user,commands[1],int(commands[2]),finnhubClient)
except:
return "The command must be given as \"!invest buy [stock] [amount of GwendoBucks to purchase with]\""
else:
@ -127,7 +125,7 @@ def parseInvest(content: str, user : str):
commands = content.split(" ")
if len(commands) == 3:
try:
return sellStock(user,commands[1],int(commands[2]))
return sellStock(user,commands[1],int(commands[2]),finnhubClient)
except:
return "The command must be given as \"!invest sell [stock] [amount of GwendoBucks to sell stocks for]\""
else:

View File

@ -70,7 +70,7 @@
"resources/starWars/destinyPoints.txt": "",
"resources/movies.txt": "The Room",
"resources/names.txt": "Gandalf",
"token.txt" : "Write token here"
"credentials.txt" : "Bot token: TOKEN\nFinnhub API key: KEY\nWordnik API Key: KEY"
},
"folder" : [
"resources/games/blackjackTables",