✨ PEP in utils
24
.gitignore
vendored
@ -153,16 +153,16 @@ static
|
|||||||
token.txt
|
token.txt
|
||||||
credentials.txt
|
credentials.txt
|
||||||
options.txt
|
options.txt
|
||||||
resources/star_wars/destinyPoints.txt
|
gwendolyn/resources/star_wars/destinyPoints.txt
|
||||||
resources/bedreNetflix/
|
gwendolyn/resources/bedre_netflix/
|
||||||
resources/games/hilo/
|
gwendolyn/resources/games/hilo/
|
||||||
resources/games/blackjackTables/
|
gwendolyn/resources/games/blackjack_tables/
|
||||||
resources/games/old_images/
|
gwendolyn/resources/games/old_images/
|
||||||
resources/games/connect4Boards/
|
gwendolyn/resources/games/connect4Boards/
|
||||||
resources/games/hexBoards/
|
gwendolyn/resources/games/hex_boards/
|
||||||
resources/games/hangmanBoards/
|
gwendolyn/resources/games/hangman_boards/
|
||||||
resources/lookup/monsters.json
|
gwendolyn/resources/lookup/monsters.json
|
||||||
resources/lookup/spells.json
|
gwendolyn/resources/lookup/spells.json
|
||||||
resources/movies.txt
|
gwendolyn/resources/movies.txt
|
||||||
resources/names.txt
|
gwendolyn/resources/names.txt
|
||||||
gwendolynTest.py
|
gwendolynTest.py
|
||||||
|
6
gwendolyn/__init__.py
Normal file
@ -0,0 +1,6 @@
|
|||||||
|
"""The main module for Gwendolyn."""
|
||||||
|
# pylint: disable=invalid-name
|
||||||
|
|
||||||
|
__all__ = ["funcs", "utils", "Gwendolyn"]
|
||||||
|
|
||||||
|
from .gwendolyn_client import Gwendolyn
|
@ -25,7 +25,7 @@ class EventCog(commands.Cog):
|
|||||||
"""Log when a slash error occurs."""
|
"""Log when a slash error occurs."""
|
||||||
await self.bot.error_handler.on_slash_command_error(ctx, error)
|
await self.bot.error_handler.on_slash_command_error(ctx, error)
|
||||||
|
|
||||||
async def on_error(self, method):
|
async def on_error(self, method, *args, **kwargs): # pylint: disable=unused-argument
|
||||||
"""Log when an error occurs."""
|
"""Log when an error occurs."""
|
||||||
await self.bot.error_handler.on_error(method)
|
await self.bot.error_handler.on_error(method)
|
||||||
|
|
@ -2,9 +2,9 @@
|
|||||||
from discord.ext import commands # Has the cog class
|
from discord.ext import commands # Has the cog class
|
||||||
from discord_slash import cog_ext # Used for slash commands
|
from discord_slash import cog_ext # Used for slash commands
|
||||||
|
|
||||||
from utils import getParams # pylint: disable=import-error
|
from gwendolyn.utils import get_params # pylint: disable=import-error
|
||||||
|
|
||||||
params = getParams()
|
params = get_params()
|
||||||
|
|
||||||
|
|
||||||
class GamesCog(commands.Cog):
|
class GamesCog(commands.Cog):
|
||||||
@ -42,48 +42,48 @@ class BlackjackCog(commands.Cog):
|
|||||||
"""Initialize the cog."""
|
"""Initialize the cog."""
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackStart"])
|
@cog_ext.cog_subcommand(**params["blackjack_start"])
|
||||||
async def blackjackStart(self, ctx):
|
async def blackjack_start(self, ctx):
|
||||||
"""Start a game of blackjack."""
|
"""Start a game of blackjack."""
|
||||||
await self.bot.games.blackjack.start(ctx)
|
await self.bot.games.blackjack.start(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackBet"])
|
@cog_ext.cog_subcommand(**params["blackjack_bet"])
|
||||||
async def blackjackBet(self, ctx, bet):
|
async def blackjack_bet(self, ctx, bet):
|
||||||
"""Enter the game of blackjack with a bet."""
|
"""Enter the game of blackjack with a bet."""
|
||||||
await self.bot.games.blackjack.enterGame(ctx, bet)
|
await self.bot.games.blackjack.enterGame(ctx, bet)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackStand"])
|
@cog_ext.cog_subcommand(**params["blackjack_stand"])
|
||||||
async def blackjackStand(self, ctx, hand=""):
|
async def blackjack_stand(self, ctx, hand=""):
|
||||||
"""Stand on your hand in blackjack."""
|
"""Stand on your hand in blackjack."""
|
||||||
await self.bot.games.blackjack.stand(ctx, hand)
|
await self.bot.games.blackjack.stand(ctx, hand)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackHit"])
|
@cog_ext.cog_subcommand(**params["blackjack_hit"])
|
||||||
async def blackjackHit(self, ctx, hand=0):
|
async def blackjack_hit(self, ctx, hand=0):
|
||||||
"""Hit on your hand in blackjack."""
|
"""Hit on your hand in blackjack."""
|
||||||
await self.bot.games.blackjack.hit(ctx, hand)
|
await self.bot.games.blackjack.hit(ctx, hand)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackDouble"])
|
@cog_ext.cog_subcommand(**params["blackjack_double"])
|
||||||
async def blackjackDouble(self, ctx, hand=0):
|
async def blackjack_double(self, ctx, hand=0):
|
||||||
"""Double in blackjack."""
|
"""Double in blackjack."""
|
||||||
await self.bot.games.blackjack.double(ctx, hand)
|
await self.bot.games.blackjack.double(ctx, hand)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackSplit"])
|
@cog_ext.cog_subcommand(**params["blackjack_split"])
|
||||||
async def blackjackSplit(self, ctx, hand=0):
|
async def blackjack_split(self, ctx, hand=0):
|
||||||
"""Split your hand in blackjack."""
|
"""Split your hand in blackjack."""
|
||||||
await self.bot.games.blackjack.split(ctx, hand)
|
await self.bot.games.blackjack.split(ctx, hand)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackHilo"])
|
@cog_ext.cog_subcommand(**params["blackjack_hilo"])
|
||||||
async def blackjackHilo(self, ctx):
|
async def blackjack_hilo(self, ctx):
|
||||||
"""Get the hilo value for the deck in blackjack."""
|
"""Get the hilo value for the deck in blackjack."""
|
||||||
await self.bot.games.blackjack.hilo(ctx)
|
await self.bot.games.blackjack.hilo(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackShuffle"])
|
@cog_ext.cog_subcommand(**params["blackjack_shuffle"])
|
||||||
async def blackjackShuffle(self, ctx):
|
async def blackjack_shuffle(self, ctx):
|
||||||
"""Shuffle the blackjack game."""
|
"""Shuffle the blackjack game."""
|
||||||
await self.bot.games.blackjack.shuffle(ctx)
|
await self.bot.games.blackjack.shuffle(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["blackjackCards"])
|
@cog_ext.cog_subcommand(**params["blackjack_cards"])
|
||||||
async def blackjackCards(self, ctx):
|
async def blackjack_cards(self, ctx):
|
||||||
"""Get the amount of cards left in the blackjack deck."""
|
"""Get the amount of cards left in the blackjack deck."""
|
||||||
await self.bot.games.blackjack.cards(ctx)
|
await self.bot.games.blackjack.cards(ctx)
|
||||||
|
|
||||||
@ -95,18 +95,18 @@ class ConnectFourCog(commands.Cog):
|
|||||||
"""Initialize the cog."""
|
"""Initialize the cog."""
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["connect_fourStartUser"])
|
@cog_ext.cog_subcommand(**params["connect_four_start_user"])
|
||||||
async def connect_fourStartUser(self, ctx, user):
|
async def connect_four_start_user(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.connect_four.start(ctx, user)
|
await self.bot.games.connect_four.start(ctx, user)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["connect_fourStartGwendolyn"])
|
@cog_ext.cog_subcommand(**params["connect_four_start_gwendolyn"])
|
||||||
async def connect_fourStartGwendolyn(self, ctx, difficulty=3):
|
async def connect_four_start_gwendolyn(self, ctx, difficulty=3):
|
||||||
"""Start a game of connect four against Gwendolyn."""
|
"""Start a game of connect four against Gwendolyn."""
|
||||||
await self.bot.games.connect_four.start(ctx, difficulty)
|
await self.bot.games.connect_four.start(ctx, difficulty)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["connect_fourSurrender"])
|
@cog_ext.cog_subcommand(**params["connect_four_surrender"])
|
||||||
async def connect_fourSurrender(self, ctx):
|
async def connect_four_surrender(self, ctx):
|
||||||
"""Surrender the game of connect four."""
|
"""Surrender the game of connect four."""
|
||||||
await self.bot.games.connect_four.surrender(ctx)
|
await self.bot.games.connect_four.surrender(ctx)
|
||||||
|
|
||||||
@ -118,13 +118,13 @@ class HangmanCog(commands.Cog):
|
|||||||
"""Initialize the cog."""
|
"""Initialize the cog."""
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hangmanStart"])
|
@cog_ext.cog_subcommand(**params["hangman_start"])
|
||||||
async def hangmanStart(self, ctx):
|
async def hangman_start(self, ctx):
|
||||||
"""Start a game of hangman."""
|
"""Start a game of hangman."""
|
||||||
await self.bot.games.hangman.start(ctx)
|
await self.bot.games.hangman.start(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hangmanStop"])
|
@cog_ext.cog_subcommand(**params["hangman_stop"])
|
||||||
async def hangmanStop(self, ctx):
|
async def hangman_stop(self, ctx):
|
||||||
"""Stop the current game of hangman."""
|
"""Stop the current game of hangman."""
|
||||||
await self.bot.games.hangman.stop(ctx)
|
await self.bot.games.hangman.stop(ctx)
|
||||||
|
|
||||||
@ -137,33 +137,33 @@ class HexCog(commands.Cog):
|
|||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.hex = self.bot.games.hex
|
self.hex = self.bot.games.hex
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hexStartUser"])
|
@cog_ext.cog_subcommand(**params["hex_start_user"])
|
||||||
async def hexStartUser(self, ctx, user):
|
async def hex_start_user(self, ctx, user):
|
||||||
"""Start a game of hex against another player."""
|
"""Start a game of hex against another player."""
|
||||||
await self.hex.start(ctx, user)
|
await self.hex.start(ctx, user)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hexStartGwendolyn"])
|
@cog_ext.cog_subcommand(**params["hex_start_gwendolyn"])
|
||||||
async def hexStartGwendolyn(self, ctx, difficulty=2):
|
async def hex_start_gwendolyn(self, ctx, difficulty=2):
|
||||||
"""Start a game of hex against Gwendolyn."""
|
"""Start a game of hex against Gwendolyn."""
|
||||||
await self.hex.start(ctx, difficulty)
|
await self.hex.start(ctx, difficulty)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hexPlace"])
|
@cog_ext.cog_subcommand(**params["hex_place"])
|
||||||
async def hexPlace(self, ctx, coordinates):
|
async def hex_place(self, ctx, coordinates):
|
||||||
"""Place a piece in the hex game."""
|
"""Place a piece in the hex game."""
|
||||||
await self.hex.placeHex(ctx, coordinates, f"#{ctx.author.id}")
|
await self.hex.placeHex(ctx, coordinates, f"#{ctx.author.id}")
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hexUndo"])
|
@cog_ext.cog_subcommand(**params["hex_undo"])
|
||||||
async def hexUndo(self, ctx):
|
async def hex_undo(self, ctx):
|
||||||
"""Undo your last hex move."""
|
"""Undo your last hex move."""
|
||||||
await self.hex.undo(ctx)
|
await self.hex.undo(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hexSwap"])
|
@cog_ext.cog_subcommand(**params["hex_swap"])
|
||||||
async def hexSwap(self, ctx):
|
async def hex_swap(self, ctx):
|
||||||
"""Perform a hex swap."""
|
"""Perform a hex swap."""
|
||||||
await self.hex.swap(ctx)
|
await self.hex.swap(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_subcommand(**params["hexSurrender"])
|
@cog_ext.cog_subcommand(**params["hex_surrender"])
|
||||||
async def hexSurrender(self, ctx):
|
async def hex_surrender(self, ctx):
|
||||||
"""Surrender the hex game."""
|
"""Surrender the hex game."""
|
||||||
await self.hex.surrender(ctx)
|
await self.hex.surrender(ctx)
|
||||||
|
|
@ -2,9 +2,9 @@
|
|||||||
from discord.ext import commands # Has the cog class
|
from discord.ext import commands # Has the cog class
|
||||||
from discord_slash import cog_ext # Used for slash commands
|
from discord_slash import cog_ext # Used for slash commands
|
||||||
|
|
||||||
from utils import getParams # pylint: disable=import-error
|
from gwendolyn.utils import get_params # pylint: disable=import-error
|
||||||
|
|
||||||
params = getParams()
|
params = get_params()
|
||||||
|
|
||||||
|
|
||||||
class LookupCog(commands.Cog):
|
class LookupCog(commands.Cog):
|
@ -2,9 +2,9 @@
|
|||||||
from discord.ext import commands # Has the cog class
|
from discord.ext import commands # Has the cog class
|
||||||
from discord_slash import cog_ext # Used for slash commands
|
from discord_slash import cog_ext # Used for slash commands
|
||||||
|
|
||||||
from utils import getParams # pylint: disable=import-error
|
from gwendolyn.utils import get_params # pylint: disable=import-error
|
||||||
|
|
||||||
params = getParams()
|
params = get_params()
|
||||||
|
|
||||||
|
|
||||||
class MiscCog(commands.Cog):
|
class MiscCog(commands.Cog):
|
||||||
@ -15,8 +15,8 @@ class MiscCog(commands.Cog):
|
|||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.bot.remove_command("help")
|
self.bot.remove_command("help")
|
||||||
self.generators = bot.other.generators
|
self.generators = bot.other.generators
|
||||||
self.bedreNetflix = bot.other.bedreNetflix
|
self.bedre_netflix = bot.other.bedre_netflix
|
||||||
self.nerdShit = bot.other.nerdShit
|
self.nerd_shit = bot.other.nerd_shit
|
||||||
|
|
||||||
@cog_ext.cog_slash(**params["ping"])
|
@cog_ext.cog_slash(**params["ping"])
|
||||||
async def ping(self, ctx):
|
async def ping(self, ctx):
|
||||||
@ -29,7 +29,7 @@ class MiscCog(commands.Cog):
|
|||||||
await self.bot.stop(ctx)
|
await self.bot.stop(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_slash(**params["help"])
|
@cog_ext.cog_slash(**params["help"])
|
||||||
async def helpCommand(self, ctx, command=""):
|
async def help_command(self, ctx, command=""):
|
||||||
"""Get help for commands."""
|
"""Get help for commands."""
|
||||||
await self.bot.other.helpFunc(ctx, command)
|
await self.bot.other.helpFunc(ctx, command)
|
||||||
|
|
||||||
@ -69,29 +69,29 @@ class MiscCog(commands.Cog):
|
|||||||
await self.generators.tavernGen(ctx)
|
await self.generators.tavernGen(ctx)
|
||||||
|
|
||||||
@cog_ext.cog_slash(**params["wiki"])
|
@cog_ext.cog_slash(**params["wiki"])
|
||||||
async def wiki(self, ctx, wikiPage=""):
|
async def wiki(self, ctx, wiki_page=""):
|
||||||
"""Get a page on a fandom wiki."""
|
"""Get a page on a fandom wiki."""
|
||||||
await self.bot.other.findWikiPage(ctx, wikiPage)
|
await self.bot.other.findWikiPage(ctx, wiki_page)
|
||||||
|
|
||||||
@cog_ext.cog_slash(**params["addMovie"])
|
@cog_ext.cog_slash(**params["add_movie"])
|
||||||
async def addMovie(self, ctx, movie):
|
async def add_movie(self, ctx, movie):
|
||||||
"""Search for a movie and add it to the Plex server."""
|
"""Search for a movie and add it to the Plex server."""
|
||||||
await self.bedreNetflix.requestMovie(ctx, movie)
|
await self.bedre_netflix.requestMovie(ctx, movie)
|
||||||
|
|
||||||
@cog_ext.cog_slash(**params["addShow"])
|
@cog_ext.cog_slash(**params["add_show"])
|
||||||
async def addShow(self, ctx, show):
|
async def add_show(self, ctx, show):
|
||||||
"""Search for a show and add it to the Plex server."""
|
"""Search for a show and add it to the Plex server."""
|
||||||
await self.bedreNetflix.requestShow(ctx, show)
|
await self.bedre_netflix.requestShow(ctx, show)
|
||||||
|
|
||||||
@cog_ext.cog_slash(**params["downloading"])
|
@cog_ext.cog_slash(**params["downloading"])
|
||||||
async def downloading(self, ctx, parameters="-d"):
|
async def downloading(self, ctx, parameters="-d"):
|
||||||
"""Get the current downloading torrents."""
|
"""Get the current downloading torrents."""
|
||||||
await self.bedreNetflix.downloading(ctx, parameters)
|
await self.bedre_netflix.downloading(ctx, parameters)
|
||||||
|
|
||||||
@cog_ext.cog_slash(**params["wolf"])
|
@cog_ext.cog_slash(**params["wolf"])
|
||||||
async def wolf(self, ctx, query):
|
async def wolf(self, ctx, query):
|
||||||
"""Perform a search on Wolfram Alpha."""
|
"""Perform a search on Wolfram Alpha."""
|
||||||
await self.nerdShit.wolfSearch(ctx, query)
|
await self.nerd_shit.wolfSearch(ctx, query)
|
||||||
|
|
||||||
|
|
||||||
def setup(bot):
|
def setup(bot):
|
@ -2,9 +2,9 @@
|
|||||||
from discord.ext import commands
|
from discord.ext import commands
|
||||||
from discord_slash import cog_ext
|
from discord_slash import cog_ext
|
||||||
|
|
||||||
from utils import getParams # pylint: disable=import-error
|
from gwendolyn.utils import get_params # pylint: disable=import-error
|
||||||
|
|
||||||
params = getParams()
|
params = get_params()
|
||||||
|
|
||||||
|
|
||||||
class StarWarsCog(commands.Cog):
|
class StarWarsCog(commands.Cog):
|
@ -18,7 +18,7 @@ from PIL import Image, ImageDraw, ImageFont
|
|||||||
|
|
||||||
from shutil import copyfile
|
from shutil import copyfile
|
||||||
|
|
||||||
from utils import replaceMultiple
|
from gwendolyn.utils import replace_multiple
|
||||||
|
|
||||||
|
|
||||||
class Blackjack():
|
class Blackjack():
|
||||||
@ -48,7 +48,7 @@ class Blackjack():
|
|||||||
self.draw = DrawBlackjack(bot)
|
self.draw = DrawBlackjack(bot)
|
||||||
self.decks = 4
|
self.decks = 4
|
||||||
|
|
||||||
def _blackjackShuffle(self, channel: str):
|
def _blackjack_shuffle(self, channel: str):
|
||||||
"""
|
"""
|
||||||
Shuffle an amount of decks equal to self.decks.
|
Shuffle an amount of decks equal to self.decks.
|
||||||
|
|
||||||
@ -62,23 +62,23 @@ class Blackjack():
|
|||||||
"""
|
"""
|
||||||
self.bot.log("Shuffling the blackjack deck")
|
self.bot.log("Shuffling the blackjack deck")
|
||||||
|
|
||||||
with open("resources/games/deckOfCards.txt", "r") as f:
|
with open("gwendolyn/resources/games/deck_of_cards.txt", "r") as f:
|
||||||
deck = f.read()
|
deck = f.read()
|
||||||
|
|
||||||
allDecks = deck.split("\n") * self.decks
|
allDecks = deck.split("\n") * self.decks
|
||||||
random.shuffle(allDecks)
|
random.shuffle(allDecks)
|
||||||
|
|
||||||
blackjackCards = self.bot.database["blackjack cards"]
|
blackjack_cards = self.bot.database["blackjack cards"]
|
||||||
cards = {"_id": channel}
|
cards = {"_id": channel}
|
||||||
cardUpdater = {"$set": {"_id": channel, "cards": allDecks}}
|
cardUpdater = {"$set": {"_id": channel, "cards": allDecks}}
|
||||||
blackjackCards.update_one(cards, cardUpdater, upsert=True)
|
blackjack_cards.update_one(cards, cardUpdater, upsert=True)
|
||||||
|
|
||||||
# Creates hilo file
|
# Creates hilo file
|
||||||
self.bot.log(f"creating hilo doc for {channel}")
|
self.bot.log(f"creating hilo doc for {channel}")
|
||||||
data = 0
|
data = 0
|
||||||
blackjackHilo = self.bot.database["hilo"]
|
blackjack_hilo = self.bot.database["hilo"]
|
||||||
hiloUpdater = {"$set": {"_id": channel, "hilo": data}}
|
hiloUpdater = {"$set": {"_id": channel, "hilo": data}}
|
||||||
blackjackHilo.update_one({"_id": channel}, hiloUpdater, upsert=True)
|
blackjack_hilo.update_one({"_id": channel}, hiloUpdater, upsert=True)
|
||||||
|
|
||||||
def _calcHandValue(self, hand: list):
|
def _calcHandValue(self, hand: list):
|
||||||
"""
|
"""
|
||||||
@ -103,7 +103,7 @@ class Blackjack():
|
|||||||
|
|
||||||
for card in hand:
|
for card in hand:
|
||||||
cardValue = card[0]
|
cardValue = card[0]
|
||||||
cardValue = replaceMultiple(cardValue, ["0", "k", "q", "j"], "10")
|
cardValue = replace_multiple(cardValue, ["0", "k", "q", "j"], "10")
|
||||||
if cardValue == "a":
|
if cardValue == "a":
|
||||||
length = len(values)
|
length = len(values)
|
||||||
for x in range(length):
|
for x in range(length):
|
||||||
@ -135,17 +135,17 @@ class Blackjack():
|
|||||||
"""
|
"""
|
||||||
self.bot.log("drawing a card")
|
self.bot.log("drawing a card")
|
||||||
|
|
||||||
blackjackCards = self.bot.database["blackjack cards"]
|
blackjack_cards = self.bot.database["blackjack cards"]
|
||||||
drawnCard = blackjackCards.find_one({"_id": channel})["cards"][0]
|
drawnCard = blackjack_cards.find_one({"_id": channel})["cards"][0]
|
||||||
blackjackCards.update_one({"_id": channel}, {"$pop": {"cards": -1}})
|
blackjack_cards.update_one({"_id": channel}, {"$pop": {"cards": -1}})
|
||||||
value = self._calcHandValue([drawnCard])
|
value = self._calcHandValue([drawnCard])
|
||||||
|
|
||||||
blackjackHilo = self.bot.database["hilo"]
|
blackjack_hilo = self.bot.database["hilo"]
|
||||||
|
|
||||||
if value <= 6:
|
if value <= 6:
|
||||||
blackjackHilo.update_one({"_id": channel}, {"$inc": {"hilo": 1}})
|
blackjack_hilo.update_one({"_id": channel}, {"$inc": {"hilo": 1}})
|
||||||
elif value >= 10:
|
elif value >= 10:
|
||||||
blackjackHilo.update_one({"_id": channel}, {"$inc": {"hilo": -1}})
|
blackjack_hilo.update_one({"_id": channel}, {"$inc": {"hilo": -1}})
|
||||||
|
|
||||||
return drawnCard
|
return drawnCard
|
||||||
|
|
||||||
@ -168,22 +168,22 @@ class Blackjack():
|
|||||||
done = False
|
done = False
|
||||||
dealerHand = game["dealer hand"]
|
dealerHand = game["dealer hand"]
|
||||||
|
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
|
|
||||||
if self._calcHandValue(dealerHand) < 17:
|
if self._calcHandValue(dealerHand) < 17:
|
||||||
dealerHand.append(self._drawCard(channel))
|
dealerHand.append(self._drawCard(channel))
|
||||||
dealerUpdater = {"$set": {"dealer hand": dealerHand}}
|
dealerUpdater = {"$set": {"dealer hand": dealerHand}}
|
||||||
blackjackGames.update_one({"_id": channel}, dealerUpdater)
|
blackjack_games.update_one({"_id": channel}, dealerUpdater)
|
||||||
else:
|
else:
|
||||||
done = True
|
done = True
|
||||||
|
|
||||||
if self._calcHandValue(dealerHand) > 21:
|
if self._calcHandValue(dealerHand) > 21:
|
||||||
dealerUpdater = {"$set": {"dealer busted": True}}
|
dealerUpdater = {"$set": {"dealer busted": True}}
|
||||||
blackjackGames.update_one({"_id": channel}, dealerUpdater)
|
blackjack_games.update_one({"_id": channel}, dealerUpdater)
|
||||||
|
|
||||||
return done
|
return done
|
||||||
|
|
||||||
def _blackjackContinue(self, channel: str):
|
def _blackjack_continue(self, channel: str):
|
||||||
"""
|
"""
|
||||||
Continues the blackjack game to the next round.
|
Continues the blackjack game to the next round.
|
||||||
|
|
||||||
@ -206,8 +206,8 @@ class Blackjack():
|
|||||||
|
|
||||||
done = False
|
done = False
|
||||||
|
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
blackjackGames.update_one({"_id": channel}, {"$inc": {"round": 1}})
|
blackjack_games.update_one({"_id": channel}, {"$inc": {"round": 1}})
|
||||||
|
|
||||||
allStanding = True
|
allStanding = True
|
||||||
preAllStanding = True
|
preAllStanding = True
|
||||||
@ -219,20 +219,20 @@ class Blackjack():
|
|||||||
done = self._dealerDraw(channel)
|
done = self._dealerDraw(channel)
|
||||||
message = "The dealer draws a card."
|
message = "The dealer draws a card."
|
||||||
|
|
||||||
blackjackGames.find_one({"_id": channel})
|
blackjack_games.find_one({"_id": channel})
|
||||||
|
|
||||||
self.bot.log("Testing if all are standing")
|
self.bot.log("Testing if all are standing")
|
||||||
for user in game["user hands"]:
|
for user in game["user hands"]:
|
||||||
userHand = game["user hands"][user]
|
userHand = game["user hands"][user]
|
||||||
testParams = [userHand, allStanding, preAllStanding, True]
|
test_parameters = [userHand, allStanding, preAllStanding, True]
|
||||||
standingTest = (self._testIfStanding(*testParams))
|
standingTest = (self._testIfStanding(*test_parameters))
|
||||||
newUser, allStanding, preAllStanding = standingTest
|
newUser, allStanding, preAllStanding = standingTest
|
||||||
handUpdater = {"$set": {"user hands."+user: newUser}}
|
handUpdater = {"$set": {"user hands."+user: newUser}}
|
||||||
blackjackGames.update_one({"_id": channel}, handUpdater)
|
blackjack_games.update_one({"_id": channel}, handUpdater)
|
||||||
|
|
||||||
if allStanding:
|
if allStanding:
|
||||||
gameUpdater = {"$set": {"all standing": True}}
|
gameUpdater = {"$set": {"all standing": True}}
|
||||||
blackjackGames.update_one({"_id": channel}, gameUpdater)
|
blackjack_games.update_one({"_id": channel}, gameUpdater)
|
||||||
|
|
||||||
self.draw.drawImage(channel)
|
self.draw.drawImage(channel)
|
||||||
|
|
||||||
@ -303,23 +303,23 @@ class Blackjack():
|
|||||||
if topLevel:
|
if topLevel:
|
||||||
if hand["split"] >= 1:
|
if hand["split"] >= 1:
|
||||||
testHand = hand["other hand"]
|
testHand = hand["other hand"]
|
||||||
testParams = [testHand, allStanding, preAllStanding, False]
|
test_parameters = [testHand, allStanding, preAllStanding, False]
|
||||||
standingTest = (self._testIfStanding(*testParams))
|
standingTest = (self._testIfStanding(*test_parameters))
|
||||||
hand["other hand"], allStanding, preAllStanding = standingTest
|
hand["other hand"], allStanding, preAllStanding = standingTest
|
||||||
if hand["split"] >= 2:
|
if hand["split"] >= 2:
|
||||||
testHand = hand["third hand"]
|
testHand = hand["third hand"]
|
||||||
testParams = [testHand, allStanding, preAllStanding, False]
|
test_parameters = [testHand, allStanding, preAllStanding, False]
|
||||||
standingTest = (self._testIfStanding(*testParams))
|
standingTest = (self._testIfStanding(*test_parameters))
|
||||||
hand["third hand"], allStanding, preAllStanding = standingTest
|
hand["third hand"], allStanding, preAllStanding = standingTest
|
||||||
if hand["split"] >= 3:
|
if hand["split"] >= 3:
|
||||||
testHand = hand["fourth hand"]
|
testHand = hand["fourth hand"]
|
||||||
testParams = [testHand, allStanding, preAllStanding, False]
|
test_parameters = [testHand, allStanding, preAllStanding, False]
|
||||||
standingTest = (self._testIfStanding(*testParams))
|
standingTest = (self._testIfStanding(*test_parameters))
|
||||||
hand["fourth hand"], allStanding, preAllStanding = standingTest
|
hand["fourth hand"], allStanding, preAllStanding = standingTest
|
||||||
|
|
||||||
return hand, allStanding, preAllStanding
|
return hand, allStanding, preAllStanding
|
||||||
|
|
||||||
def _blackjackFinish(self, channel: str):
|
def _blackjack_finish(self, channel: str):
|
||||||
"""
|
"""
|
||||||
Generate the winnings message after the blackjack game ends.
|
Generate the winnings message after the blackjack game ends.
|
||||||
|
|
||||||
@ -352,21 +352,21 @@ class Blackjack():
|
|||||||
winningCalc = (self._calcWinnings(*_calcWinningsParams))
|
winningCalc = (self._calcWinnings(*_calcWinningsParams))
|
||||||
winnings, netWinnings, reason = winningCalc
|
winnings, netWinnings, reason = winningCalc
|
||||||
|
|
||||||
userName = self.bot.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
|
|
||||||
if winnings < 0:
|
if winnings < 0:
|
||||||
if winnings == -1:
|
if winnings == -1:
|
||||||
finalWinnings += f"{userName} lost 1 GwendoBuck {reason}\n"
|
finalWinnings += f"{user_name} lost 1 GwendoBuck {reason}\n"
|
||||||
else:
|
else:
|
||||||
moneyLost = -1 * winnings
|
moneyLost = -1 * winnings
|
||||||
winningText = f"{userName} lost {moneyLost} GwendoBucks"
|
winningText = f"{user_name} lost {moneyLost} GwendoBucks"
|
||||||
winningText += f" {reason}\n"
|
winningText += f" {reason}\n"
|
||||||
finalWinnings += winningText
|
finalWinnings += winningText
|
||||||
else:
|
else:
|
||||||
if winnings == 1:
|
if winnings == 1:
|
||||||
finalWinnings += f"{userName} won 1 GwendoBuck {reason}\n"
|
finalWinnings += f"{user_name} won 1 GwendoBuck {reason}\n"
|
||||||
else:
|
else:
|
||||||
winningText = f"{userName} won {winnings} GwendoBucks"
|
winningText = f"{user_name} won {winnings} GwendoBucks"
|
||||||
winningText += f" {reason}\n"
|
winningText += f" {reason}\n"
|
||||||
finalWinnings += winningText
|
finalWinnings += winningText
|
||||||
|
|
||||||
@ -554,7 +554,7 @@ class Blackjack():
|
|||||||
|
|
||||||
return roundDone
|
return roundDone
|
||||||
|
|
||||||
async def _blackjackLoop(self, channel, gameRound: int, gameID: str):
|
async def _blackjack_loop(self, channel, gameRound: int, gameID: str):
|
||||||
"""
|
"""
|
||||||
Run blackjack logic and continue if enough time passes.
|
Run blackjack logic and continue if enough time passes.
|
||||||
|
|
||||||
@ -569,31 +569,31 @@ class Blackjack():
|
|||||||
"""
|
"""
|
||||||
self.bot.log("Loop "+str(gameRound), str(channel.id))
|
self.bot.log("Loop "+str(gameRound), str(channel.id))
|
||||||
|
|
||||||
oldImagePath = f"resources/games/old_images/blackjack{channel.id}"
|
old_imagePath = f"gwendolyn/resources/games/old_images/blackjack{channel.id}"
|
||||||
with open(oldImagePath, "r") as f:
|
with open(old_imagePath, "r") as f:
|
||||||
oldImage = await channel.fetch_message(int(f.read()))
|
old_image = await channel.fetch_message(int(f.read()))
|
||||||
|
|
||||||
continueData = (self._blackjackContinue(str(channel.id)))
|
continueData = (self._blackjack_continue(str(channel.id)))
|
||||||
new_message, allStanding, gamedone = continueData
|
new_message, allStanding, gamedone = continueData
|
||||||
if new_message != "":
|
if new_message != "":
|
||||||
self.bot.log(new_message, str(channel.id))
|
self.bot.log(new_message, str(channel.id))
|
||||||
await channel.send(new_message)
|
await channel.send(new_message)
|
||||||
|
|
||||||
if not gamedone:
|
if not gamedone:
|
||||||
await oldImage.delete()
|
await old_image.delete()
|
||||||
tablesPath = "resources/games/blackjackTables/"
|
tablesPath = "gwendolyn/resources/games/blackjack_tables/"
|
||||||
filePath = f"{tablesPath}blackjackTable{channel.id}.png"
|
file_path = f"{tablesPath}blackjack_table{channel.id}.png"
|
||||||
oldImage = await channel.send(file=discord.File(filePath))
|
old_image = await channel.send(file=discord.File(file_path))
|
||||||
with open(oldImagePath, "w") as f:
|
with open(old_imagePath, "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
|
|
||||||
if allStanding:
|
if allStanding:
|
||||||
await asyncio.sleep(5)
|
await asyncio.sleep(5)
|
||||||
else:
|
else:
|
||||||
await asyncio.sleep(120)
|
await asyncio.sleep(120)
|
||||||
|
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
game = blackjackGames.find_one({"_id": str(channel.id)})
|
game = blackjack_games.find_one({"_id": str(channel.id)})
|
||||||
|
|
||||||
if game is None:
|
if game is None:
|
||||||
rightRound = False
|
rightRound = False
|
||||||
@ -604,11 +604,11 @@ class Blackjack():
|
|||||||
|
|
||||||
if rightRound:
|
if rightRound:
|
||||||
if not gamedone:
|
if not gamedone:
|
||||||
log_message = f"Loop {gameRound} calling self._blackjackLoop()"
|
log_message = f"Loop {gameRound} calling self._blackjack_loop()"
|
||||||
self.bot.log(log_message, str(channel.id))
|
self.bot.log(log_message, str(channel.id))
|
||||||
await self._blackjackLoop(channel, gameRound+1, gameID)
|
await self._blackjack_loop(channel, gameRound+1, gameID)
|
||||||
else:
|
else:
|
||||||
new_message = self._blackjackFinish(str(channel.id))
|
new_message = self._blackjack_finish(str(channel.id))
|
||||||
await channel.send(new_message)
|
await channel.send(new_message)
|
||||||
else:
|
else:
|
||||||
log_message = f"Ending loop on round {gameRound}"
|
log_message = f"Ending loop on round {gameRound}"
|
||||||
@ -631,8 +631,8 @@ class Blackjack():
|
|||||||
user = f"#{ctx.author.id}"
|
user = f"#{ctx.author.id}"
|
||||||
roundDone = False
|
roundDone = False
|
||||||
|
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
|
|
||||||
if user in game["user hands"]:
|
if user in game["user hands"]:
|
||||||
|
|
||||||
@ -670,8 +670,8 @@ class Blackjack():
|
|||||||
handPath = f"user hands.{user}"
|
handPath = f"user hands.{user}"
|
||||||
|
|
||||||
gameUpdater = {"$set": {handPath: hand}}
|
gameUpdater = {"$set": {handPath: hand}}
|
||||||
blackjackGames.update_one({"_id": channel}, gameUpdater)
|
blackjack_games.update_one({"_id": channel}, gameUpdater)
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
roundDone = self._isRoundDone(game)
|
roundDone = self._isRoundDone(game)
|
||||||
|
|
||||||
sendMessage = f"{ctx.author.display_name} hit"
|
sendMessage = f"{ctx.author.display_name} hit"
|
||||||
@ -685,8 +685,8 @@ class Blackjack():
|
|||||||
|
|
||||||
if roundDone:
|
if roundDone:
|
||||||
gameID = game["gameID"]
|
gameID = game["gameID"]
|
||||||
self.bot.log("Hit calling self._blackjackLoop()", channel)
|
self.bot.log("Hit calling self._blackjack_loop()", channel)
|
||||||
await self._blackjackLoop(ctx.channel, game["round"]+1, gameID)
|
await self._blackjack_loop(ctx.channel, game["round"]+1, gameID)
|
||||||
|
|
||||||
async def double(self, ctx: discord_slash.context.SlashContext,
|
async def double(self, ctx: discord_slash.context.SlashContext,
|
||||||
handNumber: int = 0):
|
handNumber: int = 0):
|
||||||
@ -704,9 +704,9 @@ class Blackjack():
|
|||||||
channel = str(ctx.channel_id)
|
channel = str(ctx.channel_id)
|
||||||
user = f"#{ctx.author.id}"
|
user = f"#{ctx.author.id}"
|
||||||
roundDone = False
|
roundDone = False
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
|
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
|
|
||||||
if user in game["user hands"]:
|
if user in game["user hands"]:
|
||||||
handParams = [game["user hands"][user], handNumber]
|
handParams = [game["user hands"][user], handNumber]
|
||||||
@ -754,14 +754,14 @@ class Blackjack():
|
|||||||
handPath = f"user hands.{user}"
|
handPath = f"user hands.{user}"
|
||||||
|
|
||||||
gameUpdater = {"$set": {handPath: hand}}
|
gameUpdater = {"$set": {handPath: hand}}
|
||||||
blackjackGames.update_one({"_id": channel}, gameUpdater)
|
blackjack_games.update_one({"_id": channel}, gameUpdater)
|
||||||
|
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
roundDone = self._isRoundDone(game)
|
roundDone = self._isRoundDone(game)
|
||||||
|
|
||||||
sendMessage = self.bot.long_strings["Blackjack double"]
|
sendMessage = self.bot.long_strings["Blackjack double"]
|
||||||
userName = self.bot.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
sendMessage = sendMessage.format(bet, userName)
|
sendMessage = sendMessage.format(bet, user_name)
|
||||||
log_message = "They succeeded"
|
log_message = "They succeeded"
|
||||||
else:
|
else:
|
||||||
log_message = "They tried to double without being in the game"
|
log_message = "They tried to double without being in the game"
|
||||||
@ -772,8 +772,8 @@ class Blackjack():
|
|||||||
|
|
||||||
if roundDone:
|
if roundDone:
|
||||||
gameID = game["gameID"]
|
gameID = game["gameID"]
|
||||||
self.bot.log("Double calling self._blackjackLoop()", channel)
|
self.bot.log("Double calling self._blackjack_loop()", channel)
|
||||||
await self._blackjackLoop(ctx.channel, game["round"]+1, gameID)
|
await self._blackjack_loop(ctx.channel, game["round"]+1, gameID)
|
||||||
|
|
||||||
async def stand(self, ctx: discord_slash.context.SlashContext,
|
async def stand(self, ctx: discord_slash.context.SlashContext,
|
||||||
handNumber: int = 0):
|
handNumber: int = 0):
|
||||||
@ -792,8 +792,8 @@ class Blackjack():
|
|||||||
user = f"#{ctx.author.id}"
|
user = f"#{ctx.author.id}"
|
||||||
roundDone = False
|
roundDone = False
|
||||||
|
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
|
|
||||||
if game is not None and user in game["user hands"]:
|
if game is not None and user in game["user hands"]:
|
||||||
handParams = [game["user hands"][user], handNumber]
|
handParams = [game["user hands"][user], handNumber]
|
||||||
@ -824,8 +824,8 @@ class Blackjack():
|
|||||||
handPath = f"user hands.{user}"
|
handPath = f"user hands.{user}"
|
||||||
|
|
||||||
gameUpdater = {"$set": {handPath: hand}}
|
gameUpdater = {"$set": {handPath: hand}}
|
||||||
blackjackGames.update_one({"_id": channel}, gameUpdater)
|
blackjack_games.update_one({"_id": channel}, gameUpdater)
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
roundDone = self._isRoundDone(game)
|
roundDone = self._isRoundDone(game)
|
||||||
|
|
||||||
sendMessage = f"{ctx.author.display_name} is standing"
|
sendMessage = f"{ctx.author.display_name} is standing"
|
||||||
@ -840,8 +840,8 @@ class Blackjack():
|
|||||||
|
|
||||||
if roundDone:
|
if roundDone:
|
||||||
gameID = game["gameID"]
|
gameID = game["gameID"]
|
||||||
self.bot.log("Stand calling self._blackjackLoop()", channel)
|
self.bot.log("Stand calling self._blackjack_loop()", channel)
|
||||||
await self._blackjackLoop(ctx.channel, game["round"]+1, gameID)
|
await self._blackjack_loop(ctx.channel, game["round"]+1, gameID)
|
||||||
|
|
||||||
async def split(self, ctx: discord_slash.context.SlashContext,
|
async def split(self, ctx: discord_slash.context.SlashContext,
|
||||||
handNumber: int = 0):
|
handNumber: int = 0):
|
||||||
@ -861,8 +861,8 @@ class Blackjack():
|
|||||||
roundDone = False
|
roundDone = False
|
||||||
handNumberError = False
|
handNumberError = False
|
||||||
|
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
|
|
||||||
if game["user hands"][user]["split"] == 0:
|
if game["user hands"][user]["split"] == 0:
|
||||||
hand = game["user hands"][user]
|
hand = game["user hands"][user]
|
||||||
@ -954,7 +954,7 @@ class Blackjack():
|
|||||||
handPath = f"user hands.{user}"
|
handPath = f"user hands.{user}"
|
||||||
|
|
||||||
gameUpdater = {"$set": {handPath: hand}}
|
gameUpdater = {"$set": {handPath: hand}}
|
||||||
blackjackGames.update_one({"_id": channel}, gameUpdater)
|
blackjack_games.update_one({"_id": channel}, gameUpdater)
|
||||||
|
|
||||||
if otherHand == 3:
|
if otherHand == 3:
|
||||||
otherHandPath = f"user hands.{user}.third hand"
|
otherHandPath = f"user hands.{user}.third hand"
|
||||||
@ -964,17 +964,17 @@ class Blackjack():
|
|||||||
otherHandPath = f"user hands.{user}.other hand"
|
otherHandPath = f"user hands.{user}.other hand"
|
||||||
|
|
||||||
gameUpdater = {"$set": {otherHandPath: newHand}}
|
gameUpdater = {"$set": {otherHandPath: newHand}}
|
||||||
blackjackGames.update_one({"_id": channel}, gameUpdater)
|
blackjack_games.update_one({"_id": channel}, gameUpdater)
|
||||||
|
|
||||||
splitUpdater = {"$inc": {"user hands."+user+".split": 1}}
|
splitUpdater = {"$inc": {"user hands."+user+".split": 1}}
|
||||||
blackjackGames.update_one({"_id": channel}, splitUpdater)
|
blackjack_games.update_one({"_id": channel}, splitUpdater)
|
||||||
|
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
roundDone = self._isRoundDone(game)
|
roundDone = self._isRoundDone(game)
|
||||||
|
|
||||||
sendMessage = self.bot.long_strings["Blackjack split"]
|
sendMessage = self.bot.long_strings["Blackjack split"]
|
||||||
userName = self.bot.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
sendMessage = sendMessage.format(userName)
|
sendMessage = sendMessage.format(user_name)
|
||||||
log_message = "They succeeded"
|
log_message = "They succeeded"
|
||||||
|
|
||||||
await ctx.send(sendMessage)
|
await ctx.send(sendMessage)
|
||||||
@ -982,8 +982,8 @@ class Blackjack():
|
|||||||
|
|
||||||
if roundDone:
|
if roundDone:
|
||||||
gameID = game["gameID"]
|
gameID = game["gameID"]
|
||||||
self.bot.log("Stand calling self._blackjackLoop()", channel)
|
self.bot.log("Stand calling self._blackjack_loop()", channel)
|
||||||
await self._blackjackLoop(ctx.channel, game["round"]+1, gameID)
|
await self._blackjack_loop(ctx.channel, game["round"]+1, gameID)
|
||||||
|
|
||||||
async def enterGame(self, ctx: discord_slash.context.SlashContext,
|
async def enterGame(self, ctx: discord_slash.context.SlashContext,
|
||||||
bet: int):
|
bet: int):
|
||||||
@ -1002,9 +1002,9 @@ 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.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
|
|
||||||
self.bot.log(f"{userName} is trying to join the Blackjack game")
|
self.bot.log(f"{user_name} 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"
|
||||||
@ -1031,13 +1031,13 @@ class Blackjack():
|
|||||||
handValue = self._calcHandValue(playerHand)
|
handValue = self._calcHandValue(playerHand)
|
||||||
|
|
||||||
if handValue == 21:
|
if handValue == 21:
|
||||||
blackjackHand = True
|
blackjack_hand = True
|
||||||
else:
|
else:
|
||||||
blackjackHand = False
|
blackjack_hand = False
|
||||||
|
|
||||||
newHand = {
|
newHand = {
|
||||||
"hand": playerHand, "bet": bet, "standing": False,
|
"hand": playerHand, "bet": bet, "standing": False,
|
||||||
"busted": False, "blackjack": blackjackHand,
|
"busted": False, "blackjack": blackjack_hand,
|
||||||
"hit": True, "doubled": False, "split": 0,
|
"hit": True, "doubled": False, "split": 0,
|
||||||
"other hand": {}, "third hand": {}, "fourth hand": {}
|
"other hand": {}, "third hand": {}, "fourth hand": {}
|
||||||
}
|
}
|
||||||
@ -1047,7 +1047,7 @@ 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"{user_name} {enterGameText} {betText}"
|
||||||
log_message = sendMessage
|
log_message = sendMessage
|
||||||
|
|
||||||
self.bot.log(log_message)
|
self.bot.log(log_message)
|
||||||
@ -1064,7 +1064,7 @@ class Blackjack():
|
|||||||
"""
|
"""
|
||||||
await self.bot.defer(ctx)
|
await self.bot.defer(ctx)
|
||||||
channel = str(ctx.channel_id)
|
channel = str(ctx.channel_id)
|
||||||
blackjackMinCards = 50
|
blackjack_minCards = 50
|
||||||
|
|
||||||
self.bot.log("Starting blackjack game")
|
self.bot.log("Starting blackjack game")
|
||||||
await ctx.send("Starting a new game of blackjack")
|
await ctx.send("Starting a new game of blackjack")
|
||||||
@ -1074,8 +1074,8 @@ class Blackjack():
|
|||||||
cardsLeft = len(cards["cards"])
|
cardsLeft = len(cards["cards"])
|
||||||
|
|
||||||
# Shuffles if not enough cards
|
# Shuffles if not enough cards
|
||||||
if cardsLeft < blackjackMinCards:
|
if cardsLeft < blackjack_minCards:
|
||||||
self._blackjackShuffle(channel)
|
self._blackjack_shuffle(channel)
|
||||||
self.bot.log("Shuffling the blackjack deck...", channel)
|
self.bot.log("Shuffling the blackjack deck...", channel)
|
||||||
await ctx.channel.send("Shuffling the deck...")
|
await ctx.channel.send("Shuffling the deck...")
|
||||||
|
|
||||||
@ -1101,9 +1101,9 @@ class Blackjack():
|
|||||||
|
|
||||||
self.bot.database["blackjack games"].insert_one(newGame)
|
self.bot.database["blackjack games"].insert_one(newGame)
|
||||||
|
|
||||||
tableImagesPath = "resources/games/blackjackTables/"
|
tableImagesPath = "gwendolyn/resources/games/blackjack_tables/"
|
||||||
emptyTableImagePath = f"resources/games/blackjackTable.png"
|
emptyTableImagePath = f"gwendolyn/resources/games/blackjack_table.png"
|
||||||
newTableImagePath = f"{tableImagesPath}blackjackTable{channel}.png"
|
newTableImagePath = f"{tableImagesPath}blackjack_table{channel}.png"
|
||||||
copyfile(emptyTableImagePath, newTableImagePath)
|
copyfile(emptyTableImagePath, newTableImagePath)
|
||||||
|
|
||||||
gameStarted = True
|
gameStarted = True
|
||||||
@ -1112,20 +1112,20 @@ class Blackjack():
|
|||||||
sendMessage = self.bot.long_strings["Blackjack started"]
|
sendMessage = self.bot.long_strings["Blackjack started"]
|
||||||
await ctx.channel.send(sendMessage)
|
await ctx.channel.send(sendMessage)
|
||||||
|
|
||||||
tableImagesPath = "resources/games/blackjackTables/"
|
tableImagesPath = "gwendolyn/resources/games/blackjack_tables/"
|
||||||
filePath = f"{tableImagesPath}blackjackTable{channel}.png"
|
file_path = f"{tableImagesPath}blackjack_table{channel}.png"
|
||||||
|
|
||||||
oldImage = await ctx.channel.send(file=discord.File(filePath))
|
old_image = await ctx.channel.send(file=discord.File(file_path))
|
||||||
|
|
||||||
with open("resources/games/old_images/blackjack"+channel, "w") as f:
|
with open("gwendolyn/resources/games/old_images/blackjack"+channel, "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
|
|
||||||
await asyncio.sleep(30)
|
await asyncio.sleep(30)
|
||||||
|
|
||||||
gamedone = False
|
gamedone = False
|
||||||
|
|
||||||
blackjackGames = self.bot.database["blackjack games"]
|
blackjack_games = self.bot.database["blackjack games"]
|
||||||
game = blackjackGames.find_one({"_id": channel})
|
game = blackjack_games.find_one({"_id": channel})
|
||||||
|
|
||||||
if len(game["user hands"]) == 0:
|
if len(game["user hands"]) == 0:
|
||||||
gamedone = True
|
gamedone = True
|
||||||
@ -1136,10 +1136,10 @@ class Blackjack():
|
|||||||
|
|
||||||
# Loop of game rounds
|
# Loop of game rounds
|
||||||
if not gamedone:
|
if not gamedone:
|
||||||
self.bot.log("start() calling _blackjackLoop()", channel)
|
self.bot.log("start() calling _blackjack_loop()", channel)
|
||||||
await self._blackjackLoop(ctx.channel, 1, gameID)
|
await self._blackjack_loop(ctx.channel, 1, gameID)
|
||||||
else:
|
else:
|
||||||
new_message = self._blackjackFinish(channel)
|
new_message = self._blackjack_finish(channel)
|
||||||
await ctx.channel.send(new_message)
|
await ctx.channel.send(new_message)
|
||||||
else:
|
else:
|
||||||
sendMessage = self.bot.long_strings["Blackjack going on"]
|
sendMessage = self.bot.long_strings["Blackjack going on"]
|
||||||
@ -1173,7 +1173,7 @@ class Blackjack():
|
|||||||
The context of the command.
|
The context of the command.
|
||||||
"""
|
"""
|
||||||
channel = ctx.channel_id
|
channel = ctx.channel_id
|
||||||
self._blackjackShuffle(str(channel))
|
self._blackjack_shuffle(str(channel))
|
||||||
self.bot.log("Shuffling the blackjack deck...", str(channel))
|
self.bot.log("Shuffling the blackjack deck...", str(channel))
|
||||||
await ctx.send("Shuffling the deck...")
|
await ctx.send("Shuffling the deck...")
|
||||||
|
|
||||||
@ -1188,8 +1188,8 @@ class Blackjack():
|
|||||||
"""
|
"""
|
||||||
channel = ctx.channel_id
|
channel = ctx.channel_id
|
||||||
cardsLeft = 0
|
cardsLeft = 0
|
||||||
blackjackGames = self.bot.database["blackjack cards"]
|
blackjack_games = self.bot.database["blackjack cards"]
|
||||||
cards = blackjackGames.find_one({"_id": str(channel)})
|
cards = blackjack_games.find_one({"_id": str(channel)})
|
||||||
if cards is not None:
|
if cards is not None:
|
||||||
cardsLeft = len(cards["cards"])
|
cardsLeft = len(cards["cards"])
|
||||||
|
|
||||||
@ -1234,11 +1234,11 @@ class DrawBlackjack():
|
|||||||
self.bot.log("Drawing blackjack table", channel)
|
self.bot.log("Drawing blackjack table", channel)
|
||||||
game = self.bot.database["blackjack games"].find_one({"_id": channel})
|
game = self.bot.database["blackjack games"].find_one({"_id": channel})
|
||||||
|
|
||||||
font = ImageFont.truetype('resources/fonts/futura-bold.ttf', 50)
|
font = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', 50)
|
||||||
smallFont = ImageFont.truetype('resources/fonts/futura-bold.ttf', 40)
|
smallFont = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', 40)
|
||||||
self.SMALLBORDER = int(self.BORDER/3.5)
|
self.SMALLBORDER = int(self.BORDER/3.5)
|
||||||
|
|
||||||
table = Image.open("resources/games/blackjackTable.png")
|
table = Image.open("gwendolyn/resources/games/blackjack_table.png")
|
||||||
textImage = ImageDraw.Draw(table)
|
textImage = ImageDraw.Draw(table)
|
||||||
hands = game["user hands"]
|
hands = game["user hands"]
|
||||||
|
|
||||||
@ -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.database_funcs.getName(key)
|
key = self.bot.database_funcs.get_name(key)
|
||||||
handParams = [
|
handParams = [
|
||||||
value["hand"],
|
value["hand"],
|
||||||
False,
|
False,
|
||||||
@ -1359,8 +1359,8 @@ class DrawBlackjack():
|
|||||||
textImage.text((textX, 1015), key, fill=white, font=smallFont)
|
textImage.text((textX, 1015), key, fill=white, font=smallFont)
|
||||||
|
|
||||||
self.bot.log("Saving table image")
|
self.bot.log("Saving table image")
|
||||||
tableImagesPath = "resources/games/blackjackTables/"
|
tableImagesPath = "gwendolyn/resources/games/blackjack_tables/"
|
||||||
tableImagePath = f"{tableImagesPath}blackjackTable{channel}.png"
|
tableImagePath = f"{tableImagesPath}blackjack_table{channel}.png"
|
||||||
table.save(tableImagePath)
|
table.save(tableImagePath)
|
||||||
|
|
||||||
return
|
return
|
||||||
@ -1388,8 +1388,8 @@ class DrawBlackjack():
|
|||||||
The image of the hand.
|
The image of the hand.
|
||||||
"""
|
"""
|
||||||
self.bot.log("Drawing hand {hand}, {busted}, {blackjack}")
|
self.bot.log("Drawing hand {hand}, {busted}, {blackjack}")
|
||||||
font = ImageFont.truetype('resources/fonts/futura-bold.ttf', 200)
|
font = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', 200)
|
||||||
font2 = ImageFont.truetype('resources/fonts/futura-bold.ttf', 120)
|
font2 = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', 120)
|
||||||
length = len(hand)
|
length = len(hand)
|
||||||
backgroundWidth = (self.BORDER*2)+691+(125*(length-1))
|
backgroundWidth = (self.BORDER*2)+691+(125*(length-1))
|
||||||
backgroundSize = (backgroundWidth, (self.BORDER*2)+1065)
|
backgroundSize = (backgroundWidth, (self.BORDER*2)+1065)
|
||||||
@ -1398,15 +1398,15 @@ class DrawBlackjack():
|
|||||||
cardY = self.BORDER+self.PLACEMENT[1]
|
cardY = self.BORDER+self.PLACEMENT[1]
|
||||||
|
|
||||||
if dealer:
|
if dealer:
|
||||||
img = Image.open("resources/games/cards/"+hand[0].upper()+".png")
|
img = Image.open("gwendolyn/resources/games/cards/"+hand[0].upper()+".png")
|
||||||
cardPosition = (self.BORDER+self.PLACEMENT[0], cardY)
|
cardPosition = (self.BORDER+self.PLACEMENT[0], cardY)
|
||||||
background.paste(img, cardPosition, img)
|
background.paste(img, cardPosition, img)
|
||||||
img = Image.open("resources/games/cards/red_back.png")
|
img = Image.open("gwendolyn/resources/games/cards/red_back.png")
|
||||||
cardPosition = (125+self.BORDER+self.PLACEMENT[0], cardY)
|
cardPosition = (125+self.BORDER+self.PLACEMENT[0], cardY)
|
||||||
background.paste(img, cardPosition, img)
|
background.paste(img, cardPosition, img)
|
||||||
else:
|
else:
|
||||||
for x in range(length):
|
for x in range(length):
|
||||||
cardPath = f"resources/games/cards/{hand[x].upper()}.png"
|
cardPath = f"gwendolyn/resources/games/cards/{hand[x].upper()}.png"
|
||||||
img = Image.open(cardPath)
|
img = Image.open(cardPath)
|
||||||
cardPosition = (self.BORDER+(x*125)+self.PLACEMENT[0], cardY)
|
cardPosition = (self.BORDER+(x*125)+self.PLACEMENT[0], cardY)
|
||||||
background.paste(img, cardPosition, img)
|
background.paste(img, cardPosition, img)
|
@ -133,8 +133,8 @@ 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.database_funcs.getName(opponent)
|
opponentName = self.bot.database_funcs.get_name(opponent)
|
||||||
turnName = self.bot.database_funcs.getName(players[0])
|
turnName = self.bot.database_funcs.get_name(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"
|
||||||
@ -146,20 +146,20 @@ class ConnectFour():
|
|||||||
|
|
||||||
# Sets the whole game in motion
|
# Sets the whole game in motion
|
||||||
if startedGame:
|
if startedGame:
|
||||||
boardsPath = "resources/games/connect4Boards/"
|
boardsPath = "gwendolyn/resources/games/connect4Boards/"
|
||||||
filePath = f"{boardsPath}board{ctx.channel_id}.png"
|
file_path = f"{boardsPath}board{ctx.channel_id}.png"
|
||||||
oldImage = await ctx.channel.send(file=discord.File(filePath))
|
old_image = await ctx.channel.send(file=discord.File(file_path))
|
||||||
|
|
||||||
old_imagesPath = "resources/games/old_images/"
|
old_imagesPath = "gwendolyn/resources/games/old_images/"
|
||||||
oldImagePath = f"{old_imagesPath}connect_four{ctx.channel_id}"
|
old_imagePath = f"{old_imagesPath}connect_four{ctx.channel_id}"
|
||||||
with open(oldImagePath, "w") as f:
|
with open(old_imagePath, "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
|
|
||||||
if gwendoTurn:
|
if gwendoTurn:
|
||||||
await self._connect_fourAI(ctx)
|
await self._connect_fourAI(ctx)
|
||||||
else:
|
else:
|
||||||
for reaction in self.REACTIONS:
|
for reaction in self.REACTIONS:
|
||||||
await oldImage.add_reaction(reaction)
|
await old_image.add_reaction(reaction)
|
||||||
|
|
||||||
async def placePiece(self, ctx: Union[SlashContext, discord.Message],
|
async def placePiece(self, ctx: Union[SlashContext, discord.Message],
|
||||||
user: int, column: int):
|
user: int, column: int):
|
||||||
@ -183,7 +183,7 @@ 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.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
placedPiece = False
|
placedPiece = False
|
||||||
|
|
||||||
if game is None:
|
if game is None:
|
||||||
@ -216,8 +216,8 @@ class ConnectFour():
|
|||||||
connect4Games.update_one({"_id": channel}, updater)
|
connect4Games.update_one({"_id": channel}, updater)
|
||||||
|
|
||||||
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(user_name, column+1)
|
||||||
log_message = f"{userName} won"
|
log_message = f"{user_name} 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"
|
||||||
@ -229,9 +229,9 @@ class ConnectFour():
|
|||||||
else:
|
else:
|
||||||
gameWon = False
|
gameWon = False
|
||||||
otherUserId = game["players"][turn]
|
otherUserId = game["players"][turn]
|
||||||
otherUserName = self.bot.database_funcs.getName(otherUserId)
|
otherUserName = self.bot.database_funcs.get_name(otherUserId)
|
||||||
sendMessage = self.bot.long_strings["Connect 4 placed"]
|
sendMessage = self.bot.long_strings["Connect 4 placed"]
|
||||||
formatParams = [userName, column+1, otherUserName]
|
formatParams = [user_name, column+1, otherUserName]
|
||||||
sendMessage = sendMessage.format(*formatParams)
|
sendMessage = sendMessage.format(*formatParams)
|
||||||
log_message = "They placed the piece"
|
log_message = "They placed the piece"
|
||||||
|
|
||||||
@ -245,28 +245,28 @@ class ConnectFour():
|
|||||||
if placedPiece:
|
if placedPiece:
|
||||||
self.draw.drawImage(channel)
|
self.draw.drawImage(channel)
|
||||||
|
|
||||||
oldImagePath = f"resources/games/old_images/connect_four{channel}"
|
old_imagePath = f"gwendolyn/resources/games/old_images/connect_four{channel}"
|
||||||
with open(oldImagePath, "r") as f:
|
with open(old_imagePath, "r") as f:
|
||||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||||
|
|
||||||
if oldImage is not None:
|
if old_image is not None:
|
||||||
await oldImage.delete()
|
await old_image.delete()
|
||||||
else:
|
else:
|
||||||
self.bot.log("The old image was already deleted")
|
self.bot.log("The old image was already deleted")
|
||||||
|
|
||||||
filePath = f"resources/games/connect4Boards/board{channel}.png"
|
file_path = f"gwendolyn/resources/games/connect4Boards/board{channel}.png"
|
||||||
oldImage = await ctx.channel.send(file=discord.File(filePath))
|
old_image = await ctx.channel.send(file=discord.File(file_path))
|
||||||
|
|
||||||
if gameWon:
|
if gameWon:
|
||||||
self._endGame(channel)
|
self._endGame(channel)
|
||||||
else:
|
else:
|
||||||
with open(oldImagePath, "w") as f:
|
with open(old_imagePath, "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
if gwendoTurn:
|
if gwendoTurn:
|
||||||
await self._connect_fourAI(ctx)
|
await self._connect_fourAI(ctx)
|
||||||
else:
|
else:
|
||||||
for reaction in self.REACTIONS:
|
for reaction in self.REACTIONS:
|
||||||
await oldImage.add_reaction(reaction)
|
await old_image.add_reaction(reaction)
|
||||||
|
|
||||||
async def surrender(self, ctx: SlashContext):
|
async def surrender(self, ctx: SlashContext):
|
||||||
"""
|
"""
|
||||||
@ -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.database_funcs.getName(winnerID)
|
winnerName = self.bot.database_funcs.get_name(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,12 +295,12 @@ 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/old_images/connect_four{channel}"
|
old_imagePath = f"gwendolyn/resources/games/old_images/connect_four{channel}"
|
||||||
with open(oldImagePath, "r") as f:
|
with open(old_imagePath, "r") as f:
|
||||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||||
|
|
||||||
if oldImage is not None:
|
if old_image is not None:
|
||||||
await oldImage.delete()
|
await old_image.delete()
|
||||||
else:
|
else:
|
||||||
self.bot.log("The old image was already deleted")
|
self.bot.log("The old image was already deleted")
|
||||||
|
|
||||||
@ -331,7 +331,7 @@ class ConnectFour():
|
|||||||
"""
|
"""
|
||||||
placementX, placementY = -1, column
|
placementX, placementY = -1, column
|
||||||
|
|
||||||
for x, line in enumerate(board):
|
for x, line in list(enumerate(board))[::-1]:
|
||||||
if line[column] == 0:
|
if line[column] == 0:
|
||||||
placementX = x
|
placementX = x
|
||||||
break
|
break
|
||||||
@ -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.database_funcs.deleteGame("connect 4 games", channel)
|
self.bot.database_funcs.delete_game("connect 4 games", channel)
|
||||||
|
|
||||||
def _isWon(self, board: dict):
|
def _isWon(self, board: dict):
|
||||||
won = 0
|
won = 0
|
||||||
@ -444,7 +444,7 @@ class ConnectFour():
|
|||||||
player = game["players"].index(f"#{self.bot.user.id}")+1
|
player = game["players"].index(f"#{self.bot.user.id}")+1
|
||||||
difficulty = game["difficulty"]
|
difficulty = game["difficulty"]
|
||||||
|
|
||||||
scores = [int(-math.inf) for _ in range(COLUMNCOUNT)]
|
scores = [-math.inf for _ in range(COLUMNCOUNT)]
|
||||||
for column in range(COLUMNCOUNT):
|
for column in range(COLUMNCOUNT):
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = self._placeOnBoard(testBoard, player, column)
|
testBoard = self._placeOnBoard(testBoard, player, column)
|
||||||
@ -454,8 +454,8 @@ class ConnectFour():
|
|||||||
difficulty,
|
difficulty,
|
||||||
player % 2+1,
|
player % 2+1,
|
||||||
player,
|
player,
|
||||||
int(-math.inf),
|
-math.inf,
|
||||||
int(math.inf),
|
math.inf,
|
||||||
False
|
False
|
||||||
]
|
]
|
||||||
scores[column] = await self._minimax(*_minimaxParams)
|
scores[column] = await self._minimax(*_minimaxParams)
|
||||||
@ -564,7 +564,7 @@ class ConnectFour():
|
|||||||
if depth == 0 or terminal or (points > 5000 or points < -6000):
|
if depth == 0 or terminal or (points > 5000 or points < -6000):
|
||||||
return points
|
return points
|
||||||
if maximizingPlayer:
|
if maximizingPlayer:
|
||||||
value = int(-math.inf)
|
value = -math.inf
|
||||||
for column in range(0, COLUMNCOUNT):
|
for column in range(0, COLUMNCOUNT):
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = self._placeOnBoard(testBoard, player, column)
|
testBoard = self._placeOnBoard(testBoard, player, column)
|
||||||
@ -587,7 +587,7 @@ class ConnectFour():
|
|||||||
break
|
break
|
||||||
return value
|
return value
|
||||||
else:
|
else:
|
||||||
value = int(math.inf)
|
value = math.inf
|
||||||
for column in range(0, COLUMNCOUNT):
|
for column in range(0, COLUMNCOUNT):
|
||||||
testBoard = copy.deepcopy(board)
|
testBoard = copy.deepcopy(board)
|
||||||
testBoard = self._placeOnBoard(testBoard, player, column)
|
testBoard = self._placeOnBoard(testBoard, player, column)
|
||||||
@ -694,7 +694,7 @@ class DrawConnectFour():
|
|||||||
winbarAlpha = 160
|
winbarAlpha = 160
|
||||||
self.WINBARCOLOR = (250, 250, 250, 255)
|
self.WINBARCOLOR = (250, 250, 250, 255)
|
||||||
self.PIECESIZE = 300
|
self.PIECESIZE = 300
|
||||||
fontPath = "resources/fonts/futura-bold.ttf"
|
fontPath = "gwendolyn/resources/fonts/futura-bold.ttf"
|
||||||
|
|
||||||
self.FONT = ImageFont.truetype(fontPath, self.TEXTSIZE)
|
self.FONT = ImageFont.truetype(fontPath, self.TEXTSIZE)
|
||||||
|
|
||||||
@ -740,7 +740,7 @@ class DrawConnectFour():
|
|||||||
|
|
||||||
self._drawFooter(d, game)
|
self._drawFooter(d, game)
|
||||||
|
|
||||||
background.save(f"resources/games/connect4Boards/board{channel}.png")
|
background.save(f"gwendolyn/resources/games/connect4Boards/board{channel}.png")
|
||||||
|
|
||||||
def _drawBoard(self, d: ImageDraw):
|
def _drawBoard(self, d: ImageDraw):
|
||||||
# This whole part was the easiest way to make a rectangle with
|
# This whole part was the easiest way to make a rectangle with
|
||||||
@ -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.database_funcs.getName(game["players"][0])
|
player1 = self.bot.database_funcs.get_name(game["players"][0])
|
||||||
|
|
||||||
if game["players"][1] == "Gwendolyn":
|
if game["players"][1] == "Gwendolyn":
|
||||||
player2 = "Gwendolyn"
|
player2 = "Gwendolyn"
|
||||||
else:
|
else:
|
||||||
player2 = self.bot.database_funcs.getName(game["players"][1])
|
player2 = self.bot.database_funcs.get_name(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
|
@ -46,7 +46,7 @@ class Hangman():
|
|||||||
self.__bot = bot
|
self.__bot = bot
|
||||||
self.__draw = DrawHangman(bot)
|
self.__draw = DrawHangman(bot)
|
||||||
self.__APIURL = "https://api.wordnik.com/v4/words.json/randomWords?"
|
self.__APIURL = "https://api.wordnik.com/v4/words.json/randomWords?"
|
||||||
apiKey = self.__bot.credentials.wordnikKey
|
apiKey = self.__bot.credentials["wordnik_key"]
|
||||||
self.__APIPARAMS = {
|
self.__APIPARAMS = {
|
||||||
"hasDictionaryDef": True,
|
"hasDictionaryDef": True,
|
||||||
"minCorpusCount": 5000,
|
"minCorpusCount": 5000,
|
||||||
@ -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.database_funcs.getName(user)
|
user_name = self.__bot.database_funcs.get_name(user)
|
||||||
startedGame = False
|
startedGame = False
|
||||||
|
|
||||||
if game is None:
|
if game is None:
|
||||||
@ -100,7 +100,7 @@ class Hangman():
|
|||||||
self.__draw.drawImage(channel)
|
self.__draw.drawImage(channel)
|
||||||
|
|
||||||
log_message = "Game started"
|
log_message = "Game started"
|
||||||
sendMessage = f"{userName} started game of hangman."
|
sendMessage = f"{user_name} started game of hangman."
|
||||||
startedGame = True
|
startedGame = True
|
||||||
else:
|
else:
|
||||||
log_message = "There was already a game going on"
|
log_message = "There was already a game going on"
|
||||||
@ -110,9 +110,9 @@ class Hangman():
|
|||||||
await ctx.send(sendMessage)
|
await ctx.send(sendMessage)
|
||||||
|
|
||||||
if startedGame:
|
if startedGame:
|
||||||
boardsPath = "resources/games/hangmanBoards/"
|
boardsPath = "gwendolyn/resources/games/hangman_boards/"
|
||||||
filePath = f"{boardsPath}hangmanBoard{channel}.png"
|
file_path = f"{boardsPath}hangman_board{channel}.png"
|
||||||
newImage = await ctx.channel.send(file=discord.File(filePath))
|
newImage = await ctx.channel.send(file=discord.File(file_path))
|
||||||
|
|
||||||
blankMessage = await ctx.channel.send("_ _")
|
blankMessage = await ctx.channel.send("_ _")
|
||||||
reactionMessages = {
|
reactionMessages = {
|
||||||
@ -120,10 +120,10 @@ class Hangman():
|
|||||||
blankMessage: remainingLetters[15:]
|
blankMessage: remainingLetters[15:]
|
||||||
}
|
}
|
||||||
|
|
||||||
oldMessages = f"{newImage.id}\n{blankMessage.id}"
|
old_messages = f"{newImage.id}\n{blankMessage.id}"
|
||||||
|
|
||||||
with open(f"resources/games/old_images/hangman{channel}", "w") as f:
|
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "w") as f:
|
||||||
f.write(oldMessages)
|
f.write(old_messages)
|
||||||
|
|
||||||
for message, letters in reactionMessages.items():
|
for message, letters in reactionMessages.items():
|
||||||
for letter in letters:
|
for letter in letters:
|
||||||
@ -149,13 +149,13 @@ 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/old_images/hangman{channel}", "r") as f:
|
with open(f"gwendolyn/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:
|
||||||
oldMessage = await ctx.channel.fetch_message(int(message))
|
old_message = await ctx.channel.fetch_message(int(message))
|
||||||
self.__bot.log("Deleting old message")
|
self.__bot.log("Deleting old message")
|
||||||
await oldMessage.delete()
|
await old_message.delete()
|
||||||
|
|
||||||
await ctx.send("Game stopped")
|
await ctx.send("Game stopped")
|
||||||
|
|
||||||
@ -173,8 +173,8 @@ class Hangman():
|
|||||||
The guess.
|
The guess.
|
||||||
"""
|
"""
|
||||||
channel = str(message.channel.id)
|
channel = str(message.channel.id)
|
||||||
hangmanGames = self.__bot.database["hangman games"]
|
hangman_games = self.__bot.database["hangman games"]
|
||||||
game = hangmanGames.find_one({"_id": channel})
|
game = hangman_games.find_one({"_id": channel})
|
||||||
|
|
||||||
gameExists = (game is not None)
|
gameExists = (game is not None)
|
||||||
singleLetter = (len(guess) == 1 and guess.isalpha())
|
singleLetter = (len(guess) == 1 and guess.isalpha())
|
||||||
@ -189,18 +189,18 @@ class Hangman():
|
|||||||
if guess == letter:
|
if guess == letter:
|
||||||
correctGuess += 1
|
correctGuess += 1
|
||||||
updater = {"$set": {f"guessed.{x}": True}}
|
updater = {"$set": {f"guessed.{x}": True}}
|
||||||
hangmanGames.update_one({"_id": channel}, updater)
|
hangman_games.update_one({"_id": channel}, updater)
|
||||||
|
|
||||||
if correctGuess == 0:
|
if correctGuess == 0:
|
||||||
updater = {"$inc": {"misses": 1}}
|
updater = {"$inc": {"misses": 1}}
|
||||||
hangmanGames.update_one({"_id": channel}, updater)
|
hangman_games.update_one({"_id": channel}, updater)
|
||||||
|
|
||||||
updater = {"$push": {"guessed letters": guess}}
|
updater = {"$push": {"guessed letters": guess}}
|
||||||
hangmanGames.update_one({"_id": channel}, updater)
|
hangman_games.update_one({"_id": channel}, updater)
|
||||||
|
|
||||||
remainingLetters = list(string.ascii_uppercase)
|
remainingLetters = list(string.ascii_uppercase)
|
||||||
|
|
||||||
game = hangmanGames.find_one({"_id": channel})
|
game = hangman_games.find_one({"_id": channel})
|
||||||
|
|
||||||
for letter in game["guessed letters"]:
|
for letter in game["guessed letters"]:
|
||||||
remainingLetters.remove(letter)
|
remainingLetters.remove(letter)
|
||||||
@ -215,28 +215,28 @@ class Hangman():
|
|||||||
self.__draw.drawImage(channel)
|
self.__draw.drawImage(channel)
|
||||||
|
|
||||||
if game["misses"] == 6:
|
if game["misses"] == 6:
|
||||||
hangmanGames.delete_one({"_id": channel})
|
hangman_games.delete_one({"_id": channel})
|
||||||
sendMessage += self.__bot.long_strings["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})
|
hangman_games.delete_one({"_id": channel})
|
||||||
self.__bot.money.addMoney(user, 15)
|
self.__bot.money.addMoney(user, 15)
|
||||||
sendMessage += self.__bot.long_strings["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/old_images/hangman{channel}", "r") as f:
|
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f:
|
||||||
oldMessageIDs = f.read().splitlines()
|
old_message_ids = f.read().splitlines()
|
||||||
|
|
||||||
for oldID in oldMessageIDs:
|
for oldID in old_message_ids:
|
||||||
oldMessage = await message.channel.fetch_message(int(oldID))
|
old_message = await message.channel.fetch_message(int(oldID))
|
||||||
self.__bot.log("Deleting old message")
|
self.__bot.log("Deleting old message")
|
||||||
await oldMessage.delete()
|
await old_message.delete()
|
||||||
|
|
||||||
boardsPath = "resources/games/hangmanBoards/"
|
boardsPath = "gwendolyn/resources/games/hangman_boards/"
|
||||||
filePath = f"{boardsPath}hangmanBoard{channel}.png"
|
file_path = f"{boardsPath}hangman_board{channel}.png"
|
||||||
newImage = await message.channel.send(file=discord.File(filePath))
|
newImage = await message.channel.send(file=discord.File(file_path))
|
||||||
|
|
||||||
if len(remainingLetters) > 0:
|
if len(remainingLetters) > 0:
|
||||||
if len(remainingLetters) > 15:
|
if len(remainingLetters) > 15:
|
||||||
@ -250,13 +250,13 @@ class Hangman():
|
|||||||
reactionMessages = {newImage: remainingLetters}
|
reactionMessages = {newImage: remainingLetters}
|
||||||
|
|
||||||
if blankMessage != "":
|
if blankMessage != "":
|
||||||
oldMessages = f"{newImage.id}\n{blankMessage.id}"
|
old_messages = f"{newImage.id}\n{blankMessage.id}"
|
||||||
else:
|
else:
|
||||||
oldMessages = str(newImage.id)
|
old_messages = str(newImage.id)
|
||||||
|
|
||||||
oldImagePath = f"resources/games/old_images/hangman{channel}"
|
old_imagePath = f"gwendolyn/resources/games/old_images/hangman{channel}"
|
||||||
with open(oldImagePath, "w") as f:
|
with open(old_imagePath, "w") as f:
|
||||||
f.write(oldMessages)
|
f.write(old_messages)
|
||||||
|
|
||||||
for message, letters in reactionMessages.items():
|
for message, letters in reactionMessages.items():
|
||||||
for letter in letters:
|
for letter in letters:
|
||||||
@ -315,7 +315,7 @@ class DrawHangman():
|
|||||||
LETTERSIZE = 75 # Wrong guesses letter size
|
LETTERSIZE = 75 # Wrong guesses letter size
|
||||||
WORDSIZE = 70 # Correct guesses letter size
|
WORDSIZE = 70 # Correct guesses letter size
|
||||||
|
|
||||||
FONTPATH = "resources/fonts/comic-sans-bold.ttf"
|
FONTPATH = "gwendolyn/resources/fonts/comic-sans-bold.ttf"
|
||||||
self.__FONT = ImageFont.truetype(FONTPATH, LETTERSIZE)
|
self.__FONT = ImageFont.truetype(FONTPATH, LETTERSIZE)
|
||||||
self.__SMALLFONT = ImageFont.truetype(FONTPATH, WORDSIZE)
|
self.__SMALLFONT = ImageFont.truetype(FONTPATH, WORDSIZE)
|
||||||
|
|
||||||
@ -588,7 +588,7 @@ class DrawHangman():
|
|||||||
|
|
||||||
random.seed(game["game ID"])
|
random.seed(game["game ID"])
|
||||||
|
|
||||||
background = Image.open("resources/paper.jpg")
|
background = Image.open("gwendolyn/resources/paper.jpg")
|
||||||
gallow = self.__drawGallows()
|
gallow = self.__drawGallows()
|
||||||
man = self.__drawMan(game["misses"], game["game ID"])
|
man = self.__drawMan(game["misses"], game["game ID"])
|
||||||
|
|
||||||
@ -608,5 +608,5 @@ class DrawHangman():
|
|||||||
missesTextWidth = missesText.size[0]
|
missesTextWidth = missesText.size[0]
|
||||||
background.paste(missesText, (850-missesTextWidth//2, 50), missesText)
|
background.paste(missesText, (850-missesTextWidth//2, 50), missesText)
|
||||||
|
|
||||||
boardPath = f"resources/games/hangmanBoards/hangmanBoard{channel}.png"
|
boardPath = f"gwendolyn/resources/games/hangman_boards/hangman_board{channel}.png"
|
||||||
background.save(boardPath)
|
background.save(boardPath)
|
@ -28,24 +28,24 @@ 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.database_funcs.getName(players[opponent])
|
opponentName = self.bot.database_funcs.get_name(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/old_images/hex{channel}", "r") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||||
|
|
||||||
if oldImage is not None:
|
if old_image is not None:
|
||||||
await oldImage.delete()
|
await old_image.delete()
|
||||||
else:
|
else:
|
||||||
self.bot.log("The old image was already deleted")
|
self.bot.log("The old image was already deleted")
|
||||||
|
|
||||||
self.bot.log("Sending the image")
|
self.bot.log("Sending the image")
|
||||||
filePath = f"resources/games/hexBoards/board{channel}.png"
|
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||||
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||||
|
|
||||||
with open(f"resources/games/old_images/hex{channel}", "w") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
|
|
||||||
self.bot.database["hex games"].delete_one({"_id":channel})
|
self.bot.database["hex games"].delete_one({"_id":channel})
|
||||||
|
|
||||||
@ -72,23 +72,23 @@ 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.database_funcs.getName(opponent)
|
opponentName = self.bot.database_funcs.get_name(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/old_images/hex{channel}", "r") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||||
|
|
||||||
if oldImage is not None:
|
if old_image is not None:
|
||||||
await oldImage.delete()
|
await old_image.delete()
|
||||||
else:
|
else:
|
||||||
self.bot.log("The old image was already deleted")
|
self.bot.log("The old image was already deleted")
|
||||||
|
|
||||||
self.bot.log("Sending the image")
|
self.bot.log("Sending the image")
|
||||||
filePath = f"resources/games/hexBoards/board{channel}.png"
|
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||||
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||||
|
|
||||||
with open(f"resources/games/old_images/hex{channel}", "w") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
|
|
||||||
if gwendoTurn:
|
if gwendoTurn:
|
||||||
await self.hexAI(ctx)
|
await self.hexAI(ctx)
|
||||||
@ -167,7 +167,7 @@ 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.database_funcs.getName(players[0])
|
turnName = self.bot.database_funcs.get_name(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"
|
||||||
log_message = "Game started"
|
log_message = "Game started"
|
||||||
|
|
||||||
@ -175,10 +175,10 @@ class HexGame():
|
|||||||
self.bot.log(log_message)
|
self.bot.log(log_message)
|
||||||
|
|
||||||
if startedGame:
|
if startedGame:
|
||||||
filePath = f"resources/games/hexBoards/board{ctx.channel_id}.png"
|
file_path = f"gwendolyn/resources/games/hex_boards/board{ctx.channel_id}.png"
|
||||||
newImage = await ctx.channel.send(file = discord.File(filePath))
|
newImage = await ctx.channel.send(file = discord.File(file_path))
|
||||||
|
|
||||||
with open(f"resources/games/old_images/hex{ctx.channel_id}", "w") as f:
|
with open(f"gwendolyn/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.database_funcs.getName(game['players'][0])} and {self.bot.database_funcs.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.get_name(game['players'][0])} and {self.bot.database_funcs.get_name(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.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)
|
sendMessage = self.bot.database_funcs.get_name(game["players"][player-1])+" placed at "+position.upper()+". It's now "+self.bot.database_funcs.get_name(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.database_funcs.getName(game["players"][player-1])+" placed at "+position.upper()+" and won!"
|
sendMessage = self.bot.database_funcs.get_name(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,17 +258,17 @@ 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/old_images/hex{channel}", "r") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||||
|
|
||||||
if oldImage is not None:
|
if old_image is not None:
|
||||||
await oldImage.delete()
|
await old_image.delete()
|
||||||
else:
|
else:
|
||||||
self.bot.log("The old image was already deleted")
|
self.bot.log("The old image was already deleted")
|
||||||
|
|
||||||
self.bot.log("Sending the image")
|
self.bot.log("Sending the image")
|
||||||
filePath = f"resources/games/hexBoards/board{channel}.png"
|
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||||
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||||
|
|
||||||
if gameWon:
|
if gameWon:
|
||||||
self.bot.log("Dealing with the winning player")
|
self.bot.log("Dealing with the winning player")
|
||||||
@ -281,8 +281,8 @@ 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/old_images/hex{channel}", "w") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
|
|
||||||
if gwendoTurn:
|
if gwendoTurn:
|
||||||
await self.hexAI(ctx)
|
await self.hexAI(ctx)
|
||||||
@ -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.database_funcs.getName(user)))
|
self.bot.log("Undoing {}'s last move".format(self.bot.database_funcs.get_name(user)))
|
||||||
|
|
||||||
lastMove = game["gameHistory"].pop()
|
lastMove = game["gameHistory"].pop()
|
||||||
game["board"][lastMove[0]][lastMove[1]] = 0
|
game["board"][lastMove[0]][lastMove[1]] = 0
|
||||||
@ -337,20 +337,20 @@ class HexGame():
|
|||||||
|
|
||||||
await ctx.send(sendMessage)
|
await ctx.send(sendMessage)
|
||||||
if undid:
|
if undid:
|
||||||
with open(f"resources/games/old_images/hex{channel}", "r") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
|
||||||
oldImage = await ctx.channel.fetch_message(int(f.read()))
|
old_image = await ctx.channel.fetch_message(int(f.read()))
|
||||||
|
|
||||||
if oldImage is not None:
|
if old_image is not None:
|
||||||
await oldImage.delete()
|
await old_image.delete()
|
||||||
else:
|
else:
|
||||||
self.bot.log("The old image was already deleted")
|
self.bot.log("The old image was already deleted")
|
||||||
|
|
||||||
self.bot.log("Sending the image")
|
self.bot.log("Sending the image")
|
||||||
filePath = f"resources/games/hexBoards/board{channel}.png"
|
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
|
||||||
oldImage = await ctx.channel.send(file = discord.File(filePath))
|
old_image = await ctx.channel.send(file = discord.File(file_path))
|
||||||
|
|
||||||
with open(f"resources/games/old_images/hex{channel}", "w") as f:
|
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "w") as f:
|
||||||
f.write(str(oldImage.id))
|
f.write(str(old_image.id))
|
||||||
|
|
||||||
|
|
||||||
# Plays as the AI
|
# Plays as the AI
|
||||||
@ -474,7 +474,7 @@ class DrawHex():
|
|||||||
self.HEXAGONHEIGHT = 1.5 * self.SIDELENGTH
|
self.HEXAGONHEIGHT = 1.5 * self.SIDELENGTH
|
||||||
self.FONTSIZE = 45
|
self.FONTSIZE = 45
|
||||||
self.TEXTCOLOR = (0,0,0)
|
self.TEXTCOLOR = (0,0,0)
|
||||||
self.FONT = ImageFont.truetype('resources/fonts/futura-bold.ttf', self.FONTSIZE)
|
self.FONT = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', self.FONTSIZE)
|
||||||
|
|
||||||
self.LINETHICKNESS = 15
|
self.LINETHICKNESS = 15
|
||||||
self.HEXTHICKNESS = 6 # This is half the width of the background lining between every hex
|
self.HEXTHICKNESS = 6 # This is half the width of the background lining between every hex
|
||||||
@ -490,7 +490,7 @@ class DrawHex():
|
|||||||
self.COLYTHICKNESS = self.COLHEXTHICKNESS * math.sin(math.pi/6)
|
self.COLYTHICKNESS = self.COLHEXTHICKNESS * math.sin(math.pi/6)
|
||||||
# The Name display things:
|
# The Name display things:
|
||||||
self.NAMESIZE = 60
|
self.NAMESIZE = 60
|
||||||
self.NAMEFONT = ImageFont.truetype('resources/fonts/futura-bold.ttf', self.NAMESIZE)
|
self.NAMEFONT = ImageFont.truetype('gwendolyn/resources/fonts/futura-bold.ttf', self.NAMESIZE)
|
||||||
self.XNAME = {1:175, 2:self.CANVASWIDTH-100}
|
self.XNAME = {1:175, 2:self.CANVASWIDTH-100}
|
||||||
self.YNAME = {1:self.CANVASHEIGHT-150, 2:150}
|
self.YNAME = {1:self.CANVASHEIGHT-150, 2:150}
|
||||||
self.NAMEHEXPADDING = 90
|
self.NAMEHEXPADDING = 90
|
||||||
@ -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.database_funcs.getName(game["players"][p-1])
|
playername = self.bot.database_funcs.get_name(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
|
||||||
@ -573,13 +573,13 @@ class DrawHex():
|
|||||||
(x, y+self.SMALLSIDELENGTH),
|
(x, y+self.SMALLSIDELENGTH),
|
||||||
],fill = self.PIECECOLOR[p])
|
],fill = self.PIECECOLOR[p])
|
||||||
|
|
||||||
im.save("resources/games/hexBoards/board"+channel+".png")
|
im.save("gwendolyn/resources/games/hex_boards/board"+channel+".png")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
def drawHexPlacement(self, channel,player,position):
|
def drawHexPlacement(self, channel,player,position):
|
||||||
FILEPATH = "resources/games/hexBoards/board"+channel+".png"
|
FILEPATH = "gwendolyn/resources/games/hex_boards/board"+channel+".png"
|
||||||
self.bot.log(f"Drawing a newly placed hex. Filename: board{channel}.png")
|
self.bot.log(f"Drawing a newly placed hex. Filename: board{channel}.png")
|
||||||
|
|
||||||
# Translates position
|
# Translates position
|
||||||
@ -589,7 +589,7 @@ class DrawHex():
|
|||||||
row = int(position[1:])-1
|
row = int(position[1:])-1
|
||||||
|
|
||||||
# Find the coordinates for the filled hex drawing
|
# Find the coordinates for the filled hex drawing
|
||||||
hexCoords = [
|
hex_coords = [
|
||||||
(self.BOARDCOORDINATES[row][column][0]+self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
|
(self.BOARDCOORDINATES[row][column][0]+self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
|
||||||
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH/2, self.BOARDCOORDINATES[row][column][1]-0.5*self.SIDELENGTH + self.COLHEXTHICKNESS),
|
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH/2, self.BOARDCOORDINATES[row][column][1]-0.5*self.SIDELENGTH + self.COLHEXTHICKNESS),
|
||||||
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH-self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
|
(self.BOARDCOORDINATES[row][column][0]+self.HEXAGONWIDTH-self.COLXTHICKNESS, self.BOARDCOORDINATES[row][column][1] + self.COLYTHICKNESS),
|
||||||
@ -603,7 +603,7 @@ class DrawHex():
|
|||||||
with Image.open(FILEPATH) as im:
|
with Image.open(FILEPATH) as im:
|
||||||
d = ImageDraw.Draw(im,"RGBA")
|
d = ImageDraw.Draw(im,"RGBA")
|
||||||
# Draws the hex piece
|
# Draws the hex piece
|
||||||
d.polygon(hexCoords,fill = self.PIECECOLOR[player], outline = self.BETWEENCOLOR)
|
d.polygon(hex_coords,fill = self.PIECECOLOR[player], outline = self.BETWEENCOLOR)
|
||||||
|
|
||||||
# Save
|
# Save
|
||||||
im.save(FILEPATH)
|
im.save(FILEPATH)
|
||||||
@ -611,7 +611,7 @@ class DrawHex():
|
|||||||
self.bot.log("Error drawing new hex on board (error code 1541")
|
self.bot.log("Error drawing new hex on board (error code 1541")
|
||||||
|
|
||||||
def drawSwap(self, channel):
|
def drawSwap(self, channel):
|
||||||
FILEPATH = "resources/games/hexBoards/board"+channel+".png"
|
FILEPATH = "gwendolyn/resources/games/hex_boards/board"+channel+".png"
|
||||||
game = self.bot.database["hex games"].find_one({"_id":channel})
|
game = self.bot.database["hex games"].find_one({"_id":channel})
|
||||||
# Opens the image
|
# Opens the image
|
||||||
try:
|
try:
|
||||||
@ -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.database_funcs.getName(game["players"][p%2])
|
playername = self.bot.database_funcs.get_name(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
|
@ -65,12 +65,12 @@ 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.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
|
|
||||||
if userInvestments in [None, {}]:
|
if userInvestments in [None, {}]:
|
||||||
return f"{userName} does not have a stock portfolio."
|
return f"{user_name} does not have a stock portfolio."
|
||||||
else:
|
else:
|
||||||
portfolio = f"**Stock portfolio for {userName}**"
|
portfolio = f"**Stock portfolio for {user_name}**"
|
||||||
|
|
||||||
for key, value in list(userInvestments["investments"].items()):
|
for key, value in list(userInvestments["investments"].items()):
|
||||||
purchaseValue = value["purchased for"]
|
purchaseValue = value["purchased for"]
|
||||||
@ -162,9 +162,9 @@ class Invest():
|
|||||||
}
|
}
|
||||||
investmentsDatabase.insert_one(newUser)
|
investmentsDatabase.insert_one(newUser)
|
||||||
|
|
||||||
userName = self.bot.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
sendMessage = "{} bought {} GwendoBucks worth of {} stock"
|
sendMessage = "{} bought {} GwendoBucks worth of {} stock"
|
||||||
sendMessage = sendMessage.format(userName, buyAmount, stock)
|
sendMessage = sendMessage.format(user_name, buyAmount, stock)
|
||||||
return sendMessage
|
return sendMessage
|
||||||
|
|
||||||
def sellStock(self, user: str, stock: str, sellAmount: int):
|
def sellStock(self, user: str, stock: str, sellAmount: int):
|
||||||
@ -219,9 +219,9 @@ 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.database_funcs.getName(user)
|
user_name = self.bot.database_funcs.get_name(user)
|
||||||
sendMessage = "{} sold {} GwendoBucks worth of {} stock"
|
sendMessage = "{} sold {} GwendoBucks worth of {} stock"
|
||||||
return sendMessage.format(userName, sellAmount, stock)
|
return sendMessage.format(user_name, sellAmount, stock)
|
||||||
else:
|
else:
|
||||||
return f"You don't have enough {stock} stocks to do that"
|
return f"You don't have enough {stock} stocks to do that"
|
||||||
else:
|
else:
|
@ -69,11 +69,11 @@ class Money():
|
|||||||
"""
|
"""
|
||||||
await self.bot.defer(ctx)
|
await self.bot.defer(ctx)
|
||||||
response = self.checkBalance("#"+str(ctx.author.id))
|
response = self.checkBalance("#"+str(ctx.author.id))
|
||||||
userName = ctx.author.display_name
|
user_name = ctx.author.display_name
|
||||||
if response == 1:
|
if response == 1:
|
||||||
new_message = f"{userName} has {response} GwendoBuck"
|
new_message = f"{user_name} has {response} GwendoBuck"
|
||||||
else:
|
else:
|
||||||
new_message = f"{userName} has {response} GwendoBucks"
|
new_message = f"{user_name} has {response} GwendoBucks"
|
||||||
await ctx.send(new_message)
|
await ctx.send(new_message)
|
||||||
|
|
||||||
# Adds money to the account of a user
|
# Adds money to the account of a user
|
||||||
@ -98,7 +98,7 @@ class Money():
|
|||||||
else:
|
else:
|
||||||
newUser = {
|
newUser = {
|
||||||
"_id": user,
|
"_id": user,
|
||||||
"user name": self.bot.database_funcs.getName(user),
|
"user name": self.bot.database_funcs.get_name(user),
|
||||||
"money": amount
|
"money": amount
|
||||||
}
|
}
|
||||||
self.database["users"].insert_one(newUser)
|
self.database["users"].insert_one(newUser)
|
||||||
@ -120,13 +120,13 @@ class Money():
|
|||||||
"""
|
"""
|
||||||
await self.bot.defer(ctx)
|
await self.bot.defer(ctx)
|
||||||
username = user.display_name
|
username = user.display_name
|
||||||
if self.bot.database_funcs.getID(username) is None:
|
if self.bot.database_funcs.get_id(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
|
||||||
userID = f"#{member.id}"
|
user_id = f"#{member.id}"
|
||||||
newUser = {
|
newUser = {
|
||||||
"_id": userID,
|
"_id": user_id,
|
||||||
"user name": username,
|
"user name": username,
|
||||||
"money": 0
|
"money": 0
|
||||||
}
|
}
|
||||||
@ -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.database_funcs.getID(username)
|
targetUser = self.bot.database_funcs.get_id(username)
|
||||||
|
|
||||||
if amount <= 0:
|
if amount <= 0:
|
||||||
self.bot.log("They tried to steal")
|
self.bot.log("They tried to steal")
|
@ -181,8 +181,8 @@ class Trivia():
|
|||||||
|
|
||||||
self.triviaCountPoints(channelId)
|
self.triviaCountPoints(channelId)
|
||||||
|
|
||||||
deleteGameParams = ["trivia questions", channelId]
|
delete_gameParams = ["trivia questions", channelId]
|
||||||
self.bot.database_funcs.deleteGame(*deleteGameParams)
|
self.bot.database_funcs.delete_game(*delete_gameParams)
|
||||||
|
|
||||||
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.long_strings["Trivia time up"]
|
sendMessage = self.bot.long_strings["Trivia time up"]
|
||||||
@ -196,8 +196,8 @@ class Trivia():
|
|||||||
userId = f"#{ctx.author.id}"
|
userId = f"#{ctx.author.id}"
|
||||||
response = self.triviaAnswer(userId, channelId, answer)
|
response = self.triviaAnswer(userId, channelId, answer)
|
||||||
if response is None:
|
if response is None:
|
||||||
userName = ctx.author.display_name
|
user_name = ctx.author.display_name
|
||||||
await ctx.send(f"{userName} answered **{answer}**")
|
await ctx.send(f"{user_name} answered **{answer}**")
|
||||||
else:
|
else:
|
||||||
await ctx.send(response)
|
await ctx.send(response)
|
||||||
else:
|
else:
|
@ -2,7 +2,7 @@ import math
|
|||||||
import json
|
import json
|
||||||
import discord
|
import discord
|
||||||
|
|
||||||
from utils import cap
|
from gwendolyn.utils import cap
|
||||||
|
|
||||||
|
|
||||||
class LookupFuncs():
|
class LookupFuncs():
|
||||||
@ -29,7 +29,7 @@ class LookupFuncs():
|
|||||||
await ctx.send("I don't know that monster...")
|
await ctx.send("I don't know that monster...")
|
||||||
else:
|
else:
|
||||||
# Opens "monsters.json"
|
# Opens "monsters.json"
|
||||||
data = json.load(open('resources/lookup/monsters.json', encoding = "utf8"))
|
data = json.load(open('gwendolyn/resources/lookup/monsters.json', encoding = "utf8"))
|
||||||
for monster in data:
|
for monster in data:
|
||||||
if "name" in monster and str(query) == monster["name"]:
|
if "name" in monster and str(query) == monster["name"]:
|
||||||
self.bot.log("Found it!")
|
self.bot.log("Found it!")
|
||||||
@ -149,7 +149,7 @@ class LookupFuncs():
|
|||||||
self.bot.log("Looking up "+query)
|
self.bot.log("Looking up "+query)
|
||||||
|
|
||||||
# Opens "spells.json"
|
# Opens "spells.json"
|
||||||
data = json.load(open('resources/lookup/spells.json', encoding = "utf8"))
|
data = json.load(open('gwendolyn/resources/lookup/spells.json', encoding = "utf8"))
|
||||||
if query in data:
|
if query in data:
|
||||||
self.bot.log("Returning spell information")
|
self.bot.log("Returning spell information")
|
||||||
sendMessage = (f"***{query}***\n*{data[query]['level']} level {data[query]['school']}\nCasting Time: {data[query]['casting_time']}\nRange:{data[query]['range']}\nComponents:{data[query]['components']}\nDuration:{data[query]['duration']}*\n \n{data[query]['description']}")
|
sendMessage = (f"***{query}***\n*{data[query]['level']} level {data[query]['school']}\nCasting Time: {data[query]['casting_time']}\nRange:{data[query]['range']}\nComponents:{data[query]['components']}\nDuration:{data[query]['duration']}*\n \n{data[query]['description']}")
|
@ -3,7 +3,7 @@ import requests, imdb, discord, json, math, time, asyncio
|
|||||||
class BedreNetflix():
|
class BedreNetflix():
|
||||||
def __init__(self,bot):
|
def __init__(self,bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
ip = ["localhost", "192.168.0.40"][self.bot.options.testing]
|
ip = ["localhost", "192.168.0.40"][self.bot.options["testing"]]
|
||||||
|
|
||||||
self.radarrURL = "http://"+ip+":7878/api/v3/"
|
self.radarrURL = "http://"+ip+":7878/api/v3/"
|
||||||
self.sonarrURL = "http://"+ip+":8989/api/"
|
self.sonarrURL = "http://"+ip+":8989/api/"
|
||||||
@ -30,7 +30,7 @@ class BedreNetflix():
|
|||||||
messageTitle = "**Is it any of these movies?**"
|
messageTitle = "**Is it any of these movies?**"
|
||||||
|
|
||||||
messageText = ""
|
messageText = ""
|
||||||
imdbIds = []
|
imdb_ids = []
|
||||||
|
|
||||||
for x, movie in enumerate(movies):
|
for x, movie in enumerate(movies):
|
||||||
try:
|
try:
|
||||||
@ -40,17 +40,17 @@ class BedreNetflix():
|
|||||||
messageText += "\n"+str(x+1)+") "+movie["title"]
|
messageText += "\n"+str(x+1)+") "+movie["title"]
|
||||||
except:
|
except:
|
||||||
messageText += "Error"
|
messageText += "Error"
|
||||||
imdbIds.append(movie.movieID)
|
imdb_ids.append(movie.movieID)
|
||||||
|
|
||||||
self.bot.log("Returning a list of "+str(len(movies))+" possible movies: "+str(imdbIds))
|
self.bot.log("Returning a list of "+str(len(movies))+" possible movies: "+str(imdb_ids))
|
||||||
|
|
||||||
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
|
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
|
||||||
|
|
||||||
message = await ctx.send(embed=em)
|
message = await ctx.send(embed=em)
|
||||||
|
|
||||||
messageData = {"messageID":message.id,"imdbIds":imdbIds}
|
messageData = {"message_id":message.id,"imdb_ids":imdb_ids}
|
||||||
|
|
||||||
with open("resources/bedreNetflix/oldMessage"+str(ctx.channel.id),"w") as f:
|
with open("gwendolyn/resources/bedre_netflix/old_message"+str(ctx.channel.id),"w") as f:
|
||||||
json.dump(messageData,f)
|
json.dump(messageData,f)
|
||||||
|
|
||||||
if len(movies) == 1:
|
if len(movies) == 1:
|
||||||
@ -66,7 +66,7 @@ class BedreNetflix():
|
|||||||
await message.clear_reactions()
|
await message.clear_reactions()
|
||||||
|
|
||||||
#Adds the requested movie to Bedre Netflix
|
#Adds the requested movie to Bedre Netflix
|
||||||
async def addMovie(self, message, imdbId, editMessage = True):
|
async def add_movie(self, message, imdbId, editMessage = True):
|
||||||
if imdbId == None:
|
if imdbId == None:
|
||||||
self.bot.log("Did not find what the user was searching for")
|
self.bot.log("Did not find what the user was searching for")
|
||||||
if editMessage:
|
if editMessage:
|
||||||
@ -75,7 +75,7 @@ class BedreNetflix():
|
|||||||
await message.channel.send("Try searching for the IMDB id")
|
await message.channel.send("Try searching for the IMDB id")
|
||||||
else:
|
else:
|
||||||
self.bot.log("Trying to add movie "+str(imdbId))
|
self.bot.log("Trying to add movie "+str(imdbId))
|
||||||
apiKey = self.bot.credentials.radarrKey
|
apiKey = self.bot.credentials["radarr_key"]
|
||||||
response = requests.get(self.radarrURL+"movie/lookup/imdb?imdbId=tt"+imdbId+"&apiKey="+apiKey)
|
response = requests.get(self.radarrURL+"movie/lookup/imdb?imdbId=tt"+imdbId+"&apiKey="+apiKey)
|
||||||
lookupData = response.json()
|
lookupData = response.json()
|
||||||
postData = {"qualityProfileId": 1,
|
postData = {"qualityProfileId": 1,
|
||||||
@ -126,7 +126,7 @@ class BedreNetflix():
|
|||||||
messageTitle = "**Is it any of these shows?**"
|
messageTitle = "**Is it any of these shows?**"
|
||||||
|
|
||||||
messageText = ""
|
messageText = ""
|
||||||
imdbNames = []
|
imdb_names = []
|
||||||
|
|
||||||
for x, show in enumerate(shows):
|
for x, show in enumerate(shows):
|
||||||
try:
|
try:
|
||||||
@ -136,17 +136,17 @@ class BedreNetflix():
|
|||||||
messageText += "\n"+str(x+1)+") "+show["title"]
|
messageText += "\n"+str(x+1)+") "+show["title"]
|
||||||
except:
|
except:
|
||||||
messageText += "Error"
|
messageText += "Error"
|
||||||
imdbNames.append(show["title"])
|
imdb_names.append(show["title"])
|
||||||
|
|
||||||
self.bot.log("Returning a list of "+str(len(shows))+" possible shows: "+str(imdbNames))
|
self.bot.log("Returning a list of "+str(len(shows))+" possible shows: "+str(imdb_names))
|
||||||
|
|
||||||
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
|
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
|
||||||
|
|
||||||
message = await ctx.send(embed=em)
|
message = await ctx.send(embed=em)
|
||||||
|
|
||||||
messageData = {"messageID":message.id,"imdbNames":imdbNames}
|
messageData = {"message_id":message.id,"imdb_names":imdb_names}
|
||||||
|
|
||||||
with open("resources/bedreNetflix/oldMessage"+str(ctx.channel.id),"w") as f:
|
with open("gwendolyn/resources/bedre_netflix/old_message"+str(ctx.channel.id),"w") as f:
|
||||||
json.dump(messageData,f)
|
json.dump(messageData,f)
|
||||||
|
|
||||||
if len(shows) == 1:
|
if len(shows) == 1:
|
||||||
@ -162,14 +162,14 @@ class BedreNetflix():
|
|||||||
await message.clear_reactions()
|
await message.clear_reactions()
|
||||||
|
|
||||||
#Adds the requested show to Bedre Netflix
|
#Adds the requested show to Bedre Netflix
|
||||||
async def addShow(self, message, imdbName):
|
async def add_show(self, message, imdb_name):
|
||||||
if imdbName == None:
|
if imdb_name == None:
|
||||||
self.bot.log("Did not find what the user was searching for")
|
self.bot.log("Did not find what the user was searching for")
|
||||||
await message.edit(embed = None, content = "Try searching for the IMDB id")
|
await message.edit(embed = None, content = "Try searching for the IMDB id")
|
||||||
else:
|
else:
|
||||||
self.bot.log("Trying to add show "+str(imdbName))
|
self.bot.log("Trying to add show "+str(imdb_name))
|
||||||
apiKey = self.bot.credentials.sonarrKey
|
apiKey = self.bot.credentials["sonarr_key"]
|
||||||
response = requests.get(self.sonarrURL+"series/lookup?term="+imdbName.replace(" ","%20")+"&apiKey="+apiKey)
|
response = requests.get(self.sonarrURL+"series/lookup?term="+imdb_name.replace(" ","%20")+"&apiKey="+apiKey)
|
||||||
lookupData = response.json()[0]
|
lookupData = response.json()[0]
|
||||||
postData = {"ProfileId" : 1,
|
postData = {"ProfileId" : 1,
|
||||||
"rootFolderPath" : self.showPath,
|
"rootFolderPath" : self.showPath,
|
||||||
@ -264,8 +264,8 @@ class BedreNetflix():
|
|||||||
movieSectionTitle = "*Missing movies not downloading*"
|
movieSectionTitle = "*Missing movies not downloading*"
|
||||||
movieSectionTitleLine = "-"*((titleWidth-len(movieSectionTitle))//2)
|
movieSectionTitleLine = "-"*((titleWidth-len(movieSectionTitle))//2)
|
||||||
message.append(movieSectionTitleLine+movieSectionTitle+movieSectionTitleLine)
|
message.append(movieSectionTitleLine+movieSectionTitle+movieSectionTitleLine)
|
||||||
movieList = requests.get(self.radarrURL+"movie?apiKey="+self.bot.credentials.radarrKey).json()
|
movieList = requests.get(self.radarrURL+"movie?apiKey="+self.bot.credentials["radarr_key"]).json()
|
||||||
movieQueue = requests.get(self.radarrURL+"queue?apiKey="+self.bot.credentials.radarrKey).json()
|
movieQueue = requests.get(self.radarrURL+"queue?apiKey="+self.bot.credentials["radarr_key"]).json()
|
||||||
movieQueueIDs = []
|
movieQueueIDs = []
|
||||||
|
|
||||||
for queueItem in movieQueue["records"]:
|
for queueItem in movieQueue["records"]:
|
||||||
@ -297,7 +297,7 @@ class BedreNetflix():
|
|||||||
showSectionTitleLine = "-"*((titleWidth-len(showSectionTitle))//2)
|
showSectionTitleLine = "-"*((titleWidth-len(showSectionTitle))//2)
|
||||||
message.append(showSectionTitleLine+showSectionTitle+showSectionTitleLine)
|
message.append(showSectionTitleLine+showSectionTitle+showSectionTitleLine)
|
||||||
|
|
||||||
showList = requests.get(self.sonarrURL+"series?apiKey="+self.bot.credentials.sonarrKey).json()
|
showList = requests.get(self.sonarrURL+"series?apiKey="+self.bot.credentials["sonarr_key"]).json()
|
||||||
|
|
||||||
for show in showList:
|
for show in showList:
|
||||||
if show["seasons"][0]["seasonNumber"] == 0:
|
if show["seasons"][0]["seasonNumber"] == 0:
|
||||||
@ -381,14 +381,14 @@ class BedreNetflix():
|
|||||||
if not allDownloaded:
|
if not allDownloaded:
|
||||||
updatesLeft = 60
|
updatesLeft = 60
|
||||||
messageText = messageText[:-3]+"\nThis message will update every 10 seconds for "+str(math.ceil(updatesLeft/6))+" more minutes\n```"
|
messageText = messageText[:-3]+"\nThis message will update every 10 seconds for "+str(math.ceil(updatesLeft/6))+" more minutes\n```"
|
||||||
oldMessage = await ctx.send(messageText)
|
old_message = await ctx.send(messageText)
|
||||||
|
|
||||||
while ((not allDownloaded) and updatesLeft > 0):
|
while ((not allDownloaded) and updatesLeft > 0):
|
||||||
await asyncio.sleep(10)
|
await asyncio.sleep(10)
|
||||||
updatesLeft -= 1
|
updatesLeft -= 1
|
||||||
messageText, allDownloaded = await self.genDownloadList(*params)
|
messageText, allDownloaded = await self.genDownloadList(*params)
|
||||||
messageText = messageText[:-3]+"\nThis message will update every 10 seconds for "+str(math.ceil(updatesLeft/6))+" more minutes\n```"
|
messageText = messageText[:-3]+"\nThis message will update every 10 seconds for "+str(math.ceil(updatesLeft/6))+" more minutes\n```"
|
||||||
await oldMessage.edit(content = messageText)
|
await old_message.edit(content = messageText)
|
||||||
|
|
||||||
messageText, allDownloaded = await self.genDownloadList(*params)
|
messageText, allDownloaded = await self.genDownloadList(*params)
|
||||||
|
|
||||||
@ -399,7 +399,7 @@ class BedreNetflix():
|
|||||||
messageText = messageText[:-3]+"\nThis message will not update anymore\n```"
|
messageText = messageText[:-3]+"\nThis message will not update anymore\n```"
|
||||||
self.bot.log("The message updated 20 times")
|
self.bot.log("The message updated 20 times")
|
||||||
|
|
||||||
await oldMessage.edit(content = messageText)
|
await old_message.edit(content = messageText)
|
||||||
|
|
||||||
else:
|
else:
|
||||||
await ctx.send(messageText)
|
await ctx.send(messageText)
|
@ -17,7 +17,7 @@ class Generators():
|
|||||||
# Generates a random name
|
# Generates a random name
|
||||||
async def nameGen(self, ctx):
|
async def nameGen(self, ctx):
|
||||||
# Makes a list of all names from "names.txt"
|
# Makes a list of all names from "names.txt"
|
||||||
names = open('resources/names.txt', encoding='utf8').read()
|
names = open('gwendolyn/resources/names.txt', encoding='utf8').read()
|
||||||
corpus = list(names)
|
corpus = list(names)
|
||||||
|
|
||||||
# Makes a list of pairs
|
# Makes a list of pairs
|
@ -8,9 +8,9 @@ class NerdShit():
|
|||||||
|
|
||||||
async def wolfSearch(self,ctx,content):
|
async def wolfSearch(self,ctx,content):
|
||||||
await self.bot.defer(ctx)
|
await self.bot.defer(ctx)
|
||||||
fnt = ImageFont.truetype('resources/fonts/times-new-roman.ttf', 20)
|
fnt = ImageFont.truetype('gwendolyn/resources/fonts/times-new-roman.ttf', 20)
|
||||||
self.bot.log("Requesting data")
|
self.bot.log("Requesting data")
|
||||||
bot = wolframalpha.Client(self.bot.credentials.wolfKey)
|
bot = wolframalpha.Client(self.bot.credentials["wolfram_alpha_key"])
|
||||||
res = bot.query(content)
|
res = bot.query(content)
|
||||||
|
|
||||||
self.bot.log("Processing data")
|
self.bot.log("Processing data")
|
||||||
@ -49,33 +49,33 @@ class NerdShit():
|
|||||||
|
|
||||||
for count, pod in enumerate(chunk):
|
for count, pod in enumerate(chunk):
|
||||||
response = requests.get(pod.img["@src"])
|
response = requests.get(pod.img["@src"])
|
||||||
file = open("resources/wolfTemp.png", "wb")
|
file = open("gwendolyn/resources/wolfTemp.png", "wb")
|
||||||
file.write(response.content)
|
file.write(response.content)
|
||||||
file.close()
|
file.close()
|
||||||
oldImage = Image.open("resources/wolfTemp.png")
|
old_image = Image.open("gwendolyn/resources/wolfTemp.png")
|
||||||
oldSize = oldImage.size
|
oldSize = old_image.size
|
||||||
if titleChucks[x][count] == "":
|
if titleChucks[x][count] == "":
|
||||||
placeForText = 0
|
placeForText = 0
|
||||||
else:
|
else:
|
||||||
placeForText = 30
|
placeForText = 30
|
||||||
newSize = (width,int(oldSize[1]+10+placeForText))
|
newSize = (width,int(oldSize[1]+10+placeForText))
|
||||||
newImage = Image.new("RGB",newSize,color=(255,255,255))
|
newImage = Image.new("RGB",newSize,color=(255,255,255))
|
||||||
newImage.paste(oldImage, (int((int(oldSize[0]+10)-oldSize[0])/2),int(((newSize[1]-placeForText)-oldSize[1])/2)+placeForText))
|
newImage.paste(old_image, (int((int(oldSize[0]+10)-oldSize[0])/2),int(((newSize[1]-placeForText)-oldSize[1])/2)+placeForText))
|
||||||
if titleChucks[x][count] != "":
|
if titleChucks[x][count] != "":
|
||||||
d = ImageDraw.Draw(newImage,"RGB")
|
d = ImageDraw.Draw(newImage,"RGB")
|
||||||
d.text((5,7),titleChucks[x][count],font=fnt,fill=(150,150,150))
|
d.text((5,7),titleChucks[x][count],font=fnt,fill=(150,150,150))
|
||||||
|
|
||||||
wolfImage.paste(newImage,(0,heights[count]))
|
wolfImage.paste(newImage,(0,heights[count]))
|
||||||
newImage.close()
|
newImage.close()
|
||||||
oldImage.close()
|
old_image.close()
|
||||||
count += 1
|
count += 1
|
||||||
|
|
||||||
wolfImage.save("resources/wolf.png")
|
wolfImage.save("gwendolyn/resources/wolf.png")
|
||||||
wolfImage.close()
|
wolfImage.close()
|
||||||
await ctx.channel.send(file = discord.File("resources/wolf.png"))
|
await ctx.channel.send(file = discord.File("gwendolyn/resources/wolf.png"))
|
||||||
|
|
||||||
os.remove("resources/wolf.png")
|
os.remove("gwendolyn/resources/wolf.png")
|
||||||
os.remove("resources/wolfTemp.png")
|
os.remove("gwendolyn/resources/wolfTemp.png")
|
||||||
else:
|
else:
|
||||||
self.bot.log("No returned data")
|
self.bot.log("No returned data")
|
||||||
await ctx.send("Could not find anything relating to your search")
|
await ctx.send("Could not find anything relating to your search")
|
@ -7,11 +7,11 @@ import lxml # Used in imageFunc
|
|||||||
import fandom # Used in findWikiPage
|
import fandom # Used in findWikiPage
|
||||||
import d20 # Used in rollDice
|
import d20 # Used in rollDice
|
||||||
import ast
|
import ast
|
||||||
from .bedreNetflix import BedreNetflix
|
from .bedre_netflix import BedreNetflix
|
||||||
from .nerdShit import NerdShit
|
from .nerd_shit import NerdShit
|
||||||
from .generators import Generators
|
from .generators import Generators
|
||||||
|
|
||||||
from utils import cap
|
from gwendolyn.utils import cap
|
||||||
|
|
||||||
fandom.set_lang("da")
|
fandom.set_lang("da")
|
||||||
fandom.set_wiki("senkulpa")
|
fandom.set_wiki("senkulpa")
|
||||||
@ -28,8 +28,8 @@ class MyStringifier(d20.MarkdownStringifier):
|
|||||||
class Other():
|
class Other():
|
||||||
def __init__(self, bot):
|
def __init__(self, bot):
|
||||||
self.bot = bot
|
self.bot = bot
|
||||||
self.bedreNetflix = BedreNetflix(self.bot)
|
self.bedre_netflix = BedreNetflix(self.bot)
|
||||||
self.nerdShit = NerdShit(self.bot)
|
self.nerd_shit = NerdShit(self.bot)
|
||||||
self.generators = Generators(self.bot)
|
self.generators = Generators(self.bot)
|
||||||
|
|
||||||
# Picks a random movie and returns information about it
|
# Picks a random movie and returns information about it
|
||||||
@ -40,7 +40,7 @@ class Other():
|
|||||||
imdbClient = imdb.IMDb()
|
imdbClient = imdb.IMDb()
|
||||||
|
|
||||||
self.bot.log("Picking a movie")
|
self.bot.log("Picking a movie")
|
||||||
with open("resources/movies.txt", "r") as f:
|
with open("gwendolyn/resources/movies.txt", "r") as f:
|
||||||
movieList = f.read().split("\n")
|
movieList = f.read().split("\n")
|
||||||
movieName = random.choice(movieList)
|
movieName = random.choice(movieList)
|
||||||
|
|
||||||
@ -183,13 +183,13 @@ class Other():
|
|||||||
|
|
||||||
async def helpFunc(self, ctx, command):
|
async def helpFunc(self, ctx, command):
|
||||||
if command == "":
|
if command == "":
|
||||||
with open("resources/help/help.txt",encoding="utf-8") as f:
|
with open("gwendolyn/resources/help/help.txt",encoding="utf-8") as f:
|
||||||
text = f.read()
|
text = f.read()
|
||||||
em = discord.Embed(title = "Help", description = text,colour = 0x59f442)
|
em = discord.Embed(title = "Help", description = text,colour = 0x59f442)
|
||||||
await ctx.send(embed = em)
|
await ctx.send(embed = em)
|
||||||
else:
|
else:
|
||||||
self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
|
self.bot.log(f"Looking for help-{command}.txt",str(ctx.channel_id))
|
||||||
with open(f"resources/help/help-{command}.txt",encoding="utf-8") as f:
|
with open(f"gwendolyn/resources/help/help-{command}.txt",encoding="utf-8") as f:
|
||||||
text = f.read()
|
text = f.read()
|
||||||
em = discord.Embed(title = command.capitalize(), description = text,colour = 0x59f442)
|
em = discord.Embed(title = command.capitalize(), description = text,colour = 0x59f442)
|
||||||
await ctx.send(embed = em)
|
await ctx.send(embed = em)
|
@ -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.database_funcs.getName(user)+"'s character")
|
self.bot.log("Getting name for "+self.bot.database_funcs.get_name(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.database_funcs.getName(user))
|
self.bot.log("Just using "+self.bot.database_funcs.get_name(user))
|
||||||
return self.bot.database_funcs.getName(user)
|
return self.bot.database_funcs.get_name(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.database_funcs.getName(user)+"'s character")
|
self.bot.log("Looking for "+self.bot.database_funcs.get_name(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/star_wars/starwarstemplates.json", "r") as f:
|
with open("gwendolyn/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.database_funcs.getName(user))
|
self.bot.log("Makin' a character for "+self.bot.database_funcs.get_name(user))
|
||||||
with open("resources/star_wars/starwarstemplates.json", "r") as f:
|
with open("gwendolyn/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.database_funcs.getName(user) + " created")
|
await ctx.send("Character for " + self.bot.database_funcs.get_name(user) + " created")
|
||||||
else:
|
else:
|
||||||
if cmd == "Purge":
|
if cmd == "Purge":
|
||||||
self.bot.log("Deleting "+self.bot.database_funcs.getName(user)+"'s character")
|
self.bot.log("Deleting "+self.bot.database_funcs.get_name(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.database_funcs.getName(user) + " deleted")
|
await ctx.send("Character for " + self.bot.database_funcs.get_name(user) + " deleted")
|
||||||
else:
|
else:
|
||||||
await ctx.send(self.replaceWithSpaces(str(self.charData(user,cmd))))
|
await ctx.send(self.replaceWithSpaces(str(self.charData(user,cmd))))
|
||||||
|
|
@ -7,13 +7,13 @@ class StarWarsDestiny():
|
|||||||
roll, diceResults = self.bot.star_wars.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/star_wars/destinyPoints.txt","wt") as f:
|
with open("gwendolyn/resources/star_wars/destinyPoints.txt","wt") as f:
|
||||||
f.write(roll)
|
f.write(roll)
|
||||||
|
|
||||||
return "Rolled for Destiny Points and got:\n"+self.bot.star_wars.roll.diceResultToEmoji(diceResults)+"\n"+self.bot.star_wars.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/star_wars/destinyPoints.txt","rt") as f:
|
with open("gwendolyn/resources/star_wars/destinyPoints.txt","rt") as f:
|
||||||
points = f.read()
|
points = f.read()
|
||||||
|
|
||||||
if user == "Nikolaj":
|
if user == "Nikolaj":
|
||||||
@ -21,7 +21,7 @@ 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/star_wars/destinyPoints.txt","wt") as f:
|
with open("gwendolyn/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.star_wars.roll.resultToEmoji(points)
|
return "Used a dark side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points)
|
||||||
@ -33,7 +33,7 @@ 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/star_wars/destinyPoints.txt","wt") as f:
|
with open("gwendolyn/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.star_wars.roll.resultToEmoji(points)
|
return "Used a light side destiny point. Destiny pool is now:\n"+self.bot.star_wars.roll.resultToEmoji(points)
|
||||||
@ -51,7 +51,7 @@ class StarWarsDestiny():
|
|||||||
|
|
||||||
if cmd == "":
|
if cmd == "":
|
||||||
self.bot.log("Retrieving destiny pool info")
|
self.bot.log("Retrieving destiny pool info")
|
||||||
with open("resources/star_wars/destinyPoints.txt","rt") as f:
|
with open("gwendolyn/resources/star_wars/destinyPoints.txt","rt") as f:
|
||||||
sendMessage = self.bot.star_wars.roll.resultToEmoji(f.read())
|
sendMessage = self.bot.star_wars.roll.resultToEmoji(f.read())
|
||||||
else:
|
else:
|
||||||
commands = cmd.upper().split(" ")
|
commands = cmd.upper().split(" ")
|
@ -3,7 +3,7 @@ import re
|
|||||||
import string
|
import string
|
||||||
import json
|
import json
|
||||||
|
|
||||||
with open("resources/star_wars/starwarsskills.json", "r") as f:
|
with open("gwendolyn/resources/star_wars/starwarsskills.json", "r") as f:
|
||||||
skillData = json.load(f)
|
skillData = json.load(f)
|
||||||
|
|
||||||
class StarWarsRoll():
|
class StarWarsRoll():
|
@ -1,25 +1,22 @@
|
|||||||
"""
|
"""
|
||||||
Contains the Gwendolyn class, and runs it when run as script.
|
Contains the Gwendolyn class, a subclass of the discord command bot.
|
||||||
|
|
||||||
*Classes*
|
*Classes*
|
||||||
---------
|
---------
|
||||||
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 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
|
||||||
|
import git # Used to pull when stopping
|
||||||
|
|
||||||
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 gwendolyn.funcs import Money, StarWars, Games, Other, LookupFuncs
|
||||||
from utils import (Options, Credentials, logThis, makeFiles, DatabaseFuncs,
|
from gwendolyn.utils import (get_options, get_credentials, log_this,
|
||||||
EventHandler, ErrorHandler, long_strings)
|
DatabaseFuncs, EventHandler, ErrorHandler,
|
||||||
|
long_strings)
|
||||||
|
|
||||||
|
|
||||||
class Gwendolyn(commands.Bot):
|
class Gwendolyn(commands.Bot):
|
||||||
@ -33,6 +30,7 @@ class Gwendolyn(commands.Bot):
|
|||||||
stop(ctx: discord_slash.context.SlashContext)
|
stop(ctx: discord_slash.context.SlashContext)
|
||||||
defer(ctx: discord_slash.context.SlashContext)
|
defer(ctx: discord_slash.context.SlashContext)
|
||||||
"""
|
"""
|
||||||
|
# pylint: disable=too-many-instance-attributes
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
"""Initialize the bot."""
|
"""Initialize the bot."""
|
||||||
@ -54,17 +52,17 @@ class Gwendolyn(commands.Bot):
|
|||||||
def _add_clients_and_options(self):
|
def _add_clients_and_options(self):
|
||||||
"""Add all the client, option and credentials objects."""
|
"""Add all the client, option and credentials objects."""
|
||||||
self.long_strings = long_strings()
|
self.long_strings = long_strings()
|
||||||
self.options = Options()
|
self.options = get_options()
|
||||||
self.credentials = Credentials()
|
self.credentials = get_credentials()
|
||||||
finnhub_key = self.credentials.finnhub_key
|
finnhub_key = self.credentials["finnhub_key"]
|
||||||
self.finnhub_client = finnhub.Client(api_key=finnhub_key)
|
self.finnhub_client = finnhub.Client(api_key=finnhub_key)
|
||||||
mongo_user = self.credentials.mongoDBUser
|
mongo_user = self.credentials["mongo_db_user"]
|
||||||
mongo_password = self.credentials.mongoDBPassword
|
mongo_password = self.credentials["mongo_db_password"]
|
||||||
mongo_url = f"mongodb+srv://{mongo_user}:{mongo_password}@gwendolyn"
|
mongo_url = f"mongodb+srv://{mongo_user}:{mongo_password}@gwendolyn"
|
||||||
mongo_url += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority"
|
mongo_url += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority"
|
||||||
database_clint = MongoClient(mongo_url)
|
database_clint = MongoClient(mongo_url)
|
||||||
|
|
||||||
if self.options.testing:
|
if self.options["testing"]:
|
||||||
self.log("Testing mode")
|
self.log("Testing mode")
|
||||||
self.database = database_clint["Gwendolyn-Test"]
|
self.database = database_clint["Gwendolyn-Test"]
|
||||||
else:
|
else:
|
||||||
@ -92,13 +90,13 @@ class Gwendolyn(commands.Bot):
|
|||||||
|
|
||||||
def _add_cogs(self):
|
def _add_cogs(self):
|
||||||
"""Load cogs."""
|
"""Load cogs."""
|
||||||
for filename in os.listdir("./cogs"):
|
for filename in os.listdir("./gwendolyn/cogs"):
|
||||||
if filename.endswith(".py"):
|
if filename.endswith(".py"):
|
||||||
self.load_extension(f"cogs.{filename[:-3]}")
|
self.load_extension(f"gwendolyn.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/util_functions.py."""
|
"""Log a message. Described in utils/util_functions.py."""
|
||||||
logThis(messages, channel, level)
|
log_this(messages, channel, level)
|
||||||
|
|
||||||
async def stop(self, ctx: discord_slash.context.SlashContext):
|
async def stop(self, ctx: discord_slash.context.SlashContext):
|
||||||
"""
|
"""
|
||||||
@ -112,12 +110,15 @@ class Gwendolyn(commands.Bot):
|
|||||||
ctx: discord_slash.context.SlashContext
|
ctx: discord_slash.context.SlashContext
|
||||||
The context of the "/stop" slash command.
|
The context of the "/stop" slash command.
|
||||||
"""
|
"""
|
||||||
if f"#{ctx.author.id}" in self.options.admins:
|
if f"#{ctx.author.id}" in self.options["admins"]:
|
||||||
await ctx.send("Pulling git repo and restarting...")
|
await ctx.send("Pulling git repo and restarting...")
|
||||||
|
|
||||||
await self.change_presence(status=discord.Status.offline)
|
await self.change_presence(status=discord.Status.offline)
|
||||||
|
|
||||||
self.database_funcs.wipeGames()
|
self.database_funcs.wipe_games()
|
||||||
|
if not self.options["testing"]:
|
||||||
|
git_client = git.cmd.Git("")
|
||||||
|
git_client.pull()
|
||||||
|
|
||||||
self.log("Logging out", level=25)
|
self.log("Logging out", level=25)
|
||||||
await self.close()
|
await self.close()
|
||||||
@ -132,20 +133,3 @@ class Gwendolyn(commands.Bot):
|
|||||||
await ctx.defer()
|
await ctx.defer()
|
||||||
except discord_slash.error.AlreadyResponded:
|
except discord_slash.error.AlreadyResponded:
|
||||||
self.log("defer failed")
|
self.log("defer failed")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
if platform.system() == "Windows":
|
|
||||||
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
|
|
||||||
|
|
||||||
# Creates the required files
|
|
||||||
makeFiles()
|
|
||||||
|
|
||||||
# Creates the Bot
|
|
||||||
bot = Gwendolyn()
|
|
||||||
|
|
||||||
try:
|
|
||||||
# Runs the whole shabang
|
|
||||||
bot.run(bot.credentials.token)
|
|
||||||
except Exception as exception: # pylint: disable=broad-except
|
|
||||||
bot.log(bot.long_strings[f"Can't log in: {repr(exception)}"])
|
|
Before Width: | Height: | Size: 529 KiB After Width: | Height: | Size: 529 KiB |
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 38 KiB |
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 29 KiB |
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
Before Width: | Height: | Size: 17 KiB After Width: | Height: | Size: 17 KiB |
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 22 KiB After Width: | Height: | Size: 22 KiB |
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 20 KiB After Width: | Height: | Size: 20 KiB |
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 19 KiB After Width: | Height: | Size: 19 KiB |
Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB |
Before Width: | Height: | Size: 27 KiB After Width: | Height: | Size: 27 KiB |
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 21 KiB |
Before Width: | Height: | Size: 23 KiB After Width: | Height: | Size: 23 KiB |
Before Width: | Height: | Size: 21 KiB After Width: | Height: | Size: 21 KiB |
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 25 KiB |
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 26 KiB |
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 31 KiB After Width: | Height: | Size: 31 KiB |
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 25 KiB |
Before Width: | Height: | Size: 26 KiB After Width: | Height: | Size: 26 KiB |
Before Width: | Height: | Size: 24 KiB After Width: | Height: | Size: 24 KiB |
Before Width: | Height: | Size: 36 KiB After Width: | Height: | Size: 36 KiB |
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 29 KiB |
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 29 KiB |
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 29 KiB |
Before Width: | Height: | Size: 37 KiB After Width: | Height: | Size: 37 KiB |
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 29 KiB |
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 29 KiB |
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 15 KiB After Width: | Height: | Size: 15 KiB |
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB |
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 28 KiB |
Before Width: | Height: | Size: 174 KiB After Width: | Height: | Size: 174 KiB |
Before Width: | Height: | Size: 178 KiB After Width: | Height: | Size: 178 KiB |
Before Width: | Height: | Size: 182 KiB After Width: | Height: | Size: 182 KiB |
Before Width: | Height: | Size: 178 KiB After Width: | Height: | Size: 178 KiB |
Before Width: | Height: | Size: 158 KiB After Width: | Height: | Size: 158 KiB |
Before Width: | Height: | Size: 168 KiB After Width: | Height: | Size: 168 KiB |
Before Width: | Height: | Size: 180 KiB After Width: | Height: | Size: 180 KiB |
Before Width: | Height: | Size: 176 KiB After Width: | Height: | Size: 176 KiB |
Before Width: | Height: | Size: 179 KiB After Width: | Height: | Size: 179 KiB |
Before Width: | Height: | Size: 183 KiB After Width: | Height: | Size: 183 KiB |
Before Width: | Height: | Size: 190 KiB After Width: | Height: | Size: 190 KiB |
Before Width: | Height: | Size: 160 KiB After Width: | Height: | Size: 160 KiB |
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 59 KiB |
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 59 KiB |
Before Width: | Height: | Size: 61 KiB After Width: | Height: | Size: 61 KiB |
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 60 KiB |
Before Width: | Height: | Size: 58 KiB After Width: | Height: | Size: 58 KiB |
Before Width: | Height: | Size: 60 KiB After Width: | Height: | Size: 60 KiB |
1
gwendolyn/resources/help/help-add_movie.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
Du kan søge efter en film ved at skrive `/add_movie [søgning]`. Gwendolyn vil derefter vise dig resultater baseret på din søgning. Du kan derfra reagere på Gwendolyns besked for at downloade en specifik film.
|
@ -1 +1 @@
|
|||||||
Du kan søge efter en film ved at skrive `/addmovie [søgning]`. Gwendolyn vil derefter vise dig resultater baseret på din søgning. Du kan derfra reagere på Gwendolyns besked for at downloade en specifik film.
|
Du kan søge efter et show ved at skrive `/add_show [søgning]`. Gwendolyn vil derefter vise dig resultater baseret på din søgning. Du kan derfra reagere på Gwendolyns besked for at downloade et specifikt show.
|