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/ .vscode/
token.txt token.txt
credentials.txt
resources/starWars/swcharacters.json resources/starWars/swcharacters.json
resources/games/games.json resources/games/games.json
resources/games/hexGames.json resources/games/hexGames.json

View File

@ -1,11 +1,32 @@
import discord, os import discord, os, finnhub
from discord.ext import commands from discord.ext import commands
from funcs import logThis, makeFiles from funcs import logThis, makeFiles
commandPrefix = "!" 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 # Logs in
@client.event @client.event
@ -14,16 +35,7 @@ async def on_ready():
game = discord.Game("Some weeb shit") game = discord.Game("Some weeb shit")
await client.change_presence(activity=game) await client.change_presence(activity=game)
# Loads and unloads cogs # Logs when user sends a command
@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}")
@client.event @client.event
async def on_command(ctx): async def on_command(ctx):
logThis(f"{ctx.message.author.display_name} ran {ctx.message.content}") 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)) logThis(f"Something went wrong, {error}",str(ctx.message.channel.id))
await ctx.send("Something went wrong (error code 000)") await ctx.send("Something went wrong (error code 000)")
#Loads cogs
for filename in os.listdir("./cogs"): for filename in os.listdir("./cogs"):
if filename.endswith(".py"): if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}") client.load_extension(f"cogs.{filename[:-3]}")
# Creates the required files try:
makeFiles()
# Gets secret bot token
with open("token.txt","r") as f:
token = f.read().replace("\n","")
# Runs the whole shabang # Runs the whole shabang
client.run(token) 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 # Invest GwendoBucks in the stock market
@commands.command(aliases=["i"]) @commands.command(aliases=["i"])
async def invest(self, ctx, *, content = "check"): 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("**"): if response.startswith("**"):
responses = response.split("\n") responses = response.split("\n")
em = discord.Embed(title=responses[0],description="\n".join(responses[1:]),colour=0x00FF00) 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 # Runs a game of Hangman
@commands.command(aliases = ["hm"]) @commands.command(aliases = ["hm"])
async def hangman(self, ctx, *, content = "start"): 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): def setup(client):
client.add_cog(GamesCog(client)) client.add_cog(GamesCog(client))

View File

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

View File

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

View File

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

View File

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

View File

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