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 pymongo import MongoClient
from funcs import logThis, makeFiles, Money, Funcs, SwChar, SwDestiny, SwRoll, Games, Generators, BedreNetflix, NerdShit
from utils import Options
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(" ","")
from utils import Options, Credentials
class Gwendolyn(commands.Bot):
def __init__(self):
@ -52,51 +35,24 @@ class Gwendolyn(commands.Bot):
super().__init__(command_prefix=" ", case_insensitive=True)
# Creates the required files
makeFiles()
if __name__ == "__main__":
if platform.system() == "Windows":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# Creates the Bot
client = Gwendolyn()
slash = SlashCommand(client, sync_commands=True, sync_on_cog_reload=True, override_type=True)
# Creates the required files
makeFiles()
# 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)
# Creates the Bot
client = Gwendolyn()
slash = SlashCommand(client, sync_commands=True, sync_on_cog_reload=True, override_type=True)
# Logs when user sends a command
@client.event
async def on_slash_command(ctx):
logThis(f"{ctx.author.display_name} ran {ctx.name}")
#Loads cogs
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
# 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"):
client.load_extension(f"cogs.{filename[:-3]}")
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")
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")

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

View File

@ -60,7 +60,7 @@
"resources/movies.txt": "The Room",
"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",
"options.txt" : "Testing: True\nTesting guild id:\nAdmins:"
"options.txt" : "Testing: True\nTesting guild ids:\nAdmins:"
},
"folder" : [
"resources/games/blackjackTables",

View File

@ -1,5 +1,5 @@
"""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(",")