🧹 More refactoring

This commit is contained in:
Nikolaj
2021-08-17 18:05:41 +02:00
parent 074a06e863
commit 573d081734
31 changed files with 1971 additions and 1787 deletions

4
.gitignore vendored
View File

@ -154,11 +154,11 @@ token.txt
credentials.txt credentials.txt
options.txt options.txt
gwendolyn/resources/star_wars/destinyPoints.txt gwendolyn/resources/star_wars/destinyPoints.txt
gwendolyn/resources/bedre_netflix/ gwendolyn/resources/plex/
gwendolyn/resources/games/hilo/ gwendolyn/resources/games/hilo/
gwendolyn/resources/games/blackjack_tables/ gwendolyn/resources/games/blackjack_tables/
gwendolyn/resources/games/old_images/ gwendolyn/resources/games/old_images/
gwendolyn/resources/games/connect4Boards/ gwendolyn/resources/games/connect_four_boards/
gwendolyn/resources/games/hex_boards/ gwendolyn/resources/games/hex_boards/
gwendolyn/resources/games/hangman_boards/ gwendolyn/resources/games/hangman_boards/
gwendolyn/resources/lookup/monsters.json gwendolyn/resources/lookup/monsters.json

View File

@ -50,7 +50,7 @@ class BlackjackCog(commands.Cog):
@cog_ext.cog_subcommand(**params["blackjack_bet"]) @cog_ext.cog_subcommand(**params["blackjack_bet"])
async def blackjack_bet(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.enter_game(ctx, bet)
@cog_ext.cog_subcommand(**params["blackjack_stand"]) @cog_ext.cog_subcommand(**params["blackjack_stand"])
async def blackjack_stand(self, ctx, hand=""): async def blackjack_stand(self, ctx, hand=""):

View File

@ -15,7 +15,7 @@ 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.bedre_netflix = bot.other.bedre_netflix self.plex = bot.other.plex
self.nerd_shit = bot.other.nerd_shit self.nerd_shit = bot.other.nerd_shit
@cog_ext.cog_slash(**params["ping"]) @cog_ext.cog_slash(**params["ping"])
@ -76,17 +76,17 @@ class MiscCog(commands.Cog):
@cog_ext.cog_slash(**params["add_movie"]) @cog_ext.cog_slash(**params["add_movie"])
async def add_movie(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.bedre_netflix.requestMovie(ctx, movie) await self.plex.request_movie(ctx, movie)
@cog_ext.cog_slash(**params["add_show"]) @cog_ext.cog_slash(**params["add_show"])
async def add_show(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.bedre_netflix.requestShow(ctx, show) await self.plex.request_show(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.bedre_netflix.downloading(ctx, parameters) await self.plex.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):

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -8,12 +8,12 @@ Deals with commands and logic for hangman games.
DrawHangman() DrawHangman()
Draws the image shown to the player. Draws the image shown to the player.
""" """
import requests # Used for getting the word in Hangman.start()
import datetime # Used for generating the game id import datetime # Used for generating the game id
import string # string.ascii_uppercase used import string # string.ascii_uppercase used
import discord # Used for discord.file and type hints
import math # Used by DrawHangman(), mainly for drawing circles import math # Used by DrawHangman(), mainly for drawing circles
import random # Used to draw poorly import random # Used to draw poorly
import requests # Used for getting the word in Hangman.start()
import discord # Used for discord.file and type hints
from discord_slash.context import SlashContext # Used for typehints from discord_slash.context import SlashContext # Used for typehints
from PIL import ImageDraw, Image, ImageFont # Used to draw the image from PIL import ImageDraw, Image, ImageFont # Used to draw the image
@ -38,16 +38,16 @@ class Hangman():
------------ ------------
draw: DrawHangman draw: DrawHangman
The DrawHangman used to draw the hangman image. The DrawHangman used to draw the hangman image.
APIURL: str API_url: str
The url to get the words from. The url to get the words from.
APIPARAMS: dict APIPARAMS: dict
The parameters to pass to every api call. The parameters to pass to every api call.
""" """
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.__API_url = "https://api.wordnik.com/v4/words.json/randomWords?" # pylint: disable=invalid-name
apiKey = self.__bot.credentials["wordnik_key"] api_key = self.__bot.credentials["wordnik_key"]
self.__APIPARAMS = { self.__APIPARAMS = { # pylint: disable=invalid-name
"hasDictionaryDef": True, "hasDictionaryDef": True,
"minCorpusCount": 5000, "minCorpusCount": 5000,
"maxCorpusCount": -1, "maxCorpusCount": -1,
@ -56,7 +56,7 @@ class Hangman():
"minLength": 3, "minLength": 3,
"maxLength": 11, "maxLength": 11,
"limit": 1, "limit": 1,
"api_key": apiKey "api_key": api_key
} }
async def start(self, ctx: SlashContext): async def start(self, ctx: SlashContext):
@ -73,59 +73,60 @@ class Hangman():
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})
user_name = self.__bot.database_funcs.get_name(user) user_name = self.__bot.database_funcs.get_name(user)
startedGame = False started_game = False
if game is None: if game is None:
word = "-" word = "-"
while "-" in word or "." in word: while "-" in word or "." in word:
response = requests.get(self.__APIURL, params=self.__APIPARAMS) response = requests.get(self.__API_url, params=self.__APIPARAMS)
word = list(response.json()[0]["word"].upper()) word = list(response.json()[0]["word"].upper())
self.__bot.log("Found the word \""+"".join(word)+"\"") self.__bot.log("Found the word \""+"".join(word)+"\"")
guessed = [False] * len(word) guessed = [False] * len(word)
gameID = datetime.datetime.now().strftime("%Y%m%d%H%M%S") game_id = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
newGame = { new_game = {
"_id": channel, "_id": channel,
"player": user, "player": user,
"guessed letters": [], "guessed letters": [],
"word": word, "word": word,
"game ID": gameID, "game ID": game_id,
"misses": 0, "misses": 0,
"guessed": guessed "guessed": guessed
} }
self.__bot.database["hangman games"].insert_one(newGame) self.__bot.database["hangman games"].insert_one(new_game)
remainingLetters = list(string.ascii_uppercase) remaining_letters = list(string.ascii_uppercase)
self.__draw.drawImage(channel) self.__draw.draw_image(channel)
log_message = "Game started" log_message = "Game started"
sendMessage = f"{user_name} started game of hangman." send_message = f"{user_name} started game of hangman."
startedGame = True started_game = True
else: else:
log_message = "There was already a game going on" log_message = "There was already a game going on"
sendMessage = self.__bot.long_strings["Hangman going on"] send_message = self.__bot.long_strings["Hangman going on"]
self.__bot.log(log_message) self.__bot.log(log_message)
await ctx.send(sendMessage) await ctx.send(send_message)
if startedGame: if started_game:
boardsPath = "gwendolyn/resources/games/hangman_boards/" boards_path = "gwendolyn/resources/games/hangman_boards/"
file_path = f"{boardsPath}hangman_board{channel}.png" file_path = f"{boards_path}hangman_board{channel}.png"
newImage = await ctx.channel.send(file=discord.File(file_path)) new_image = await ctx.channel.send(file=discord.File(file_path))
blankMessage = await ctx.channel.send("_ _") blank_message = await ctx.channel.send("_ _")
reactionMessages = { reaction_messages = {
newImage: remainingLetters[:15], new_image: remaining_letters[:15],
blankMessage: remainingLetters[15:] blank_message: remaining_letters[15:]
} }
old_messages = f"{newImage.id}\n{blankMessage.id}" old_messages = f"{new_image.id}\n{blank_message.id}"
old_images_path = "gwendolyn/resources/games/old_images/"
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "w") as f: with open(old_images_path+f"hangman{channel}", "w") as file_pointer:
f.write(old_messages) file_pointer.write(old_messages)
for message, letters in reactionMessages.items(): for message, letters in reaction_messages.items():
for letter in letters: for letter in letters:
emoji = chr(ord(letter)+127397) emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji) await message.add_reaction(emoji)
@ -148,9 +149,10 @@ class Hangman():
await ctx.send("You can't end a game you're not in") await ctx.send("You can't end a game you're not in")
else: else:
self.__bot.database["hangman games"].delete_one({"_id": channel}) self.__bot.database["hangman games"].delete_one({"_id": channel})
old_images_path = "gwendolyn/resources/games/old_images/"
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f: with open(old_images_path+f"hangman{channel}", "r") as file_pointer:
messages = f.read().splitlines() messages = file_pointer.read().splitlines()
for message in messages: for message in messages:
old_message = await ctx.channel.fetch_message(int(message)) old_message = await ctx.channel.fetch_message(int(message))
@ -176,89 +178,91 @@ class Hangman():
hangman_games = self.__bot.database["hangman games"] hangman_games = self.__bot.database["hangman games"]
game = hangman_games.find_one({"_id": channel}) game = hangman_games.find_one({"_id": channel})
gameExists = (game is not None) game_exists = (game is not None)
singleLetter = (len(guess) == 1 and guess.isalpha()) single_letter = (len(guess) == 1 and guess.isalpha())
newGuess = (guess not in game["guessed letters"]) new_guess = (guess not in game["guessed letters"])
validGuess = (gameExists and singleLetter and newGuess) valid_guess = (game_exists and single_letter and new_guess)
if validGuess: if valid_guess:
self.__bot.log("Guessed the letter") self.__bot.log("Guessed the letter")
correctGuess = 0 correct_guess = 0
for x, letter in enumerate(game["word"]): for i, letter in enumerate(game["word"]):
if guess == letter: if guess == letter:
correctGuess += 1 correct_guess += 1
updater = {"$set": {f"guessed.{x}": True}} updater = {"$set": {f"guessed.{i}": True}}
hangman_games.update_one({"_id": channel}, updater) hangman_games.update_one({"_id": channel}, updater)
if correctGuess == 0: if correct_guess == 0:
updater = {"$inc": {"misses": 1}} updater = {"$inc": {"misses": 1}}
hangman_games.update_one({"_id": channel}, updater) hangman_games.update_one({"_id": channel}, updater)
updater = {"$push": {"guessed letters": guess}} updater = {"$push": {"guessed letters": guess}}
hangman_games.update_one({"_id": channel}, updater) hangman_games.update_one({"_id": channel}, updater)
remainingLetters = list(string.ascii_uppercase) remaining_letters = list(string.ascii_uppercase)
game = hangman_games.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) remaining_letters.remove(letter)
if correctGuess == 1: if correct_guess == 1:
sendMessage = "Guessed {}. There was 1 {} in the word." send_message = "Guessed {}. There was 1 {} in the word."
sendMessage = sendMessage.format(guess, guess) send_message = send_message.format(guess, guess)
else: else:
sendMessage = "Guessed {}. There were {} {}s in the word." send_message = "Guessed {}. There were {} {}s in the word."
sendMessage = sendMessage.format(guess, correctGuess, guess) send_message = send_message.format(guess, correct_guess, guess)
self.__draw.drawImage(channel) self.__draw.draw_image(channel)
if game["misses"] == 6: if game["misses"] == 6:
hangman_games.delete_one({"_id": channel}) hangman_games.delete_one({"_id": channel})
sendMessage += self.__bot.long_strings["Hangman lost game"] send_message += self.__bot.long_strings["Hangman lost game"]
remainingLetters = [] remaining_letters = []
elif all(game["guessed"]): elif all(game["guessed"]):
hangman_games.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"] send_message += self.__bot.long_strings["Hangman guessed word"]
remainingLetters = [] remaining_letters = []
await message.channel.send(sendMessage) await message.channel.send(send_message)
old_images_path = "gwendolyn/resources/games/old_images/"
with open(f"gwendolyn/resources/games/old_images/hangman{channel}", "r") as f: with open(old_images_path+f"hangman{channel}", "r") as file_pointer:
old_message_ids = f.read().splitlines() old_message_ids = file_pointer.read().splitlines()
for oldID in old_message_ids: for old_id in old_message_ids:
old_message = await message.channel.fetch_message(int(oldID)) old_message = await message.channel.fetch_message(int(old_id))
self.__bot.log("Deleting old message") self.__bot.log("Deleting old message")
await old_message.delete() await old_message.delete()
boardsPath = "gwendolyn/resources/games/hangman_boards/" boards_path = "gwendolyn/resources/games/hangman_boards/"
file_path = f"{boardsPath}hangman_board{channel}.png" file_path = f"{boards_path}hangman_board{channel}.png"
newImage = await message.channel.send(file=discord.File(file_path)) new_image = await message.channel.send(file=discord.File(file_path))
if len(remainingLetters) > 0: if len(remaining_letters) > 0:
if len(remainingLetters) > 15: if len(remaining_letters) > 15:
blankMessage = await message.channel.send("_ _") blank_message = await message.channel.send("_ _")
reactionMessages = { reaction_messages = {
newImage: remainingLetters[:15], new_image: remaining_letters[:15],
blankMessage: remainingLetters[15:] blank_message: remaining_letters[15:]
} }
else: else:
blankMessage = "" blank_message = ""
reactionMessages = {newImage: remainingLetters} reaction_messages = {new_image: remaining_letters}
if blankMessage != "": if blank_message != "":
old_messages = f"{newImage.id}\n{blankMessage.id}" old_messages = f"{new_image.id}\n{blank_message.id}"
else: else:
old_messages = str(newImage.id) old_messages = str(new_image.id)
old_imagePath = f"gwendolyn/resources/games/old_images/hangman{channel}" old_images_path = "gwendolyn/resources/games/old_images/"
with open(old_imagePath, "w") as f: old_image_path = old_images_path + f"hangman{channel}"
f.write(old_messages) with open(old_image_path, "w") as file_pointer:
file_pointer.write(old_messages)
for message, letters in reactionMessages.items(): for message, letters in reaction_messages.items():
for letter in letters: for letter in letters:
emoji = chr(ord(letter)+127397) emoji = chr(ord(letter)+127397)
await message.add_reaction(emoji) await message.add_reaction(emoji)
@ -270,7 +274,7 @@ class DrawHangman():
*Methods* *Methods*
--------- ---------
drawImage(channel: str) draw_image(channel: str)
""" """
def __init__(self, bot): def __init__(self, bot):
@ -293,6 +297,7 @@ class DrawHangman():
SMALLFONT SMALLFONT
""" """
self.__bot = bot self.__bot = bot
# pylint: disable=invalid-name
self.__CIRCLESIZE = 120 self.__CIRCLESIZE = 120
self.__LINEWIDTH = 12 self.__LINEWIDTH = 12
@ -318,129 +323,132 @@ class DrawHangman():
FONTPATH = "gwendolyn/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)
# pylint: enable=invalid-name
def __deviate(self, preDeviance: int, preDevianceAccuracy: int, def __deviate(self, pre_deviance: int, pre_deviance_accuracy: int,
positionChange: float, maxmin: int, position_change: float, maxmin: int,
maxAcceleration: float): max_acceleration: float):
randomDeviance = random.uniform(-positionChange, positionChange) random_deviance = random.uniform(-position_change, position_change)
devianceAccuracy = preDevianceAccuracy + randomDeviance deviance_accuracy = pre_deviance_accuracy + random_deviance
if devianceAccuracy > maxmin * maxAcceleration: if deviance_accuracy > maxmin * max_acceleration:
devianceAccuracy = maxmin * maxAcceleration deviance_accuracy = maxmin * max_acceleration
elif devianceAccuracy < -maxmin * maxAcceleration: elif deviance_accuracy < -maxmin * max_acceleration:
devianceAccuracy = -maxmin * maxAcceleration deviance_accuracy = -maxmin * max_acceleration
deviance = preDeviance + devianceAccuracy deviance = pre_deviance + deviance_accuracy
if deviance > maxmin: if deviance > maxmin:
deviance = maxmin deviance = maxmin
elif deviance < -maxmin: elif deviance < -maxmin:
deviance = -maxmin deviance = -maxmin
return deviance, devianceAccuracy return deviance, deviance_accuracy
def __badCircle(self): def __bad_circle(self):
circlePadding = (self.__LINEWIDTH*3) circle_padding = (self.__LINEWIDTH*3)
imageWidth = self.__CIRCLESIZE+circlePadding image_width = self.__CIRCLESIZE+circle_padding
imageSize = (imageWidth, imageWidth) image_size = (image_width, image_width)
background = Image.new("RGBA", imageSize, color=(0, 0, 0, 0)) background = Image.new("RGBA", image_size, color=(0, 0, 0, 0))
d = ImageDraw.Draw(background, "RGBA") drawer = ImageDraw.Draw(background, "RGBA")
middle = (self.__CIRCLESIZE+(self.__LINEWIDTH*3))/2 middle = (self.__CIRCLESIZE+(self.__LINEWIDTH*3))/2
devianceX = 0 deviance_x = 0
devianceY = 0 deviance_y = 0
devianceAccuracyX = 0 deviance_accuracy_x = 0
devianceAccuracyY = 0 deviance_accuracy_y = 0
start = random.randint(-100, -80) start = random.randint(-100, -80)
degreesAmount = 360 + random.randint(-10, 30) degreess_amount = 360 + random.randint(-10, 30)
for degree in range(degreesAmount): for degree in range(degreess_amount):
devianceXParams = [ deviance_x, deviance_accuracy_x = self.__deviate(
devianceX, deviance_x,
devianceAccuracyX, deviance_accuracy_x,
self.__LINEWIDTH/100, self.__LINEWIDTH/100,
self.__LINEWIDTH, self.__LINEWIDTH,
0.03 0.03
] )
devianceYParams = [ deviance_y, deviance_accuracy_y = self.__deviate(
devianceY, deviance_y,
devianceAccuracyY, deviance_accuracy_y,
self.__LINEWIDTH/100, self.__LINEWIDTH/100,
self.__LINEWIDTH, self.__LINEWIDTH,
0.03 0.03
] )
devianceX, devianceAccuracyX = self.__deviate(*devianceXParams)
devianceY, devianceAccuracyY = self.__deviate(*devianceYParams)
radians = math.radians(degree+start) radians = math.radians(degree+start)
circleX = (math.cos(radians) * (self.__CIRCLESIZE/2)) circle_x = (math.cos(radians) * (self.__CIRCLESIZE/2))
circleY = (math.sin(radians) * (self.__CIRCLESIZE/2)) circle_y = (math.sin(radians) * (self.__CIRCLESIZE/2))
x = middle + circleX - (self.__LINEWIDTH/2) + devianceX position_x = middle + circle_x - (self.__LINEWIDTH/2) + deviance_x
y = middle + circleY - (self.__LINEWIDTH/2) + devianceY position_y = middle + circle_y - (self.__LINEWIDTH/2) + deviance_y
circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)] circle_position = [
d.ellipse(circlePosition, fill=(0, 0, 0, 255)) (position_x, position_y),
(position_x+self.__LINEWIDTH, position_y+self.__LINEWIDTH)
]
drawer.ellipse(circle_position, fill=(0, 0, 0, 255))
return background return background
def __badLine(self, length: int, rotated: bool = False): def __bad_line(self, length: int, rotated: bool = False):
if rotated: if rotated:
w, h = length+self.__LINEWIDTH*3, self.__LINEWIDTH*3 width, height = length+self.__LINEWIDTH*3, self.__LINEWIDTH*3
else: else:
w, h = self.__LINEWIDTH*3, length+self.__LINEWIDTH*3 width, height = self.__LINEWIDTH*3, length+self.__LINEWIDTH*3
background = Image.new("RGBA", (w, h), color=(0, 0, 0, 0)) background = Image.new("RGBA", (width, height), color=(0, 0, 0, 0))
d = ImageDraw.Draw(background, "RGBA") drawer = ImageDraw.Draw(background, "RGBA")
possibleDeviance = int(self.__LINEWIDTH/3) possible_deviance = int(self.__LINEWIDTH/3)
devianceX = random.randint(-possibleDeviance, possibleDeviance) deviance_x = random.randint(-possible_deviance, possible_deviance)
devianceY = 0 deviance_y = 0
devianceAccuracyX = 0 deviance_accuracy_x = 0
devianceAccuracyY = 0 deviance_accuracy_y = 0
for pixel in range(length): for pixel in range(length):
devianceParamsX = [ deviance_x, deviance_accuracy_x = self.__deviate(
devianceX, deviance_x,
devianceAccuracyX, deviance_accuracy_x,
self.__LINEWIDTH/1000, self.__LINEWIDTH/1000,
self.__LINEWIDTH, self.__LINEWIDTH,
0.004 0.004
] )
devianceParamsY = [ deviance_y, deviance_accuracy_y = self.__deviate(
devianceY, deviance_y,
devianceAccuracyY, deviance_accuracy_y,
self.__LINEWIDTH/1000, self.__LINEWIDTH/1000,
self.__LINEWIDTH, self.__LINEWIDTH,
0.004 0.004
] )
devianceX, devianceAccuracyX = self.__deviate(*devianceParamsX)
devianceY, devianceAccuracyY = self.__deviate(*devianceParamsY)
if rotated: if rotated:
x = self.__LINEWIDTH + pixel + devianceX position_x = self.__LINEWIDTH + pixel + deviance_x
y = self.__LINEWIDTH + devianceY position_y = self.__LINEWIDTH + deviance_y
else: else:
x = self.__LINEWIDTH + devianceX position_x = self.__LINEWIDTH + deviance_x
y = self.__LINEWIDTH + pixel + devianceY position_y = self.__LINEWIDTH + pixel + deviance_y
circlePosition = [(x, y), (x+self.__LINEWIDTH, y+self.__LINEWIDTH)] circle_position = [
d.ellipse(circlePosition, fill=(0, 0, 0, 255)) (position_x, position_y),
(position_x+self.__LINEWIDTH, position_y+self.__LINEWIDTH)
]
drawer.ellipse(circle_position, fill=(0, 0, 0, 255))
return background return background
def __drawMan(self, misses: int, seed: str): def __draw_man(self, misses: int, seed: str):
random.seed(seed) random.seed(seed)
manSize = (self.__MANX, self.__MANY) man_size = (self.__MANX, self.__MANY)
background = Image.new("RGBA", manSize, color=(0, 0, 0, 0)) background = Image.new("RGBA", man_size, color=(0, 0, 0, 0))
if misses >= 1: if misses >= 1:
head = self.__badCircle() head = self.__bad_circle()
pasteX = (self.__MANX-(self.__CIRCLESIZE+(self.__LINEWIDTH*3)))//2 paste_x = (self.__MANX-(self.__CIRCLESIZE+(self.__LINEWIDTH*3)))//2
pastePosition = (pasteX, 0) paste_position = (paste_x, 0)
background.paste(head, pastePosition, head) background.paste(head, paste_position, head)
if misses >= 2: if misses >= 2:
body = self.__badLine(self.__BODYSIZE) body = self.__bad_line(self.__BODYSIZE)
pasteX = (self.__MANX-(self.__LINEWIDTH*3))//2 paste_x = (self.__MANX-(self.__LINEWIDTH*3))//2
pastePosition = (pasteX, self.__CIRCLESIZE) paste_position = (paste_x, self.__CIRCLESIZE)
background.paste(body, pastePosition, body) background.paste(body, paste_position, body)
if misses >= 3: if misses >= 3:
limbs = random.sample(["rl", "ll", "ra", "la"], min(misses-2, 4)) limbs = random.sample(["rl", "ll", "ra", "la"], min(misses-2, 4))
@ -450,131 +458,138 @@ class DrawHangman():
random.seed(seed) random.seed(seed)
for limb in limbs: for limb in limbs:
limbDrawing = self.__badLine(self.__LIMBSIZE, True) limb_drawing = self.__bad_line(self.__LIMBSIZE, True)
xPosition = (self.__MANX-(self.__LINEWIDTH*3))//2 x_position = (self.__MANX-(self.__LINEWIDTH*3))//2
if limb[1] == "a": if limb[1] == "a":
rotation = random.randint(-45, 45) rotation = random.randint(-45, 45)
shift = math.sin(math.radians(rotation)) shift = math.sin(math.radians(rotation))
lineLength = self.__LIMBSIZE+(self.__LINEWIDTH*3) line_length = self.__LIMBSIZE+(self.__LINEWIDTH*3)
compensation = int(shift*lineLength) compensation = int(shift*line_length)
limbDrawing = limbDrawing.rotate(rotation, expand=1) limb_drawing = limb_drawing.rotate(rotation, expand=1)
yPosition = self.__CIRCLESIZE + self.__ARMPOSITION y_position = self.__CIRCLESIZE + self.__ARMPOSITION
if limb == "ra": if limb == "ra":
compensation = min(-compensation, 0) compensation = min(-compensation, 0)
else: else:
xPosition -= self.__LIMBSIZE x_position -= self.__LIMBSIZE
compensation = min(compensation, 0) compensation = min(compensation, 0)
yPosition += compensation y_position += compensation
else: else:
rotation = random.randint(-15, 15) rotation = random.randint(-15, 15)
yPosition = self.__CIRCLESIZE+self.__BODYSIZE-self.__LINEWIDTH y_position = self.__CIRCLESIZE+self.__BODYSIZE-self.__LINEWIDTH
if limb == "rl": if limb == "rl":
limbDrawing = limbDrawing.rotate(rotation-45, expand=1) limb_drawing = limb_drawing.rotate(rotation-45, expand=1)
else: else:
xPosition += -limbDrawing.size[0]+self.__LINEWIDTH*3 x_position += -limb_drawing.size[0]+self.__LINEWIDTH*3
limbDrawing = limbDrawing.rotate(rotation+45, expand=1) limb_drawing = limb_drawing.rotate(rotation+45, expand=1)
pastePosition = (xPosition, yPosition) paste_position = (x_position, y_position)
background.paste(limbDrawing, pastePosition, limbDrawing) background.paste(limb_drawing, paste_position, limb_drawing)
return background return background
def __badText(self, text: str, big: bool, color: tuple = (0, 0, 0, 255)): def __bad_text(self, text: str, big: bool, color: tuple = (0, 0, 0, 255)):
if big: if big:
font = self.__FONT font = self.__FONT
else: else:
font = self.__SMALLFONT font = self.__SMALLFONT
w, h = font.getsize(text) width, height = font.getsize(text)
img = Image.new("RGBA", (w, h), color=(0, 0, 0, 0)) img = Image.new("RGBA", (width, height), color=(0, 0, 0, 0))
d = ImageDraw.Draw(img, "RGBA") drawer = ImageDraw.Draw(img, "RGBA")
d.text((0, 0), text, font=font, fill=color) drawer.text((0, 0), text, font=font, fill=color)
return img return img
def __drawGallows(self): def __draw_gallows(self):
gallowSize = (self.__GALLOWX, self.__GALLOWY) gallow_size = (self.__GALLOWX, self.__GALLOWY)
background = Image.new("RGBA", gallowSize, color=(0, 0, 0, 0)) background = Image.new("RGBA", gallow_size, color=(0, 0, 0, 0))
bottomLine = self.__badLine(int(self.__GALLOWX * 0.75), True) bottom_line = self.__bad_line(int(self.__GALLOWX * 0.75), True)
bottomLineX = int(self.__GALLOWX * 0.125) bottom_line_x = int(self.__GALLOWX * 0.125)
bottomLineY = self.__GALLOWY-(self.__LINEWIDTH*4) bottom_line_y = self.__GALLOWY-(self.__LINEWIDTH*4)
pastePosition = (bottomLineX, bottomLineY) paste_position = (bottom_line_x, bottom_line_y)
background.paste(bottomLine, pastePosition, bottomLine) background.paste(bottom_line, paste_position, bottom_line)
lineTwo = self.__badLine(self.__GALLOWY-self.__LINEWIDTH*6) line_two = self.__bad_line(self.__GALLOWY-self.__LINEWIDTH*6)
lineTwoX = int(self.__GALLOWX*(0.75*self.__PHI)) line_two_x = int(self.__GALLOWX*(0.75*self.__PHI))
lineTwoY = self.__LINEWIDTH*2 line_two_y = self.__LINEWIDTH*2
pastePosition = (lineTwoX, lineTwoY) paste_position = (line_two_x, line_two_y)
background.paste(lineTwo, pastePosition, lineTwo) background.paste(line_two, paste_position, line_two)
topLine = self.__badLine(int(self.__GALLOWY*0.30), True) top_line = self.__bad_line(int(self.__GALLOWY*0.30), True)
pasteX = int(self.__GALLOWX*(0.75*self.__PHI))-self.__LINEWIDTH paste_x = int(self.__GALLOWX*(0.75*self.__PHI))-self.__LINEWIDTH
pastePosition = (pasteX, self.__LINEWIDTH*3) paste_position = (paste_x, self.__LINEWIDTH*3)
background.paste(topLine, pastePosition, topLine) background.paste(top_line, paste_position, top_line)
lastLine = self.__badLine(int(self.__GALLOWY*0.125)) last_line = self.__bad_line(int(self.__GALLOWY*0.125))
pasteX += int(self.__GALLOWY*0.30) paste_x += int(self.__GALLOWY*0.30)
background.paste(lastLine, (pasteX, self.__LINEWIDTH*3), lastLine) background.paste(last_line, (paste_x, self.__LINEWIDTH*3), last_line)
return background return background
def __drawLetterLines(self, word: str, guessed: list, misses: int): def __draw_letter_lines(self, word: str, guessed: list, misses: int):
letterWidth = self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE letter_width = self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE
imageWidth = letterWidth*len(word) image_width = letter_width*len(word)
imageSize = (imageWidth, self.__LETTERLINELENGTH+self.__LINEWIDTH*3) image_size = (image_width, self.__LETTERLINELENGTH+self.__LINEWIDTH*3)
letterLines = Image.new("RGBA", imageSize, color=(0, 0, 0, 0)) letter_lines = Image.new("RGBA", image_size, color=(0, 0, 0, 0))
for x, letter in enumerate(word): for i, letter in enumerate(word):
line = self.__badLine(self.__LETTERLINELENGTH, True) line = self.__bad_line(self.__LETTERLINELENGTH, True)
pasteX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE) paste_x = i*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
pastePosition = (pasteX, self.__LETTERLINELENGTH) paste_position = (paste_x, self.__LETTERLINELENGTH)
letterLines.paste(line, pastePosition, line) letter_lines.paste(line, paste_position, line)
if guessed[x]: if guessed[i]:
letterDrawing = self.__badText(letter, True) letter_drawing = self.__bad_text(letter, True)
letterWidth = self.__FONT.getsize(letter)[0] letter_width = self.__FONT.getsize(letter)[0]
letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE) letter_x = i*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letterX -= (letterWidth//2) letter_x -= (letter_width//2)
letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2) letter_x += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letterLines.paste(letterDrawing, (letterX, 0), letterDrawing) letter_lines.paste(
letter_drawing,
(letter_x, 0),
letter_drawing
)
elif misses == 6: elif misses == 6:
letterDrawing = self.__badText(letter, True, (242, 66, 54)) letter_drawing = self.__bad_text(letter, True, (242, 66, 54))
letterWidth = self.__FONT.getsize(letter)[0] letter_width = self.__FONT.getsize(letter)[0]
letterX = x*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE) letter_x = i*(self.__LETTERLINELENGTH+self.__LETTERLINEDISTANCE)
letterX -= (letterWidth//2) letter_x -= (letter_width//2)
letterX += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2) letter_x += (self.__LETTERLINELENGTH//2)+(self.__LINEWIDTH*2)
letterLines.paste(letterDrawing, (letterX, 0), letterDrawing) letter_lines.paste(
letter_drawing,
(letter_x, 0),
letter_drawing
)
return letterLines return letter_lines
def __shortestDist(self, positions: list, newPosition: tuple): def __shortest_dist(self, positions: list, new_position: tuple):
__shortestDist = math.inf shortest_dist = math.inf
x, y = newPosition
for i, j in positions: for i, j in positions:
xDistance = abs(i-x) x_distance = abs(i-new_position[0])
yDistance = abs(j-y) y_distance = abs(j-new_position[1])
dist = math.sqrt(xDistance**2+yDistance**2) dist = math.sqrt(x_distance**2+y_distance**2)
if __shortestDist > dist: if shortest_dist > dist:
__shortestDist = dist shortest_dist = dist
return __shortestDist return shortest_dist
def __drawMisses(self, guesses: list, word: str): def __draw_misses(self, guesses: list, word: str):
background = Image.new("RGBA", (600, 400), color=(0, 0, 0, 0)) background = Image.new("RGBA", (600, 400), color=(0, 0, 0, 0))
pos = [] pos = []
for guess in guesses: for guess in guesses:
if guess not in word: if guess not in word:
placed = False placed = False
while not placed: while not placed:
letter = self.__badText(guess, True) letter = self.__bad_text(guess, True)
w, h = self.__FONT.getsize(guess) w, h = self.__FONT.getsize(guess)
x = random.randint(0, 600-w) x = random.randint(0, 600-w)
y = random.randint(0, 400-h) y = random.randint(0, 400-h)
if self.__shortestDist(pos, (x, y)) > 70: if self.__shortest_dist(pos, (x, y)) > 70:
pos.append((x, y)) pos.append((x, y))
background.paste(letter, (x, y), letter) background.paste(letter, (x, y), letter)
placed = True placed = True
return background return background
def drawImage(self, channel: str): def draw_image(self, channel: str):
""" """
Draw a hangman Image. Draw a hangman Image.
@ -589,24 +604,24 @@ class DrawHangman():
random.seed(game["game ID"]) random.seed(game["game ID"])
background = Image.open("gwendolyn/resources/paper.jpg") background = Image.open("gwendolyn/resources/paper.jpg")
gallow = self.__drawGallows() gallow = self.__draw_gallows()
man = self.__drawMan(game["misses"], game["game ID"]) man = self.__draw_man(game["misses"], game["game ID"])
random.seed(game["game ID"]) random.seed(game["game ID"])
letterLineParams = [game["word"], game["guessed"], game["misses"]] letter_line_parameters = [game["word"], game["guessed"], game["misses"]]
letterLines = self.__drawLetterLines(*letterLineParams) letter_lines = self.__draw_letter_lines(*letter_line_parameters)
random.seed(game["game ID"]) random.seed(game["game ID"])
misses = self.__drawMisses(game["guessed letters"], game["word"]) misses = self.__draw_misses(game["guessed letters"], game["word"])
background.paste(gallow, (100, 100), gallow) background.paste(gallow, (100, 100), gallow)
background.paste(man, (300, 210), man) background.paste(man, (300, 210), man)
background.paste(letterLines, (120, 840), letterLines) background.paste(letter_lines, (120, 840), letter_lines)
background.paste(misses, (600, 150), misses) background.paste(misses, (600, 150), misses)
missesText = self.__badText("MISSES", False) misses_text = self.__bad_text("MISSES", False)
missesTextWidth = missesText.size[0] misses_text_width = misses_text.size[0]
background.paste(missesText, (850-missesTextWidth//2, 50), missesText) background.paste(misses_text, (850-misses_text_width//2, 50), misses_text)
boardPath = f"gwendolyn/resources/games/hangman_boards/hangman_board{channel}.png" board_path = f"gwendolyn/resources/games/hangman_boards/hangman_board{channel}.png"
background.save(boardPath) background.save(board_path)

View File

@ -28,7 +28,7 @@ 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.get_name(players[opponent]) opponent_name = 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")
@ -71,9 +71,9 @@ class HexGame():
self.draw.drawSwap(channel) self.draw.drawSwap(channel)
opponent = game["players"][::-1][game["turn"]-1] opponent = game["players"][::-1][game["turn"]-1]
gwendoTurn = (opponent == f"#{self.bot.user.id}") gwendolyn_turn = (opponent == f"#{self.bot.user.id}")
opponentName = self.bot.database_funcs.get_name(opponent) opponent_name = 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 {opponent_name}'s turn")
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f: with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
old_image = await ctx.channel.fetch_message(int(f.read())) old_image = await ctx.channel.fetch_message(int(f.read()))
@ -90,7 +90,7 @@ class HexGame():
with open(f"gwendolyn/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(old_image.id)) f.write(str(old_image.id))
if gwendoTurn: if gwendolyn_turn:
await self.hexAI(ctx) await self.hexAI(ctx)
# Starts the game # Starts the game
@ -100,109 +100,109 @@ class HexGame():
channel = str(ctx.channel_id) channel = str(ctx.channel_id)
game = self.bot.database["hex games"].find_one({"_id":channel}) game = self.bot.database["hex games"].find_one({"_id":channel})
startedGame = False started_game = False
canStart = True can_start = True
if game != None: if game != None:
sendMessage = "There's already a hex game going on in this channel" send_message = "There's already a hex game going on in this channel"
log_message = "There was already a game going on" log_message = "There was already a game going on"
canStart = False can_start = False
else: else:
if type(opponent) == int: if type(opponent) == int:
# Opponent is Gwendolyn # Opponent is Gwendolyn
if opponent in range(1, 6): if opponent in range(1, 6):
opponentName = "Gwendolyn" opponent_name = "Gwendolyn"
difficulty = int(opponent) difficulty = int(opponent)
diffText = f" with difficulty {difficulty}" difficulty_text = f" with difficulty {difficulty}"
opponent = f"#{self.bot.user.id}" opponent = f"#{self.bot.user.id}"
else: else:
sendMessage = "Difficulty doesn't exist" send_message = "Difficulty doesn't exist"
log_message = "They tried to play against a difficulty that doesn't exist" log_message = "They tried to play against a difficulty that doesn't exist"
canStart = False can_start = False
elif type(opponent) == discord.member.Member: elif type(opponent) == discord.member.Member:
if opponent.bot: if opponent.bot:
# User has challenged a bot # User has challenged a bot
if opponent == self.bot.user: if opponent == self.bot.user:
# It was Gwendolyn # It was Gwendolyn
opponentName = "Gwendolyn" opponent_name = "Gwendolyn"
difficulty = 2 difficulty = 2
diffText = f" with difficulty {difficulty}" difficulty_text = f" with difficulty {difficulty}"
opponent = f"#{self.bot.user.id}" opponent = f"#{self.bot.user.id}"
else: else:
sendMessage = "You can't challenge a bot!" send_message = "You can't challenge a bot!"
log_message = "They tried to challenge a bot" log_message = "They tried to challenge a bot"
canStart = False can_start = False
else: else:
# Opponent is another player # Opponent is another player
if ctx.author != opponent: if ctx.author != opponent:
opponentName = opponent.display_name opponent_name = opponent.display_name
opponent = f"#{opponent.id}" opponent = f"#{opponent.id}"
difficulty = 5 difficulty = 5
diffText = "" difficulty_text = ""
else: else:
sendMessage = "You can't play against yourself" send_message = "You can't play against yourself"
log_message = "They tried to play against themself" log_message = "They tried to play against themself"
canStart = False can_start = False
else: else:
canStart = False can_start = False
log_message = f"Opponent was neither int or member. It was {type(opponent)}" log_message = f"Opponent was neither int or member. It was {type(opponent)}"
sendMessage = "Something went wrong" send_message = "Something went wrong"
if canStart: if can_start:
# board is 11x11 # board is 11x11
board = [[0 for i in range(self.BOARDWIDTH)] for j in range(self.BOARDWIDTH)] board = [[0 for i in range(self.BOARDWIDTH)] for j in range(self.BOARDWIDTH)]
players = [user, opponent] players = [user, opponent]
random.shuffle(players) # random starting player random.shuffle(players) # random starting player
gameHistory = [] gameHistory = []
newGame = {"_id":channel,"board":board, "winner":0, new_game = {"_id":channel,"board":board, "winner":0,
"players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory} "players":players, "turn":1, "difficulty":difficulty, "gameHistory":gameHistory}
self.bot.database["hex games"].insert_one(newGame) self.bot.database["hex games"].insert_one(new_game)
# draw the board # draw the board
self.draw.drawBoard(channel) self.draw.drawBoard(channel)
gwendoTurn = (players[0] == f"#{self.bot.user.id}") gwendolyn_turn = (players[0] == f"#{self.bot.user.id}")
startedGame = True started_game = True
turnName = self.bot.database_funcs.get_name(players[0]) turn_name = self.bot.database_funcs.get_name(players[0])
sendMessage = f"Started Hex game against {opponentName}{diffText}. It's {turnName}'s turn" send_message = f"Started Hex game against {opponent_name}{difficulty_text}. It's {turn_name}'s turn"
log_message = "Game started" log_message = "Game started"
await ctx.send(sendMessage) await ctx.send(send_message)
self.bot.log(log_message) self.bot.log(log_message)
if startedGame: if started_game:
file_path = f"gwendolyn/resources/games/hex_boards/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(file_path)) new_image = await ctx.channel.send(file = discord.File(file_path))
with open(f"gwendolyn/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(new_image.id))
if gwendoTurn: if gwendolyn_turn:
await self.hexAI(ctx) await self.hexAI(ctx)
# Places a piece at the given location and checks things afterwards # Places a piece at the given location and checks things afterwards
async def placeHex(self, ctx, position : str, user): async def placeHex(self, ctx, position : str, user):
channel = str(ctx.channel_id) channel = str(ctx.channel_id)
game = self.bot.database["hex games"].find_one({"_id":channel}) game = self.bot.database["hex games"].find_one({"_id":channel})
placedPiece = False placed_piece = False
if game == None: if game == None:
sendMessage = "There's no game in this channel" send_message = "There's no game in this channel"
self.bot.log("There was no game going on") self.bot.log("There was no game going on")
elif not (position[0].isalpha() and position[1:].isnumeric() and len(position) in [2, 3]): elif not (position[0].isalpha() and position[1:].isnumeric() and len(position) in [2, 3]):
sendMessage = "The position must be a letter followed by a number." send_message = "The position must be a letter followed by a number."
self.bot.log(f"The position was not valid, {position}") self.bot.log(f"The position was not valid, {position}")
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.get_name(game['players'][0])} and {self.bot.database_funcs.get_name(game['players'][1])}." send_message = 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" send_message = "It's not your turn"
self.bot.log("It wasn't their turn") self.bot.log("It wasn't their turn")
else: else:
player = game["turn"] player = game["turn"]
@ -215,7 +215,7 @@ class HexGame():
if board is None: if board is None:
self.bot.log("It was an invalid position") self.bot.log("It was an invalid position")
sendMessage = ("That's an invalid position. You must place your piece on an empty field.") send_message = ("That's an invalid position. You must place your piece on an empty field.")
else: else:
# If the move is valid: # If the move is valid:
self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"board":board}}) self.bot.database["hex games"].update_one({"_id":channel},{"$set":{"board":board}})
@ -227,34 +227,34 @@ class HexGame():
winner = self.evaluateBoard(game["board"])[1] winner = self.evaluateBoard(game["board"])[1]
if winner == 0: # Continue with the game. if winner == 0: # Continue with the game.
gameWon = False game_won = False
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) send_message = 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 game_won = 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.get_name(game["players"][player-1])+" placed at "+position.upper()+" and won!" send_message = 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 win_amount = game["difficulty"]*10
sendMessage += " Adding "+str(winAmount)+" GwendoBucks to their account." send_message += " Adding "+str(win_amount)+" GwendoBucks to their account."
self.bot.database["hex games"].update_one({"_id":channel}, self.bot.database["hex games"].update_one({"_id":channel},
{"$push":{"gameHistory":(int(position[1])-1, ord(position[0])-97)}}) {"$push":{"gameHistory":(int(position[1])-1, ord(position[0])-97)}})
# Is it now Gwendolyn's turn? # Is it now Gwendolyn's turn?
gwendoTurn = False gwendolyn_turn = False
if game["players"][turn-1] == f"#{self.bot.user.id}": if game["players"][turn-1] == f"#{self.bot.user.id}":
self.bot.log("It's Gwendolyn's turn") self.bot.log("It's Gwendolyn's turn")
gwendoTurn = True gwendolyn_turn = True
placedPiece = True placed_piece = True
if user == f"#{self.bot.user.id}": if user == f"#{self.bot.user.id}":
await ctx.channel.send(sendMessage) await ctx.channel.send(send_message)
else: else:
await ctx.send(sendMessage) await ctx.send(send_message)
if placedPiece: if placed_piece:
# Update the board # Update the board
self.draw.drawHexPlacement(channel,player, position) self.draw.drawHexPlacement(channel,player, position)
@ -270,7 +270,7 @@ class HexGame():
file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png" file_path = f"gwendolyn/resources/games/hex_boards/board{channel}.png"
old_image = await ctx.channel.send(file = discord.File(file_path)) old_image = await ctx.channel.send(file = discord.File(file_path))
if gameWon: if game_won:
self.bot.log("Dealing with the winning player") self.bot.log("Dealing with the winning player")
game = self.bot.database["hex games"].find_one({"_id":channel}) game = self.bot.database["hex games"].find_one({"_id":channel})
@ -284,7 +284,7 @@ class HexGame():
with open(f"gwendolyn/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(old_image.id)) f.write(str(old_image.id))
if gwendoTurn: if gwendolyn_turn:
await self.hexAI(ctx) await self.hexAI(ctx)
# Returns a board where the placement has ocurred # Returns a board where the placement has ocurred
@ -314,11 +314,11 @@ class HexGame():
game = self.bot.database["hex games"].find_one({"_id":channel}) game = self.bot.database["hex games"].find_one({"_id":channel})
if user not in game["players"]: if user not in game["players"]:
sendMessage = "You're not a player in the game" send_message = "You're not a player in the game"
elif len(game["gameHistory"]) == 0: elif len(game["gameHistory"]) == 0:
sendMessage = "You can't undo nothing" send_message = "You can't undo nothing"
elif user != game["players"][(game["turn"] % 2)]: # If it's not your turn elif user != game["players"][(game["turn"] % 2)]: # If it's not your turn
sendMessage = "It's not your turn" send_message = "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.get_name(user))) self.bot.log("Undoing {}'s last move".format(self.bot.database_funcs.get_name(user)))
@ -332,10 +332,10 @@ class HexGame():
# Update the board # Update the board
self.draw.drawHexPlacement(channel,0,"abcdefghijk"[lastMove[1]]+str(lastMove[0]+1)) # The zero makes the hex disappear self.draw.drawHexPlacement(channel,0,"abcdefghijk"[lastMove[1]]+str(lastMove[0]+1)) # The zero makes the hex disappear
sendMessage = f"You undid your last move at {lastMove}" send_message = f"You undid your last move at {lastMove}"
undid = True undid = True
await ctx.send(sendMessage) await ctx.send(send_message)
if undid: if undid:
with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f: with open(f"gwendolyn/resources/games/old_images/hex{channel}", "r") as f:
old_image = await ctx.channel.fetch_message(int(f.read())) old_image = await ctx.channel.fetch_message(int(f.read()))
@ -417,20 +417,20 @@ class HexGame():
return scores[2]-scores[1], winner return scores[2]-scores[1], winner
def minimaxHex(self, board, depth, alpha, beta, maximizingPlayer): def minimaxHex(self, board, depth, alpha, beta, maximizing_player):
# The depth is how many moves ahead the computer checks. This value is the difficulty. # The depth is how many moves ahead the computer checks. This value is the difficulty.
if depth == 0 or 0 not in sum(board,[]): if depth == 0 or 0 not in sum(board,[]):
score = self.evaluateBoard(board)[0] score = self.evaluateBoard(board)[0]
return score return score
# if final depth is not reached, look another move ahead: # if final depth is not reached, look another move ahead:
if maximizingPlayer: # red player predicts next move if maximizing_player: # red player predicts next move
maxEval = -math.inf maxEval = -math.inf
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0] possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
#self.bot.log("Judging a red move at depth {}".format(depth)) #self.bot.log("Judging a red move at depth {}".format(depth))
for i in possiblePlaces: for i in possiblePlaces:
testBoard = copy.deepcopy(board) test_board = copy.deepcopy(board)
testBoard[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 1 # because maximizingPlayer is Red which is number 1 test_board[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 1 # because maximizing_player is Red which is number 1
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,False) evaluation = self.minimaxHex(test_board,depth-1,alpha,beta,False)
maxEval = max(maxEval, evaluation) maxEval = max(maxEval, evaluation)
alpha = max(alpha, evaluation) alpha = max(alpha, evaluation)
if beta <= alpha: if beta <= alpha:
@ -442,9 +442,9 @@ class HexGame():
possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0] possiblePlaces = [i for i,v in enumerate(sum(board,[])) if v == 0]
#self.bot.log("Judging a blue move at depth {}".format(depth)) #self.bot.log("Judging a blue move at depth {}".format(depth))
for i in possiblePlaces: for i in possiblePlaces:
testBoard = copy.deepcopy(board) test_board = copy.deepcopy(board)
testBoard[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2 test_board[i // self.BOARDWIDTH][i % self.BOARDWIDTH] = 2 # because minimizingPlayer is Blue which is number 2
evaluation = self.minimaxHex(testBoard,depth-1,alpha,beta,True) evaluation = self.minimaxHex(test_board,depth-1,alpha,beta,True)
minEval = min(minEval, evaluation) minEval = min(minEval, evaluation)
beta = min(beta, evaluation) beta = min(beta, evaluation)
if beta <= alpha: if beta <= alpha:

View File

@ -62,8 +62,8 @@ class Invest():
portfolio: str portfolio: str
The portfolio. The portfolio.
""" """
investmentsDatabase = self.bot.database["investments"] investments_database = self.bot.database["investments"]
userInvestments = investmentsDatabase.find_one({"_id": user}) userInvestments = investments_database.find_one({"_id": user})
user_name = self.bot.database_funcs.get_name(user) user_name = self.bot.database_funcs.get_name(user)
@ -101,7 +101,7 @@ class Invest():
*Returns* *Returns*
--------- ---------
sendMessage: str send_message: str
The message to return to the user. The message to return to the user.
""" """
if buyAmount < 100: if buyAmount < 100:
@ -111,9 +111,9 @@ class Invest():
elif self.getPrice(stock) <= 0: elif self.getPrice(stock) <= 0:
return f"{stock} is not traded on the american market." return f"{stock} is not traded on the american market."
else: else:
investmentsDatabase = self.bot.database["investments"] investments_database = self.bot.database["investments"]
stockPrice = self.getPrice(stock) stockPrice = self.getPrice(stock)
userInvestments = investmentsDatabase.find_one({"_id": user}) userInvestments = investments_database.find_one({"_id": user})
self.bot.money.addMoney(user, -1*buyAmount) self.bot.money.addMoney(user, -1*buyAmount)
stock = stock.upper() stock = stock.upper()
@ -126,18 +126,18 @@ class Invest():
currentValue = int(valueChange * value["purchased"]) currentValue = int(valueChange * value["purchased"])
newAmount = currentValue + buyAmount newAmount = currentValue + buyAmount
valuePath = f"investments.{stock}.value at purchase" value_path = f"investments.{stock}.value at purchase"
updater = {"$set": {valuePath: stockPrice}} updater = {"$set": {value_path: stockPrice}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
purchasedPath = f"investments.{stock}.purchased" purchased_path = f"investments.{stock}.purchased"
updater = {"$set": {purchasedPath: newAmount}} updater = {"$set": {purchased_path: newAmount}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
if value["purchased for"] != "?": if value["purchased for"] != "?":
purchasedForPath = f"investments.{stock}.purchased for" purchasedFor_path = f"investments.{stock}.purchased for"
updater = {"$set": {purchasedForPath: buyAmount}} updater = {"$set": {purchasedFor_path: buyAmount}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
else: else:
updater = { updater = {
"$set": { "$set": {
@ -148,9 +148,9 @@ class Invest():
} }
} }
} }
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
else: else:
newUser = { new_user = {
"_id": user, "_id": user,
"investments": { "investments": {
stock: { stock: {
@ -160,12 +160,12 @@ class Invest():
} }
} }
} }
investmentsDatabase.insert_one(newUser) investments_database.insert_one(new_user)
user_name = self.bot.database_funcs.get_name(user) user_name = self.bot.database_funcs.get_name(user)
sendMessage = "{} bought {} GwendoBucks worth of {} stock" send_message = "{} bought {} GwendoBucks worth of {} stock"
sendMessage = sendMessage.format(user_name, buyAmount, stock) send_message = send_message.format(user_name, buyAmount, stock)
return sendMessage return send_message
def sellStock(self, user: str, stock: str, sellAmount: int): def sellStock(self, user: str, stock: str, sellAmount: int):
""" """
@ -182,15 +182,15 @@ class Invest():
*Returns* *Returns*
--------- ---------
sendMessage: str send_message: str
The message to return to the user. The message to return to the user.
""" """
if sellAmount <= 0: if sellAmount <= 0:
return "no" return "no"
else: else:
investmentsDatabase = self.bot.database["investments"] investments_database = self.bot.database["investments"]
userData = investmentsDatabase.find_one({"_id": user}) user_data = investments_database.find_one({"_id": user})
userInvestments = userData["investments"] userInvestments = user_data["investments"]
stock = stock.upper() stock = stock.upper()
@ -199,29 +199,29 @@ class Invest():
stockPrice = self.getPrice(stock) stockPrice = self.getPrice(stock)
priceChange = (stockPrice / value["value at purchase"]) priceChange = (stockPrice / value["value at purchase"])
purchasedAmount = int(priceChange * value["purchased"]) purchasedAmount = int(priceChange * value["purchased"])
purchasedPath = f"investments.{stock}.purchased" purchased_path = f"investments.{stock}.purchased"
updater = {"$set": {purchasedPath: purchasedAmount}} updater = {"$set": {purchased_path: purchasedAmount}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
valueAtPurchasePath = f"investments.{stock}.value at purchase" valueAtPurchase_path = f"investments.{stock}.value at purchase"
updater = {"$set": {valueAtPurchasePath: stockPrice}} updater = {"$set": {valueAtPurchase_path: stockPrice}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
if value["purchased"] >= sellAmount: if value["purchased"] >= sellAmount:
self.bot.money.addMoney(user, sellAmount) self.bot.money.addMoney(user, sellAmount)
if sellAmount < value["purchased"]: if sellAmount < value["purchased"]:
purchasedPath = f"investments.{stock}.purchased" purchased_path = f"investments.{stock}.purchased"
updater = {"$inc": {purchasedPath: -sellAmount}} updater = {"$inc": {purchased_path: -sellAmount}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
purchasedForPath = f"investments.{stock}.purchased for" purchasedFor_path = f"investments.{stock}.purchased for"
updater = {"$set": {purchasedForPath: "?"}} updater = {"$set": {purchasedFor_path: "?"}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
else: else:
updater = {"$unset": {f"investments.{stock}": ""}} updater = {"$unset": {f"investments.{stock}": ""}}
investmentsDatabase.update_one({"_id": user}, updater) investments_database.update_one({"_id": user}, updater)
user_name = self.bot.database_funcs.get_name(user) user_name = self.bot.database_funcs.get_name(user)
sendMessage = "{} sold {} GwendoBucks worth of {} stock" send_message = "{} sold {} GwendoBucks worth of {} stock"
return sendMessage.format(user_name, sellAmount, stock) return send_message.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:

View File

@ -51,10 +51,10 @@ class Money():
""" """
self.bot.log("checking "+user+"'s account balance") self.bot.log("checking "+user+"'s account balance")
userData = self.database["users"].find_one({"_id": user}) user_data = self.database["users"].find_one({"_id": user})
if userData is not None: if user_data is not None:
return userData["money"] return user_data["money"]
else: else:
return 0 return 0
@ -90,18 +90,18 @@ class Money():
""" """
self.bot.log("adding "+str(amount)+" to "+user+"'s account") self.bot.log("adding "+str(amount)+" to "+user+"'s account")
userData = self.database["users"].find_one({"_id": user}) user_data = self.database["users"].find_one({"_id": user})
if userData is not None: if user_data is not None:
updater = {"$inc": {"money": amount}} updater = {"$inc": {"money": amount}}
self.database["users"].update_one({"_id": user}, updater) self.database["users"].update_one({"_id": user}, updater)
else: else:
newUser = { new_user = {
"_id": user, "_id": user,
"user name": self.bot.database_funcs.get_name(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(new_user)
# Transfers money from one user to another # Transfers money from one user to another
async def giveMoney(self, ctx: discord_slash.context.SlashContext, async def giveMoney(self, ctx: discord_slash.context.SlashContext,
@ -125,15 +125,15 @@ class Money():
if member.display_name.lower() == username.lower(): if member.display_name.lower() == username.lower():
username = member.display_name username = member.display_name
user_id = f"#{member.id}" user_id = f"#{member.id}"
newUser = { new_user = {
"_id": user_id, "_id": user_id,
"user name": username, "user name": username,
"money": 0 "money": 0
} }
self.bot.database["users"].insert_one(newUser) self.bot.database["users"].insert_one(new_user)
userid = f"#{ctx.author.id}" userid = f"#{ctx.author.id}"
userData = self.database["users"].find_one({"_id": userid}) user_data = self.database["users"].find_one({"_id": userid})
targetUser = self.bot.database_funcs.get_id(username) targetUser = self.bot.database_funcs.get_id(username)
if amount <= 0: if amount <= 0:
@ -142,7 +142,7 @@ class Money():
elif targetUser is None: elif targetUser is None:
self.bot.log("They weren't in the system") self.bot.log("They weren't in the system")
await ctx.send("The target doesn't exist") await ctx.send("The target doesn't exist")
elif userData is None or userData["money"] < amount: elif user_data is None or user_data["money"] < amount:
self.bot.log("They didn't have enough GwendoBucks") self.bot.log("They didn't have enough GwendoBucks")
await ctx.send("You don't have that many GwendoBuck") await ctx.send("You don't have that many GwendoBuck")
else: else:

View File

@ -45,7 +45,7 @@ class Trivia():
*Returns* *Returns*
--------- ---------
sendMessage: str send_message: str
The message to return to the user. The message to return to the user.
""" """
triviaQuestions = self.bot.database["trivia questions"] triviaQuestions = self.bot.database["trivia questions"]
@ -110,7 +110,7 @@ class Trivia():
*Returns* *Returns*
--------- ---------
sendMessage: str send_message: str
The message to send if the function failed. The message to send if the function failed.
""" """
triviaQuestions = self.bot.database["trivia questions"] triviaQuestions = self.bot.database["trivia questions"]
@ -185,10 +185,10 @@ class Trivia():
self.bot.database_funcs.delete_game(*delete_gameParams) 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"] send_message = self.bot.long_strings["Trivia time up"]
formatParams = [chr(correctAnswer), options[correctAnswer-97]] format_parameters = [chr(correctAnswer), options[correctAnswer-97]]
sendMessage = sendMessage.format(*formatParams) send_message = send_message.format(*format_parameters)
await ctx.send(sendMessage) await ctx.send(send_message)
else: else:
await ctx.send(question, hidden=True) await ctx.send(question, hidden=True)

View File

@ -152,13 +152,13 @@ class LookupFuncs():
data = json.load(open('gwendolyn/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']}") send_message = (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']}")
else: else:
self.bot.log("I don't know that spell (error code 501)") self.bot.log("I don't know that spell (error code 501)")
sendMessage = "I don't think that's a spell (error code 501)" send_message = "I don't think that's a spell (error code 501)"
if len(sendMessage) > 2000: if len(send_message) > 2000:
await ctx.send(sendMessage[:2000]) await ctx.send(send_message[:2000])
await ctx.send(sendMessage[2000:]) await ctx.send(send_message[2000:])
else: else:
await ctx.send(sendMessage) await ctx.send(send_message)

View File

@ -1,413 +0,0 @@
import requests, imdb, discord, json, math, time, asyncio
class BedreNetflix():
def __init__(self,bot):
self.bot = bot
ip = ["localhost", "192.168.0.40"][self.bot.options["testing"]]
self.radarrURL = "http://"+ip+":7878/api/v3/"
self.sonarrURL = "http://"+ip+":8989/api/"
self.qbittorrentURL = "http://"+ip+":8080/api/v2/"
self.moviePath = "/media/plex/Server/movies/"
self.showPath = "/media/plex/Server/Shows/"
#Returns a list of no more than 5 options when user requests a movie
async def requestMovie(self, ctx, movieName):
await self.bot.defer(ctx)
self.bot.log("Searching for "+movieName)
movieList = imdb.IMDb().search_movie(movieName)
movies = []
for movie in movieList:
if movie["kind"] == "movie":
movies.append(movie)
if len(movies) > 5:
movies = movies[:5]
if len(movies) == 1:
messageTitle = "**Is it this movie?**"
else:
messageTitle = "**Is it any of these movies?**"
messageText = ""
imdb_ids = []
for x, movie in enumerate(movies):
try:
messageText += "\n"+str(x+1)+") "+movie["title"]+" ("+str(movie["year"])+")"
except:
try:
messageText += "\n"+str(x+1)+") "+movie["title"]
except:
messageText += "Error"
imdb_ids.append(movie.movieID)
self.bot.log("Returning a list of "+str(len(movies))+" possible movies: "+str(imdb_ids))
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
message = await ctx.send(embed=em)
messageData = {"message_id":message.id,"imdb_ids":imdb_ids}
with open("gwendolyn/resources/bedre_netflix/old_message"+str(ctx.channel.id),"w") as f:
json.dump(messageData,f)
if len(movies) == 1:
await message.add_reaction("✔️")
else:
for x in range(len(movies)):
await message.add_reaction(["1","2","3","4","5"][x])
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if message.content != "" and not isinstance(ctx.channel, discord.DMChannel):
await message.clear_reactions()
#Adds the requested movie to Bedre Netflix
async def add_movie(self, message, imdbId, editMessage = True):
if imdbId == None:
self.bot.log("Did not find what the user was searching for")
if editMessage:
await message.edit(embed = None, content = "Try searching for the IMDB id")
else:
await message.channel.send("Try searching for the IMDB id")
else:
self.bot.log("Trying to add movie "+str(imdbId))
apiKey = self.bot.credentials["radarr_key"]
response = requests.get(self.radarrURL+"movie/lookup/imdb?imdbId=tt"+imdbId+"&apiKey="+apiKey)
lookupData = response.json()
postData = {"qualityProfileId": 1,
"rootFolderPath" : self.moviePath,
"monitored" : True,
"addOptions": {"searchForMovie": True}}
for key in ["tmdbId","title","titleSlug","images","year"]:
postData.update({key : lookupData[key]})
r = requests.post(url= self.radarrURL+"movie?apikey="+apiKey,json = postData)
if r.status_code == 201:
if editMessage:
await message.edit(embed = None, content = postData["title"]+" successfully added to Bedre Netflix")
else:
await message.channel.send(postData["title"]+" successfully added to Bedre Netflix")
self.bot.log("Added "+postData["title"]+" to Bedre Netflix")
elif r.status_code == 400:
text = f"{postData['title']} is either already on Bedre Netflix, downloading, or not available"
if editMessage:
await message.edit(embed = None, content = text)
else:
await message.channel.send(text)
else:
if editMessage:
await message.edit(embed = None, content = "Something went wrong")
else:
await message.channel.send("Something went wrong")
self.bot.log(str(r.status_code)+" "+r.reason)
#Returns a list of no more than 5 options when user requests a show
async def requestShow(self, ctx, showName):
await self.bot.defer(ctx)
self.bot.log("Searching for "+showName)
movies = imdb.IMDb().search_movie(showName) #Replace with tvdb
shows = []
for movie in movies:
if movie["kind"] in ["tv series","tv miniseries"]:
shows.append(movie)
if len(shows) > 5:
shows = shows[:5]
if len(shows) == 1:
messageTitle = "**Is it this show?**"
else:
messageTitle = "**Is it any of these shows?**"
messageText = ""
imdb_names = []
for x, show in enumerate(shows):
try:
messageText += "\n"+str(x+1)+") "+show["title"]+" ("+str(show["year"])+")"
except:
try:
messageText += "\n"+str(x+1)+") "+show["title"]
except:
messageText += "Error"
imdb_names.append(show["title"])
self.bot.log("Returning a list of "+str(len(shows))+" possible shows: "+str(imdb_names))
em = discord.Embed(title=messageTitle,description=messageText,colour=0x00FF00)
message = await ctx.send(embed=em)
messageData = {"message_id":message.id,"imdb_names":imdb_names}
with open("gwendolyn/resources/bedre_netflix/old_message"+str(ctx.channel.id),"w") as f:
json.dump(messageData,f)
if len(shows) == 1:
await message.add_reaction("✔️")
else:
for x in range(len(shows)):
await message.add_reaction(["1","2","3","4","5"][x])
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if message.content != "" and not isinstance(ctx.channel, discord.DMChannel):
await message.clear_reactions()
#Adds the requested show to Bedre Netflix
async def add_show(self, message, imdb_name):
if imdb_name == None:
self.bot.log("Did not find what the user was searching for")
await message.edit(embed = None, content = "Try searching for the IMDB id")
else:
self.bot.log("Trying to add show "+str(imdb_name))
apiKey = self.bot.credentials["sonarr_key"]
response = requests.get(self.sonarrURL+"series/lookup?term="+imdb_name.replace(" ","%20")+"&apiKey="+apiKey)
lookupData = response.json()[0]
postData = {"ProfileId" : 1,
"rootFolderPath" : self.showPath,
"monitored" : True,
"addOptions" : {"searchForMissingEpisodes" : True}}
for key in ["tvdbId","title","titleSlug","images","seasons"]:
postData.update({key : lookupData[key]})
r = requests.post(url= self.sonarrURL+"series?apikey="+apiKey,json = postData)
if r.status_code == 201:
await message.edit(embed = None, content = postData["title"]+" successfully added to Bedre Netflix")
self.bot.log("Added a "+postData["title"]+" to Bedre Netflix")
elif r.status_code == 400:
text = f"{postData['title']} is either already on Bedre Netflix, downloading, or not available"
await message.edit(embed = None, content = text)
else:
await message.edit(embed = None, content = "Something went wrong")
self.bot.log(str(r.status_code)+" "+r.reason)
#Generates a list of all torrents and returns formatted list and whether all torrents are downloaded
async def genDownloadList(self, showDM, showMovies, showShows, episodes):
self.bot.log("Generating torrent list")
titleWidth = 100
message = []
allDownloaded = True
if showDM:
message.append("")
DMSectionTitle = "*Torrent Downloads*"
DMSectionTitleLine = "-"*((titleWidth-len(DMSectionTitle))//2)
message.append(DMSectionTitleLine+DMSectionTitle+DMSectionTitleLine)
response = requests.get(self.qbittorrentURL+"torrents/info")
torrentList = response.json()
if len(torrentList) > 0:
for torrent in torrentList:
torrentName = torrent["name"]
if len(torrentName) > 30:
if torrentName[26] == " ":
torrentName = torrentName[:26]+"...."
else:
torrentName = torrentName[:27]+"..."
while len(torrentName) < 30:
torrentName += " "
if torrent["size"] == 0:
downloadedRatio = 0
elif torrent["amount_left"] == 0:
downloadedRatio = 1
else:
downloadedRatio = min(torrent["downloaded"]/torrent["size"],1)
progressBar = "|"+(""*math.floor(downloadedRatio*20))
while len(progressBar) < 21:
progressBar += " "
progressBar += "| "+str(math.floor(downloadedRatio*100))+"%"
while len(progressBar) < 27:
progressBar += " "
etaInSeconds = torrent["eta"]
if etaInSeconds >= 8640000:
eta = ""
else:
eta = ""
if etaInSeconds >= 86400:
eta += str(math.floor(etaInSeconds/86400))+"d "
if etaInSeconds >= 3600:
eta += str(math.floor((etaInSeconds%86400)/3600))+"h "
if etaInSeconds >= 60:
eta += str(math.floor((etaInSeconds%3600)/60))+"m "
eta += str(etaInSeconds%60)+"s"
torrentInfo = torrentName+" "+progressBar+" (Eta: "+eta+")"
if torrent["state"] == "stalledDL":
torrentInfo += " (Stalled)"
if not (downloadedRatio == 1 and torrent["last_activity"] < time.time()-7200):
message.append(torrentInfo)
if downloadedRatio < 1 and torrent["state"] != "stalledDL":
allDownloaded = False
else:
message.append("No torrents currently downloading")
if showMovies:
message.append("")
movieSectionTitle = "*Missing movies not downloading*"
movieSectionTitleLine = "-"*((titleWidth-len(movieSectionTitle))//2)
message.append(movieSectionTitleLine+movieSectionTitle+movieSectionTitleLine)
movieList = requests.get(self.radarrURL+"movie?apiKey="+self.bot.credentials["radarr_key"]).json()
movieQueue = requests.get(self.radarrURL+"queue?apiKey="+self.bot.credentials["radarr_key"]).json()
movieQueueIDs = []
for queueItem in movieQueue["records"]:
movieQueueIDs.append(queueItem["movieId"])
for movie in movieList:
if not movie["hasFile"]:
if movie["id"] not in movieQueueIDs:
movieName = movie["title"]
if len(movieName) > 40:
if movieName[36] == " ":
movieName = movieName[:36]+"...."
else:
movieName = movieName[:37]+"..."
while len(movieName) < 41:
movieName += " "
if movie["monitored"]:
movieInfo = movieName+"Could not find a torrent"
else:
movieInfo = movieName+"No torrent exists. Likely because the movie is not yet released on DVD"
message.append(movieInfo)
if showShows:
message.append("")
showSectionTitle = "*Missing shows not downloading*"
showSectionTitleLine = "-"*((titleWidth-len(showSectionTitle))//2)
message.append(showSectionTitleLine+showSectionTitle+showSectionTitleLine)
showList = requests.get(self.sonarrURL+"series?apiKey="+self.bot.credentials["sonarr_key"]).json()
for show in showList:
if show["seasons"][0]["seasonNumber"] == 0:
seasons = show["seasons"][1:]
else:
seasons = show["seasons"]
if any(i["statistics"]["episodeCount"] != i["statistics"]["totalEpisodeCount"] for i in seasons):
if all(i["statistics"]["episodeCount"] == 0 for i in seasons):
message.append(show["title"] + " (all episodes)")
else:
if episodes:
missingEpisodes = sum(i["statistics"]["totalEpisodeCount"] - i["statistics"]["episodeCount"] for i in seasons)
message.append(show["title"] + f" ({missingEpisodes} episodes)")
message.append("-"*titleWidth)
messageText = "```"+"\n".join(message[1:])+"```"
if messageText == "``````":
messageText = "There are no torrents downloading right. If the torrent you're looking for was added more than 24 hours ago, it might already be on Bedre Netflix."
return messageText, allDownloaded
async def downloading(self, ctx, content):
async def SendLongMessage(ctx,messageText):
if len(messageText) <= 1994:
await ctx.send("```"+messageText+"```")
else:
cutOffIndex = messageText[:1994].rfind("\n")
await ctx.send("```"+messageText[:cutOffIndex]+"```")
await SendLongMessage(ctx,messageText[cutOffIndex+1:])
await self.bot.defer(ctx)
# showDM, showMovies, showShows, episodes
params = [False, False, False, False]
showDMArgs = ["d", "dm", "downloading", "downloadmanager"]
showMoviesArgs = ["m", "movies"]
showShowsArgs = ["s", "shows", "series"]
episodesArgs = ["e", "episodes"]
argList = [showDMArgs, showMoviesArgs, showShowsArgs, episodesArgs]
inputArgs = []
validArguments = True
while content != "" and validArguments:
if content[0] == " ":
content = content[1:]
elif content[0] == "-":
if content[1] == "-":
argStart = 2
if " " in content:
argStop = content.find(" ")
else:
argStop = None
else:
argStart = 1
argStop = 2
inputArgs.append(content[argStart:argStop])
if argStop is None:
content = ""
else:
content = content[argStop:]
else:
validArguments = False
if validArguments:
for x, argAliases in enumerate(argList):
argInInput = [i in inputArgs for i in argAliases]
if any(argInInput):
inputArgs.remove(argAliases[argInInput.index(True)])
params[x] = True
if len(inputArgs) != 0 or (params[2] == False and params[3] == True):
validArguments = False
showAnything = any(i for i in params)
if validArguments and showAnything:
messageText, allDownloaded = await self.genDownloadList(*params)
if messageText.startswith("```"):
if len(messageText) <= 2000:
if not allDownloaded:
updatesLeft = 60
messageText = messageText[:-3]+"\nThis message will update every 10 seconds for "+str(math.ceil(updatesLeft/6))+" more minutes\n```"
old_message = await ctx.send(messageText)
while ((not allDownloaded) and updatesLeft > 0):
await asyncio.sleep(10)
updatesLeft -= 1
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```"
await old_message.edit(content = messageText)
messageText, allDownloaded = await self.genDownloadList(*params)
if messageText.startswith("```"):
if allDownloaded:
self.bot.log("All torrents are downloaded")
else:
messageText = messageText[:-3]+"\nThis message will not update anymore\n```"
self.bot.log("The message updated 20 times")
await old_message.edit(content = messageText)
else:
await ctx.send(messageText)
else:
messageText = messageText[3:-3]
await SendLongMessage(ctx,messageText)
else:
await ctx.send(messageText)
else:
await ctx.send("Invalid or repeated parameters. Use '/help downloading' to see valid parameters.")

View File

@ -72,15 +72,15 @@ class Generators():
# Ends name if the name ends # Ends name if the name ends
if new_letter == "\n": if new_letter == "\n":
done = True done = True
genName = "".join(chain) gen_name = "".join(chain)
self.bot.log("Generated "+genName[:-1]) self.bot.log("Generated "+gen_name[:-1])
# Returns the name # Returns the name
await ctx.send(genName) await ctx.send(gen_name)
# Generates a random tavern name # Generates a random tavern name
async def tavernGen(self, ctx): async def tavernGen(self, ctx):
# Lists first parts, second parts and third parts of tavern names # _lists first parts, second parts and third parts of tavern names
fp = ["The Silver","The Golden","The Staggering","The Laughing","The Prancing","The Gilded","The Running","The Howling","The Slaughtered","The Leering","The Drunken","The Leaping","The Roaring","The Frowning","The Lonely","The Wandering","The Mysterious","The Barking","The Black","The Gleaming","The Tap-Dancing","The Sad","The Sexy","The Artificial","The Groovy","The Merciful","The Confused","The Pouting","The Horny","The Okay","The Friendly","The Hungry","The Handicapped","The Fire-breathing","The One-Eyed","The Psychotic","The Mad","The Evil","The Idiotic","The Trusty","The Busty"] fp = ["The Silver","The Golden","The Staggering","The Laughing","The Prancing","The Gilded","The Running","The Howling","The Slaughtered","The Leering","The Drunken","The Leaping","The Roaring","The Frowning","The Lonely","The Wandering","The Mysterious","The Barking","The Black","The Gleaming","The Tap-Dancing","The Sad","The Sexy","The Artificial","The Groovy","The Merciful","The Confused","The Pouting","The Horny","The Okay","The Friendly","The Hungry","The Handicapped","The Fire-breathing","The One-Eyed","The Psychotic","The Mad","The Evil","The Idiotic","The Trusty","The Busty"]
sp = ["Eel","Dolphin","Dwarf","Pegasus","Pony","Rose","Stag","Wolf","Lamb","Demon","Goat","Spirit","Horde","Jester","Mountain","Eagle","Satyr","Dog","Spider","Star","Dad","Rat","Jeremy","Mouse","Unicorn","Pearl","Ant","Crab","Penguin","Octopus","Lawyer","Ghost","Toad","Handjob","Immigrant","SJW","Dragon","Bard","Sphinx","Soldier","Salmon","Owlbear","Kite","Frost Giant","Arsonist"] sp = ["Eel","Dolphin","Dwarf","Pegasus","Pony","Rose","Stag","Wolf","Lamb","Demon","Goat","Spirit","Horde","Jester","Mountain","Eagle","Satyr","Dog","Spider","Star","Dad","Rat","Jeremy","Mouse","Unicorn","Pearl","Ant","Crab","Penguin","Octopus","Lawyer","Ghost","Toad","Handjob","Immigrant","SJW","Dragon","Bard","Sphinx","Soldier","Salmon","Owlbear","Kite","Frost Giant","Arsonist"]
tp = [" Tavern"," Inn","","","","","","","","",""] tp = [" Tavern"," Inn","","","","","","","","",""]

View File

@ -38,10 +38,10 @@ class NerdShit():
heights += [height] heights += [height]
width = max(width,int(pod.img['@width'])) width = max(width,int(pod.img['@width']))
if titleChucks[x][count] == "": if titleChucks[x][count] == "":
placeForText = 0 placeFor_text = 0
else: else:
placeForText = 30 placeFor_text = 30
height += int(pod.img["@height"]) + 10 + placeForText height += int(pod.img["@height"]) + 10 + placeFor_text
width += 10 width += 10
height += 5 height += 5
@ -55,18 +55,18 @@ class NerdShit():
old_image = Image.open("gwendolyn/resources/wolfTemp.png") old_image = Image.open("gwendolyn/resources/wolfTemp.png")
oldSize = old_image.size oldSize = old_image.size
if titleChucks[x][count] == "": if titleChucks[x][count] == "":
placeForText = 0 placeFor_text = 0
else: else:
placeForText = 30 placeFor_text = 30
newSize = (width,int(oldSize[1]+10+placeForText)) newSize = (width,int(oldSize[1]+10+placeFor_text))
newImage = Image.new("RGB",newSize,color=(255,255,255)) new_image = Image.new("RGB",newSize,color=(255,255,255))
newImage.paste(old_image, (int((int(oldSize[0]+10)-oldSize[0])/2),int(((newSize[1]-placeForText)-oldSize[1])/2)+placeForText)) new_image.paste(old_image, (int((int(oldSize[0]+10)-oldSize[0])/2),int(((newSize[1]-placeFor_text)-oldSize[1])/2)+placeFor_text))
if titleChucks[x][count] != "": if titleChucks[x][count] != "":
d = ImageDraw.Draw(newImage,"RGB") d = ImageDraw.Draw(new_image,"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(new_image,(0,heights[count]))
newImage.close() new_image.close()
old_image.close() old_image.close()
count += 1 count += 1

View File

@ -7,7 +7,7 @@ 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 .bedre_netflix import BedreNetflix from .plex import Plex
from .nerd_shit import NerdShit from .nerd_shit import NerdShit
from .generators import Generators from .generators import Generators
@ -19,16 +19,16 @@ fandom.set_wiki("senkulpa")
class MyStringifier(d20.MarkdownStringifier): class MyStringifier(d20.MarkdownStringifier):
def _str_expression(self, node): def _str_expression(self, node):
if node.comment == None: if node.comment == None:
resultText = "Result" result_text = "Result"
else: else:
resultText = node.comment.capitalize() result_text = node.comment.capitalize()
return f"**{resultText}**: {self._stringify(node.roll)}\n**Total**: {int(node.total)}" return f"**{result_text}**: {self._stringify(node.roll)}\n**Total**: {int(node.total)}"
class Other(): class Other():
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.bedre_netflix = BedreNetflix(self.bot) self.plex = Plex(self.bot)
self.nerd_shit = NerdShit(self.bot) self.nerd_shit = NerdShit(self.bot)
self.generators = Generators(self.bot) self.generators = Generators(self.bot)
@ -41,11 +41,11 @@ class Other():
self.bot.log("Picking a movie") self.bot.log("Picking a movie")
with open("gwendolyn/resources/movies.txt", "r") as f: with open("gwendolyn/resources/movies.txt", "r") as f:
movieList = f.read().split("\n") movie_list = f.read().split("\n")
movieName = random.choice(movieList) movie_name = random.choice(movie_list)
self.bot.log(f"Searching for {movieName}") self.bot.log(f"Searching for {movie_name}")
searchResult = imdbClient.search_movie(movieName) searchResult = imdbClient.search_movie(movie_name)
self.bot.log("Getting the data") self.bot.log("Getting the data")
movie = searchResult[0] movie = searchResult[0]
@ -74,17 +74,17 @@ class Other():
author = ctx.author.display_name author = ctx.author.display_name
now = datetime.datetime.now() now = datetime.datetime.now()
if time_in_range(now.replace(hour=5, minute=0, second=0, microsecond=0),now.replace(hour=10, minute=0, second=0, microsecond=0), now): if time_in_range(now.replace(hour=5, minute=0, second=0, microsecond=0),now.replace(hour=10, minute=0, second=0, microsecond=0), now):
sendMessage = "Good morning, "+str(author) send_message = "Good morning, "+str(author)
elif time_in_range(now.replace(hour=13, minute=0, second=0, microsecond=0),now.replace(hour=18, minute=0, second=0, microsecond=0), now): elif time_in_range(now.replace(hour=13, minute=0, second=0, microsecond=0),now.replace(hour=18, minute=0, second=0, microsecond=0), now):
sendMessage = "Good afternoon, "+str(author) send_message = "Good afternoon, "+str(author)
elif time_in_range(now.replace(hour=18, minute=0, second=0, microsecond=0),now.replace(hour=22, minute=0, second=0, microsecond=0), now): elif time_in_range(now.replace(hour=18, minute=0, second=0, microsecond=0),now.replace(hour=22, minute=0, second=0, microsecond=0), now):
sendMessage = "Good evening, "+str(author) send_message = "Good evening, "+str(author)
elif time_in_range(now.replace(hour=22, minute=0, second=0, microsecond=0),now.replace(hour=23, minute=59, second=59, microsecond=0), now): elif time_in_range(now.replace(hour=22, minute=0, second=0, microsecond=0),now.replace(hour=23, minute=59, second=59, microsecond=0), now):
sendMessage = "Good night, "+str(author) send_message = "Good night, "+str(author)
else: else:
sendMessage = "Hello, "+str(author) send_message = "Hello, "+str(author)
await ctx.send(sendMessage) await ctx.send(send_message)
# Finds a random picture online # Finds a random picture online
async def imageFunc(self, ctx): async def imageFunc(self, ctx):

View File

@ -0,0 +1,536 @@
"""Plex integration with the bot."""
from math import floor, ceil
import time
import json
import asyncio
import requests
import imdb
import discord
class Plex():
"""Container for Plex functions and commands."""
def __init__(self,bot):
self.bot = bot
self.credentials = self.bot.credentials
self.long_strings = self.bot.long_strings
server_ip = ["localhost", "192.168.0.40"][self.bot.options["testing"]]
self.radarr_url = "http://"+server_ip+":7878/api/v3/"
self.sonarr_url = "http://"+server_ip+":8989/api/"
self.qbittorrent_url = "http://"+server_ip+":8080/api/v2/"
self.movie_path = "/media/plex/Server/movies/"
self.show_path = "/media/plex/Server/Shows/"
async def request_movie(self, ctx, movie_name):
"""Request a movie for the Plex Server"""
await self.bot.defer(ctx)
self.bot.log("Searching for "+movie_name)
movie_list = imdb.IMDb().search_movie(movie_name)
movies = []
for movie in movie_list:
if movie["kind"] == "movie":
movies.append(movie)
if len(movies) > 5:
movies = movies[:5]
if len(movies) == 1:
message_title = "**Is it this movie?**"
else:
message_title = "**Is it any of these movies?**"
message_text = ""
imdb_ids = []
for i, movie in enumerate(movies):
try:
message_text += "\n"+str(i+1)+") "+movie["title"]
try:
message_text += " ("+str(movie["year"])+")"
except KeyError:
self.bot.log(f"{movie['title']} has no year.")
except KeyError:
message_text += "Error"
imdb_ids.append(movie.movieID)
self.bot.log(
f"Returning a list of {len(movies)} possible movies: {imdb_ids}"
)
embed = discord.Embed(
title=message_title,
description=message_text,
colour=0x00FF00
)
message = await ctx.send(embed=embed)
message_data = {"message_id":message.id,"imdb_ids":imdb_ids}
file_path = f"gwendolyn/resources/plex/old_message{ctx.channel.id}"
with open(file_path,"w") as file_pointer:
json.dump(message_data, file_pointer)
if len(movies) == 1:
await message.add_reaction("✔️")
else:
for i in range(len(movies)):
await message.add_reaction(["1","2","3","4","5"][i])
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if (message.content != "" and
not isinstance(ctx.channel, discord.DMChannel)):
await message.clear_reactions()
async def add_movie(self, message, imdb_id, edit_message = True):
"""Add a movie to Plex server."""
if imdb_id is None:
self.bot.log("Did not find what the user was searching for")
if edit_message:
await message.edit(
embed = None,
content = "Try searching for the IMDB id"
)
else:
await message.channel.send("Try searching for the IMDB id")
else:
self.bot.log("Trying to add movie "+str(imdb_id))
api_key = self.credentials["radarr_key"]
request_url = self.radarr_url+"movie/lookup/imdb?imdbId=tt"+imdb_id
request_url += "&apiKey="+api_key
response = requests.get(request_url)
lookup_data = response.json()
post_data = {"qualityProfileId": 1,
"rootFolder_path" : self.movie_path,
"monitored" : True,
"addOptions": {"searchForMovie": True}}
for key in ["tmdbId","title","titleSlug","images","year"]:
post_data.update({key : lookup_data[key]})
response = requests.post(
url= self.radarr_url+"movie?apikey="+api_key,
json = post_data
)
if response.status_code == 201:
success_message = "{} successfully added to Plex".format(
post_data["title"]
)
if edit_message:
await message.edit(
embed = None,
content = success_message
)
else:
await message.channel.send(success_message)
self.bot.log("Added "+post_data["title"]+" to Plex")
elif response.status_code == 400:
fail_text = self.long_strings["Already on Plex"].format(
post_data['title']
)
if edit_message:
await message.edit(embed = None, content = fail_text)
else:
await message.channel.send(fail_text)
else:
if edit_message:
await message.edit(
embed = None,
content = "Something went wrong"
)
else:
await message.channel.send("Something went wrong")
self.bot.log(str(response.status_code)+" "+response.reason)
async def request_show(self, ctx, show_name):
"""Request a show for the Plex server."""
await self.bot.defer(ctx)
self.bot.log("Searching for "+show_name)
movies = imdb.IMDb().search_movie(show_name) # Replace with tvdb
shows = []
for movie in movies:
if movie["kind"] in ["tv series","tv miniseries"]:
shows.append(movie)
if len(shows) > 5:
shows = shows[:5]
if len(shows) == 1:
message_title = "**Is it this show?**"
else:
message_title = "**Is it any of these shows?**"
message_text = ""
imdb_names = []
for i, show in enumerate(shows):
try:
message_text += f"\n{i+1}) {show['title']} ({show['year']})"
except KeyError:
try:
message_text += "\n"+str(i+1)+") "+show["title"]
except KeyError:
message_text += "Error"
imdb_names.append(show["title"])
self.bot.log(
f"Returning a list of {len(shows)} possible shows: {imdb_names}"
)
embed = discord.Embed(
title=message_title,
description=message_text,
colour=0x00FF00
)
message = await ctx.send(embed=embed)
message_data = {"message_id":message.id,"imdb_names":imdb_names}
file_path = "gwendolyn/resources/plex/old_message"+str(ctx.channel.id)
with open(file_path,"w") as file_pointer:
json.dump(message_data, file_pointer)
if len(shows) == 1:
await message.add_reaction("✔️")
else:
for i in range(len(shows)):
await message.add_reaction(["1","2","3","4","5"][i])
await message.add_reaction("")
message = await ctx.channel.fetch_message(message.id)
if message.content != "":
if not isinstance(ctx.channel, discord.DMChannel):
await message.clear_reactions()
async def add_show(self, message, imdb_name):
"""Add the requested show to Plex."""
if imdb_name is None:
self.bot.log("Did not find what the user was searching for")
await message.edit(
embed = None,
content = "Try searching for the IMDB id"
)
else:
self.bot.log("Trying to add show "+str(imdb_name))
api_key = self.credentials["sonarr_key"]
request_url = self.sonarr_url+"series/lookup?term="
request_url += imdb_name.replace(" ","%20")
request_url += "&apiKey="+api_key
response = requests.get(request_url)
lookup_data = response.json()[0]
post_data = {
"ProfileId" : 1,
"rootFolder_path" : self.show_path,
"monitored" : True,
"addOptions" : {"searchForMissingEpisodes" : True}
}
for key in ["tvdbId","title","titleSlug","images","seasons"]:
post_data.update({key : lookup_data[key]})
response = requests.post(
url= self.sonarr_url+"series?apikey="+api_key,
json = post_data
)
if response.status_code == 201:
await message.edit(
embed = None,
content = post_data["title"]+" successfully added to Plex"
)
self.bot.log("Added a "+post_data["title"]+" to Plex")
elif response.status_code == 400:
text = self.long_strings["Already on Plex"].format(
post_data['title']
)
await message.edit(embed = None, content = text)
else:
await message.edit(
embed = None,
content = "Something went wrong"
)
self.bot.log(str(response.status_code)+" "+response.reason)
async def __generate_download_list(self, show_dm, show_movies, show_shows,
episodes):
"""Generate a list of all torrents.
*Returns*
message_text: str
A formatted list of all torrents
all_downloaded: bool
Whether all torrents are downloaded
"""
self.bot.log("Generating torrent list")
title_width = 100
message = []
all_downloaded = True
if show_dm:
message.append("")
dm_section_title = "*Torrent Downloads*"
dm_section_title_line = "-"*((title_width-len(dm_section_title))//2)
message.append(
dm_section_title_line+dm_section_title+dm_section_title_line
)
response = requests.get(self.qbittorrent_url+"torrents/info")
torrent_list = response.json()
if len(torrent_list) > 0:
for torrent in torrent_list:
torrent_name = torrent["name"]
if len(torrent_name) > 30:
if torrent_name[26] == " ":
torrent_name = torrent_name[:26]+"...."
else:
torrent_name = torrent_name[:27]+"..."
while len(torrent_name) < 30:
torrent_name += " "
if torrent["size"] == 0:
download_ratio = 0
elif torrent["amount_left"] == 0:
download_ratio = 1
else:
download_ratio = min(
torrent["downloaded"]/torrent["size"],
1
)
progress_bar = "|"+(""*floor(download_ratio*20))
while len(progress_bar) < 21:
progress_bar += " "
progress_bar += "| "+str(floor(download_ratio*100))+"%"
while len(progress_bar) < 27:
progress_bar += " "
eta_in_seconds = torrent["eta"]
if eta_in_seconds >= 8640000:
eta = ""
else:
eta = ""
if eta_in_seconds >= 86400:
eta += str(floor(eta_in_seconds/86400))+"d "
if eta_in_seconds >= 3600:
eta += str(floor((eta_in_seconds%86400)/3600))+"h "
if eta_in_seconds >= 60:
eta += str(floor((eta_in_seconds%3600)/60))+"m "
eta += str(eta_in_seconds%60)+"s"
torrent_info = f"{torrent_name} {progress_bar} "
torrent_info += f"(Eta: {eta})"
if torrent["state"] == "stalledDL":
torrent_info += " (Stalled)"
if not (download_ratio == 1 and
torrent["last_activity"] < time.time()-7200):
message.append(torrent_info)
if download_ratio < 1 and torrent["state"] != "stalledDL":
all_downloaded = False
else:
message.append("No torrents currently downloading")
if show_movies:
message.append("")
movies_section_title = "*Missing movies not downloading*"
movies_section_line = (
"-"*((title_width-len(movies_section_title))//2)
)
message.append(
movies_section_line+movies_section_title+movies_section_line
)
movie_list = requests.get(
self.radarr_url+"movie?api_key="+self.credentials["radarr_key"]
).json()
movie_queue = requests.get(
self.radarr_url+"queue?api_key="+self.credentials["radarr_key"]
).json()
movie_queue_ids = []
for queue_item in movie_queue["records"]:
movie_queue_ids.append(queue_item["movieId"])
for movie in movie_list:
if (not movie["hasFile"] and
movie["id"] not in movie_queue_ids):
movie_name = movie["title"]
if len(movie_name) > 40:
if movie_name[36] == " ":
movie_name = movie_name[:36]+"...."
else:
movie_name = movie_name[:37]+"..."
while len(movie_name) < 41:
movie_name += " "
if movie["monitored"]:
movie_info = movie_name+"Could not find a torrent"
else:
movie_info = self.long_strings["No torrent"].format(
movie_name
)
message.append(movie_info)
if show_shows:
message.append("")
show_section_title = "*Missing shows not downloading*"
show_section_line = "-"*((title_width-len(show_section_title))//2)
message.append(
show_section_line+show_section_title+show_section_line
)
show_list = requests.get(
self.sonarr_url+"series?api_key="+self.credentials["sonarr_key"]
).json()
for show in show_list:
if show["seasons"][0]["seasonNumber"] == 0:
seasons = show["seasons"][1:]
else:
seasons = show["seasons"]
if any(
(
i["statistics"]["episodeCount"] !=
i["statistics"]["totalEpisodeCount"]
) for i in seasons):
if all(
i["statistics"]["episodeCount"] == 0 for i in seasons
):
message.append(show["title"] + " (all episodes)")
else:
if episodes:
missing_episodes = sum(
(i["statistics"]["totalEpisodeCount"] -
i["statistics"]["episodeCount"])
for i in seasons)
message.append(
f"{show['title']} ({missing_episodes} episodes)"
)
message.append("-"*title_width)
message_text = "```"+"\n".join(message[1:])+"```"
if message_text == "``````":
message_text = self.long_strings["No torrents downloading"]
return message_text, all_downloaded
async def downloading(self, ctx, content):
"""Send message with list of all downloading torrents."""
async def send_long_message(ctx,message_text):
if len(message_text) <= 1994:
await ctx.send("```"+message_text+"```")
else:
cut_off_index = message_text[:1994].rfind("\n")
await ctx.send("```"+message_text[:cut_off_index]+"```")
await send_long_message(ctx,message_text[cut_off_index+1:])
await self.bot.defer(ctx)
# showDM, showMovies, showShows, episodes
parameters = [False, False, False, False]
show_dm_args = ["d", "dm", "downloading", "downloadmanager"]
show_movies_args = ["m", "movies"]
show_shows_args = ["s", "shows", "series"]
show_episode_args = ["e", "episodes"]
arg_list = [
show_dm_args, show_movies_args, show_shows_args, show_episode_args
]
input_args = []
valid_arguments = True
while content != "" and valid_arguments:
if content[0] == " ":
content = content[1:]
elif content[0] == "-":
if content[1] == "-":
arg_start = 2
if " " in content:
arg_stop = content.find(" ")
else:
arg_stop = None
else:
arg_start = 1
arg_stop = 2
input_args.append(content[arg_start:arg_stop])
if arg_stop is None:
content = ""
else:
content = content[arg_stop:]
else:
valid_arguments = False
if valid_arguments:
for arg_index, arg_aliases in enumerate(arg_list):
arg_in_input = [i in input_args for i in arg_aliases]
if any(arg_in_input):
input_args.remove(arg_aliases[arg_in_input.index(True)])
parameters[arg_index] = True
if len(input_args) != 0 or (not parameters[2] and parameters[3]):
valid_arguments = False
show_anything = any(i for i in parameters)
if not (valid_arguments and show_anything):
await ctx.send(self.long_strings["Invalid parameters"])
else:
message_text, all_downloaded = await self.__generate_download_list(
*parameters
)
if not message_text.startswith("```"):
await ctx.send(message_text)
elif len(message_text) > 2000:
message_text = message_text[3:-3]
await send_long_message(ctx,message_text)
elif all_downloaded:
await ctx.send(message_text)
else:
updates_left = 60
message_text = self.long_strings["Update"].format(
message_text[:-3], ceil(updates_left/6)
)
old_message = await ctx.send(message_text)
while ((not all_downloaded) and updates_left > 0):
await asyncio.sleep(10)
updates_left -= 1
message_text, all_downloaded = await (
self.__generate_download_list(*parameters)
)
message_text = self.long_strings["Update"].format(
message_text[:-3],
ceil(updates_left/6)
)
await old_message.edit(content = message_text)
message_text, all_downloaded = await (
self.__generate_download_list(*parameters)
)
if message_text.startswith("```"):
if all_downloaded:
self.bot.log("All torrents are downloaded")
else:
message_text = self.long_strings["No updates"].format(
message_text[:-3]
)
self.bot.log("The message updated 20 times")
await old_message.edit(content = message_text)

View File

@ -6,7 +6,7 @@ class StarWarsChar():
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
def getCharName(self, user : str): def getChar_name(self, user : str):
self.bot.log("Getting name for "+self.bot.database_funcs.get_name(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})
@ -239,7 +239,7 @@ class StarWarsChar():
return name, text1+text2+"\n\n"+text3+divider+text4+"\n"+divider+text5+text6+text7+text8 return name, text1+text2+"\n\n"+text3+divider+text4+"\n"+divider+text5+text6+text7+text8
def charData(self,user : str,cmd : str): def char_data(self,user : str,cmd : str):
userCharacter = self.bot.database["starwars characters"].find_one({"_id":user}) userCharacter = self.bot.database["starwars characters"].find_one({"_id":user})
key = string.capwords(cmd.split(" ")[0]) key = string.capwords(cmd.split(" ")[0])
@ -508,7 +508,7 @@ class StarWarsChar():
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.get_name(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.char_data(user,cmd))))
if returnEmbed: if returnEmbed:
em = discord.Embed(title = title, description = text, colour=0xDEADBF) em = discord.Embed(title = title, description = text, colour=0xDEADBF)

View File

@ -52,21 +52,21 @@ class StarWarsDestiny():
if cmd == "": if cmd == "":
self.bot.log("Retrieving destiny pool info") self.bot.log("Retrieving destiny pool info")
with open("gwendolyn/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()) send_message = self.bot.star_wars.roll.resultToEmoji(f.read())
else: else:
commands = cmd.upper().split(" ") commands = cmd.upper().split(" ")
if commands[0] == "N": if commands[0] == "N":
if len(commands) > 1: if len(commands) > 1:
sendMessage = self.destinyNew(int(commands[1])) send_message = self.destinyNew(int(commands[1]))
else: else:
sendMessage = "You need to give an amount of players (error code 921)" send_message = "You need to give an amount of players (error code 921)"
elif commands[0] == "U": elif commands[0] == "U":
sendMessage = self.destinyUse(user) send_message = self.destinyUse(user)
else: else:
sendMessage = "I didn't quite understand that (error code 922)" send_message = "I didn't quite understand that (error code 922)"
messageList = sendMessage.split("\n") message_list = send_message.split("\n")
await ctx.send(messageList[0]) await ctx.send(message_list[0])
if len(messageList) > 1: if len(message_list) > 1:
for messageItem in messageList[1:]: for messageItem in message_list[1:]:
await ctx.channel.send(messageItem) await ctx.channel.send(messageItem)

View File

@ -4,7 +4,7 @@ import string
import json import json
with open("gwendolyn/resources/star_wars/starwarsskills.json", "r") as f: with open("gwendolyn/resources/star_wars/starwarsskills.json", "r") as f:
skillData = json.load(f) skill_data = json.load(f)
class StarWarsRoll(): class StarWarsRoll():
def __init__(self, bot): def __init__(self, bot):
@ -288,12 +288,12 @@ class StarWarsRoll():
characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"]) characteristic = random.choice(["brawn"] * 3 + ["agility"] * 3 + ["intellect", "cunning", "presence"])
results = "**Gruesome Injury**: The target's "+characteristic+" is permanently one lower, "+dd+dd+dd+dd results = "**Gruesome Injury**: The target's "+characteristic+" is permanently one lower, "+dd+dd+dd+dd
sendMessage = "Roll: "+str(roll)+"\nInjury:\n"+results send_message = "Roll: "+str(roll)+"\nInjury:\n"+results
messageList = sendMessage.split("\n") message_list = send_message.split("\n")
await ctx.send(messageList[0]) await ctx.send(message_list[0])
if len(messageList) > 1: if len(message_list) > 1:
for messageItem in messageList[1:]: for messageItem in message_list[1:]:
await ctx.channel.send(messageItem) await ctx.channel.send(messageItem)
# Parses the command into something the other functions understand # Parses the command into something the other functions understand
@ -312,19 +312,19 @@ class StarWarsRoll():
rollParameters = [0,0,0,0,0,0,0] rollParameters = [0,0,0,0,0,0,0]
if string.capwords(commands[0]) == "Obligations": if string.capwords(commands[0]) == "Obligations":
sendMessage = self.obligationRoll() send_message = self.obligationRoll()
elif string.capwords(commands[0]) in skillData: elif string.capwords(commands[0]) in skill_data:
self.bot.log("Oh look! This guy has skills!") self.bot.log("Oh look! This guy has skills!")
if self.bot.star_wars.character.userHasChar(user): if self.bot.star_wars.character.userHasChar(user):
self.bot.log("They have a character. That much we know") self.bot.log("They have a character. That much we know")
skillLevel = self.bot.star_wars.character.charData(user,"Skills " + string.capwords(commands[0])) skillLevel = self.bot.star_wars.character.char_data(user,"Skills " + string.capwords(commands[0]))
if string.capwords(commands[0]) == "Lightsaber": if string.capwords(commands[0]) == "Lightsaber":
self.bot.log("The skill is lightsaber") self.bot.log("The skill is lightsaber")
charLevel = self.bot.star_wars.character.charData(user,"Characteristics " + self.bot.star_wars.character.lightsaberChar(user)) charLevel = self.bot.star_wars.character.char_data(user,"Characteristics " + self.bot.star_wars.character.lightsaberChar(user))
else: else:
charLevel = self.bot.star_wars.character.charData(user,"Characteristics " + skillData[string.capwords(commands[0])]) charLevel = self.bot.star_wars.character.char_data(user,"Characteristics " + skill_data[string.capwords(commands[0])])
abilityDice = abs(charLevel-skillLevel) abilityDice = abs(charLevel-skillLevel)
proficiencyDice = min(skillLevel,charLevel) proficiencyDice = min(skillLevel,charLevel)
@ -334,14 +334,14 @@ class StarWarsRoll():
validCommand = True validCommand = True
else: else:
self.bot.log("Okay, no they don't i guess") self.bot.log("Okay, no they don't i guess")
sendMessage = "You don't have a user. You can make one with /starwarscharacter" send_message = "You don't have a user. You can make one with /starwarscharacter"
elif string.capwords(commands[0]) in ["Ranged","Piloting"]: elif string.capwords(commands[0]) in ["Ranged","Piloting"]:
self.bot.log("They fucked up writing the name of a ranged or piloting skill") self.bot.log("They fucked up writing the name of a ranged or piloting skill")
if string.capwords(commands[0]) == "Ranged": if string.capwords(commands[0]) == "Ranged":
sendMessage = "Did you mean \"Ranged - Heavy\" or \"Ranged - Light\" (error code 913)" send_message = "Did you mean \"Ranged - Heavy\" or \"Ranged - Light\" (error code 913)"
else: else:
sendMessage = "Did you mean \"Piloting - Planetary\" or \"Piloting - Space\" (error code 913)" send_message = "Did you mean \"Piloting - Planetary\" or \"Piloting - Space\" (error code 913)"
else: else:
validCommand = True validCommand = True
@ -372,19 +372,19 @@ class StarWarsRoll():
simplified = self.simplify(rollResults) simplified = self.simplify(rollResults)
name = self.bot.star_wars.character.getCharName(user) name = self.bot.star_wars.character.getChar_name(user)
self.bot.log("Returns results and simplified results") self.bot.log("Returns results and simplified results")
if simplified == "": if simplified == "":
sendMessage = name + " rolls: " + "\n" + self.diceResultToEmoji(diceResults) + "\nEverything cancels out!" send_message = name + " rolls: " + "\n" + self.diceResultToEmoji(diceResults) + "\nEverything cancels out!"
else: else:
sendMessage = name + " rolls: " + "\n" + self.diceResultToEmoji(diceResults) + "\n" + self.resultToEmoji(simplified) send_message = name + " rolls: " + "\n" + self.diceResultToEmoji(diceResults) + "\n" + self.resultToEmoji(simplified)
messageList = sendMessage.split("\n") message_list = send_message.split("\n")
await ctx.send(messageList[0]) await ctx.send(message_list[0])
if len(messageList) > 1: if len(message_list) > 1:
for messageItem in messageList[1:]: for messageItem in message_list[1:]:
if messageItem == "": if messageItem == "":
self.bot.log("Tried to send empty message") self.bot.log("Tried to send empty message")
else: else:

View File

@ -1,4 +1,4 @@
Viser dig de film og serier der er "requested" men ikke endnu på Bedre Netflix. Kommandoen kan tage imod op til 4 parametre: Viser dig de film og serier der er "requested" men ikke endnu på Plex. Kommandoen kan tage imod op til 4 parametre:
`-d`, `--downloading`, `--dm`, `--downloadManager` - Viser de torrents der er _ved_ at downloade. Hvis ingen parametre er givet, bliver det her parameter givet automatisk som det eneste. `-d`, `--downloading`, `--dm`, `--downloadManager` - Viser de torrents der er _ved_ at downloade. Hvis ingen parametre er givet, bliver det her parameter givet automatisk som det eneste.

View File

@ -1 +1 @@
Giver titlen på en tilfældig film fra Bedre Netflix. Giver titlen på en tilfældig film fra Plex.

View File

@ -3,7 +3,7 @@
`/spell` - Slå en besværgelse op. `/spell` - Slå en besværgelse op.
`/monster` - Slå et monster op. `/monster` - Slå et monster op.
`/image` - Finder et tilfældigt billede fra internettet. `/image` - Finder et tilfældigt billede fra internettet.
`/movie` - Giver titlen på en tilfældig film fra Bedre Netflix `/movie` - Giver titlen på en tilfældig film fra Plex
`/name` - Genererer et tilfældigt navn. `/name` - Genererer et tilfældigt navn.
`/tavern` - Genererer en tilfældig tavern. `/tavern` - Genererer en tilfældig tavern.
`/give` - Lader dig give GwendoBucks til andre. `/give` - Lader dig give GwendoBucks til andre.
@ -17,8 +17,8 @@
`/hex` - Lader dig spille et spil Hex. `/hex` - Lader dig spille et spil Hex.
`/hangman` - Lader dig spille et spil hangman. `/hangman` - Lader dig spille et spil hangman.
`/wolf` - Lader dig slå ting op på Wolfram Alpha. `/wolf` - Lader dig slå ting op på Wolfram Alpha.
`/add_movie` - Lader dig tilføje film til Bedre Netflix. `/add_movie` - Lader dig tilføje film til Plex.
`/add_show` - Lader dig tilføje tv shows til Bedre Netflix. `/add_show` - Lader dig tilføje tv shows til Plex.
`/downloading` - Viser dig hvor langt de torrents der er ved at downloade er kommet. `/downloading` - Viser dig hvor langt de torrents der er ved at downloade er kommet.
`/thank` - Lader dig takke Gwendolyn. `/thank` - Lader dig takke Gwendolyn.
Du kan få ekstra information om kommandoerne med "/help [kommando]". Du kan få ekstra information om kommandoerne med "/help [kommando]".

View File

@ -1,21 +0,0 @@
{
"missing parameters" : "Missing command parameters. Try using `!help [command]` to find out how to use the command.",
"Can't log in": "Could not log in. Remember to write your bot token in the credentials.txt file",
"Blackjack all players standing": "All players are standing. The dealer now shows his cards and draws.",
"Blackjack first round": ". You can also double down with \"/blackjack double\" or split with \"/blackjack split\"",
"Blackjack commands": "You have 2 minutes to either hit or stand with \"/blackjack hit\" or \"/blackjack stand\"{}. It's assumed you're standing if you don't make a choice.",
"Blackjack double": "Adding another {} GwendoBucks to {}'s bet and drawing another card.",
"Blackjack different cards": "You can only split if your cards have the same value",
"Blackjack split": "Splitting {}'s hand into 2. Adding their original bet to the second hand. You can use \"/blackjack hit/stand/double 1\" and \"/blackjack hit/stand/double 2\" to play the different hands.",
"Blackjack started": "Blackjack game started. Use \"/blackjack bet [amount]\" to enter the game within the next 30 seconds.",
"Blackjack going on": "There's already a blackjack game going on. Try again in a few minutes.",
"Stock value": "The current {} stock is valued at **{}** GwendoBucks",
"Stock parameters": "You must give both a stock name and an amount of GwendoBucks you wish to spend.",
"Trivia going on": "There's already a trivia question going on. Try again in like, a minute",
"Trivia time up": "Time's up! The answer was \"*{}) {}*\". Anyone who answered that has gotten 1 GwendoBuck",
"Connect 4 going on": "There's already a connect 4 game going on in this channel",
"Connect 4 placed": "{} placed a piece in column {}. It's now {}'s turn",
"Hangman going on": "There's already a Hangman game going on in the channel",
"Hangman lost game": " You've guessed wrong six times and have lost the game.",
"Hangman guessed word": " You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account"
}

View File

@ -17,5 +17,11 @@
"Connect 4 placed": "{} placed a piece in column {}. It's now {}'s turn", "Connect 4 placed": "{} placed a piece in column {}. It's now {}'s turn",
"Hangman going on": "There's already a Hangman game going on in the channel", "Hangman going on": "There's already a Hangman game going on in the channel",
"Hangman lost game": " You've guessed wrong six times and have lost the game.", "Hangman lost game": " You've guessed wrong six times and have lost the game.",
"Hangman guessed word": " You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account" "Hangman guessed word": " You've guessed the word! Congratulations! Adding 15 GwendoBucks to your account",
"Already on Plex": "{} is either already on Plex, downloading, or not available",
"No torrent": "{}No torrent exists. Likely because the movie is not yet released on DVD",
"No torrents downloading": "There are no torrents downloading right. If the torrent you're looking for was added more than 24 hours ago, it might already be on Plex.",
"Update": "{}\nThis message will update every 10 seconds for {} more minutes\n```",
"No updates": "{}\nThis message will not update anymore\n```",
"Invalid parameters": "Invalid or repeated parameters. Use '/help downloading' to see valid parameters."
} }

View File

@ -1,7 +1,7 @@
{ {
"add_movie" : { "add_movie" : {
"name" : "add_movie", "name" : "add_movie",
"description" : "Request a movie for Bedre Netflix", "description" : "Request a movie for Plex",
"options" : [ "options" : [
{ {
"name" : "movie", "name" : "movie",
@ -13,7 +13,7 @@
}, },
"add_show" : { "add_show" : {
"name" : "add_show", "name" : "add_show",
"description" : "Request a show for Bedre Netflix", "description" : "Request a show for Plex",
"options" : [ "options" : [
{ {
"name" : "show", "name" : "show",
@ -147,7 +147,7 @@
}, },
"downloading" : { "downloading" : {
"name" : "downloading", "name" : "downloading",
"description" : "See current downloads for Bedre Netflix", "description" : "See current downloads for Plex",
"options" : [ "options" : [
{ {
"name" : "parameters", "name" : "parameters",
@ -162,7 +162,7 @@
"description" : "Set the 'playing' text for Gwendolyn", "description" : "Set the 'playing' text for Gwendolyn",
"options" : [ "options" : [
{ {
"name" : "gameText", "name" : "game_text",
"description" : "The game to set the 'playing' text to", "description" : "The game to set the 'playing' text to",
"type" : 3, "type" : 3,
"required" : "true" "required" : "true"

View File

@ -65,10 +65,10 @@
"folder" : [ "folder" : [
"gwendolyn/resources/lookup", "gwendolyn/resources/lookup",
"gwendolyn/resources/games/blackjack_tables", "gwendolyn/resources/games/blackjack_tables",
"gwendolyn/resources/games/connect4Boards", "gwendolyn/resources/games/connect_four_boards",
"gwendolyn/resources/games/hex_boards", "gwendolyn/resources/games/hex_boards",
"gwendolyn/resources/games/hangman_boards", "gwendolyn/resources/games/hangman_boards",
"gwendolyn/resources/bedre_netflix", "gwendolyn/resources/plex",
"gwendolyn/resources/games/old_images" "gwendolyn/resources/games/old_images"
] ]
} }

View File

@ -72,7 +72,7 @@ class EventHandler():
channel = message.channel channel = message.channel
reacted_message = f"{user.display_name} reacted to a message" reacted_message = f"{user.display_name} reacted to a message"
self.bot.log(reacted_message, str(channel.id)) self.bot.log(reacted_message, str(channel.id))
plex_data = tests.bedre_netflix_reaction_test(message) plex_data = tests.plex_reaction_test(message)
# plex_data is a list containing 3 elements: whether it was # plex_data is a list containing 3 elements: whether it was
# the add_show/add_movie command message the reaction was to # the add_show/add_movie command message the reaction was to
# (bool), whether it's a movie (bool) (if false, it's a # (bool), whether it's a movie (bool) (if false, it's a
@ -84,10 +84,10 @@ class EventHandler():
if tests.connect_four_reaction_test(*reaction_test_parameters): if tests.connect_four_reaction_test(*reaction_test_parameters):
column = emoji_to_command(reaction.emoji) column = emoji_to_command(reaction.emoji)
params = [message, f"#{user.id}", column-1] params = [message, f"#{user.id}", column-1]
await self.bot.games.connect_four.placePiece(*params) await self.bot.games.connect_four.place_piece(*params)
if plex_data[0]: if plex_data[0]:
plex_functions = self.bot.other.bedre_netflix plex_functions = self.bot.other.plex
if plex_data[1]: if plex_data[1]:
movie_pick = emoji_to_command(reaction.emoji) movie_pick = emoji_to_command(reaction.emoji)
if movie_pick == "none": if movie_pick == "none":

View File

@ -27,7 +27,7 @@ class DatabaseFuncs():
user: discord.User) -> bool user: discord.User) -> bool
hangman_reaction_test(message: discord.Message, hangman_reaction_test(message: discord.Message,
user: discord.User) -> bool user: discord.User) -> bool
bedre_netflix_reaction_test(message: discord.Message, plex_reaction_test(message: discord.Message,
user: discord.User) -> bool, bool, user: discord.User) -> bool, bool,
list list
imdb_commands() imdb_commands()
@ -206,7 +206,7 @@ class DatabaseFuncs():
return game_message return game_message
def bedre_netflix_reaction_test(self, message: discord.Message): def plex_reaction_test(self, message: discord.Message):
""" """
Test if the given message is the response to a plex request. Test if the given message is the response to a plex request.
@ -227,7 +227,7 @@ class DatabaseFuncs():
Gwendolyn presented after the request. Gwendolyn presented after the request.
""" """
channel = message.channel channel = message.channel
old_messages_path = "gwendolyn/resources/bedre_netflix/" old_messages_path = "gwendolyn/resources/plex/"
file_path = old_messages_path + f"old_message{str(channel.id)}" file_path = old_messages_path + f"old_message{str(channel.id)}"
if os.path.isfile(file_path): if os.path.isfile(file_path):
with open(file_path, "r") as file_pointer: with open(file_path, "r") as file_pointer:

View File

@ -16,7 +16,7 @@ Contains utility functions used by parts of the bot.
new_string: str) -> str new_string: str) -> str
emoji_to_command(emoji: str) -> str emoji_to_command(emoji: str) -> str
""" """
import json # Used by longString(), get_params() and make_files() import json # Used by long_strings(), get_params() and make_files()
import logging # Used for logging import logging # Used for logging
import os # Used by make_files() to check if files exist import os # Used by make_files() to check if files exist
import sys # Used to specify printing for logging import sys # Used to specify printing for logging

View File

@ -21,7 +21,7 @@ idna==2.10
IMDbPY==2020.9.25 IMDbPY==2020.9.25
isort==5.8.0 isort==5.8.0
jaraco.context==4.0.0 jaraco.context==4.0.0
lark-parser==0.11.2 lark-parser==0.9.0
lazy-object-proxy==1.6.0 lazy-object-proxy==1.6.0
lxml==4.6.3 lxml==4.6.3
mccabe==0.6.1 mccabe==0.6.1