🧹 PEP updating

This commit is contained in:
Nikolaj
2021-06-14 21:00:10 +02:00
parent 8f6c8b06be
commit 8c253aca3d
43 changed files with 343 additions and 333 deletions

View File

@ -1,40 +0,0 @@
"""Contains the StarWarsCog, which deals with Star Wars commands."""
from discord.ext import commands
from discord_slash import cog_ext
from utils import getParams # pylint: disable=import-error
params = getParams()
class StarWarsCog(commands.Cog):
"""Contains the Star Wars commands."""
def __init__(self, bot):
"""Initialize the cog."""
self.bot = bot
@cog_ext.cog_slash(**params["starWarsRoll"])
async def starWarsRoll(self, ctx, dice=""):
"""Roll Star Wars dice."""
await self.bot.starWars.roll.parseRoll(ctx, dice)
@cog_ext.cog_slash(**params["starWarsDestiny"])
async def starWarsDestiny(self, ctx, parameters=""):
"""Control Star Wars destiny points."""
await self.bot.starWars.destiny.parseDestiny(ctx, parameters)
@cog_ext.cog_slash(**params["starWarsCrit"])
async def starWarsCrit(self, ctx, severity: int = 0):
"""Roll for critical injuries."""
await self.bot.starWars.roll.critRoll(ctx, severity)
@cog_ext.cog_slash(**params["starWarsCharacter"])
async def starWarsCharacter(self, ctx, parameters=""):
"""Access and change Star Wars character sheet data."""
await self.bot.starWars.character.parseChar(ctx, parameters)
def setup(bot):
"""Add the cog to the bot."""
bot.add_cog(StarWarsCog(bot))

View File

@ -13,26 +13,26 @@ class EventCog(commands.Cog):
@commands.Cog.listener() @commands.Cog.listener()
async def on_ready(self): async def on_ready(self):
"""Log and set bot status when bot logs in.""" """Log and set bot status when bot logs in."""
await self.bot.eventHandler.on_ready() await self.bot.event_handler.on_ready()
@commands.Cog.listener() @commands.Cog.listener()
async def on_slash_command(self, ctx): async def on_slash_command(self, ctx):
"""Log when a slash command is run.""" """Log when a slash command is run."""
await self.bot.eventHandler.on_slash_command(ctx) await self.bot.event_handler.on_slash_command(ctx)
@commands.Cog.listener() @commands.Cog.listener()
async def on_slash_command_error(self, ctx, error): async def on_slash_command_error(self, ctx, error):
"""Log when a slash error occurs.""" """Log when a slash error occurs."""
await self.bot.errorHandler.on_slash_command_error(ctx, error) await self.bot.error_handler.on_slash_command_error(ctx, error)
async def on_error(self, method, *args, **kwargs): async def on_error(self, method):
"""Log when an error occurs.""" """Log when an error occurs."""
await self.bot.errorHandler.on_error(method) await self.bot.error_handler.on_error(method)
@commands.Cog.listener() @commands.Cog.listener()
async def on_reaction_add(self, reaction, user): async def on_reaction_add(self, reaction, user):
"""Handle when someone reacts to a message.""" """Handle when someone reacts to a message."""
await self.bot.eventHandler.on_reaction_add(reaction, user) await self.bot.event_handler.on_reaction_add(reaction, user)
def setup(bot): def setup(bot):

View File

@ -95,20 +95,20 @@ class ConnectFourCog(commands.Cog):
"""Initialize the cog.""" """Initialize the cog."""
self.bot = bot self.bot = bot
@cog_ext.cog_subcommand(**params["connectFourStartUser"]) @cog_ext.cog_subcommand(**params["connect_fourStartUser"])
async def connectFourStartUser(self, ctx, user): async def connect_fourStartUser(self, ctx, user):
"""Start a game of connect four against another user.""" """Start a game of connect four against another user."""
await self.bot.games.connectFour.start(ctx, user) await self.bot.games.connect_four.start(ctx, user)
@cog_ext.cog_subcommand(**params["connectFourStartGwendolyn"]) @cog_ext.cog_subcommand(**params["connect_fourStartGwendolyn"])
async def connectFourStartGwendolyn(self, ctx, difficulty=3): async def connect_fourStartGwendolyn(self, ctx, difficulty=3):
"""Start a game of connect four against Gwendolyn.""" """Start a game of connect four against Gwendolyn."""
await self.bot.games.connectFour.start(ctx, difficulty) await self.bot.games.connect_four.start(ctx, difficulty)
@cog_ext.cog_subcommand(**params["connectFourSurrender"]) @cog_ext.cog_subcommand(**params["connect_fourSurrender"])
async def connectFourSurrender(self, ctx): async def connect_fourSurrender(self, ctx):
"""Surrender the game of connect four.""" """Surrender the game of connect four."""
await self.bot.games.connectFour.surrender(ctx) await self.bot.games.connect_four.surrender(ctx)
class HangmanCog(commands.Cog): class HangmanCog(commands.Cog):

View File

@ -18,13 +18,13 @@ class LookupCog(commands.Cog):
@cog_ext.cog_slash(**params["spell"]) @cog_ext.cog_slash(**params["spell"])
async def spell(self, ctx, query): async def spell(self, ctx, query):
"""Look up a spell.""" """Look up a spell."""
await self.bot.lookupFuncs.spellFunc(ctx, query) await self.bot.lookup_funcs.spellFunc(ctx, query)
# Looks up a monster # Looks up a monster
@cog_ext.cog_slash(**params["monster"]) @cog_ext.cog_slash(**params["monster"])
async def monster(self, ctx, query): async def monster(self, ctx, query):
"""Look up a monster.""" """Look up a monster."""
await self.bot.lookupFuncs.monsterFunc(ctx, query) await self.bot.lookup_funcs.monsterFunc(ctx, query)
def setup(bot): def setup(bot):

40
cogs/star_wars_cog.py Normal file
View File

@ -0,0 +1,40 @@
"""Contains the StarWarsCog, which deals with Star Wars commands."""
from discord.ext import commands
from discord_slash import cog_ext
from utils import getParams # pylint: disable=import-error
params = getParams()
class StarWarsCog(commands.Cog):
"""Contains the Star Wars commands."""
def __init__(self, bot):
"""Initialize the cog."""
self.bot = bot
@cog_ext.cog_slash(**params["star_wars_roll"])
async def star_wars_roll(self, ctx, dice=""):
"""Roll Star Wars dice."""
await self.bot.star_wars.roll.parseRoll(ctx, dice)
@cog_ext.cog_slash(**params["star_wars_destiny"])
async def star_wars_destiny(self, ctx, parameters=""):
"""Control Star Wars destiny points."""
await self.bot.star_wars.destiny.parseDestiny(ctx, parameters)
@cog_ext.cog_slash(**params["star_wars_crit"])
async def star_wars_crit(self, ctx, severity: int = 0):
"""Roll for critical injuries."""
await self.bot.star_wars.roll.critRoll(ctx, severity)
@cog_ext.cog_slash(**params["star_wars_character"])
async def star_wars_character(self, ctx, parameters=""):
"""Access and change Star Wars character sheet data."""
await self.bot.star_wars.character.parseChar(ctx, parameters)
def setup(bot):
"""Add the cog to the bot."""
bot.add_cog(StarWarsCog(bot))

View File

@ -8,4 +8,4 @@ from .lookup import LookupFuncs
from .other import Other from .other import Other
from .starWarsFuncs import StarWars from .star_wars_funcs import StarWars

View File

@ -3,4 +3,4 @@
__all__ = ["Money", "Games"] __all__ = ["Money", "Games"]
from .money import Money from .money import Money
from .gamesContainer import Games from .games_container import Games

View File

@ -211,7 +211,7 @@ class Blackjack():
allStanding = True allStanding = True
preAllStanding = True preAllStanding = True
message = self.bot.longStrings["Blackjack all players standing"] message = self.bot.long_strings["Blackjack all players standing"]
if game["all standing"]: if game["all standing"]:
self.bot.log("All are standing") self.bot.log("All are standing")
@ -245,11 +245,11 @@ class Blackjack():
return "", True, done return "", True, done
else: else:
if game["round"] == 0: if game["round"] == 0:
firstRoundMsg = self.bot.longStrings["Blackjack first round"] firstRoundMsg = self.bot.long_strings["Blackjack first round"]
else: else:
firstRoundMsg = "" firstRoundMsg = ""
sendMessage = self.bot.longStrings["Blackjack commands"] sendMessage = self.bot.long_strings["Blackjack commands"]
print(firstRoundMsg) print(firstRoundMsg)
sendMessage = sendMessage.format(firstRoundMsg) sendMessage = sendMessage.format(firstRoundMsg)
return sendMessage, False, done return sendMessage, False, done
@ -352,7 +352,7 @@ class Blackjack():
winningCalc = (self._calcWinnings(*_calcWinningsParams)) winningCalc = (self._calcWinnings(*_calcWinningsParams))
winnings, netWinnings, reason = winningCalc winnings, netWinnings, reason = winningCalc
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
if winnings < 0: if winnings < 0:
if winnings == -1: if winnings == -1:
@ -569,7 +569,7 @@ class Blackjack():
""" """
self.bot.log("Loop "+str(gameRound), str(channel.id)) self.bot.log("Loop "+str(gameRound), str(channel.id))
oldImagePath = f"resources/games/oldImages/blackjack{channel.id}" oldImagePath = f"resources/games/old_images/blackjack{channel.id}"
with open(oldImagePath, "r") as f: with open(oldImagePath, "r") as f:
oldImage = await channel.fetch_message(int(f.read())) oldImage = await channel.fetch_message(int(f.read()))
@ -604,15 +604,15 @@ class Blackjack():
if rightRound: if rightRound:
if not gamedone: if not gamedone:
logMessage = f"Loop {gameRound} calling self._blackjackLoop()" log_message = f"Loop {gameRound} calling self._blackjackLoop()"
self.bot.log(logMessage, str(channel.id)) self.bot.log(log_message, str(channel.id))
await self._blackjackLoop(channel, gameRound+1, gameID) await self._blackjackLoop(channel, gameRound+1, gameID)
else: else:
new_message = self._blackjackFinish(str(channel.id)) new_message = self._blackjackFinish(str(channel.id))
await channel.send(new_message) await channel.send(new_message)
else: else:
logMessage = f"Ending loop on round {gameRound}" log_message = f"Ending loop on round {gameRound}"
self.bot.log(logMessage, str(channel.id)) self.bot.log(log_message, str(channel.id))
async def hit(self, ctx: discord_slash.context.SlashContext, async def hit(self, ctx: discord_slash.context.SlashContext,
handNumber: int = 0): handNumber: int = 0):
@ -640,16 +640,16 @@ class Blackjack():
hand, handNumber = self._getHandNumber(userHands, handNumber) hand, handNumber = self._getHandNumber(userHands, handNumber)
if hand is None: if hand is None:
logMessage = "They didn't specify a hand" log_message = "They didn't specify a hand"
sendMessage = "You need to specify a hand" sendMessage = "You need to specify a hand"
elif game["round"] <= 0: elif game["round"] <= 0:
logMessage = "They tried to hit on the 0th round" log_message = "They tried to hit on the 0th round"
sendMessage = "You can't hit before you see your cards" sendMessage = "You can't hit before you see your cards"
elif hand["hit"]: elif hand["hit"]:
logMessage = "They've already hit this round" log_message = "They've already hit this round"
sendMessage = "You've already hit this round" sendMessage = "You've already hit this round"
elif hand["standing"]: elif hand["standing"]:
logMessage = "They're already standing" log_message = "They're already standing"
sendMessage = "You can't hit when you're standing" sendMessage = "You can't hit when you're standing"
else: else:
hand["hand"].append(self._drawCard(channel)) hand["hand"].append(self._drawCard(channel))
@ -675,13 +675,13 @@ class Blackjack():
roundDone = self._isRoundDone(game) roundDone = self._isRoundDone(game)
sendMessage = f"{ctx.author.display_name} hit" sendMessage = f"{ctx.author.display_name} hit"
logMessage = "They succeeded" log_message = "They succeeded"
else: else:
logMessage = "They tried to hit without being in the game" log_message = "They tried to hit without being in the game"
sendMessage = "You have to enter the game before you can hit" sendMessage = "You have to enter the game before you can hit"
await ctx.send(sendMessage) await ctx.send(sendMessage)
self.bot.log(logMessage) self.bot.log(log_message)
if roundDone: if roundDone:
gameID = game["gameID"] gameID = game["gameID"]
@ -713,22 +713,22 @@ class Blackjack():
hand, handNumber = self._getHandNumber(*handParams) hand, handNumber = self._getHandNumber(*handParams)
if hand is None: if hand is None:
logMessage = "They didn't specify a hand" log_message = "They didn't specify a hand"
sendMessage = "You need to specify a hand" sendMessage = "You need to specify a hand"
elif game["round"] <= 0: elif game["round"] <= 0:
logMessage = "They tried to hit on the 0th round" log_message = "They tried to hit on the 0th round"
sendMessage = "You can't hit before you see your cards" sendMessage = "You can't hit before you see your cards"
elif hand["hit"]: elif hand["hit"]:
logMessage = "They've already hit this round" log_message = "They've already hit this round"
sendMessage = "You've already hit this round" sendMessage = "You've already hit this round"
elif hand["standing"]: elif hand["standing"]:
logMessage = "They're already standing" log_message = "They're already standing"
sendMessage = "You can't hit when you're standing" sendMessage = "You can't hit when you're standing"
elif len(hand["hand"]) != 2: elif len(hand["hand"]) != 2:
logMessage = "They tried to double after round 1" log_message = "They tried to double after round 1"
sendMessage = "You can only double on the first round" sendMessage = "You can only double on the first round"
elif self.bot.money.checkBalance(user) < hand["bet"]: elif self.bot.money.checkBalance(user) < hand["bet"]:
logMessage = "They tried to double without being in the game" log_message = "They tried to double without being in the game"
sendMessage = "You can't double when you're not in the game" sendMessage = "You can't double when you're not in the game"
else: else:
bet = hand["bet"] bet = hand["bet"]
@ -759,16 +759,16 @@ class Blackjack():
game = blackjackGames.find_one({"_id": channel}) game = blackjackGames.find_one({"_id": channel})
roundDone = self._isRoundDone(game) roundDone = self._isRoundDone(game)
sendMessage = self.bot.longStrings["Blackjack double"] sendMessage = self.bot.long_strings["Blackjack double"]
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
sendMessage = sendMessage.format(bet, userName) sendMessage = sendMessage.format(bet, userName)
logMessage = "They succeeded" log_message = "They succeeded"
else: else:
logMessage = "They tried to double without being in the game" log_message = "They tried to double without being in the game"
sendMessage = "You can't double when you're not in the game" sendMessage = "You can't double when you're not in the game"
await ctx.send(sendMessage) await ctx.send(sendMessage)
self.bot.log(logMessage) self.bot.log(log_message)
if roundDone: if roundDone:
gameID = game["gameID"] gameID = game["gameID"]
@ -801,16 +801,16 @@ class Blackjack():
if hand is None: if hand is None:
sendMessage = "You need to specify which hand" sendMessage = "You need to specify which hand"
logMessage = "They didn't specify a hand" log_message = "They didn't specify a hand"
elif game["round"] <= 0: elif game["round"] <= 0:
sendMessage = "You can't stand before you see your cards" sendMessage = "You can't stand before you see your cards"
logMessage = "They tried to stand on round 0" log_message = "They tried to stand on round 0"
elif hand["hit"]: elif hand["hit"]:
sendMessage = "You've already hit this round" sendMessage = "You've already hit this round"
logMessage = "They'd already hit this round" log_message = "They'd already hit this round"
elif hand["standing"]: elif hand["standing"]:
sendMessage = "You're already standing" sendMessage = "You're already standing"
logMessage = "They're already standing" log_message = "They're already standing"
else: else:
hand["standing"] = True hand["standing"] = True
@ -829,14 +829,14 @@ class Blackjack():
roundDone = self._isRoundDone(game) roundDone = self._isRoundDone(game)
sendMessage = f"{ctx.author.display_name} is standing" sendMessage = f"{ctx.author.display_name} is standing"
logMessage = "They succeeded" log_message = "They succeeded"
else: else:
logMessage = "They tried to stand without being in the game" log_message = "They tried to stand without being in the game"
sendMessage = "You have to enter the game before you can stand" sendMessage = "You have to enter the game before you can stand"
await ctx.send(sendMessage) await ctx.send(sendMessage)
self.bot.log(logMessage) self.bot.log(log_message)
if roundDone: if roundDone:
gameID = game["gameID"] gameID = game["gameID"]
@ -887,33 +887,33 @@ class Blackjack():
otherHand = 4 otherHand = 4
if handNumberError: if handNumberError:
logMessage = "They didn't specify a hand" log_message = "They didn't specify a hand"
sendMessage = "You have to specify the hand you're hitting with" sendMessage = "You have to specify the hand you're hitting with"
elif game["round"] == 0: elif game["round"] == 0:
logMessage = "They tried to split on round 0" log_message = "They tried to split on round 0"
sendMessage = "You can't split before you see your cards" sendMessage = "You can't split before you see your cards"
elif game["user hands"][user]["split"] > 3: elif game["user hands"][user]["split"] > 3:
logMessage = "They tried to split more than three times" log_message = "They tried to split more than three times"
sendMessage = "You can only split 3 times" sendMessage = "You can only split 3 times"
elif hand["hit"]: elif hand["hit"]:
logMessage = "They've already hit" log_message = "They've already hit"
sendMessage = "You've already hit or split this hand." sendMessage = "You've already hit or split this hand."
elif hand["standing"]: elif hand["standing"]:
logMessage = "They're already standing" log_message = "They're already standing"
sendMessage = "You're already standing" sendMessage = "You're already standing"
elif len(hand["hand"]) != 2: elif len(hand["hand"]) != 2:
logMessage = "They tried to split after the first round" log_message = "They tried to split after the first round"
sendMessage = "You can only split on the first round" sendMessage = "You can only split on the first round"
else: else:
firstCard = self._calcHandValue([hand["hand"][0]]) firstCard = self._calcHandValue([hand["hand"][0]])
secondCard = self._calcHandValue([hand["hand"][1]]) secondCard = self._calcHandValue([hand["hand"][1]])
if firstCard != secondCard: if firstCard != secondCard:
logMessage = "They tried to split two different cards" log_message = "They tried to split two different cards"
sendMessage = self.bot.longStrings["Blackjack different cards"] sendMessage = self.bot.long_strings["Blackjack different cards"]
else: else:
bet = hand["bet"] bet = hand["bet"]
if self.bot.money.checkBalance(user) < bet: if self.bot.money.checkBalance(user) < bet:
logMessage = "They didn't have enough GwendoBucks" log_message = "They didn't have enough GwendoBucks"
sendMessage = "You don't have enough GwendoBucks" sendMessage = "You don't have enough GwendoBucks"
else: else:
self.bot.money.addMoney(user, -1 * bet) self.bot.money.addMoney(user, -1 * bet)
@ -972,13 +972,13 @@ class Blackjack():
game = blackjackGames.find_one({"_id": channel}) game = blackjackGames.find_one({"_id": channel})
roundDone = self._isRoundDone(game) roundDone = self._isRoundDone(game)
sendMessage = self.bot.longStrings["Blackjack split"] sendMessage = self.bot.long_strings["Blackjack split"]
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
sendMessage = sendMessage.format(userName) sendMessage = sendMessage.format(userName)
logMessage = "They succeeded" log_message = "They succeeded"
await ctx.send(sendMessage) await ctx.send(sendMessage)
self.bot.log(logMessage) self.bot.log(log_message)
if roundDone: if roundDone:
gameID = game["gameID"] gameID = game["gameID"]
@ -1002,28 +1002,28 @@ class Blackjack():
user = f"#{ctx.author.id}" user = f"#{ctx.author.id}"
collection = self.bot.database["blackjack games"] collection = self.bot.database["blackjack games"]
game = collection.find_one({"_id": channel}) game = collection.find_one({"_id": channel})
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
self.bot.log(f"{userName} is trying to join the Blackjack game") self.bot.log(f"{userName} is trying to join the Blackjack game")
if game is None: if game is None:
sendMessage = "There is no game going on in this channel" sendMessage = "There is no game going on in this channel"
logMessage = sendMessage log_message = sendMessage
elif user in game["user hands"]: elif user in game["user hands"]:
sendMessage = "You're already in the game!" sendMessage = "You're already in the game!"
logMessage = "They're already in the game" log_message = "They're already in the game"
elif len(game["user hands"]) >= 5: elif len(game["user hands"]) >= 5:
sendMessage = "There can't be more than 5 players in a game" sendMessage = "There can't be more than 5 players in a game"
logMessage = "There were already 5 players in the game" log_message = "There were already 5 players in the game"
elif game["round"] != 0: elif game["round"] != 0:
sendMessage = "The table is no longer taking bets" sendMessage = "The table is no longer taking bets"
logMessage = "They tried to join after the game begun" log_message = "They tried to join after the game begun"
elif bet < 0: elif bet < 0:
sendMessage = "You can't bet a negative amount" sendMessage = "You can't bet a negative amount"
logMessage = "They tried to bet a negative amount" log_message = "They tried to bet a negative amount"
elif self.bot.money.checkBalance(user) < bet: elif self.bot.money.checkBalance(user) < bet:
sendMessage = "You don't have enough GwendoBucks" sendMessage = "You don't have enough GwendoBucks"
logMessage = "They didn't have enough GwendoBucks" log_message = "They didn't have enough GwendoBucks"
else: else:
self.bot.money.addMoney(user, -1 * bet) self.bot.money.addMoney(user, -1 * bet)
playerHand = [self._drawCard(channel) for _ in range(2)] playerHand = [self._drawCard(channel) for _ in range(2)]
@ -1048,9 +1048,9 @@ class Blackjack():
enterGameText = "entered the game with a bet of" enterGameText = "entered the game with a bet of"
betText = f"{bet} GwendoBucks" betText = f"{bet} GwendoBucks"
sendMessage = f"{userName} {enterGameText} {betText}" sendMessage = f"{userName} {enterGameText} {betText}"
logMessage = sendMessage log_message = sendMessage
self.bot.log(logMessage) self.bot.log(log_message)
await ctx.send(sendMessage) await ctx.send(sendMessage)
async def start(self, ctx: discord_slash.context.SlashContext): async def start(self, ctx: discord_slash.context.SlashContext):
@ -1109,7 +1109,7 @@ class Blackjack():
gameStarted = True gameStarted = True
if gameStarted: if gameStarted:
sendMessage = self.bot.longStrings["Blackjack started"] sendMessage = self.bot.long_strings["Blackjack started"]
await ctx.channel.send(sendMessage) await ctx.channel.send(sendMessage)
tableImagesPath = "resources/games/blackjackTables/" tableImagesPath = "resources/games/blackjackTables/"
@ -1117,7 +1117,7 @@ class Blackjack():
oldImage = await ctx.channel.send(file=discord.File(filePath)) oldImage = await ctx.channel.send(file=discord.File(filePath))
with open("resources/games/oldImages/blackjack"+channel, "w") as f: with open("resources/games/old_images/blackjack"+channel, "w") as f:
f.write(str(oldImage.id)) f.write(str(oldImage.id))
await asyncio.sleep(30) await asyncio.sleep(30)
@ -1142,7 +1142,7 @@ class Blackjack():
new_message = self._blackjackFinish(channel) new_message = self._blackjackFinish(channel)
await ctx.channel.send(new_message) await ctx.channel.send(new_message)
else: else:
sendMessage = self.bot.longStrings["Blackjack going on"] sendMessage = self.bot.long_strings["Blackjack going on"]
await ctx.channel.send(sendMessage) await ctx.channel.send(sendMessage)
self.bot.log("There was already a game going on") self.bot.log("There was already a game going on")
@ -1267,7 +1267,7 @@ class DrawBlackjack():
for x in range(len(hands)): for x in range(len(hands)):
key, value = list(hands.items())[x] key, value = list(hands.items())[x]
key = self.bot.databaseFuncs.getName(key) key = self.bot.database_funcs.getName(key)
handParams = [ handParams = [
value["hand"], value["hand"],
False, False,

View File

@ -73,8 +73,8 @@ class ConnectFour():
canStart = True canStart = True
if game is not None: if game is not None:
sendMessage = self.bot.longStrings["Connect 4 going on"] sendMessage = self.bot.long_strings["Connect 4 going on"]
logMessage = "There was already a game going on" log_message = "There was already a game going on"
canStart = False canStart = False
elif type(opponent) == int: elif type(opponent) == int:
# Opponent is Gwendolyn # Opponent is Gwendolyn
@ -84,7 +84,7 @@ class ConnectFour():
opponent = f"#{self.bot.user.id}" opponent = f"#{self.bot.user.id}"
else: else:
sendMessage = "Difficulty doesn't exist" sendMessage = "Difficulty doesn't exist"
logMessage = "They challenged a difficulty that doesn't exist" log_message = "They challenged a difficulty that doesn't exist"
canStart = False canStart = False
elif type(opponent) == discord.User: elif type(opponent) == discord.User:
if opponent.bot: if opponent.bot:
@ -96,7 +96,7 @@ class ConnectFour():
opponent = f"#{self.bot.user.id}" opponent = f"#{self.bot.user.id}"
else: else:
sendMessage = "You can't challenge a bot!" sendMessage = "You can't challenge a bot!"
logMessage = "They tried to challenge a bot" log_message = "They tried to challenge a bot"
canStart = False canStart = False
else: else:
# Opponent is another player # Opponent is another player
@ -106,7 +106,7 @@ class ConnectFour():
diffText = "" diffText = ""
else: else:
sendMessage = "You can't play against yourself" sendMessage = "You can't play against yourself"
logMessage = "They tried to play against themself" log_message = "They tried to play against themself"
canStart = False canStart = False
if canStart: if canStart:
@ -133,15 +133,15 @@ class ConnectFour():
gwendoTurn = (players[0] == f"#{self.bot.user.id}") gwendoTurn = (players[0] == f"#{self.bot.user.id}")
startedGame = True startedGame = True
opponentName = self.bot.databaseFuncs.getName(opponent) opponentName = self.bot.database_funcs.getName(opponent)
turnName = self.bot.databaseFuncs.getName(players[0]) turnName = self.bot.database_funcs.getName(players[0])
startedText = f"Started game against {opponentName}{diffText}." startedText = f"Started game against {opponentName}{diffText}."
turnText = f"It's {turnName}'s turn" turnText = f"It's {turnName}'s turn"
sendMessage = f"{startedText} {turnText}" sendMessage = f"{startedText} {turnText}"
logMessage = "They started a game" log_message = "They started a game"
self.bot.log(logMessage) self.bot.log(log_message)
await ctx.send(sendMessage) await ctx.send(sendMessage)
# Sets the whole game in motion # Sets the whole game in motion
@ -150,13 +150,13 @@ class ConnectFour():
filePath = f"{boardsPath}board{ctx.channel_id}.png" filePath = f"{boardsPath}board{ctx.channel_id}.png"
oldImage = await ctx.channel.send(file=discord.File(filePath)) oldImage = await ctx.channel.send(file=discord.File(filePath))
oldImagesPath = "resources/games/oldImages/" old_imagesPath = "resources/games/old_images/"
oldImagePath = f"{oldImagesPath}connectFour{ctx.channel_id}" oldImagePath = f"{old_imagesPath}connect_four{ctx.channel_id}"
with open(oldImagePath, "w") as f: with open(oldImagePath, "w") as f:
f.write(str(oldImage.id)) f.write(str(oldImage.id))
if gwendoTurn: if gwendoTurn:
await self._connectFourAI(ctx) await self._connect_fourAI(ctx)
else: else:
for reaction in self.REACTIONS: for reaction in self.REACTIONS:
await oldImage.add_reaction(reaction) await oldImage.add_reaction(reaction)
@ -183,19 +183,19 @@ class ConnectFour():
connect4Games = self.bot.database["connect 4 games"] connect4Games = self.bot.database["connect 4 games"]
game = connect4Games.find_one({"_id": channel}) game = connect4Games.find_one({"_id": channel})
playerNumber = game["players"].index(user)+1 playerNumber = game["players"].index(user)+1
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
placedPiece = False placedPiece = False
if game is None: if game is None:
sendMessage = "There's no game in this channel" sendMessage = "There's no game in this channel"
logMessage = "There was no game in the channel" log_message = "There was no game in the channel"
else: else:
board = game["board"] board = game["board"]
board = self._placeOnBoard(board, playerNumber, column) board = self._placeOnBoard(board, playerNumber, column)
if board is None: if board is None:
sendMessage = "There isn't any room in that column" sendMessage = "There isn't any room in that column"
logMessage = "There wasn't any room in the column" log_message = "There wasn't any room in the column"
else: else:
updater = {"$set": {"board": board}} updater = {"$set": {"board": board}}
connect4Games.update_one({"_id": channel}, updater) connect4Games.update_one({"_id": channel}, updater)
@ -217,7 +217,7 @@ class ConnectFour():
sendMessage = "{} placed a piece in column {} and won. " sendMessage = "{} placed a piece in column {} and won. "
sendMessage = sendMessage.format(userName, column+1) sendMessage = sendMessage.format(userName, column+1)
logMessage = f"{userName} won" log_message = f"{userName} won"
winAmount = int(game["difficulty"])**2+5 winAmount = int(game["difficulty"])**2+5
if game["players"][won-1] != f"#{self.bot.user.id}": if game["players"][won-1] != f"#{self.bot.user.id}":
sendMessage += "Adding {} GwendoBucks to their account" sendMessage += "Adding {} GwendoBucks to their account"
@ -225,27 +225,27 @@ class ConnectFour():
elif 0 not in board[0]: elif 0 not in board[0]:
gameWon = True gameWon = True
sendMessage = "It's a draw!" sendMessage = "It's a draw!"
logMessage = "The game ended in a draw" log_message = "The game ended in a draw"
else: else:
gameWon = False gameWon = False
otherUserId = game["players"][turn] otherUserId = game["players"][turn]
otherUserName = self.bot.databaseFuncs.getName(otherUserId) otherUserName = self.bot.database_funcs.getName(otherUserId)
sendMessage = self.bot.longStrings["Connect 4 placed"] sendMessage = self.bot.long_strings["Connect 4 placed"]
formatParams = [userName, column+1, otherUserName] formatParams = [userName, column+1, otherUserName]
sendMessage = sendMessage.format(*formatParams) sendMessage = sendMessage.format(*formatParams)
logMessage = "They placed the piece" log_message = "They placed the piece"
gwendoTurn = (game["players"][turn] == f"#{self.bot.user.id}") gwendoTurn = (game["players"][turn] == f"#{self.bot.user.id}")
placedPiece = True placedPiece = True
await ctx.channel.send(sendMessage) await ctx.channel.send(sendMessage)
self.bot.log(logMessage) self.bot.log(log_message)
if placedPiece: if placedPiece:
self.draw.drawImage(channel) self.draw.drawImage(channel)
oldImagePath = f"resources/games/oldImages/connectFour{channel}" oldImagePath = f"resources/games/old_images/connect_four{channel}"
with open(oldImagePath, "r") as f: with open(oldImagePath, "r") as f:
oldImage = await ctx.channel.fetch_message(int(f.read())) oldImage = await ctx.channel.fetch_message(int(f.read()))
@ -263,7 +263,7 @@ class ConnectFour():
with open(oldImagePath, "w") as f: with open(oldImagePath, "w") as f:
f.write(str(oldImage.id)) f.write(str(oldImage.id))
if gwendoTurn: if gwendoTurn:
await self._connectFourAI(ctx) await self._connect_fourAI(ctx)
else: else:
for reaction in self.REACTIONS: for reaction in self.REACTIONS:
await oldImage.add_reaction(reaction) await oldImage.add_reaction(reaction)
@ -285,7 +285,7 @@ class ConnectFour():
loserIndex = game["players"].index(f"#{ctx.author.id}") loserIndex = game["players"].index(f"#{ctx.author.id}")
winnerIndex = (loserIndex+1) % 2 winnerIndex = (loserIndex+1) % 2
winnerID = game["players"][winnerIndex] winnerID = game["players"][winnerIndex]
winnerName = self.bot.databaseFuncs.getName(winnerID) winnerName = self.bot.database_funcs.getName(winnerID)
sendMessage = f"{ctx.author.display_name} surrenders." sendMessage = f"{ctx.author.display_name} surrenders."
sendMessage += f" This means {winnerName} is the winner." sendMessage += f" This means {winnerName} is the winner."
@ -295,7 +295,7 @@ class ConnectFour():
sendMessage += f" Adding {reward} to their account" sendMessage += f" Adding {reward} to their account"
await ctx.send(sendMessage) await ctx.send(sendMessage)
oldImagePath = f"resources/games/oldImages/connectFour{channel}" oldImagePath = f"resources/games/old_images/connect_four{channel}"
with open(oldImagePath, "r") as f: with open(oldImagePath, "r") as f:
oldImage = await ctx.channel.fetch_message(int(f.read())) oldImage = await ctx.channel.fetch_message(int(f.read()))
@ -353,7 +353,7 @@ class ConnectFour():
reward = difficulty**2 + 5 reward = difficulty**2 + 5
self.bot.money.addMoney(game["players"][winner-1], reward) self.bot.money.addMoney(game["players"][winner-1], reward)
self.bot.databaseFuncs.deleteGame("connect 4 games", channel) self.bot.database_funcs.deleteGame("connect 4 games", channel)
def _isWon(self, board: dict): def _isWon(self, board: dict):
won = 0 won = 0
@ -429,7 +429,7 @@ class ConnectFour():
return won, winDirection, winCoordinates return won, winDirection, winCoordinates
async def _connectFourAI(self, ctx: SlashContext): async def _connect_fourAI(self, ctx: SlashContext):
def outOfRange(possibleScores: list): def outOfRange(possibleScores: list):
allowedRange = max(possibleScores)*(1-0.1) allowedRange = max(possibleScores)*(1-0.1)
moreThanOne = len(possibleScores) != 1 moreThanOne = len(possibleScores) != 1
@ -1023,12 +1023,12 @@ class DrawConnectFour():
if game["players"][0] == "Gwendolyn": if game["players"][0] == "Gwendolyn":
player1 = "Gwendolyn" player1 = "Gwendolyn"
else: else:
player1 = self.bot.databaseFuncs.getName(game["players"][0]) player1 = self.bot.database_funcs.getName(game["players"][0])
if game["players"][1] == "Gwendolyn": if game["players"][1] == "Gwendolyn":
player2 = "Gwendolyn" player2 = "Gwendolyn"
else: else:
player2 = self.bot.databaseFuncs.getName(game["players"][1]) player2 = self.bot.database_funcs.getName(game["players"][1])
exampleHeight = self.HEIGHT - self.BORDER exampleHeight = self.HEIGHT - self.BORDER
exampleHeight += (self.BOTTOMBORDER+self.BORDER)//2 - self.TEXTSIZE//2 exampleHeight += (self.BOTTOMBORDER+self.BORDER)//2 - self.TEXTSIZE//2

View File

@ -11,7 +11,7 @@ Has a container for game functions.
from .invest import Invest from .invest import Invest
from .trivia import Trivia from .trivia import Trivia
from .blackjack import Blackjack from .blackjack import Blackjack
from .connectFour import ConnectFour from .connect_four import ConnectFour
from .hangman import Hangman from .hangman import Hangman
from .hex import HexGame from .hex import HexGame
@ -28,7 +28,7 @@ class Games():
Contains investment functions. Contains investment functions.
blackjack blackjack
Contains blackjack functions. Contains blackjack functions.
connectFour connect_four
Contains connect four functions. Contains connect four functions.
hangman hangman
Contains hangman functions. Contains hangman functions.
@ -43,6 +43,6 @@ class Games():
self.invest = Invest(bot) self.invest = Invest(bot)
self.trivia = Trivia(bot) self.trivia = Trivia(bot)
self.blackjack = Blackjack(bot) self.blackjack = Blackjack(bot)
self.connectFour = ConnectFour(bot) self.connect_four = ConnectFour(bot)
self.hangman = Hangman(bot) self.hangman = Hangman(bot)
self.hex = HexGame(bot) self.hex = HexGame(bot)

View File

@ -72,7 +72,7 @@ class Hangman():
channel = str(ctx.channel_id) channel = str(ctx.channel_id)
user = f"#{ctx.author.id}" user = f"#{ctx.author.id}"
game = self.__bot.database["hangman games"].find_one({"_id": channel}) game = self.__bot.database["hangman games"].find_one({"_id": channel})
userName = self.__bot.databaseFuncs.getName(user) userName = self.__bot.database_funcs.getName(user)
startedGame = False startedGame = False
if game is None: if game is None:
@ -99,14 +99,14 @@ class Hangman():
self.__draw.drawImage(channel) self.__draw.drawImage(channel)
logMessage = "Game started" log_message = "Game started"
sendMessage = f"{userName} started game of hangman." sendMessage = f"{userName} started game of hangman."
startedGame = True startedGame = True
else: else:
logMessage = "There was already a game going on" log_message = "There was already a game going on"
sendMessage = self.__bot.longStrings["Hangman going on"] sendMessage = self.__bot.long_strings["Hangman going on"]
self.__bot.log(logMessage) self.__bot.log(log_message)
await ctx.send(sendMessage) await ctx.send(sendMessage)
if startedGame: if startedGame:
@ -122,7 +122,7 @@ class Hangman():
oldMessages = f"{newImage.id}\n{blankMessage.id}" oldMessages = f"{newImage.id}\n{blankMessage.id}"
with open(f"resources/games/oldImages/hangman{channel}", "w") as f: with open(f"resources/games/old_images/hangman{channel}", "w") as f:
f.write(oldMessages) f.write(oldMessages)
for message, letters in reactionMessages.items(): for message, letters in reactionMessages.items():
@ -149,7 +149,7 @@ class Hangman():
else: else:
self.__bot.database["hangman games"].delete_one({"_id": channel}) self.__bot.database["hangman games"].delete_one({"_id": channel})
with open(f"resources/games/oldImages/hangman{channel}", "r") as f: with open(f"resources/games/old_images/hangman{channel}", "r") as f:
messages = f.read().splitlines() messages = f.read().splitlines()
for message in messages: for message in messages:
@ -216,17 +216,17 @@ class Hangman():
if game["misses"] == 6: if game["misses"] == 6:
hangmanGames.delete_one({"_id": channel}) hangmanGames.delete_one({"_id": channel})
sendMessage += self.__bot.longStrings["Hangman lost game"] sendMessage += self.__bot.long_strings["Hangman lost game"]
remainingLetters = [] remainingLetters = []
elif all(game["guessed"]): elif all(game["guessed"]):
hangmanGames.delete_one({"_id": channel}) hangmanGames.delete_one({"_id": channel})
self.__bot.money.addMoney(user, 15) self.__bot.money.addMoney(user, 15)
sendMessage += self.__bot.longStrings["Hangman guessed word"] sendMessage += self.__bot.long_strings["Hangman guessed word"]
remainingLetters = [] remainingLetters = []
await message.channel.send(sendMessage) await message.channel.send(sendMessage)
with open(f"resources/games/oldImages/hangman{channel}", "r") as f: with open(f"resources/games/old_images/hangman{channel}", "r") as f:
oldMessageIDs = f.read().splitlines() oldMessageIDs = f.read().splitlines()
for oldID in oldMessageIDs: for oldID in oldMessageIDs:
@ -254,7 +254,7 @@ class Hangman():
else: else:
oldMessages = str(newImage.id) oldMessages = str(newImage.id)
oldImagePath = f"resources/games/oldImages/hangman{channel}" oldImagePath = f"resources/games/old_images/hangman{channel}"
with open(oldImagePath, "w") as f: with open(oldImagePath, "w") as f:
f.write(oldMessages) f.write(oldMessages)

View File

@ -28,11 +28,11 @@ class HexGame():
await ctx.send("You can't surrender when you're not a player.") await ctx.send("You can't surrender when you're not a player.")
else: else:
opponent = (players.index(user) + 1) % 2 opponent = (players.index(user) + 1) % 2
opponentName = self.bot.databaseFuncs.getName(players[opponent]) opponentName = self.bot.database_funcs.getName(players[opponent])
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":opponent + 1}}) self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":opponent + 1}})
await ctx.send(f"{ctx.author.display_name} surrendered") await ctx.send(f"{ctx.author.display_name} surrendered")
with open(f"resources/games/oldImages/hex{channel}", "r") as f: with open(f"resources/games/old_images/hex{channel}", "r") as f:
oldImage = await ctx.channel.fetch_message(int(f.read())) oldImage = await ctx.channel.fetch_message(int(f.read()))
if oldImage is not None: if oldImage is not None:
@ -44,7 +44,7 @@ class HexGame():
filePath = f"resources/games/hexBoards/board{channel}.png" filePath = f"resources/games/hexBoards/board{channel}.png"
oldImage = await ctx.channel.send(file = discord.File(filePath)) oldImage = await ctx.channel.send(file = discord.File(filePath))
with open(f"resources/games/oldImages/hex{channel}", "w") as f: with open(f"resources/games/old_images/hex{channel}", "w") as f:
f.write(str(oldImage.id)) f.write(str(oldImage.id))
self.bot.database["hex games"].delete_one({"_id":channel}) self.bot.database["hex games"].delete_one({"_id":channel})
@ -72,10 +72,10 @@ class HexGame():
opponent = game["players"][::-1][game["turn"]-1] opponent = game["players"][::-1][game["turn"]-1]
gwendoTurn = (opponent == f"#{self.bot.user.id}") gwendoTurn = (opponent == f"#{self.bot.user.id}")
opponentName = self.bot.databaseFuncs.getName(opponent) opponentName = self.bot.database_funcs.getName(opponent)
await ctx.send(f"The color of the players were swapped. It is now {opponentName}'s turn") await ctx.send(f"The color of the players were swapped. It is now {opponentName}'s turn")
with open(f"resources/games/oldImages/hex{channel}", "r") as f: with open(f"resources/games/old_images/hex{channel}", "r") as f:
oldImage = await ctx.channel.fetch_message(int(f.read())) oldImage = await ctx.channel.fetch_message(int(f.read()))
if oldImage is not None: if oldImage is not None:
@ -87,7 +87,7 @@ class HexGame():
filePath = f"resources/games/hexBoards/board{channel}.png" filePath = f"resources/games/hexBoards/board{channel}.png"
oldImage = await ctx.channel.send(file = discord.File(filePath)) oldImage = await ctx.channel.send(file = discord.File(filePath))
with open(f"resources/games/oldImages/hex{channel}", "w") as f: with open(f"resources/games/old_images/hex{channel}", "w") as f:
f.write(str(oldImage.id)) f.write(str(oldImage.id))
if gwendoTurn: if gwendoTurn:
@ -105,7 +105,7 @@ class HexGame():
if game != None: if game != None:
sendMessage = "There's already a hex game going on in this channel" sendMessage = "There's already a hex game going on in this channel"
logMessage = "There was already a game going on" log_message = "There was already a game going on"
canStart = False canStart = False
else: else:
if type(opponent) == int: if type(opponent) == int:
@ -117,7 +117,7 @@ class HexGame():
opponent = f"#{self.bot.user.id}" opponent = f"#{self.bot.user.id}"
else: else:
sendMessage = "Difficulty doesn't exist" sendMessage = "Difficulty doesn't exist"
logMessage = "They tried to play against a difficulty that doesn't exist" log_message = "They tried to play against a difficulty that doesn't exist"
canStart = False canStart = False
elif type(opponent) == discord.member.Member: elif type(opponent) == discord.member.Member:
@ -131,7 +131,7 @@ class HexGame():
opponent = f"#{self.bot.user.id}" opponent = f"#{self.bot.user.id}"
else: else:
sendMessage = "You can't challenge a bot!" sendMessage = "You can't challenge a bot!"
logMessage = "They tried to challenge a bot" log_message = "They tried to challenge a bot"
canStart = False canStart = False
else: else:
# Opponent is another player # Opponent is another player
@ -142,11 +142,11 @@ class HexGame():
diffText = "" diffText = ""
else: else:
sendMessage = "You can't play against yourself" sendMessage = "You can't play against yourself"
logMessage = "They tried to play against themself" log_message = "They tried to play against themself"
canStart = False canStart = False
else: else:
canStart = False canStart = False
logMessage = f"Opponent was neither int or member. It was {type(opponent)}" log_message = f"Opponent was neither int or member. It was {type(opponent)}"
sendMessage = "Something went wrong" sendMessage = "Something went wrong"
if canStart: if canStart:
@ -167,18 +167,18 @@ class HexGame():
gwendoTurn = (players[0] == f"#{self.bot.user.id}") gwendoTurn = (players[0] == f"#{self.bot.user.id}")
startedGame = True startedGame = True
turnName = self.bot.databaseFuncs.getName(players[0]) turnName = self.bot.database_funcs.getName(players[0])
sendMessage = f"Started Hex game against {opponentName}{diffText}. It's {turnName}'s turn" sendMessage = f"Started Hex game against {opponentName}{diffText}. It's {turnName}'s turn"
logMessage = "Game started" log_message = "Game started"
await ctx.send(sendMessage) await ctx.send(sendMessage)
self.bot.log(logMessage) self.bot.log(log_message)
if startedGame: if startedGame:
filePath = f"resources/games/hexBoards/board{ctx.channel_id}.png" filePath = f"resources/games/hexBoards/board{ctx.channel_id}.png"
newImage = await ctx.channel.send(file = discord.File(filePath)) newImage = await ctx.channel.send(file = discord.File(filePath))
with open(f"resources/games/oldImages/hex{ctx.channel_id}", "w") as f: with open(f"resources/games/old_images/hex{ctx.channel_id}", "w") as f:
f.write(str(newImage.id)) f.write(str(newImage.id))
if gwendoTurn: if gwendoTurn:
@ -199,7 +199,7 @@ class HexGame():
else: else:
players = game["players"] players = game["players"]
if user not in players: if user not in players:
sendMessage = f"You can't place when you're not in the game. The game's players are: {self.bot.databaseFuncs.getName(game['players'][0])} and {self.bot.databaseFuncs.getName(game['players'][1])}." sendMessage = f"You can't place when you're not in the game. The game's players are: {self.bot.database_funcs.getName(game['players'][0])} and {self.bot.database_funcs.getName(game['players'][1])}."
self.bot.log("They aren't in the game") self.bot.log("They aren't in the game")
elif players[game["turn"]-1] != user: elif players[game["turn"]-1] != user:
sendMessage = "It's not your turn" sendMessage = "It's not your turn"
@ -228,12 +228,12 @@ class HexGame():
if winner == 0: # Continue with the game. if winner == 0: # Continue with the game.
gameWon = False gameWon = False
sendMessage = self.bot.databaseFuncs.getName(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.databaseFuncs.getName(game["players"][turn-1])+"'s turn."# The score is "+str(score) sendMessage = self.bot.database_funcs.getName(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.database_funcs.getName(game["players"][turn-1])+"'s turn."# The score is "+str(score)
else: # Congratulations! else: # Congratulations!
gameWon = True gameWon = True
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":winner}}) self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"winner":winner}})
sendMessage = self.bot.databaseFuncs.getName(game["players"][player-1])+" placed at "+position.upper()+" and won!" sendMessage = self.bot.database_funcs.getName(game["players"][player-1])+" placed at "+position.upper()+" and won!"
if game["players"][winner-1] != f"#{self.bot.user.id}": if game["players"][winner-1] != f"#{self.bot.user.id}":
winAmount = game["difficulty"]*10 winAmount = game["difficulty"]*10
sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account." sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account."
@ -258,7 +258,7 @@ class HexGame():
# Update the board # Update the board
self.draw.drawHexPlacement(channel,player, position) self.draw.drawHexPlacement(channel,player, position)
with open(f"resources/games/oldImages/hex{channel}", "r") as f: with open(f"resources/games/old_images/hex{channel}", "r") as f:
oldImage = await ctx.channel.fetch_message(int(f.read())) oldImage = await ctx.channel.fetch_message(int(f.read()))
if oldImage is not None: if oldImage is not None:
@ -281,7 +281,7 @@ class HexGame():
self.bot.database["hex games"].delete_one({"_id":channel}) self.bot.database["hex games"].delete_one({"_id":channel})
else: else:
with open(f"resources/games/oldImages/hex{channel}", "w") as f: with open(f"resources/games/old_images/hex{channel}", "w") as f:
f.write(str(oldImage.id)) f.write(str(oldImage.id))
if gwendoTurn: if gwendoTurn:
@ -321,7 +321,7 @@ class HexGame():
sendMessage = "It's not your turn" sendMessage = "It's not your turn"
else: else:
turn = game["turn"] turn = game["turn"]
self.bot.log("Undoing {}'s last move".format(self.bot.databaseFuncs.getName(user))) self.bot.log("Undoing {}'s last move".format(self.bot.database_funcs.getName(user)))
lastMove = game["gameHistory"].pop() lastMove = game["gameHistory"].pop()
game["board"][lastMove[0]][lastMove[1]] = 0 game["board"][lastMove[0]][lastMove[1]] = 0
@ -337,7 +337,7 @@ class HexGame():
await ctx.send(sendMessage) await ctx.send(sendMessage)
if undid: if undid:
with open(f"resources/games/oldImages/hex{channel}", "r") as f: with open(f"resources/games/old_images/hex{channel}", "r") as f:
oldImage = await ctx.channel.fetch_message(int(f.read())) oldImage = await ctx.channel.fetch_message(int(f.read()))
if oldImage is not None: if oldImage is not None:
@ -349,7 +349,7 @@ class HexGame():
filePath = f"resources/games/hexBoards/board{channel}.png" filePath = f"resources/games/hexBoards/board{channel}.png"
oldImage = await ctx.channel.send(file = discord.File(filePath)) oldImage = await ctx.channel.send(file = discord.File(filePath))
with open(f"resources/games/oldImages/hex{channel}", "w") as f: with open(f"resources/games/old_images/hex{channel}", "w") as f:
f.write(str(oldImage.id)) f.write(str(oldImage.id))
@ -556,7 +556,7 @@ class DrawHex():
game = self.bot.database["hex games"].find_one({"_id":channel}) game = self.bot.database["hex games"].find_one({"_id":channel})
for p in [1,2]: for p in [1,2]:
playername = self.bot.databaseFuncs.getName(game["players"][p-1]) playername = self.bot.database_funcs.getName(game["players"][p-1])
# Draw name # Draw name
x = self.XNAME[p] x = self.XNAME[p]
x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
@ -620,7 +620,7 @@ class DrawHex():
# Write player names and color # Write player names and color
for p in [1,2]: for p in [1,2]:
playername = self.bot.databaseFuncs.getName(game["players"][p%2]) playername = self.bot.database_funcs.getName(game["players"][p%2])
x = self.XNAME[p] x = self.XNAME[p]
x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned x -= self.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned

View File

@ -42,7 +42,7 @@ class Invest():
price: int price: int
The price of the stock. The price of the stock.
""" """
res = self.bot.finnhubClient.quote(symbol.upper()) res = self.bot.finnhub_client.quote(symbol.upper())
if res == {}: if res == {}:
return 0 return 0
else: else:
@ -65,7 +65,7 @@ class Invest():
investmentsDatabase = self.bot.database["investments"] investmentsDatabase = self.bot.database["investments"]
userInvestments = investmentsDatabase.find_one({"_id": user}) userInvestments = investmentsDatabase.find_one({"_id": user})
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
if userInvestments in [None, {}]: if userInvestments in [None, {}]:
return f"{userName} does not have a stock portfolio." return f"{userName} does not have a stock portfolio."
@ -162,7 +162,7 @@ class Invest():
} }
investmentsDatabase.insert_one(newUser) investmentsDatabase.insert_one(newUser)
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
sendMessage = "{} bought {} GwendoBucks worth of {} stock" sendMessage = "{} bought {} GwendoBucks worth of {} stock"
sendMessage = sendMessage.format(userName, buyAmount, stock) sendMessage = sendMessage.format(userName, buyAmount, stock)
return sendMessage return sendMessage
@ -219,7 +219,7 @@ class Invest():
updater = {"$unset": {f"investments.{stock}": ""}} updater = {"$unset": {f"investments.{stock}": ""}}
investmentsDatabase.update_one({"_id": user}, updater) investmentsDatabase.update_one({"_id": user}, updater)
userName = self.bot.databaseFuncs.getName(user) userName = self.bot.database_funcs.getName(user)
sendMessage = "{} sold {} GwendoBucks worth of {} stock" sendMessage = "{} sold {} GwendoBucks worth of {} stock"
return sendMessage.format(userName, sellAmount, stock) return sendMessage.format(userName, sellAmount, stock)
else: else:
@ -252,7 +252,7 @@ class Invest():
response = response.format(commands[0].upper()) response = response.format(commands[0].upper())
else: else:
price = f"{price:,}".replace(",", ".") price = f"{price:,}".replace(",", ".")
response = self.bot.longStrings["Stock value"] response = self.bot.long_strings["Stock value"]
response = response.format(commands[1].upper(), price) response = response.format(commands[1].upper(), price)
elif parameters.startswith("buy"): elif parameters.startswith("buy"):
@ -260,14 +260,14 @@ class Invest():
if len(commands) == 3: if len(commands) == 3:
response = self.buyStock(user, commands[1], int(commands[2])) response = self.buyStock(user, commands[1], int(commands[2]))
else: else:
response = self.bot.longStrings["Stock parameters"] response = self.bot.long_strings["Stock parameters"]
elif parameters.startswith("sell"): elif parameters.startswith("sell"):
commands = parameters.split(" ") commands = parameters.split(" ")
if len(commands) == 3: if len(commands) == 3:
response = self.sellStock(user, commands[1], int(commands[2])) response = self.sellStock(user, commands[1], int(commands[2]))
else: else:
response = self.bot.longStrings["Stock parameters"] response = self.bot.long_strings["Stock parameters"]
else: else:
response = "Incorrect parameters" response = "Incorrect parameters"
@ -280,7 +280,7 @@ class Invest():
"description": text, "description": text,
"colour": 0x00FF00 "colour": 0x00FF00
} }
em = discord.Embed(*embedParams) em = discord.Embed(**embedParams)
await ctx.send(embed=em) await ctx.send(embed=em)
else: else:
await ctx.send(response) await ctx.send(response)

View File

@ -98,7 +98,7 @@ class Money():
else: else:
newUser = { newUser = {
"_id": user, "_id": user,
"user name": self.bot.databaseFuncs.getName(user), "user name": self.bot.database_funcs.getName(user),
"money": amount "money": amount
} }
self.database["users"].insert_one(newUser) self.database["users"].insert_one(newUser)
@ -120,7 +120,7 @@ class Money():
""" """
await self.bot.defer(ctx) await self.bot.defer(ctx)
username = user.display_name username = user.display_name
if self.bot.databaseFuncs.getID(username) is None: if self.bot.database_funcs.getID(username) is None:
async for member in ctx.guild.fetch_members(limit=None): async for member in ctx.guild.fetch_members(limit=None):
if member.display_name.lower() == username.lower(): if member.display_name.lower() == username.lower():
username = member.display_name username = member.display_name
@ -134,7 +134,7 @@ class Money():
userid = f"#{ctx.author.id}" userid = f"#{ctx.author.id}"
userData = self.database["users"].find_one({"_id": userid}) userData = self.database["users"].find_one({"_id": userid})
targetUser = self.bot.databaseFuncs.getID(username) targetUser = self.bot.database_funcs.getID(username)
if amount <= 0: if amount <= 0:
self.bot.log("They tried to steal") self.bot.log("They tried to steal")

View File

@ -91,9 +91,9 @@ class Trivia():
return question, answers, correctAnswer return question, answers, correctAnswer
else: else:
logMessage = "There was already a trivia question for that channel" log_message = "There was already a trivia question for that channel"
self.bot.log(logMessage) self.bot.log(log_message)
return self.bot.longStrings["Trivia going on"], "", "" return self.bot.long_strings["Trivia going on"], "", ""
def triviaAnswer(self, user: str, channel: str, command: str): def triviaAnswer(self, user: str, channel: str, command: str):
""" """
@ -182,10 +182,10 @@ class Trivia():
self.triviaCountPoints(channelId) self.triviaCountPoints(channelId)
deleteGameParams = ["trivia questions", channelId] deleteGameParams = ["trivia questions", channelId]
self.bot.databaseFuncs.deleteGame(*deleteGameParams) self.bot.database_funcs.deleteGame(*deleteGameParams)
self.bot.log("Time's up for the trivia question", channelId) self.bot.log("Time's up for the trivia question", channelId)
sendMessage = self.bot.longStrings["Trivia time up"] sendMessage = self.bot.long_strings["Trivia time up"]
formatParams = [chr(correctAnswer), options[correctAnswer-97]] formatParams = [chr(correctAnswer), options[correctAnswer-97]]
sendMessage = sendMessage.format(*formatParams) sendMessage = sendMessage.format(*formatParams)
await ctx.send(sendMessage) await ctx.send(sendMessage)

View File

@ -2,4 +2,4 @@
__all__ = ["LookupFuncs"] __all__ = ["LookupFuncs"]
from .lookupFuncs import LookupFuncs from .lookup_funcs import LookupFuncs

View File

@ -64,7 +64,7 @@ class Generators():
if random.randint(1,10) > 1: if random.randint(1,10) > 1:
try: try:
new_letter = random.choice(letter_dict[chain[-2]+chain[-1]]) new_letter = random.choice(letter_dict[chain[-2]+chain[-1]])
except: except KeyError():
new_letter = random.choice(letter_dict[chain[-1]]) new_letter = random.choice(letter_dict[chain[-1]])
else: else:
new_letter = random.choice(letter_dict[chain[-1]]) new_letter = random.choice(letter_dict[chain[-1]])

View File

@ -2,4 +2,4 @@
__all__ = ["StarWars"] __all__ = ["StarWars"]
from .starWars import StarWars from .star_wars import StarWars

View File

@ -1,6 +1,6 @@
from .starWarsChar import StarWarsChar from .star_wars_char import StarWarsChar
from .starWarsRoll import StarWarsRoll from .star_wars_roll import StarWarsRoll
from .starWarsDestiny import StarWarsDestiny from .star_wars_destiny import StarWarsDestiny
class StarWars(): class StarWars():
def __init__(self, bot): def __init__(self, bot):

View File

@ -7,15 +7,15 @@ class StarWarsChar():
self.bot = bot self.bot = bot
def getCharName(self, user : str): def getCharName(self, user : str):
self.bot.log("Getting name for "+self.bot.databaseFuncs.getName(user)+"'s character") self.bot.log("Getting name for "+self.bot.database_funcs.getName(user)+"'s character")
userCharacter = self.bot.database["starwars characters"].find_one({"_id":user}) userCharacter = self.bot.database["starwars characters"].find_one({"_id":user})
if userCharacter != None: if userCharacter != None:
self.bot.log("Name is "+userCharacter["Name"]) self.bot.log("Name is "+userCharacter["Name"])
return userCharacter["Name"] return userCharacter["Name"]
else: else:
self.bot.log("Just using "+self.bot.databaseFuncs.getName(user)) self.bot.log("Just using "+self.bot.database_funcs.getName(user))
return self.bot.databaseFuncs.getName(user) return self.bot.database_funcs.getName(user)
def setUpDict(self, cmd : dict): def setUpDict(self, cmd : dict):
self.bot.log("Setting up a dictionary in a nice way") self.bot.log("Setting up a dictionary in a nice way")
@ -252,7 +252,7 @@ class StarWarsChar():
if cmd == "": if cmd == "":
break break
self.bot.log("Looking for "+self.bot.databaseFuncs.getName(user)+"'s character") self.bot.log("Looking for "+self.bot.database_funcs.getName(user)+"'s character")
if userCharacter != None: if userCharacter != None:
self.bot.log("Found it! Looking for "+key+" in the data") self.bot.log("Found it! Looking for "+key+" in the data")
if key in userCharacter: if key in userCharacter:
@ -303,7 +303,7 @@ class StarWarsChar():
return cmd[0]+" added to "+key+" for " + userCharacter["Name"] return cmd[0]+" added to "+key+" for " + userCharacter["Name"]
elif key == "Weapons": elif key == "Weapons":
with open("resources/starWars/starwarstemplates.json", "r") as f: with open("resources/star_wars/starwarstemplates.json", "r") as f:
templates = json.load(f) templates = json.load(f)
newWeapon = templates["Weapon"] newWeapon = templates["Weapon"]
self.bot.log("Adding "+cmd+" to "+key) self.bot.log("Adding "+cmd+" to "+key)
@ -495,18 +495,18 @@ class StarWarsChar():
text = self.replaceWithSpaces(text) text = self.replaceWithSpaces(text)
returnEmbed = True returnEmbed = True
else: else:
self.bot.log("Makin' a character for "+self.bot.databaseFuncs.getName(user)) self.bot.log("Makin' a character for "+self.bot.database_funcs.getName(user))
with open("resources/starWars/starwarstemplates.json", "r") as f: with open("resources/star_wars/starwarstemplates.json", "r") as f:
templates = json.load(f) templates = json.load(f)
newChar = templates["Character"] newChar = templates["Character"]
newChar["_id"] = user newChar["_id"] = user
self.bot.database["starwars characters"].insert_one(newChar) self.bot.database["starwars characters"].insert_one(newChar)
await ctx.send("Character for " + self.bot.databaseFuncs.getName(user) + " created") await ctx.send("Character for " + self.bot.database_funcs.getName(user) + " created")
else: else:
if cmd == "Purge": if cmd == "Purge":
self.bot.log("Deleting "+self.bot.databaseFuncs.getName(user)+"'s character") self.bot.log("Deleting "+self.bot.database_funcs.getName(user)+"'s character")
self.bot.database["starwars characters"].delete_one({"_id":user}) self.bot.database["starwars characters"].delete_one({"_id":user})
await ctx.send("Character for " + self.bot.databaseFuncs.getName(user) + " deleted") await ctx.send("Character for " + self.bot.database_funcs.getName(user) + " deleted")
else: else:
await ctx.send(self.replaceWithSpaces(str(self.charData(user,cmd)))) await ctx.send(self.replaceWithSpaces(str(self.charData(user,cmd))))

View File

@ -4,16 +4,16 @@ class StarWarsDestiny():
def destinyNew(self, num : int): def destinyNew(self, num : int):
self.bot.log("Creating a new destiny pool with "+str(num)+" players") self.bot.log("Creating a new destiny pool with "+str(num)+" players")
roll, diceResults = self.bot.starWars.roll.roll(0,0,0,0,0,0,num) roll, diceResults = self.bot.star_wars.roll.roll(0,0,0,0,0,0,num)
roll = "".join(sorted(roll)) roll = "".join(sorted(roll))
with open("resources/starWars/destinyPoints.txt","wt") as f: with open("resources/star_wars/destinyPoints.txt","wt") as f:
f.write(roll) f.write(roll)
return "Rolled for Destiny Points and got:\n"+self.bot.starWars.roll.diceResultToEmoji(diceResults)+"\n"+self.bot.starWars.roll.resultToEmoji(roll) return "Rolled for Destiny Points and got:\n"+self.bot.star_wars.roll.diceResultToEmoji(diceResults)+"\n"+self.bot.star_wars.roll.resultToEmoji(roll)
def destinyUse(self, user : str): def destinyUse(self, user : str):
with open("resources/starWars/destinyPoints.txt","rt") as f: with open("resources/star_wars/destinyPoints.txt","rt") as f:
points = f.read() points = f.read()
if user == "Nikolaj": if user == "Nikolaj":
@ -21,10 +21,10 @@ class StarWarsDestiny():
if 'B' in points: if 'B' in points:
points = points.replace("B","L",1) points = points.replace("B","L",1)
points = "".join(sorted(points)) points = "".join(sorted(points))
with open("resources/starWars/destinyPoints.txt","wt") as f: with open("resources/star_wars/destinyPoints.txt","wt") as f:
f.write(points) f.write(points)
self.bot.log("Did it") self.bot.log("Did it")
return "Used a dark side destiny point. Destiny pool is now:\n"+self.bot.starWars.roll.resultToEmoji(points) return "Used a dark side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points)
else: else:
self.bot.log("There were no dark side destiny points") self.bot.log("There were no dark side destiny points")
return "No dark side destiny points" return "No dark side destiny points"
@ -33,10 +33,10 @@ class StarWarsDestiny():
if 'L' in points: if 'L' in points:
points = points.replace("L","B",1) points = points.replace("L","B",1)
points = "".join(sorted(points)) points = "".join(sorted(points))
with open("resources/starWars/destinyPoints.txt","wt") as f: with open("resources/star_wars/destinyPoints.txt","wt") as f:
f.write(points) f.write(points)
self.bot.log("Did it") self.bot.log("Did it")
return "Used a light side destiny point. Destiny pool is now:\n"+self.bot.starWars.roll.resultToEmoji(points) return "Used a light side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points)
else: else:
self.bot.log("There were no dark side destiny points") self.bot.log("There were no dark side destiny points")
return "No light side destiny points" return "No light side destiny points"
@ -51,8 +51,8 @@ class StarWarsDestiny():
if cmd == "": if cmd == "":
self.bot.log("Retrieving destiny pool info") self.bot.log("Retrieving destiny pool info")
with open("resources/starWars/destinyPoints.txt","rt") as f: with open("resources/star_wars/destinyPoints.txt","rt") as f:
sendMessage = self.bot.starWars.roll.resultToEmoji(f.read()) sendMessage = self.bot.star_wars.roll.resultToEmoji(f.read())
else: else:
commands = cmd.upper().split(" ") commands = cmd.upper().split(" ")
if commands[0] == "N": if commands[0] == "N":

View File

@ -3,7 +3,7 @@ import re
import string import string
import json import json
with open("resources/starWars/starwarsskills.json", "r") as f: with open("resources/star_wars/starwarsskills.json", "r") as f:
skillData = json.load(f) skillData = json.load(f)
class StarWarsRoll(): class StarWarsRoll():
@ -302,7 +302,7 @@ class StarWarsRoll():
cmd = re.sub(' +',' ',cmd.upper()) + " " cmd = re.sub(' +',' ',cmd.upper()) + " "
if cmd[0] == " ": if cmd[0] == " ":
cmd = cmd[1:] cmd = cmd[1:]
cmd = self.bot.starWars.character.replaceSpaces(string.capwords(cmd)) cmd = self.bot.star_wars.character.replaceSpaces(string.capwords(cmd))
commands = cmd.split(" ") commands = cmd.split(" ")
validCommand = False validCommand = False
@ -316,15 +316,15 @@ class StarWarsRoll():
elif string.capwords(commands[0]) in skillData: elif string.capwords(commands[0]) in skillData:
self.bot.log("Oh look! This guy has skills!") self.bot.log("Oh look! This guy has skills!")
if self.bot.starWars.character.userHasChar(user): if self.bot.star_wars.character.userHasChar(user):
self.bot.log("They have a character. That much we know") self.bot.log("They have a character. That much we know")
skillLevel = self.bot.starWars.character.charData(user,"Skills " + string.capwords(commands[0])) skillLevel = self.bot.star_wars.character.charData(user,"Skills " + string.capwords(commands[0]))
if string.capwords(commands[0]) == "Lightsaber": if string.capwords(commands[0]) == "Lightsaber":
self.bot.log("The skill is lightsaber") self.bot.log("The skill is lightsaber")
charLevel = self.bot.starWars.character.charData(user,"Characteristics " + self.bot.starWars.character.lightsaberChar(user)) charLevel = self.bot.star_wars.character.charData(user,"Characteristics " + self.bot.star_wars.character.lightsaberChar(user))
else: else:
charLevel = self.bot.starWars.character.charData(user,"Characteristics " + skillData[string.capwords(commands[0])]) charLevel = self.bot.star_wars.character.charData(user,"Characteristics " + skillData[string.capwords(commands[0])])
abilityDice = abs(charLevel-skillLevel) abilityDice = abs(charLevel-skillLevel)
proficiencyDice = min(skillLevel,charLevel) proficiencyDice = min(skillLevel,charLevel)
@ -372,7 +372,7 @@ class StarWarsRoll():
simplified = self.simplify(rollResults) simplified = self.simplify(rollResults)
name = self.bot.starWars.character.getCharName(user) name = self.bot.star_wars.character.getCharName(user)
self.bot.log("Returns results and simplified results") self.bot.log("Returns results and simplified results")

View File

@ -5,20 +5,21 @@ Contains the Gwendolyn class, and runs it when run as script.
--------- ---------
Gwendolyn(discord.ext.commands.Bot) Gwendolyn(discord.ext.commands.Bot)
""" """
import platform # Used to test if the bot is running on windows, in
# order to fix a bug with asyncio
import asyncio # used to set change the loop policy if the bot is
# running on windows
import os # Used for loading cogs in Gwendolyn.addCogs import os # Used for loading cogs in Gwendolyn.addCogs
import finnhub # Used to add a finhub client to the bot import finnhub # Used to add a finhub client to the bot
import platform # Used to test if the bot is running on windows, in
# order to fix a bug with asyncio
import asyncio # used to set change the loop policy if the bot is
# running on windows
import discord # Used for discord.Intents and discord.Status import discord # Used for discord.Intents and discord.Status
import discord_slash # Used to initialized SlashCommands object import discord_slash # Used to initialized SlashCommands object
from discord.ext import commands # Used to inherit from commands.bot from discord.ext import commands # Used to inherit from commands.bot
from pymongo import MongoClient # Used for database management from pymongo import MongoClient # Used for database management
from funcs import Money, StarWars, Games, Other, LookupFuncs from funcs import Money, StarWars, Games, Other, LookupFuncs
from utils import (Options, Credentials, logThis, makeFiles, databaseFuncs, from utils import (Options, Credentials, logThis, makeFiles, DatabaseFuncs,
EventHandler, ErrorHandler, longStrings) EventHandler, ErrorHandler, long_strings)
class Gwendolyn(commands.Bot): class Gwendolyn(commands.Bot):
@ -37,66 +38,66 @@ class Gwendolyn(commands.Bot):
"""Initialize the bot.""" """Initialize the bot."""
intents = discord.Intents.default() intents = discord.Intents.default()
intents.members = True intents.members = True
initParams = { initiation_parameters = {
"command_prefix": " ", "command_prefix": " ",
"case_insensitive": True, "case_insensitive": True,
"intents": intents, "intents": intents,
"status": discord.Status.dnd "status": discord.Status.dnd
} }
super().__init__(**initParams) super().__init__(**initiation_parameters)
self._addClientsAndOptions() self._add_clients_and_options()
self._addUtilClasses() self._add_util_classes()
self._addFunctionContainers() self._add_function_containers()
self._addCogs() self._add_cogs()
def _addClientsAndOptions(self): def _add_clients_and_options(self):
"""Add all the client, option and credentials objects.""" """Add all the client, option and credentials objects."""
self.longStrings = longStrings() self.long_strings = long_strings()
self.options = Options() self.options = Options()
self.credentials = Credentials() self.credentials = Credentials()
finnhubKey = self.credentials.finnhubKey finnhub_key = self.credentials.finnhub_key
self.finnhubClient = finnhub.Client(api_key=finnhubKey) self.finnhub_client = finnhub.Client(api_key=finnhub_key)
mongoUser = self.credentials.mongoDBUser mongo_user = self.credentials.mongoDBUser
mongoPassword = self.credentials.mongoDBPassword mongo_password = self.credentials.mongoDBPassword
mongoLink = f"mongodb+srv://{mongoUser}:{mongoPassword}@gwendolyn" mongo_url = f"mongodb+srv://{mongo_user}:{mongo_password}@gwendolyn"
mongoLink += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority" mongo_url += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority"
dataBaseClient = MongoClient(mongoLink) database_clint = MongoClient(mongo_url)
if self.options.testing: if self.options.testing:
self.log("Testing mode") self.log("Testing mode")
self.database = dataBaseClient["Gwendolyn-Test"] self.database = database_clint["Gwendolyn-Test"]
else: else:
self.database = dataBaseClient["Gwendolyn"] self.database = database_clint["Gwendolyn"]
def _addUtilClasses(self): def _add_util_classes(self):
"""Add all the classes used as utility.""" """Add all the classes used as utility."""
self.databaseFuncs = databaseFuncs(self) self.database_funcs = DatabaseFuncs(self)
self.eventHandler = EventHandler(self) self.event_handler = EventHandler(self)
self.errorHandler = ErrorHandler(self) self.error_handler = ErrorHandler(self)
slashParams = { slash_parameters = {
"sync_commands": True, "sync_commands": True,
"sync_on_cog_reload": True, "sync_on_cog_reload": True,
"override_type": True "override_type": True
} }
self.slash = discord_slash.SlashCommand(self, **slashParams) self.slash = discord_slash.SlashCommand(self, **slash_parameters)
def _addFunctionContainers(self): def _add_function_containers(self):
"""Add all the function containers used for commands.""" """Add all the function containers used for commands."""
self.starWars = StarWars(self) self.star_wars = StarWars(self)
self.other = Other(self) self.other = Other(self)
self.lookupFuncs = LookupFuncs(self) self.lookup_funcs = LookupFuncs(self)
self.games = Games(self) self.games = Games(self)
self.money = Money(self) self.money = Money(self)
def _addCogs(self): def _add_cogs(self):
"""Load cogs.""" """Load cogs."""
for filename in os.listdir("./cogs"): for filename in os.listdir("./cogs"):
if filename.endswith(".py"): if filename.endswith(".py"):
self.load_extension(f"cogs.{filename[:-3]}") self.load_extension(f"cogs.{filename[:-3]}")
def log(self, messages, channel: str = "", level: int = 20): def log(self, messages, channel: str = "", level: int = 20):
"""Log a message. Described in utils/utilFunctions.py.""" """Log a message. Described in utils/util_functions.py."""
logThis(messages, channel, level) logThis(messages, channel, level)
async def stop(self, ctx: discord_slash.context.SlashContext): async def stop(self, ctx: discord_slash.context.SlashContext):
@ -116,13 +117,13 @@ class Gwendolyn(commands.Bot):
await self.change_presence(status=discord.Status.offline) await self.change_presence(status=discord.Status.offline)
self.databaseFuncs.wipeGames() self.database_funcs.wipeGames()
self.log("Logging out", level=25) self.log("Logging out", level=25)
await self.close() await self.close()
else: else:
logMessage = f"{ctx.author.display_name} tried to stop me!" log_message = f"{ctx.author.display_name} tried to stop me!"
self.log(logMessage, str(ctx.channel_id)) self.log(log_message, str(ctx.channel_id))
await ctx.send(f"I don't think I will, {ctx.author.display_name}") await ctx.send(f"I don't think I will, {ctx.author.display_name}")
async def defer(self, ctx: discord_slash.context.SlashContext): async def defer(self, ctx: discord_slash.context.SlashContext):
@ -146,5 +147,5 @@ if __name__ == "__main__":
try: try:
# Runs the whole shabang # Runs the whole shabang
bot.run(bot.credentials.token) bot.run(bot.credentials.token)
except Exception: except Exception as exception: # pylint: disable=broad-except
bot.log(bot.longStrings["Can't log in"]) bot.log(bot.long_strings[f"Can't log in: {repr(exception)}"])

View File

@ -42,8 +42,8 @@ Comments, strings, variable names, class names, docstrings, as well as all other
# Code # Code
## Code Style ## Code Style
All the Python code should follow the [PEP 8 guidelines](https://www.python.org/dev/peps/pep-0008/), with the following differences: All the Python code should follow the [PEP 8 guidelines](https://www.python.org/dev/peps/pep-0008/), with the following additions:
+ Variable and function names must be camelCase, and must fully consist of either full words or common/understandable abbreviations. + Variable and function names must fully consist of either full words or common/understandable abbreviations.
+ Use f-strings when applicable. + Use f-strings when applicable.
### Documentation ### Documentation

View File

@ -0,0 +1 @@
854063181868695593

View File

@ -0,0 +1,2 @@
854064833909489734
854064835040641044

View File

@ -0,0 +1 @@
854064794356023346

View File

@ -1 +1 @@
Brug `/connectFour start` til at starte et spil imod Gwendolyn. Brug `/connectFour start [modstander]` for at spille imod en anden person. Du kan også bruge `/connectFour start [1-5]`, hvor tallet er sværhedsgraden af Gwendolyn du gerne vil spille imod. Brug `/connect_four start` til at starte et spil imod Gwendolyn. Brug `/connect_four start [modstander]` for at spille imod en anden person. Du kan også bruge `/connect_four start [1-5]`, hvor tallet er sværhedsgraden af Gwendolyn du gerne vil spille imod.

View File

@ -0,0 +1 @@
Du kan bruge kommandoer som `/star_wars_character name Jared` eller `/star_wars_character skills astrogation 3` til at ændre din karakters info. Kommandoen `/star_wars_character` vil give dig et character sheet for din karakter.

View File

@ -1 +1 @@
Lader dig rulle Star Wars terninger. Du kan skrive tal der repræsenterer antallet af hver terning i rækkefølgen: ability, proficiency, difficulty, challenge, boost, setback og force. Du behøver ikke skrive et tal til alle terningerne. Du kan også skrive forbogstavet for terningen du vil rulle før antallet, såsom "/starWarsRoll f2", der ruller 2 force terninger. Lader dig rulle Star Wars terninger. Du kan skrive tal der repræsenterer antallet af hver terning i rækkefølgen: ability, proficiency, difficulty, challenge, boost, setback og force. Du behøver ikke skrive et tal til alle terningerne. Du kan også skrive forbogstavet for terningen du vil rulle før antallet, såsom "/star_wars_roll f2", der ruller 2 force terninger.

View File

@ -1 +0,0 @@
Du kan bruge kommandoer som `/starWarsCharacter name Jared` eller `/starWarsCharacter skills astrogation 3` til at ændre din karakters info. Kommandoen `/starWarsCharacter` vil give dig et character sheet for din karakter.

View File

@ -7,13 +7,13 @@
`/name` - Genererer et tilfældigt navn. `/name` - Genererer et tilfældigt navn.
`/tavern` - Genererer en tilfældig tavern. `/tavern` - Genererer en tilfældig tavern.
`/give` - Lader dig give GwendoBucks til andre. `/give` - Lader dig give GwendoBucks til andre.
`/starWarsCharacter` - Lader dig lave en Star Wars karakter. `/star_wars_character` - Lader dig lave en Star Wars karakter.
`/starWarsRoll` - Lader dig rulle Star Wars terninger. `/star_wars_roll` - Lader dig rulle Star Wars terninger.
`/balance` - Viser dig hvor mange GwendoBucks du har. `/balance` - Viser dig hvor mange GwendoBucks du har.
`/invest` - Lader dig investere dine GwendoBucks i aktiemarkedet. `/invest` - Lader dig investere dine GwendoBucks i aktiemarkedet.
`/blackjack` - Lader dig spille et spil blackjack. `/blackjack` - Lader dig spille et spil blackjack.
`/trivia` - Lader dig spille et spil trivia, hvor du kan tjene GwendoBucks. `/trivia` - Lader dig spille et spil trivia, hvor du kan tjene GwendoBucks.
`/connectFour` - Lader dig spille et spil fire på stribe. `/connect_four` - Lader dig spille et spil fire på stribe.
`/hex` - Lader dig spille et spil Hex. `/hex` - Lader dig spille et spil Hex.
`/hangman` - Lader dig spille et spil hangman. `/hangman` - Lader dig spille et spil hangman.
`/wolf` - Lader dig slå ting op på Wolfram Alpha. `/wolf` - Lader dig slå ting op på Wolfram Alpha.

View File

@ -112,8 +112,8 @@
"name" : "start", "name" : "start",
"description" : "Start a game of blackjack" "description" : "Start a game of blackjack"
}, },
"connectFourStartGwendolyn" : { "connect_fourStartGwendolyn" : {
"base" : "connectFour", "base" : "connect_four",
"subcommand_group" : "start", "subcommand_group" : "start",
"name" : "Gwendolyn", "name" : "Gwendolyn",
"description" : "Start a game of connect four against Gwendolyn", "description" : "Start a game of connect four against Gwendolyn",
@ -126,8 +126,8 @@
} }
] ]
}, },
"connectFourStartUser" : { "connect_fourStartUser" : {
"base" : "connectFour", "base" : "connect_four",
"subcommand_group" : "start", "subcommand_group" : "start",
"name" : "user", "name" : "user",
"description" : "Start a game of connect four against another user", "description" : "Start a game of connect four against another user",
@ -140,8 +140,8 @@
} }
] ]
}, },
"connectFourSurrender" : { "connect_fourSurrender" : {
"base" : "connectFour", "base" : "connect_four",
"name" : "surrender", "name" : "surrender",
"description" : "Surrender the game of connect four" "description" : "Surrender the game of connect four"
}, },
@ -333,8 +333,8 @@
} }
] ]
}, },
"starWarsCharacter" : { "star_wars_character" : {
"name" : "starWarsCharacter", "name" : "star_wars_character",
"description" : "Manage your Star Wars character sheet", "description" : "Manage your Star Wars character sheet",
"options" : [ "options" : [
{ {
@ -345,8 +345,8 @@
} }
] ]
}, },
"starWarsCrit" : { "star_wars_crit" : {
"name" : "starWarsCrit", "name" : "star_wars_crit",
"description" : "Roll a Star Wars critical injury", "description" : "Roll a Star Wars critical injury",
"options" : [ "options" : [
{ {
@ -357,8 +357,8 @@
} }
] ]
}, },
"starWarsDestiny" : { "star_wars_destiny" : {
"name" : "starWarsDestiny", "name" : "star_wars_destiny",
"description" : "Use and see Star Wars Destiny points", "description" : "Use and see Star Wars Destiny points",
"options" : [ "options" : [
{ {
@ -369,8 +369,8 @@
} }
] ]
}, },
"starWarsRoll" : { "star_wars_roll" : {
"name" : "starWarsRoll", "name" : "star_wars_roll",
"description" : "Roll Star Wars dice", "description" : "Roll Star Wars dice",
"options" : [ "options" : [
{ {

View File

@ -56,9 +56,9 @@
] ]
}, },
"txt": { "txt": {
"resources/starWars/destinyPoints.txt": "", "resources/star_wars/destinyPoints.txt": "",
"resources/movies.txt": "The Room", "resources/movies.txt": "The Room",
"resources/names.txt": "Gandalf", "resources/names.txt": "Gandalf\n",
"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 ids:\nAdmins:" "options.txt" : "Testing: True\nTesting guild ids:\nAdmins:"
}, },
@ -69,6 +69,6 @@
"resources/games/hexBoards", "resources/games/hexBoards",
"resources/games/hangmanBoards", "resources/games/hangmanBoards",
"resources/bedreNetflix", "resources/bedreNetflix",
"resources/games/oldImages" "resources/games/old_images"
] ]
} }

View File

@ -1,10 +1,10 @@
"""A collections of utilities used by Gwendolyn and her functions.""" """A collections of utilities used by Gwendolyn and her functions."""
__all__ = ["Options", "Credentials", "databaseFuncs", "EventHandler", __all__ = ["Options", "Credentials", "DatabaseFuncs", "EventHandler",
"ErrorHandler", "getParams", "logThis", "cap", "makeFiles", "ErrorHandler", "getParams", "logThis", "cap", "makeFiles",
"replaceMultiple", "emojiToCommand"] "replaceMultiple", "emojiToCommand"]
from .helperClasses import Options, Credentials, databaseFuncs from .helper_classes import Options, Credentials, DatabaseFuncs
from .eventHandlers import EventHandler, ErrorHandler from .event_handlers import EventHandler, ErrorHandler
from .utilFunctions import (getParams, logThis, cap, makeFiles, from .util_functions import (getParams, logThis, cap, makeFiles,
replaceMultiple, emojiToCommand, longStrings) replaceMultiple, emojiToCommand, long_strings)

View File

@ -15,7 +15,7 @@ from discord.ext import commands # Used to compare errors with command
# errors # errors
from discord_slash.context import SlashContext from discord_slash.context import SlashContext
from utils.utilFunctions import emojiToCommand from utils.util_functions import emojiToCommand
class EventHandler(): class EventHandler():
@ -35,7 +35,9 @@ class EventHandler():
async def on_ready(self): async def on_ready(self):
"""Log and sets status when it logs in.""" """Log and sets status when it logs in."""
await self.bot.databaseFuncs.syncCommands() slashCommandList = await self.bot.slash.to_dict()
print(slashCommandList['guild'][740652054388932679][13])
await self.bot.database_funcs.syncCommands()
name = self.bot.user.name name = self.bot.user.name
userid = str(self.bot.user.id) userid = str(self.bot.user.id)
loggedInMessage = f"Logged in as {name}, {userid}" loggedInMessage = f"Logged in as {name}, {userid}"
@ -59,14 +61,14 @@ class EventHandler():
args = " ".join([str(i) for i in ctx.args]) args = " ".join([str(i) for i in ctx.args])
fullCommand = f"/{ctx.command}{subcommand}{subcommandGroup}{args}" fullCommand = f"/{ctx.command}{subcommand}{subcommandGroup}{args}"
logMessage = f"{ctx.author.display_name} ran {fullCommand}" log_message = f"{ctx.author.display_name} ran {fullCommand}"
self.bot.log(logMessage, str(ctx.channel_id), level=25) self.bot.log(log_message, str(ctx.channel_id), level=25)
async def on_reaction_add(self, reaction: discord.Reaction, async def on_reaction_add(self, reaction: discord.Reaction,
user: discord.User): user: discord.User):
"""Take action if the reaction is on a command message.""" """Take action if the reaction is on a command message."""
if not user.bot: if not user.bot:
tests = self.bot.databaseFuncs tests = self.bot.database_funcs
message = reaction.message message = reaction.message
channel = message.channel channel = message.channel
reactedMessage = f"{user.display_name} reacted to a message" reactedMessage = f"{user.display_name} reacted to a message"
@ -80,10 +82,10 @@ class EventHandler():
reactionTestParams = [message, f"#{str(user.id)}"] reactionTestParams = [message, f"#{str(user.id)}"]
if tests.connectFourReactionTest(*reactionTestParams): if tests.connect_fourReactionTest(*reactionTestParams):
column = emojiToCommand(reaction.emoji) column = emojiToCommand(reaction.emoji)
params = [message, f"#{user.id}", column-1] params = [message, f"#{user.id}", column-1]
await self.bot.games.connectFour.placePiece(*params) await self.bot.games.connect_four.placePiece(*params)
if plexData[0]: if plexData[0]:
plexFuncs = self.bot.other.bedreNetflix plexFuncs = self.bot.other.bedreNetflix
@ -150,14 +152,14 @@ class ErrorHandler():
self.bot.log("Deleted message before I could add all reactions") self.bot.log("Deleted message before I could add all reactions")
elif isinstance(error, commands.errors.MissingRequiredArgument): elif isinstance(error, commands.errors.MissingRequiredArgument):
self.bot.log(f"{error}", str(ctx.channel_id)) self.bot.log(f"{error}", str(ctx.channel_id))
await ctx.send(self.bot.longStrings["missing parameters"]) await ctx.send(self.bot.long_strings["missing parameters"])
else: else:
params = [type(error), error, error.__traceback__] params = [type(error), error, error.__traceback__]
exception = traceback.format_exception(*params) exception = traceback.format_exception(*params)
exceptionString = "".join(exception) exceptionString = "".join(exception)
logMessages = [f"exception in /{ctx.name}", f"{exceptionString}"] log_messages = [f"exception in /{ctx.name}", f"{exceptionString}"]
self.bot.log(logMessages, str(ctx.channel_id), 40) self.bot.log(log_messages, str(ctx.channel_id), 40)
if isinstance(error, discord.errors.NotFound): if isinstance(error, discord.errors.NotFound):
self.bot.log("Context is non-existant", level=40) self.bot.log("Context is non-existant", level=40)
else: else:
@ -172,5 +174,5 @@ class ErrorHandler():
exception = traceback.format_exc() exception = traceback.format_exc()
exceptionString = "".join(exception) exceptionString = "".join(exception)
logMessages = [f"exception in {method}", f"{exceptionString}"] log_messages = [f"exception in {method}", f"{exceptionString}"]
self.bot.log(logMessages, level=40) self.bot.log(log_messages, level=40)

View File

@ -84,7 +84,7 @@ class Credentials():
data = sanitize(f.read()) data = sanitize(f.read())
self.token = data["bot token"] self.token = data["bot token"]
self.finnhubKey = data["finnhub api key"] self.finnhub_key = data["finnhub api key"]
self.wordnikKey = data["wordnik api key"] self.wordnikKey = data["wordnik api key"]
self.mongoDBUser = data["mongodb user"] self.mongoDBUser = data["mongodb user"]
self.mongoDBPassword = data["mongodb password"] self.mongoDBPassword = data["mongodb password"]
@ -93,7 +93,7 @@ class Credentials():
self.sonarrKey = data["sonarr api key"] self.sonarrKey = data["sonarr api key"]
class databaseFuncs(): class DatabaseFuncs():
""" """
Manages database functions. Manages database functions.
@ -103,7 +103,7 @@ class databaseFuncs():
getID(userName: str) -> str getID(userName: str) -> str
deleteGame(gameType: str, channel: str) deleteGame(gameType: str, channel: str)
wipeGames() wipeGames()
connectFourReactionTest(message: discord.Message, connect_fourReactionTest(message: discord.Message,
user: discord.User) -> bool user: discord.User) -> bool
hangmanReactionTest(message: discord.Message, hangmanReactionTest(message: discord.Message,
user: discord.User) -> bool user: discord.User) -> bool
@ -195,7 +195,7 @@ class databaseFuncs():
g = git.cmd.Git("") g = git.cmd.Git("")
g.pull() g.pull()
def connectFourReactionTest(self, message: discord.Message, def connect_fourReactionTest(self, message: discord.Message,
user: discord.User): user: discord.User):
""" """
Test if the given message is the current connect four game. Test if the given message is the current connect four game.
@ -219,12 +219,15 @@ class databaseFuncs():
channelSearch = {"_id": str(channel.id)} channelSearch = {"_id": str(channel.id)}
game = self.bot.database["connect 4 games"].find_one(channelSearch) game = self.bot.database["connect 4 games"].find_one(channelSearch)
filePath = f"resources/games/oldImages/connectFour{channel.id}" filePath = f"resources/games/old_images/connect_four{channel.id}"
with open(filePath, "r") as f: if os.path.isfile(filePath):
oldImage = int(f.read()) with open(filePath, "r") as f:
oldImage = int(f.read())
else:
oldImage = 0
if message.id == oldImage: if message.id == oldImage:
self.bot.log("They reacted to the connectFour game") self.bot.log("They reacted to the connect_four game")
turn = game["turn"] turn = game["turn"]
if user == game["players"][turn]: if user == game["players"][turn]:
return True return True
@ -255,7 +258,7 @@ class databaseFuncs():
hangman. hangman.
""" """
channel = message.channel channel = message.channel
filePath = f"resources/games/oldImages/hangman{channel.id}" filePath = f"resources/games/old_images/hangman{channel.id}"
if os.path.isfile(filePath): if os.path.isfile(filePath):
with open(filePath, "r") as f: with open(filePath, "r") as f:
oldMessages = f.read().splitlines() oldMessages = f.read().splitlines()

View File

@ -3,7 +3,7 @@ Contains utility functions used by parts of the bot.
*Functions* *Functions*
----------- -----------
longstrings() -> dict long_strings() -> dict
getParams() -> dict getParams() -> dict
logThis(messages: Union[str, list], channel: str = "", logThis(messages: Union[str, list], channel: str = "",
level: int = 20) level: int = 20)
@ -18,7 +18,7 @@ import logging # Used for logging
import os # Used by makeFiles() to check if files exist import os # Used by makeFiles() to check if files exist
import sys # Used to specify printing for logging import sys # Used to specify printing for logging
import imdb # Used to disable logging for the module import imdb # Used to disable logging for the module
from .helperClasses import Options # Used by getParams() from .helper_classes import Options # Used by getParams()
# All of this is logging configuration # All of this is logging configuration
@ -45,16 +45,16 @@ imdb._logging.setLevel("CRITICAL") # Basically disables imdbpy
# logging, since it's printed to the terminal. # logging, since it's printed to the terminal.
def longStrings(): def long_strings():
""" """
Get the data from resources/longStrings.json. Get the data from resources/long_strings.json.
*Returns* *Returns*
--------- ---------
data: dict data: dict
The long strings and their keys. The long strings and their keys.
""" """
with open("resources/longStrings.json", "r") as f: with open("resources/long_strings.json", "r") as f:
data = json.load(f) data = json.load(f)
return data return data
@ -116,8 +116,8 @@ def logThis(messages, channel: str = "", level: int = 20):
if level >= 25: if level >= 25:
printer.log(level, printMessage) printer.log(level, printMessage)
for logMessage in messages: for log_message in messages:
logger.log(level, logMessage) logger.log(level, log_message)
def cap(s: str): def cap(s: str):