🧹 PEP updating
This commit is contained in:
@ -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))
|
@ -13,26 +13,26 @@ class EventCog(commands.Cog):
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
"""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()
|
||||
async def on_slash_command(self, ctx):
|
||||
"""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()
|
||||
async def on_slash_command_error(self, ctx, error):
|
||||
"""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."""
|
||||
await self.bot.errorHandler.on_error(method)
|
||||
await self.bot.error_handler.on_error(method)
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_reaction_add(self, reaction, user):
|
||||
"""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):
|
@ -95,20 +95,20 @@ class ConnectFourCog(commands.Cog):
|
||||
"""Initialize the cog."""
|
||||
self.bot = bot
|
||||
|
||||
@cog_ext.cog_subcommand(**params["connectFourStartUser"])
|
||||
async def connectFourStartUser(self, ctx, user):
|
||||
@cog_ext.cog_subcommand(**params["connect_fourStartUser"])
|
||||
async def connect_fourStartUser(self, ctx, 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"])
|
||||
async def connectFourStartGwendolyn(self, ctx, difficulty=3):
|
||||
@cog_ext.cog_subcommand(**params["connect_fourStartGwendolyn"])
|
||||
async def connect_fourStartGwendolyn(self, ctx, difficulty=3):
|
||||
"""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"])
|
||||
async def connectFourSurrender(self, ctx):
|
||||
@cog_ext.cog_subcommand(**params["connect_fourSurrender"])
|
||||
async def connect_fourSurrender(self, ctx):
|
||||
"""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):
|
@ -18,13 +18,13 @@ class LookupCog(commands.Cog):
|
||||
@cog_ext.cog_slash(**params["spell"])
|
||||
async def spell(self, ctx, query):
|
||||
"""Look up a spell."""
|
||||
await self.bot.lookupFuncs.spellFunc(ctx, query)
|
||||
await self.bot.lookup_funcs.spellFunc(ctx, query)
|
||||
|
||||
# Looks up a monster
|
||||
@cog_ext.cog_slash(**params["monster"])
|
||||
async def monster(self, ctx, query):
|
||||
"""Look up a monster."""
|
||||
await self.bot.lookupFuncs.monsterFunc(ctx, query)
|
||||
await self.bot.lookup_funcs.monsterFunc(ctx, query)
|
||||
|
||||
|
||||
def setup(bot):
|
40
cogs/star_wars_cog.py
Normal file
40
cogs/star_wars_cog.py
Normal 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))
|
@ -8,4 +8,4 @@ from .lookup import LookupFuncs
|
||||
|
||||
from .other import Other
|
||||
|
||||
from .starWarsFuncs import StarWars
|
||||
from .star_wars_funcs import StarWars
|
||||
|
@ -3,4 +3,4 @@
|
||||
__all__ = ["Money", "Games"]
|
||||
|
||||
from .money import Money
|
||||
from .gamesContainer import Games
|
||||
from .games_container import Games
|
||||
|
@ -211,7 +211,7 @@ class Blackjack():
|
||||
|
||||
allStanding = True
|
||||
preAllStanding = True
|
||||
message = self.bot.longStrings["Blackjack all players standing"]
|
||||
message = self.bot.long_strings["Blackjack all players standing"]
|
||||
|
||||
if game["all standing"]:
|
||||
self.bot.log("All are standing")
|
||||
@ -245,11 +245,11 @@ class Blackjack():
|
||||
return "", True, done
|
||||
else:
|
||||
if game["round"] == 0:
|
||||
firstRoundMsg = self.bot.longStrings["Blackjack first round"]
|
||||
firstRoundMsg = self.bot.long_strings["Blackjack first round"]
|
||||
else:
|
||||
firstRoundMsg = ""
|
||||
|
||||
sendMessage = self.bot.longStrings["Blackjack commands"]
|
||||
sendMessage = self.bot.long_strings["Blackjack commands"]
|
||||
print(firstRoundMsg)
|
||||
sendMessage = sendMessage.format(firstRoundMsg)
|
||||
return sendMessage, False, done
|
||||
@ -352,7 +352,7 @@ class Blackjack():
|
||||
winningCalc = (self._calcWinnings(*_calcWinningsParams))
|
||||
winnings, netWinnings, reason = winningCalc
|
||||
|
||||
userName = self.bot.databaseFuncs.getName(user)
|
||||
userName = self.bot.database_funcs.getName(user)
|
||||
|
||||
if winnings < 0:
|
||||
if winnings == -1:
|
||||
@ -569,7 +569,7 @@ class Blackjack():
|
||||
"""
|
||||
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:
|
||||
oldImage = await channel.fetch_message(int(f.read()))
|
||||
|
||||
@ -604,15 +604,15 @@ class Blackjack():
|
||||
|
||||
if rightRound:
|
||||
if not gamedone:
|
||||
logMessage = f"Loop {gameRound} calling self._blackjackLoop()"
|
||||
self.bot.log(logMessage, str(channel.id))
|
||||
log_message = f"Loop {gameRound} calling self._blackjackLoop()"
|
||||
self.bot.log(log_message, str(channel.id))
|
||||
await self._blackjackLoop(channel, gameRound+1, gameID)
|
||||
else:
|
||||
new_message = self._blackjackFinish(str(channel.id))
|
||||
await channel.send(new_message)
|
||||
else:
|
||||
logMessage = f"Ending loop on round {gameRound}"
|
||||
self.bot.log(logMessage, str(channel.id))
|
||||
log_message = f"Ending loop on round {gameRound}"
|
||||
self.bot.log(log_message, str(channel.id))
|
||||
|
||||
async def hit(self, ctx: discord_slash.context.SlashContext,
|
||||
handNumber: int = 0):
|
||||
@ -640,16 +640,16 @@ class Blackjack():
|
||||
hand, handNumber = self._getHandNumber(userHands, handNumber)
|
||||
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
elif hand["standing"]:
|
||||
logMessage = "They're already standing"
|
||||
log_message = "They're already standing"
|
||||
sendMessage = "You can't hit when you're standing"
|
||||
else:
|
||||
hand["hand"].append(self._drawCard(channel))
|
||||
@ -675,13 +675,13 @@ class Blackjack():
|
||||
roundDone = self._isRoundDone(game)
|
||||
|
||||
sendMessage = f"{ctx.author.display_name} hit"
|
||||
logMessage = "They succeeded"
|
||||
log_message = "They succeeded"
|
||||
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"
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
self.bot.log(logMessage)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if roundDone:
|
||||
gameID = game["gameID"]
|
||||
@ -713,22 +713,22 @@ class Blackjack():
|
||||
hand, handNumber = self._getHandNumber(*handParams)
|
||||
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
elif hand["standing"]:
|
||||
logMessage = "They're already standing"
|
||||
log_message = "They're already standing"
|
||||
sendMessage = "You can't hit when you're standing"
|
||||
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"
|
||||
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"
|
||||
else:
|
||||
bet = hand["bet"]
|
||||
@ -759,16 +759,16 @@ class Blackjack():
|
||||
game = blackjackGames.find_one({"_id": channel})
|
||||
roundDone = self._isRoundDone(game)
|
||||
|
||||
sendMessage = self.bot.longStrings["Blackjack double"]
|
||||
userName = self.bot.databaseFuncs.getName(user)
|
||||
sendMessage = self.bot.long_strings["Blackjack double"]
|
||||
userName = self.bot.database_funcs.getName(user)
|
||||
sendMessage = sendMessage.format(bet, userName)
|
||||
logMessage = "They succeeded"
|
||||
log_message = "They succeeded"
|
||||
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"
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
self.bot.log(logMessage)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if roundDone:
|
||||
gameID = game["gameID"]
|
||||
@ -801,16 +801,16 @@ class Blackjack():
|
||||
|
||||
if hand is None:
|
||||
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:
|
||||
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"]:
|
||||
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"]:
|
||||
sendMessage = "You're already standing"
|
||||
logMessage = "They're already standing"
|
||||
log_message = "They're already standing"
|
||||
else:
|
||||
hand["standing"] = True
|
||||
|
||||
@ -829,14 +829,14 @@ class Blackjack():
|
||||
roundDone = self._isRoundDone(game)
|
||||
|
||||
sendMessage = f"{ctx.author.display_name} is standing"
|
||||
logMessage = "They succeeded"
|
||||
log_message = "They succeeded"
|
||||
|
||||
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"
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
self.bot.log(logMessage)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if roundDone:
|
||||
gameID = game["gameID"]
|
||||
@ -887,33 +887,33 @@ class Blackjack():
|
||||
otherHand = 4
|
||||
|
||||
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"
|
||||
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"
|
||||
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"
|
||||
elif hand["hit"]:
|
||||
logMessage = "They've already hit"
|
||||
log_message = "They've already hit"
|
||||
sendMessage = "You've already hit or split this hand."
|
||||
elif hand["standing"]:
|
||||
logMessage = "They're already standing"
|
||||
log_message = "They're already standing"
|
||||
sendMessage = "You're already standing"
|
||||
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"
|
||||
else:
|
||||
firstCard = self._calcHandValue([hand["hand"][0]])
|
||||
secondCard = self._calcHandValue([hand["hand"][1]])
|
||||
if firstCard != secondCard:
|
||||
logMessage = "They tried to split two different cards"
|
||||
sendMessage = self.bot.longStrings["Blackjack different cards"]
|
||||
log_message = "They tried to split two different cards"
|
||||
sendMessage = self.bot.long_strings["Blackjack different cards"]
|
||||
else:
|
||||
bet = hand["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"
|
||||
else:
|
||||
self.bot.money.addMoney(user, -1 * bet)
|
||||
@ -972,13 +972,13 @@ class Blackjack():
|
||||
game = blackjackGames.find_one({"_id": channel})
|
||||
roundDone = self._isRoundDone(game)
|
||||
|
||||
sendMessage = self.bot.longStrings["Blackjack split"]
|
||||
userName = self.bot.databaseFuncs.getName(user)
|
||||
sendMessage = self.bot.long_strings["Blackjack split"]
|
||||
userName = self.bot.database_funcs.getName(user)
|
||||
sendMessage = sendMessage.format(userName)
|
||||
logMessage = "They succeeded"
|
||||
log_message = "They succeeded"
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
self.bot.log(logMessage)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if roundDone:
|
||||
gameID = game["gameID"]
|
||||
@ -1002,28 +1002,28 @@ class Blackjack():
|
||||
user = f"#{ctx.author.id}"
|
||||
collection = self.bot.database["blackjack games"]
|
||||
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")
|
||||
|
||||
if game is None:
|
||||
sendMessage = "There is no game going on in this channel"
|
||||
logMessage = sendMessage
|
||||
log_message = sendMessage
|
||||
elif user in game["user hands"]:
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
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:
|
||||
sendMessage = "You don't have enough GwendoBucks"
|
||||
logMessage = "They didn't have enough GwendoBucks"
|
||||
log_message = "They didn't have enough GwendoBucks"
|
||||
else:
|
||||
self.bot.money.addMoney(user, -1 * bet)
|
||||
playerHand = [self._drawCard(channel) for _ in range(2)]
|
||||
@ -1048,9 +1048,9 @@ class Blackjack():
|
||||
enterGameText = "entered the game with a bet of"
|
||||
betText = f"{bet} GwendoBucks"
|
||||
sendMessage = f"{userName} {enterGameText} {betText}"
|
||||
logMessage = sendMessage
|
||||
log_message = sendMessage
|
||||
|
||||
self.bot.log(logMessage)
|
||||
self.bot.log(log_message)
|
||||
await ctx.send(sendMessage)
|
||||
|
||||
async def start(self, ctx: discord_slash.context.SlashContext):
|
||||
@ -1109,7 +1109,7 @@ class Blackjack():
|
||||
gameStarted = True
|
||||
|
||||
if gameStarted:
|
||||
sendMessage = self.bot.longStrings["Blackjack started"]
|
||||
sendMessage = self.bot.long_strings["Blackjack started"]
|
||||
await ctx.channel.send(sendMessage)
|
||||
|
||||
tableImagesPath = "resources/games/blackjackTables/"
|
||||
@ -1117,7 +1117,7 @@ class Blackjack():
|
||||
|
||||
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))
|
||||
|
||||
await asyncio.sleep(30)
|
||||
@ -1142,7 +1142,7 @@ class Blackjack():
|
||||
new_message = self._blackjackFinish(channel)
|
||||
await ctx.channel.send(new_message)
|
||||
else:
|
||||
sendMessage = self.bot.longStrings["Blackjack going on"]
|
||||
sendMessage = self.bot.long_strings["Blackjack going on"]
|
||||
await ctx.channel.send(sendMessage)
|
||||
self.bot.log("There was already a game going on")
|
||||
|
||||
@ -1267,7 +1267,7 @@ class DrawBlackjack():
|
||||
|
||||
for x in range(len(hands)):
|
||||
key, value = list(hands.items())[x]
|
||||
key = self.bot.databaseFuncs.getName(key)
|
||||
key = self.bot.database_funcs.getName(key)
|
||||
handParams = [
|
||||
value["hand"],
|
||||
False,
|
||||
|
@ -73,8 +73,8 @@ class ConnectFour():
|
||||
canStart = True
|
||||
|
||||
if game is not None:
|
||||
sendMessage = self.bot.longStrings["Connect 4 going on"]
|
||||
logMessage = "There was already a game going on"
|
||||
sendMessage = self.bot.long_strings["Connect 4 going on"]
|
||||
log_message = "There was already a game going on"
|
||||
canStart = False
|
||||
elif type(opponent) == int:
|
||||
# Opponent is Gwendolyn
|
||||
@ -84,7 +84,7 @@ class ConnectFour():
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
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
|
||||
elif type(opponent) == discord.User:
|
||||
if opponent.bot:
|
||||
@ -96,7 +96,7 @@ class ConnectFour():
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
sendMessage = "You can't challenge a bot!"
|
||||
logMessage = "They tried to challenge a bot"
|
||||
log_message = "They tried to challenge a bot"
|
||||
canStart = False
|
||||
else:
|
||||
# Opponent is another player
|
||||
@ -106,7 +106,7 @@ class ConnectFour():
|
||||
diffText = ""
|
||||
else:
|
||||
sendMessage = "You can't play against yourself"
|
||||
logMessage = "They tried to play against themself"
|
||||
log_message = "They tried to play against themself"
|
||||
canStart = False
|
||||
|
||||
if canStart:
|
||||
@ -133,15 +133,15 @@ class ConnectFour():
|
||||
gwendoTurn = (players[0] == f"#{self.bot.user.id}")
|
||||
startedGame = True
|
||||
|
||||
opponentName = self.bot.databaseFuncs.getName(opponent)
|
||||
turnName = self.bot.databaseFuncs.getName(players[0])
|
||||
opponentName = self.bot.database_funcs.getName(opponent)
|
||||
turnName = self.bot.database_funcs.getName(players[0])
|
||||
|
||||
startedText = f"Started game against {opponentName}{diffText}."
|
||||
turnText = f"It's {turnName}'s turn"
|
||||
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)
|
||||
|
||||
# Sets the whole game in motion
|
||||
@ -150,13 +150,13 @@ class ConnectFour():
|
||||
filePath = f"{boardsPath}board{ctx.channel_id}.png"
|
||||
oldImage = await ctx.channel.send(file=discord.File(filePath))
|
||||
|
||||
oldImagesPath = "resources/games/oldImages/"
|
||||
oldImagePath = f"{oldImagesPath}connectFour{ctx.channel_id}"
|
||||
old_imagesPath = "resources/games/old_images/"
|
||||
oldImagePath = f"{old_imagesPath}connect_four{ctx.channel_id}"
|
||||
with open(oldImagePath, "w") as f:
|
||||
f.write(str(oldImage.id))
|
||||
|
||||
if gwendoTurn:
|
||||
await self._connectFourAI(ctx)
|
||||
await self._connect_fourAI(ctx)
|
||||
else:
|
||||
for reaction in self.REACTIONS:
|
||||
await oldImage.add_reaction(reaction)
|
||||
@ -183,19 +183,19 @@ class ConnectFour():
|
||||
connect4Games = self.bot.database["connect 4 games"]
|
||||
game = connect4Games.find_one({"_id": channel})
|
||||
playerNumber = game["players"].index(user)+1
|
||||
userName = self.bot.databaseFuncs.getName(user)
|
||||
userName = self.bot.database_funcs.getName(user)
|
||||
placedPiece = False
|
||||
|
||||
if game is None:
|
||||
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:
|
||||
board = game["board"]
|
||||
board = self._placeOnBoard(board, playerNumber, column)
|
||||
|
||||
if board is None:
|
||||
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:
|
||||
updater = {"$set": {"board": board}}
|
||||
connect4Games.update_one({"_id": channel}, updater)
|
||||
@ -217,7 +217,7 @@ class ConnectFour():
|
||||
|
||||
sendMessage = "{} placed a piece in column {} and won. "
|
||||
sendMessage = sendMessage.format(userName, column+1)
|
||||
logMessage = f"{userName} won"
|
||||
log_message = f"{userName} won"
|
||||
winAmount = int(game["difficulty"])**2+5
|
||||
if game["players"][won-1] != f"#{self.bot.user.id}":
|
||||
sendMessage += "Adding {} GwendoBucks to their account"
|
||||
@ -225,27 +225,27 @@ class ConnectFour():
|
||||
elif 0 not in board[0]:
|
||||
gameWon = True
|
||||
sendMessage = "It's a draw!"
|
||||
logMessage = "The game ended in a draw"
|
||||
log_message = "The game ended in a draw"
|
||||
else:
|
||||
gameWon = False
|
||||
otherUserId = game["players"][turn]
|
||||
otherUserName = self.bot.databaseFuncs.getName(otherUserId)
|
||||
sendMessage = self.bot.longStrings["Connect 4 placed"]
|
||||
otherUserName = self.bot.database_funcs.getName(otherUserId)
|
||||
sendMessage = self.bot.long_strings["Connect 4 placed"]
|
||||
formatParams = [userName, column+1, otherUserName]
|
||||
sendMessage = sendMessage.format(*formatParams)
|
||||
logMessage = "They placed the piece"
|
||||
log_message = "They placed the piece"
|
||||
|
||||
gwendoTurn = (game["players"][turn] == f"#{self.bot.user.id}")
|
||||
|
||||
placedPiece = True
|
||||
|
||||
await ctx.channel.send(sendMessage)
|
||||
self.bot.log(logMessage)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if placedPiece:
|
||||
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:
|
||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
||||
|
||||
@ -263,7 +263,7 @@ class ConnectFour():
|
||||
with open(oldImagePath, "w") as f:
|
||||
f.write(str(oldImage.id))
|
||||
if gwendoTurn:
|
||||
await self._connectFourAI(ctx)
|
||||
await self._connect_fourAI(ctx)
|
||||
else:
|
||||
for reaction in self.REACTIONS:
|
||||
await oldImage.add_reaction(reaction)
|
||||
@ -285,7 +285,7 @@ class ConnectFour():
|
||||
loserIndex = game["players"].index(f"#{ctx.author.id}")
|
||||
winnerIndex = (loserIndex+1) % 2
|
||||
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" This means {winnerName} is the winner."
|
||||
@ -295,7 +295,7 @@ class ConnectFour():
|
||||
sendMessage += f" Adding {reward} to their account"
|
||||
|
||||
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:
|
||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
||||
|
||||
@ -353,7 +353,7 @@ class ConnectFour():
|
||||
reward = difficulty**2 + 5
|
||||
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):
|
||||
won = 0
|
||||
@ -429,7 +429,7 @@ class ConnectFour():
|
||||
|
||||
return won, winDirection, winCoordinates
|
||||
|
||||
async def _connectFourAI(self, ctx: SlashContext):
|
||||
async def _connect_fourAI(self, ctx: SlashContext):
|
||||
def outOfRange(possibleScores: list):
|
||||
allowedRange = max(possibleScores)*(1-0.1)
|
||||
moreThanOne = len(possibleScores) != 1
|
||||
@ -1023,12 +1023,12 @@ class DrawConnectFour():
|
||||
if game["players"][0] == "Gwendolyn":
|
||||
player1 = "Gwendolyn"
|
||||
else:
|
||||
player1 = self.bot.databaseFuncs.getName(game["players"][0])
|
||||
player1 = self.bot.database_funcs.getName(game["players"][0])
|
||||
|
||||
if game["players"][1] == "Gwendolyn":
|
||||
player2 = "Gwendolyn"
|
||||
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.BOTTOMBORDER+self.BORDER)//2 - self.TEXTSIZE//2
|
@ -11,7 +11,7 @@ Has a container for game functions.
|
||||
from .invest import Invest
|
||||
from .trivia import Trivia
|
||||
from .blackjack import Blackjack
|
||||
from .connectFour import ConnectFour
|
||||
from .connect_four import ConnectFour
|
||||
from .hangman import Hangman
|
||||
from .hex import HexGame
|
||||
|
||||
@ -28,7 +28,7 @@ class Games():
|
||||
Contains investment functions.
|
||||
blackjack
|
||||
Contains blackjack functions.
|
||||
connectFour
|
||||
connect_four
|
||||
Contains connect four functions.
|
||||
hangman
|
||||
Contains hangman functions.
|
||||
@ -43,6 +43,6 @@ class Games():
|
||||
self.invest = Invest(bot)
|
||||
self.trivia = Trivia(bot)
|
||||
self.blackjack = Blackjack(bot)
|
||||
self.connectFour = ConnectFour(bot)
|
||||
self.connect_four = ConnectFour(bot)
|
||||
self.hangman = Hangman(bot)
|
||||
self.hex = HexGame(bot)
|
@ -72,7 +72,7 @@ class Hangman():
|
||||
channel = str(ctx.channel_id)
|
||||
user = f"#{ctx.author.id}"
|
||||
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
|
||||
|
||||
if game is None:
|
||||
@ -99,14 +99,14 @@ class Hangman():
|
||||
|
||||
self.__draw.drawImage(channel)
|
||||
|
||||
logMessage = "Game started"
|
||||
log_message = "Game started"
|
||||
sendMessage = f"{userName} started game of hangman."
|
||||
startedGame = True
|
||||
else:
|
||||
logMessage = "There was already a game going on"
|
||||
sendMessage = self.__bot.longStrings["Hangman going on"]
|
||||
log_message = "There was already a game going on"
|
||||
sendMessage = self.__bot.long_strings["Hangman going on"]
|
||||
|
||||
self.__bot.log(logMessage)
|
||||
self.__bot.log(log_message)
|
||||
await ctx.send(sendMessage)
|
||||
|
||||
if startedGame:
|
||||
@ -122,7 +122,7 @@ class Hangman():
|
||||
|
||||
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)
|
||||
|
||||
for message, letters in reactionMessages.items():
|
||||
@ -149,7 +149,7 @@ class Hangman():
|
||||
else:
|
||||
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()
|
||||
|
||||
for message in messages:
|
||||
@ -216,17 +216,17 @@ class Hangman():
|
||||
|
||||
if game["misses"] == 6:
|
||||
hangmanGames.delete_one({"_id": channel})
|
||||
sendMessage += self.__bot.longStrings["Hangman lost game"]
|
||||
sendMessage += self.__bot.long_strings["Hangman lost game"]
|
||||
remainingLetters = []
|
||||
elif all(game["guessed"]):
|
||||
hangmanGames.delete_one({"_id": channel})
|
||||
self.__bot.money.addMoney(user, 15)
|
||||
sendMessage += self.__bot.longStrings["Hangman guessed word"]
|
||||
sendMessage += self.__bot.long_strings["Hangman guessed word"]
|
||||
remainingLetters = []
|
||||
|
||||
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()
|
||||
|
||||
for oldID in oldMessageIDs:
|
||||
@ -254,7 +254,7 @@ class Hangman():
|
||||
else:
|
||||
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:
|
||||
f.write(oldMessages)
|
||||
|
||||
|
@ -28,11 +28,11 @@ class HexGame():
|
||||
await ctx.send("You can't surrender when you're not a player.")
|
||||
else:
|
||||
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}})
|
||||
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()))
|
||||
|
||||
if oldImage is not None:
|
||||
@ -44,7 +44,7 @@ class HexGame():
|
||||
filePath = f"resources/games/hexBoards/board{channel}.png"
|
||||
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))
|
||||
|
||||
self.bot.database["hex games"].delete_one({"_id":channel})
|
||||
@ -72,10 +72,10 @@ class HexGame():
|
||||
|
||||
opponent = game["players"][::-1][game["turn"]-1]
|
||||
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")
|
||||
|
||||
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()))
|
||||
|
||||
if oldImage is not None:
|
||||
@ -87,7 +87,7 @@ class HexGame():
|
||||
filePath = f"resources/games/hexBoards/board{channel}.png"
|
||||
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))
|
||||
|
||||
if gwendoTurn:
|
||||
@ -105,7 +105,7 @@ class HexGame():
|
||||
|
||||
if game != None:
|
||||
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
|
||||
else:
|
||||
if type(opponent) == int:
|
||||
@ -117,7 +117,7 @@ class HexGame():
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
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
|
||||
|
||||
elif type(opponent) == discord.member.Member:
|
||||
@ -131,7 +131,7 @@ class HexGame():
|
||||
opponent = f"#{self.bot.user.id}"
|
||||
else:
|
||||
sendMessage = "You can't challenge a bot!"
|
||||
logMessage = "They tried to challenge a bot"
|
||||
log_message = "They tried to challenge a bot"
|
||||
canStart = False
|
||||
else:
|
||||
# Opponent is another player
|
||||
@ -142,11 +142,11 @@ class HexGame():
|
||||
diffText = ""
|
||||
else:
|
||||
sendMessage = "You can't play against yourself"
|
||||
logMessage = "They tried to play against themself"
|
||||
log_message = "They tried to play against themself"
|
||||
canStart = False
|
||||
else:
|
||||
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"
|
||||
|
||||
if canStart:
|
||||
@ -167,18 +167,18 @@ class HexGame():
|
||||
gwendoTurn = (players[0] == f"#{self.bot.user.id}")
|
||||
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"
|
||||
logMessage = "Game started"
|
||||
log_message = "Game started"
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
self.bot.log(logMessage)
|
||||
self.bot.log(log_message)
|
||||
|
||||
if startedGame:
|
||||
filePath = f"resources/games/hexBoards/board{ctx.channel_id}.png"
|
||||
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))
|
||||
|
||||
if gwendoTurn:
|
||||
@ -199,7 +199,7 @@ class HexGame():
|
||||
else:
|
||||
players = game["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")
|
||||
elif players[game["turn"]-1] != user:
|
||||
sendMessage = "It's not your turn"
|
||||
@ -228,12 +228,12 @@ class HexGame():
|
||||
|
||||
if winner == 0: # Continue with the game.
|
||||
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!
|
||||
gameWon = True
|
||||
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}":
|
||||
winAmount = game["difficulty"]*10
|
||||
sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account."
|
||||
@ -258,7 +258,7 @@ class HexGame():
|
||||
# Update the board
|
||||
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()))
|
||||
|
||||
if oldImage is not None:
|
||||
@ -281,7 +281,7 @@ class HexGame():
|
||||
|
||||
self.bot.database["hex games"].delete_one({"_id":channel})
|
||||
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))
|
||||
|
||||
if gwendoTurn:
|
||||
@ -321,7 +321,7 @@ class HexGame():
|
||||
sendMessage = "It's not your turn"
|
||||
else:
|
||||
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()
|
||||
game["board"][lastMove[0]][lastMove[1]] = 0
|
||||
@ -337,7 +337,7 @@ class HexGame():
|
||||
|
||||
await ctx.send(sendMessage)
|
||||
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()))
|
||||
|
||||
if oldImage is not None:
|
||||
@ -349,7 +349,7 @@ class HexGame():
|
||||
filePath = f"resources/games/hexBoards/board{channel}.png"
|
||||
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))
|
||||
|
||||
|
||||
@ -556,7 +556,7 @@ class DrawHex():
|
||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||
|
||||
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
|
||||
x = self.XNAME[p]
|
||||
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
|
||||
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.NAMEFONT.getsize(playername)[0] if p==2 else 0 # player2's name is right-aligned
|
||||
|
@ -42,7 +42,7 @@ class Invest():
|
||||
price: int
|
||||
The price of the stock.
|
||||
"""
|
||||
res = self.bot.finnhubClient.quote(symbol.upper())
|
||||
res = self.bot.finnhub_client.quote(symbol.upper())
|
||||
if res == {}:
|
||||
return 0
|
||||
else:
|
||||
@ -65,7 +65,7 @@ class Invest():
|
||||
investmentsDatabase = self.bot.database["investments"]
|
||||
userInvestments = investmentsDatabase.find_one({"_id": user})
|
||||
|
||||
userName = self.bot.databaseFuncs.getName(user)
|
||||
userName = self.bot.database_funcs.getName(user)
|
||||
|
||||
if userInvestments in [None, {}]:
|
||||
return f"{userName} does not have a stock portfolio."
|
||||
@ -162,7 +162,7 @@ class Invest():
|
||||
}
|
||||
investmentsDatabase.insert_one(newUser)
|
||||
|
||||
userName = self.bot.databaseFuncs.getName(user)
|
||||
userName = self.bot.database_funcs.getName(user)
|
||||
sendMessage = "{} bought {} GwendoBucks worth of {} stock"
|
||||
sendMessage = sendMessage.format(userName, buyAmount, stock)
|
||||
return sendMessage
|
||||
@ -219,7 +219,7 @@ class Invest():
|
||||
updater = {"$unset": {f"investments.{stock}": ""}}
|
||||
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"
|
||||
return sendMessage.format(userName, sellAmount, stock)
|
||||
else:
|
||||
@ -252,7 +252,7 @@ class Invest():
|
||||
response = response.format(commands[0].upper())
|
||||
else:
|
||||
price = f"{price:,}".replace(",", ".")
|
||||
response = self.bot.longStrings["Stock value"]
|
||||
response = self.bot.long_strings["Stock value"]
|
||||
response = response.format(commands[1].upper(), price)
|
||||
|
||||
elif parameters.startswith("buy"):
|
||||
@ -260,14 +260,14 @@ class Invest():
|
||||
if len(commands) == 3:
|
||||
response = self.buyStock(user, commands[1], int(commands[2]))
|
||||
else:
|
||||
response = self.bot.longStrings["Stock parameters"]
|
||||
response = self.bot.long_strings["Stock parameters"]
|
||||
|
||||
elif parameters.startswith("sell"):
|
||||
commands = parameters.split(" ")
|
||||
if len(commands) == 3:
|
||||
response = self.sellStock(user, commands[1], int(commands[2]))
|
||||
else:
|
||||
response = self.bot.longStrings["Stock parameters"]
|
||||
response = self.bot.long_strings["Stock parameters"]
|
||||
|
||||
else:
|
||||
response = "Incorrect parameters"
|
||||
@ -280,7 +280,7 @@ class Invest():
|
||||
"description": text,
|
||||
"colour": 0x00FF00
|
||||
}
|
||||
em = discord.Embed(*embedParams)
|
||||
em = discord.Embed(**embedParams)
|
||||
await ctx.send(embed=em)
|
||||
else:
|
||||
await ctx.send(response)
|
||||
|
@ -98,7 +98,7 @@ class Money():
|
||||
else:
|
||||
newUser = {
|
||||
"_id": user,
|
||||
"user name": self.bot.databaseFuncs.getName(user),
|
||||
"user name": self.bot.database_funcs.getName(user),
|
||||
"money": amount
|
||||
}
|
||||
self.database["users"].insert_one(newUser)
|
||||
@ -120,7 +120,7 @@ class Money():
|
||||
"""
|
||||
await self.bot.defer(ctx)
|
||||
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):
|
||||
if member.display_name.lower() == username.lower():
|
||||
username = member.display_name
|
||||
@ -134,7 +134,7 @@ class Money():
|
||||
|
||||
userid = f"#{ctx.author.id}"
|
||||
userData = self.database["users"].find_one({"_id": userid})
|
||||
targetUser = self.bot.databaseFuncs.getID(username)
|
||||
targetUser = self.bot.database_funcs.getID(username)
|
||||
|
||||
if amount <= 0:
|
||||
self.bot.log("They tried to steal")
|
||||
|
@ -91,9 +91,9 @@ class Trivia():
|
||||
|
||||
return question, answers, correctAnswer
|
||||
else:
|
||||
logMessage = "There was already a trivia question for that channel"
|
||||
self.bot.log(logMessage)
|
||||
return self.bot.longStrings["Trivia going on"], "", ""
|
||||
log_message = "There was already a trivia question for that channel"
|
||||
self.bot.log(log_message)
|
||||
return self.bot.long_strings["Trivia going on"], "", ""
|
||||
|
||||
def triviaAnswer(self, user: str, channel: str, command: str):
|
||||
"""
|
||||
@ -182,10 +182,10 @@ class Trivia():
|
||||
self.triviaCountPoints(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)
|
||||
sendMessage = self.bot.longStrings["Trivia time up"]
|
||||
sendMessage = self.bot.long_strings["Trivia time up"]
|
||||
formatParams = [chr(correctAnswer), options[correctAnswer-97]]
|
||||
sendMessage = sendMessage.format(*formatParams)
|
||||
await ctx.send(sendMessage)
|
||||
|
@ -2,4 +2,4 @@
|
||||
|
||||
__all__ = ["LookupFuncs"]
|
||||
|
||||
from .lookupFuncs import LookupFuncs
|
||||
from .lookup_funcs import LookupFuncs
|
@ -64,7 +64,7 @@ class Generators():
|
||||
if random.randint(1,10) > 1:
|
||||
try:
|
||||
new_letter = random.choice(letter_dict[chain[-2]+chain[-1]])
|
||||
except:
|
||||
except KeyError():
|
||||
new_letter = random.choice(letter_dict[chain[-1]])
|
||||
else:
|
||||
new_letter = random.choice(letter_dict[chain[-1]])
|
||||
|
@ -2,4 +2,4 @@
|
||||
|
||||
__all__ = ["StarWars"]
|
||||
|
||||
from .starWars import StarWars
|
||||
from .star_wars import StarWars
|
@ -1,6 +1,6 @@
|
||||
from .starWarsChar import StarWarsChar
|
||||
from .starWarsRoll import StarWarsRoll
|
||||
from .starWarsDestiny import StarWarsDestiny
|
||||
from .star_wars_char import StarWarsChar
|
||||
from .star_wars_roll import StarWarsRoll
|
||||
from .star_wars_destiny import StarWarsDestiny
|
||||
|
||||
class StarWars():
|
||||
def __init__(self, bot):
|
@ -7,15 +7,15 @@ class StarWarsChar():
|
||||
self.bot = bot
|
||||
|
||||
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})
|
||||
|
||||
if userCharacter != None:
|
||||
self.bot.log("Name is "+userCharacter["Name"])
|
||||
return userCharacter["Name"]
|
||||
else:
|
||||
self.bot.log("Just using "+self.bot.databaseFuncs.getName(user))
|
||||
return self.bot.databaseFuncs.getName(user)
|
||||
self.bot.log("Just using "+self.bot.database_funcs.getName(user))
|
||||
return self.bot.database_funcs.getName(user)
|
||||
|
||||
def setUpDict(self, cmd : dict):
|
||||
self.bot.log("Setting up a dictionary in a nice way")
|
||||
@ -252,7 +252,7 @@ class StarWarsChar():
|
||||
if cmd == "":
|
||||
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:
|
||||
self.bot.log("Found it! Looking for "+key+" in the data")
|
||||
if key in userCharacter:
|
||||
@ -303,7 +303,7 @@ class StarWarsChar():
|
||||
return cmd[0]+" added to "+key+" for " + userCharacter["Name"]
|
||||
|
||||
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)
|
||||
newWeapon = templates["Weapon"]
|
||||
self.bot.log("Adding "+cmd+" to "+key)
|
||||
@ -495,18 +495,18 @@ class StarWarsChar():
|
||||
text = self.replaceWithSpaces(text)
|
||||
returnEmbed = True
|
||||
else:
|
||||
self.bot.log("Makin' a character for "+self.bot.databaseFuncs.getName(user))
|
||||
with open("resources/starWars/starwarstemplates.json", "r") as f:
|
||||
self.bot.log("Makin' a character for "+self.bot.database_funcs.getName(user))
|
||||
with open("resources/star_wars/starwarstemplates.json", "r") as f:
|
||||
templates = json.load(f)
|
||||
newChar = templates["Character"]
|
||||
newChar["_id"] = user
|
||||
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:
|
||||
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})
|
||||
await ctx.send("Character for " + self.bot.databaseFuncs.getName(user) + " deleted")
|
||||
await ctx.send("Character for " + self.bot.database_funcs.getName(user) + " deleted")
|
||||
else:
|
||||
await ctx.send(self.replaceWithSpaces(str(self.charData(user,cmd))))
|
||||
|
@ -4,16 +4,16 @@ class StarWarsDestiny():
|
||||
|
||||
def destinyNew(self, num : int):
|
||||
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))
|
||||
|
||||
with open("resources/starWars/destinyPoints.txt","wt") as f:
|
||||
with open("resources/star_wars/destinyPoints.txt","wt") as f:
|
||||
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):
|
||||
with open("resources/starWars/destinyPoints.txt","rt") as f:
|
||||
with open("resources/star_wars/destinyPoints.txt","rt") as f:
|
||||
points = f.read()
|
||||
|
||||
if user == "Nikolaj":
|
||||
@ -21,10 +21,10 @@ class StarWarsDestiny():
|
||||
if 'B' in points:
|
||||
points = points.replace("B","L",1)
|
||||
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)
|
||||
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:
|
||||
self.bot.log("There were no dark side destiny points")
|
||||
return "No dark side destiny points"
|
||||
@ -33,10 +33,10 @@ class StarWarsDestiny():
|
||||
if 'L' in points:
|
||||
points = points.replace("L","B",1)
|
||||
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)
|
||||
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:
|
||||
self.bot.log("There were no dark side destiny points")
|
||||
return "No light side destiny points"
|
||||
@ -51,8 +51,8 @@ class StarWarsDestiny():
|
||||
|
||||
if cmd == "":
|
||||
self.bot.log("Retrieving destiny pool info")
|
||||
with open("resources/starWars/destinyPoints.txt","rt") as f:
|
||||
sendMessage = self.bot.starWars.roll.resultToEmoji(f.read())
|
||||
with open("resources/star_wars/destinyPoints.txt","rt") as f:
|
||||
sendMessage = self.bot.star_wars.roll.resultToEmoji(f.read())
|
||||
else:
|
||||
commands = cmd.upper().split(" ")
|
||||
if commands[0] == "N":
|
@ -3,7 +3,7 @@ import re
|
||||
import string
|
||||
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)
|
||||
|
||||
class StarWarsRoll():
|
||||
@ -302,7 +302,7 @@ class StarWarsRoll():
|
||||
cmd = re.sub(' +',' ',cmd.upper()) + " "
|
||||
if cmd[0] == " ":
|
||||
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(" ")
|
||||
validCommand = False
|
||||
|
||||
@ -316,15 +316,15 @@ class StarWarsRoll():
|
||||
|
||||
elif string.capwords(commands[0]) in skillData:
|
||||
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")
|
||||
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":
|
||||
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:
|
||||
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)
|
||||
proficiencyDice = min(skillLevel,charLevel)
|
||||
@ -372,7 +372,7 @@ class StarWarsRoll():
|
||||
|
||||
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")
|
||||
|
@ -5,20 +5,21 @@ Contains the Gwendolyn class, and runs it when run as script.
|
||||
---------
|
||||
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 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_slash # Used to initialized SlashCommands object
|
||||
|
||||
from discord.ext import commands # Used to inherit from commands.bot
|
||||
from pymongo import MongoClient # Used for database management
|
||||
from funcs import Money, StarWars, Games, Other, LookupFuncs
|
||||
from utils import (Options, Credentials, logThis, makeFiles, databaseFuncs,
|
||||
EventHandler, ErrorHandler, longStrings)
|
||||
from utils import (Options, Credentials, logThis, makeFiles, DatabaseFuncs,
|
||||
EventHandler, ErrorHandler, long_strings)
|
||||
|
||||
|
||||
class Gwendolyn(commands.Bot):
|
||||
@ -37,66 +38,66 @@ class Gwendolyn(commands.Bot):
|
||||
"""Initialize the bot."""
|
||||
intents = discord.Intents.default()
|
||||
intents.members = True
|
||||
initParams = {
|
||||
initiation_parameters = {
|
||||
"command_prefix": " ",
|
||||
"case_insensitive": True,
|
||||
"intents": intents,
|
||||
"status": discord.Status.dnd
|
||||
}
|
||||
super().__init__(**initParams)
|
||||
super().__init__(**initiation_parameters)
|
||||
|
||||
self._addClientsAndOptions()
|
||||
self._addUtilClasses()
|
||||
self._addFunctionContainers()
|
||||
self._addCogs()
|
||||
self._add_clients_and_options()
|
||||
self._add_util_classes()
|
||||
self._add_function_containers()
|
||||
self._add_cogs()
|
||||
|
||||
def _addClientsAndOptions(self):
|
||||
def _add_clients_and_options(self):
|
||||
"""Add all the client, option and credentials objects."""
|
||||
self.longStrings = longStrings()
|
||||
self.long_strings = long_strings()
|
||||
self.options = Options()
|
||||
self.credentials = Credentials()
|
||||
finnhubKey = self.credentials.finnhubKey
|
||||
self.finnhubClient = finnhub.Client(api_key=finnhubKey)
|
||||
mongoUser = self.credentials.mongoDBUser
|
||||
mongoPassword = self.credentials.mongoDBPassword
|
||||
mongoLink = f"mongodb+srv://{mongoUser}:{mongoPassword}@gwendolyn"
|
||||
mongoLink += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority"
|
||||
dataBaseClient = MongoClient(mongoLink)
|
||||
finnhub_key = self.credentials.finnhub_key
|
||||
self.finnhub_client = finnhub.Client(api_key=finnhub_key)
|
||||
mongo_user = self.credentials.mongoDBUser
|
||||
mongo_password = self.credentials.mongoDBPassword
|
||||
mongo_url = f"mongodb+srv://{mongo_user}:{mongo_password}@gwendolyn"
|
||||
mongo_url += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority"
|
||||
database_clint = MongoClient(mongo_url)
|
||||
|
||||
if self.options.testing:
|
||||
self.log("Testing mode")
|
||||
self.database = dataBaseClient["Gwendolyn-Test"]
|
||||
self.database = database_clint["Gwendolyn-Test"]
|
||||
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."""
|
||||
self.databaseFuncs = databaseFuncs(self)
|
||||
self.eventHandler = EventHandler(self)
|
||||
self.errorHandler = ErrorHandler(self)
|
||||
slashParams = {
|
||||
self.database_funcs = DatabaseFuncs(self)
|
||||
self.event_handler = EventHandler(self)
|
||||
self.error_handler = ErrorHandler(self)
|
||||
slash_parameters = {
|
||||
"sync_commands": True,
|
||||
"sync_on_cog_reload": 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."""
|
||||
self.starWars = StarWars(self)
|
||||
self.star_wars = StarWars(self)
|
||||
self.other = Other(self)
|
||||
self.lookupFuncs = LookupFuncs(self)
|
||||
self.lookup_funcs = LookupFuncs(self)
|
||||
self.games = Games(self)
|
||||
self.money = Money(self)
|
||||
|
||||
def _addCogs(self):
|
||||
def _add_cogs(self):
|
||||
"""Load cogs."""
|
||||
for filename in os.listdir("./cogs"):
|
||||
if filename.endswith(".py"):
|
||||
self.load_extension(f"cogs.{filename[:-3]}")
|
||||
|
||||
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)
|
||||
|
||||
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)
|
||||
|
||||
self.databaseFuncs.wipeGames()
|
||||
self.database_funcs.wipeGames()
|
||||
|
||||
self.log("Logging out", level=25)
|
||||
await self.close()
|
||||
else:
|
||||
logMessage = f"{ctx.author.display_name} tried to stop me!"
|
||||
self.log(logMessage, str(ctx.channel_id))
|
||||
log_message = f"{ctx.author.display_name} tried to stop me!"
|
||||
self.log(log_message, str(ctx.channel_id))
|
||||
await ctx.send(f"I don't think I will, {ctx.author.display_name}")
|
||||
|
||||
async def defer(self, ctx: discord_slash.context.SlashContext):
|
||||
@ -146,5 +147,5 @@ if __name__ == "__main__":
|
||||
try:
|
||||
# Runs the whole shabang
|
||||
bot.run(bot.credentials.token)
|
||||
except Exception:
|
||||
bot.log(bot.longStrings["Can't log in"])
|
||||
except Exception as exception: # pylint: disable=broad-except
|
||||
bot.log(bot.long_strings[f"Can't log in: {repr(exception)}"])
|
@ -42,8 +42,8 @@ Comments, strings, variable names, class names, docstrings, as well as all other
|
||||
# Code
|
||||
|
||||
## Code Style
|
||||
All the Python code should follow the [PEP 8 guidelines](https://www.python.org/dev/peps/pep-0008/), with the following differences:
|
||||
+ Variable and function names must be camelCase, and must fully consist of either full words or common/understandable abbreviations.
|
||||
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 fully consist of either full words or common/understandable abbreviations.
|
||||
+ Use f-strings when applicable.
|
||||
|
||||
### Documentation
|
||||
|
1
resources/games/oldImages/blackjack740652054388932682
Normal file
1
resources/games/oldImages/blackjack740652054388932682
Normal file
@ -0,0 +1 @@
|
||||
854063181868695593
|
2
resources/games/oldImages/hangman740652054388932682
Normal file
2
resources/games/oldImages/hangman740652054388932682
Normal file
@ -0,0 +1,2 @@
|
||||
854064833909489734
|
||||
854064835040641044
|
1
resources/games/oldImages/hex740652054388932682
Normal file
1
resources/games/oldImages/hex740652054388932682
Normal file
@ -0,0 +1 @@
|
||||
854064794356023346
|
@ -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.
|
1
resources/help/help-star_wars_character.txt
Normal file
1
resources/help/help-star_wars_character.txt
Normal 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.
|
@ -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.
|
@ -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.
|
@ -7,13 +7,13 @@
|
||||
`/name` - Genererer et tilfældigt navn.
|
||||
`/tavern` - Genererer en tilfældig tavern.
|
||||
`/give` - Lader dig give GwendoBucks til andre.
|
||||
`/starWarsCharacter` - Lader dig lave en Star Wars karakter.
|
||||
`/starWarsRoll` - Lader dig rulle Star Wars terninger.
|
||||
`/star_wars_character` - Lader dig lave en Star Wars karakter.
|
||||
`/star_wars_roll` - Lader dig rulle Star Wars terninger.
|
||||
`/balance` - Viser dig hvor mange GwendoBucks du har.
|
||||
`/invest` - Lader dig investere dine GwendoBucks i aktiemarkedet.
|
||||
`/blackjack` - Lader dig spille et spil blackjack.
|
||||
`/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.
|
||||
`/hangman` - Lader dig spille et spil hangman.
|
||||
`/wolf` - Lader dig slå ting op på Wolfram Alpha.
|
||||
|
@ -112,8 +112,8 @@
|
||||
"name" : "start",
|
||||
"description" : "Start a game of blackjack"
|
||||
},
|
||||
"connectFourStartGwendolyn" : {
|
||||
"base" : "connectFour",
|
||||
"connect_fourStartGwendolyn" : {
|
||||
"base" : "connect_four",
|
||||
"subcommand_group" : "start",
|
||||
"name" : "Gwendolyn",
|
||||
"description" : "Start a game of connect four against Gwendolyn",
|
||||
@ -126,8 +126,8 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"connectFourStartUser" : {
|
||||
"base" : "connectFour",
|
||||
"connect_fourStartUser" : {
|
||||
"base" : "connect_four",
|
||||
"subcommand_group" : "start",
|
||||
"name" : "user",
|
||||
"description" : "Start a game of connect four against another user",
|
||||
@ -140,8 +140,8 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"connectFourSurrender" : {
|
||||
"base" : "connectFour",
|
||||
"connect_fourSurrender" : {
|
||||
"base" : "connect_four",
|
||||
"name" : "surrender",
|
||||
"description" : "Surrender the game of connect four"
|
||||
},
|
||||
@ -333,8 +333,8 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"starWarsCharacter" : {
|
||||
"name" : "starWarsCharacter",
|
||||
"star_wars_character" : {
|
||||
"name" : "star_wars_character",
|
||||
"description" : "Manage your Star Wars character sheet",
|
||||
"options" : [
|
||||
{
|
||||
@ -345,8 +345,8 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"starWarsCrit" : {
|
||||
"name" : "starWarsCrit",
|
||||
"star_wars_crit" : {
|
||||
"name" : "star_wars_crit",
|
||||
"description" : "Roll a Star Wars critical injury",
|
||||
"options" : [
|
||||
{
|
||||
@ -357,8 +357,8 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"starWarsDestiny" : {
|
||||
"name" : "starWarsDestiny",
|
||||
"star_wars_destiny" : {
|
||||
"name" : "star_wars_destiny",
|
||||
"description" : "Use and see Star Wars Destiny points",
|
||||
"options" : [
|
||||
{
|
||||
@ -369,8 +369,8 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
"starWarsRoll" : {
|
||||
"name" : "starWarsRoll",
|
||||
"star_wars_roll" : {
|
||||
"name" : "star_wars_roll",
|
||||
"description" : "Roll Star Wars dice",
|
||||
"options" : [
|
||||
{
|
||||
|
@ -56,9 +56,9 @@
|
||||
]
|
||||
},
|
||||
"txt": {
|
||||
"resources/starWars/destinyPoints.txt": "",
|
||||
"resources/star_wars/destinyPoints.txt": "",
|
||||
"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",
|
||||
"options.txt" : "Testing: True\nTesting guild ids:\nAdmins:"
|
||||
},
|
||||
@ -69,6 +69,6 @@
|
||||
"resources/games/hexBoards",
|
||||
"resources/games/hangmanBoards",
|
||||
"resources/bedreNetflix",
|
||||
"resources/games/oldImages"
|
||||
"resources/games/old_images"
|
||||
]
|
||||
}
|
@ -1,10 +1,10 @@
|
||||
"""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",
|
||||
"replaceMultiple", "emojiToCommand"]
|
||||
|
||||
from .helperClasses import Options, Credentials, databaseFuncs
|
||||
from .eventHandlers import EventHandler, ErrorHandler
|
||||
from .utilFunctions import (getParams, logThis, cap, makeFiles,
|
||||
replaceMultiple, emojiToCommand, longStrings)
|
||||
from .helper_classes import Options, Credentials, DatabaseFuncs
|
||||
from .event_handlers import EventHandler, ErrorHandler
|
||||
from .util_functions import (getParams, logThis, cap, makeFiles,
|
||||
replaceMultiple, emojiToCommand, long_strings)
|
||||
|
@ -15,7 +15,7 @@ from discord.ext import commands # Used to compare errors with command
|
||||
# errors
|
||||
|
||||
from discord_slash.context import SlashContext
|
||||
from utils.utilFunctions import emojiToCommand
|
||||
from utils.util_functions import emojiToCommand
|
||||
|
||||
|
||||
class EventHandler():
|
||||
@ -35,7 +35,9 @@ class EventHandler():
|
||||
|
||||
async def on_ready(self):
|
||||
"""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
|
||||
userid = str(self.bot.user.id)
|
||||
loggedInMessage = f"Logged in as {name}, {userid}"
|
||||
@ -59,14 +61,14 @@ class EventHandler():
|
||||
|
||||
args = " ".join([str(i) for i in ctx.args])
|
||||
fullCommand = f"/{ctx.command}{subcommand}{subcommandGroup}{args}"
|
||||
logMessage = f"{ctx.author.display_name} ran {fullCommand}"
|
||||
self.bot.log(logMessage, str(ctx.channel_id), level=25)
|
||||
log_message = f"{ctx.author.display_name} ran {fullCommand}"
|
||||
self.bot.log(log_message, str(ctx.channel_id), level=25)
|
||||
|
||||
async def on_reaction_add(self, reaction: discord.Reaction,
|
||||
user: discord.User):
|
||||
"""Take action if the reaction is on a command message."""
|
||||
if not user.bot:
|
||||
tests = self.bot.databaseFuncs
|
||||
tests = self.bot.database_funcs
|
||||
message = reaction.message
|
||||
channel = message.channel
|
||||
reactedMessage = f"{user.display_name} reacted to a message"
|
||||
@ -80,10 +82,10 @@ class EventHandler():
|
||||
|
||||
reactionTestParams = [message, f"#{str(user.id)}"]
|
||||
|
||||
if tests.connectFourReactionTest(*reactionTestParams):
|
||||
if tests.connect_fourReactionTest(*reactionTestParams):
|
||||
column = emojiToCommand(reaction.emoji)
|
||||
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]:
|
||||
plexFuncs = self.bot.other.bedreNetflix
|
||||
@ -150,14 +152,14 @@ class ErrorHandler():
|
||||
self.bot.log("Deleted message before I could add all reactions")
|
||||
elif isinstance(error, commands.errors.MissingRequiredArgument):
|
||||
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:
|
||||
params = [type(error), error, error.__traceback__]
|
||||
exception = traceback.format_exception(*params)
|
||||
|
||||
exceptionString = "".join(exception)
|
||||
logMessages = [f"exception in /{ctx.name}", f"{exceptionString}"]
|
||||
self.bot.log(logMessages, str(ctx.channel_id), 40)
|
||||
log_messages = [f"exception in /{ctx.name}", f"{exceptionString}"]
|
||||
self.bot.log(log_messages, str(ctx.channel_id), 40)
|
||||
if isinstance(error, discord.errors.NotFound):
|
||||
self.bot.log("Context is non-existant", level=40)
|
||||
else:
|
||||
@ -172,5 +174,5 @@ class ErrorHandler():
|
||||
exception = traceback.format_exc()
|
||||
|
||||
exceptionString = "".join(exception)
|
||||
logMessages = [f"exception in {method}", f"{exceptionString}"]
|
||||
self.bot.log(logMessages, level=40)
|
||||
log_messages = [f"exception in {method}", f"{exceptionString}"]
|
||||
self.bot.log(log_messages, level=40)
|
@ -84,7 +84,7 @@ class Credentials():
|
||||
data = sanitize(f.read())
|
||||
|
||||
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.mongoDBUser = data["mongodb user"]
|
||||
self.mongoDBPassword = data["mongodb password"]
|
||||
@ -93,7 +93,7 @@ class Credentials():
|
||||
self.sonarrKey = data["sonarr api key"]
|
||||
|
||||
|
||||
class databaseFuncs():
|
||||
class DatabaseFuncs():
|
||||
"""
|
||||
Manages database functions.
|
||||
|
||||
@ -103,7 +103,7 @@ class databaseFuncs():
|
||||
getID(userName: str) -> str
|
||||
deleteGame(gameType: str, channel: str)
|
||||
wipeGames()
|
||||
connectFourReactionTest(message: discord.Message,
|
||||
connect_fourReactionTest(message: discord.Message,
|
||||
user: discord.User) -> bool
|
||||
hangmanReactionTest(message: discord.Message,
|
||||
user: discord.User) -> bool
|
||||
@ -195,7 +195,7 @@ class databaseFuncs():
|
||||
g = git.cmd.Git("")
|
||||
g.pull()
|
||||
|
||||
def connectFourReactionTest(self, message: discord.Message,
|
||||
def connect_fourReactionTest(self, message: discord.Message,
|
||||
user: discord.User):
|
||||
"""
|
||||
Test if the given message is the current connect four game.
|
||||
@ -219,12 +219,15 @@ class databaseFuncs():
|
||||
channelSearch = {"_id": str(channel.id)}
|
||||
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}"
|
||||
if os.path.isfile(filePath):
|
||||
with open(filePath, "r") as f:
|
||||
oldImage = int(f.read())
|
||||
else:
|
||||
oldImage = 0
|
||||
|
||||
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"]
|
||||
if user == game["players"][turn]:
|
||||
return True
|
||||
@ -255,7 +258,7 @@ class databaseFuncs():
|
||||
hangman.
|
||||
"""
|
||||
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):
|
||||
with open(filePath, "r") as f:
|
||||
oldMessages = f.read().splitlines()
|
@ -3,7 +3,7 @@ Contains utility functions used by parts of the bot.
|
||||
|
||||
*Functions*
|
||||
-----------
|
||||
longstrings() -> dict
|
||||
long_strings() -> dict
|
||||
getParams() -> dict
|
||||
logThis(messages: Union[str, list], channel: str = "",
|
||||
level: int = 20)
|
||||
@ -18,7 +18,7 @@ import logging # Used for logging
|
||||
import os # Used by makeFiles() to check if files exist
|
||||
import sys # Used to specify printing for logging
|
||||
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
|
||||
@ -45,16 +45,16 @@ imdb._logging.setLevel("CRITICAL") # Basically disables imdbpy
|
||||
# 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*
|
||||
---------
|
||||
data: dict
|
||||
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)
|
||||
|
||||
return data
|
||||
@ -116,8 +116,8 @@ def logThis(messages, channel: str = "", level: int = 20):
|
||||
if level >= 25:
|
||||
printer.log(level, printMessage)
|
||||
|
||||
for logMessage in messages:
|
||||
logger.log(level, logMessage)
|
||||
for log_message in messages:
|
||||
logger.log(level, log_message)
|
||||
|
||||
|
||||
def cap(s: str):
|
Reference in New Issue
Block a user