More converting

This commit is contained in:
Nikolaj Danger
2021-03-30 18:27:47 +02:00
parent e8c7fb95e5
commit a8a7e5eabd
7 changed files with 113 additions and 74 deletions

View File

@ -4,24 +4,7 @@ from discord.ext import commands
from discord_slash import SlashCommand from discord_slash import SlashCommand
from pymongo import MongoClient from pymongo import MongoClient
from funcs import logThis, makeFiles, Money, Funcs, SwChar, SwDestiny, SwRoll, Games, Generators, BedreNetflix, NerdShit from funcs import logThis, makeFiles, Money, Funcs, SwChar, SwDestiny, SwRoll, Games, Generators, BedreNetflix, NerdShit
from utils import Options from utils import Options, Credentials
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
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(" ","")
self.mongoDBUser = data[3][13:].replace(" ","")
self.mongoDBPassword = data[4][17:].replace(" ","")
self.wolfKey = data[5][19:].replace(" ","")
self.radarrKey = data[6][15:].replace(" ","")
self.sonarrKey = data[7][15:].replace(" ","")
class Gwendolyn(commands.Bot): class Gwendolyn(commands.Bot):
def __init__(self): def __init__(self):
@ -52,51 +35,24 @@ class Gwendolyn(commands.Bot):
super().__init__(command_prefix=" ", case_insensitive=True) super().__init__(command_prefix=" ", case_insensitive=True)
# Creates the required files if __name__ == "__main__":
makeFiles() if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Creates the Bot # Creates the required files
client = Gwendolyn() makeFiles()
slash = SlashCommand(client, sync_commands=True, sync_on_cog_reload=True, override_type=True)
# Logs in # Creates the Bot
@client.event client = Gwendolyn()
async def on_ready(): slash = SlashCommand(client, sync_commands=True, sync_on_cog_reload=True, override_type=True)
logThis("Logged in as "+client.user.name+", "+str(client.user.id))
game = discord.Game("Some weeb shit")
await client.change_presence(activity=game)
# Logs when user sends a command #Loads cogs
@client.event for filename in os.listdir("./cogs"):
async def on_slash_command(ctx):
logThis(f"{ctx.author.display_name} ran {ctx.name}")
# Logs if a command experiences an error
@client.event
async def on_slash_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("That's not a command (error code 001)")
elif isinstance(error,commands.errors.MissingRequiredArgument):
logThis(f"{error}",str(ctx.channel_id))
await ctx.send("Missing command parameters (error code 002). Try using `!help [command]` to find out how to use the command.")
else:
exception = traceback.format_exception(type(error), error, error.__traceback__)
stopAt = "\nThe above exception was the direct cause of the following exception:\n\n"
if stopAt in exception:
index = exception.index(stopAt)
exception = exception[:index]
exceptionString = "".join(exception)
logThis([f"exception in {ctx.name} command", f"{exceptionString}"],str(ctx.channel_id), 40)
await ctx.send("Something went wrong (error code 000)")
#Loads 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]}")
try: try:
# Runs the whole shabang # Runs the whole shabang
client.run(client.credentials.token) client.run(client.credentials.token)
except: except:
logThis("Could not log in. Remember to write your bot token in the credentials.txt file") logThis("Could not log in. Remember to write your bot token in the credentials.txt file")

36
cogs/EventCog.py Normal file
View File

@ -0,0 +1,36 @@
from discord.ext import commands
class EventCog(commands.cog):
def __init__(bot):
self.bot = bot
# Sets the game and logs when the bot logs in
@client.event
async def on_ready():
logThis("Logged in as "+client.user.name+", "+str(client.user.id))
game = discord.Game("Some weeb shit")
await client.change_presence(activity=game)
# Logs when user sends a command
@client.event
async def on_slash_command(ctx):
logThis(f"{ctx.author.display_name} ran {ctx.name}")
# Logs if a command experiences an error
@client.event
async def on_slash_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("That's not a command (error code 001)")
elif isinstance(error,commands.errors.MissingRequiredArgument):
logThis(f"{error}",str(ctx.channel_id))
await ctx.send("Missing command parameters (error code 002). Try using `!help [command]` to find out how to use the command.")
else:
exception = traceback.format_exception(type(error), error, error.__traceback__)
stopAt = "\nThe above exception was the direct cause of the following exception:\n\n"
if stopAt in exception:
index = exception.index(stopAt)
exception = exception[:index]
exceptionString = "".join(exception)
logThis([f"exception in {ctx.name} command", f"{exceptionString}"],str(ctx.channel_id), 40)
await ctx.send("Something went wrong (error code 000)")

View File

@ -24,6 +24,7 @@ class GamesCog(commands.Cog):
# Checks user balance # Checks user balance
@cog_ext.cog_slash(**params["balance"]) @cog_ext.cog_slash(**params["balance"])
async def balance(self, ctx): async def balance(self, ctx):
await ctx.defer()
response = self.bot.money.checkBalance("#"+str(ctx.author.id)) response = self.bot.money.checkBalance("#"+str(ctx.author.id))
if response == 1: if response == 1:
new_message = ctx.author.display_name + " has " + str(response) + " GwendoBuck" new_message = ctx.author.display_name + " has " + str(response) + " GwendoBuck"
@ -34,6 +35,7 @@ class GamesCog(commands.Cog):
# Gives another user an amount of GwendoBucks # Gives another user an amount of GwendoBucks
@cog_ext.cog_slash(**params["give"]) @cog_ext.cog_slash(**params["give"])
async def give(self, ctx, parameters): async def give(self, ctx, parameters):
await ctx.defer()
commands = parameters.split(" ") commands = parameters.split(" ")
amount = int(commands[-1]) amount = int(commands[-1])
username = " ".join(commands[:-1]) username = " ".join(commands[:-1])
@ -49,6 +51,7 @@ class GamesCog(commands.Cog):
# Invest GwendoBucks in the stock market # Invest GwendoBucks in the stock market
@cog_ext.cog_slash(**params["invest"]) @cog_ext.cog_slash(**params["invest"])
async def invest(self, ctx, parameters = "check"): async def invest(self, ctx, parameters = "check"):
await ctx.defer()
response = self.bot.invest.parseInvest(parameters,"#"+str(ctx.author.id)) response = self.bot.invest.parseInvest(parameters,"#"+str(ctx.author.id))
if response.startswith("**"): if response.startswith("**"):
responses = response.split("\n") responses = response.split("\n")
@ -60,6 +63,7 @@ class GamesCog(commands.Cog):
# Runs a game of trivia # Runs a game of trivia
@cog_ext.cog_slash(**params["trivia"]) @cog_ext.cog_slash(**params["trivia"])
async def trivia(self, ctx, answer = ""): async def trivia(self, ctx, answer = ""):
await ctx.defer()
if answer == "": if answer == "":
question, options, correctAnswer = self.bot.trivia.triviaStart(str(ctx.channel_id)) question, options, correctAnswer = self.bot.trivia.triviaStart(str(ctx.channel_id))
if options != "": if options != "":
@ -93,16 +97,19 @@ class GamesCog(commands.Cog):
# Runs a game of blackjack # Runs a game of blackjack
@cog_ext.cog_slash(**params["blackjack"]) @cog_ext.cog_slash(**params["blackjack"])
async def blackjack(self, ctx, parameters = ""): async def blackjack(self, ctx, parameters = ""):
await ctx.defer()
await self.bot.blackjack.parseBlackjack(parameters, ctx) await self.bot.blackjack.parseBlackjack(parameters, ctx)
# Start a game of connect four against a user # Start a game of connect four against a user
@cog_ext.cog_subcommand(**params["connectFourStartUser"]) @cog_ext.cog_subcommand(**params["connectFourStartUser"])
async def connectFourStartUser(self, ctx, user): async def connectFourStartUser(self, ctx, user):
await ctx.defer()
await self.bot.gameLoops.connectFour(ctx, "start "+user.display_name) await self.bot.gameLoops.connectFour(ctx, "start "+user.display_name)
# Start a game of connect four against gwendolyn # Start a game of connect four against gwendolyn
@cog_ext.cog_subcommand(**params["connectFourStartGwendolyn"]) @cog_ext.cog_subcommand(**params["connectFourStartGwendolyn"])
async def connectFourStartGwendolyn(self, ctx, difficulty = 3): async def connectFourStartGwendolyn(self, ctx, difficulty = 3):
await ctx.defer()
await self.bot.gameLoops.connectFour(ctx, "start "+str(difficulty)) await self.bot.gameLoops.connectFour(ctx, "start "+str(difficulty))
# Stop the current game of connect four # Stop the current game of connect four
@ -118,6 +125,7 @@ class GamesCog(commands.Cog):
# Starts a game of Hangman # Starts a game of Hangman
@cog_ext.cog_subcommand(**params["hangmanStart"]) @cog_ext.cog_subcommand(**params["hangmanStart"])
async def hangmanStart(self, ctx): async def hangmanStart(self, ctx):
await ctx.defer()
await self.bot.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"start", ctx) await self.bot.gameLoops.runHangman(ctx.channel,"#"+str(ctx.author.id),"start", ctx)
# Stops a game of Hangman # Stops a game of Hangman
@ -128,11 +136,13 @@ class GamesCog(commands.Cog):
# Start a game of Hex against another user # Start a game of Hex against another user
@cog_ext.cog_subcommand(**params["hexStartUser"]) @cog_ext.cog_subcommand(**params["hexStartUser"])
async def hexStartUser(self, ctx, user): async def hexStartUser(self, ctx, user):
await ctx.defer()
await self.bot.gameLoops.runHex(ctx, "start "+user.display_name, "#"+str(ctx.author.id)) await self.bot.gameLoops.runHex(ctx, "start "+user.display_name, "#"+str(ctx.author.id))
# Start a game of Hex against Gwendolyn # Start a game of Hex against Gwendolyn
@cog_ext.cog_subcommand(**params["hexStartGwendolyn"]) @cog_ext.cog_subcommand(**params["hexStartGwendolyn"])
async def hexStartGwendolyn(self, ctx, difficulty = 2): async def hexStartGwendolyn(self, ctx, difficulty = 2):
await ctx.defer()
await self.bot.gameLoops.runHex(ctx, "start "+str(difficulty), "#"+str(ctx.author.id)) await self.bot.gameLoops.runHex(ctx, "start "+str(difficulty), "#"+str(ctx.author.id))
# Undo your last hex move # Undo your last hex move

View File

@ -60,7 +60,7 @@
"resources/movies.txt": "The Room", "resources/movies.txt": "The Room",
"resources/names.txt": "Gandalf", "resources/names.txt": "Gandalf",
"credentials.txt" : "Bot token: TOKEN\nFinnhub API key: KEY\nWordnik API Key: KEY\nMongoDB user: USERNAME\nMongoDB password: PASSWORD\nWolframAlpha AppID: APPID\nRadarr API key: KEY\nSonarr API key: KEY", "credentials.txt" : "Bot token: TOKEN\nFinnhub API key: KEY\nWordnik API Key: KEY\nMongoDB user: USERNAME\nMongoDB password: PASSWORD\nWolframAlpha AppID: APPID\nRadarr API key: KEY\nSonarr API key: KEY",
"options.txt" : "Testing: True\nTesting guild id:\nAdmins:" "options.txt" : "Testing: True\nTesting guild ids:\nAdmins:"
}, },
"folder" : [ "folder" : [
"resources/games/blackjackTables", "resources/games/blackjackTables",

View File

@ -1,5 +1,5 @@
"""A collections of utilities used by Gwendolyn and her functions""" """A collections of utilities used by Gwendolyn and her functions"""
__all__ = ["Options"] __all__ = ["Options", "Credentials"]
from .options import Options from .helperClasses import Options, Credentials

46
utils/helperClasses.py Normal file
View File

@ -0,0 +1,46 @@
def sanitize(data : str, options : bool = False):
data = data.splitlines()
dct = {}
for line in data:
if line[0] != "#" and ":" in line:
lineValues = line.split(":")
lineValues[0] = lineValues[0].lower()
lineValues[1] = lineValues[1].replace(" ", "")
if options:
lineValues[1] = lineValues[1].lower()
if lineValues[0] in ["testing guild ids", "admins"]:
lineValues[1] = lineValues[1].split(",")
if all(i.isnumeric() for i in lineValues[1]):
lineValues[1] = [int(i) for i in lineValues[1]]
if any(i == lineValues[1] for i in ["true", "false"]):
lineValues[1] = (lineValues[1] == "true")
dct[lineValues[0]] = lineValues[1]
return dct
class Options():
def __init__(self):
with open("options.txt","r") as f:
data = sanitize(f.read(), True)
self.testing = data["testing"]
self.guildIds = data["testing guild ids"]
self.admins = data["admins"]
class Credentials():
def __init__(self):
with open("credentials.txt","r") as f:
data = sanitize(f.read())
self.token = data["bot token"]
self.finnhubKey = data["finnhub api key"]
self.wordnikKey = data["wordnik api key"]
self.mongoDBUser = data["mongodb user"]
self.mongoDBPassword = data["mongodb password"]
self.wolfKey = data["wolframalpha appid"]
self.radarrKey = data["radarr api key"]
self.sonarrKey = data["sonarr api key"]

View File

@ -1,9 +0,0 @@
class Options():
def __init__(self):
with open("options.txt","r") as f:
data = f.read().splitlines()
self.testing = (data[0][8:].replace(" ","").lower() == "true")
guildIds = data[1][17:].replace(" ","").split(",")
self.guildIds = [int(i) for i in guildIds]
self.admins = data[2][7:].replace(" ","").split(",")