""" Contains utility functions used by parts of the bot. *Functions* ----------- longstrings() -> dict getParams() -> dict logThis(messages: Union[str, list], channel: str = "", level: int = 20) cap(s: str) -> str makeFiles() replaceMultiple(mainString: str, toBeReplaced: list, newString: str) -> str emojiToCommand(emoji: str) -> str """ import json # Used by longString(), getParams() and makeFiles() import logging # Used for logging import os # Used by makeFiles() to check if files exist import sys # Used to specify printing for logging import imdb # Used to disable logging for the module from .helperClasses import Options # Used by getParams() # All of this is logging configuration FORMAT = " %(asctime)s | %(name)-16s | %(levelname)-8s | %(message)s" PRINTFORMAT = "%(asctime)s - %(message)s" DATEFORMAT = "%Y-%m-%d %H:%M:%S" logging.addLevelName(25, "PRINT") loggingConfigParams = { "format": FORMAT, "datefmt": DATEFORMAT, "level": logging.INFO, "filename": "gwendolyn.log" } logging.basicConfig(**loggingConfigParams) logger = logging.getLogger("Gwendolyn") printer = logging.getLogger("printer") handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter(fmt=PRINTFORMAT, datefmt=DATEFORMAT)) printer.addHandler(handler) printer.propagate = False imdb._logging.setLevel("CRITICAL") # Basically disables imdbpy # logging, since it's printed to the terminal. def longStrings(): """ Get the data from resources/longStrings.json. *Returns* --------- data: dict The long strings and their keys. """ with open("resources/longStrings.json", "r") as f: data = json.load(f) return data def getParams(): """ Get the slash command parameters. *Returns* --------- params: dict The parameters for every slash command. """ with open("resources/slashParameters.json", "r") as f: params = json.load(f) options = Options() if options.testing: for p in params: params[p]["guild_ids"] = options.guildIds return params def logThis(messages, channel: str = "", level: int = 20): """ Log something in Gwendolyn's logs. *Parameters* ------------ messages: Union[str, list] A string or list of strings to be logged. If there are multiple strings and the level is PRINT (25) or higher, only the first string will be printed. channel: str = "" The channel the event to be logged occurred in. Will be logged along with the message(s). level: int = 20 The level to log the message(s) at. If PRINT (25) or higher, the first message will be printed to the console. """ channel = channel.replace("Direct Message with ", "") if type(messages) is str: messages = [messages] printMessage = messages[0] for x, msg in enumerate(messages): if channel != "": messages[x] = f"{msg} - ({channel})" # Adds channel to log # messages if len(messages) > 1: # Tells user to check the log if there are # more messages there printMessage += " (details in log)" if level >= 25: printer.log(level, printMessage) for logMessage in messages: logger.log(level, logMessage) def cap(s: str): """ Capitalize a string like a movie title. That means "of" and "the" are not capitalized. *Parameters* ------------ s: str The string to capitalized. *Returns* --------- res: str The capitalized string. """ no_caps_list = ["of", "the"] word_number = 0 lst = s.split() res = '' for word in lst: word_number += 1 if word not in no_caps_list or word_number == 1: word = word.capitalize() res += word+" " res = res[:-1] return res def makeFiles(): """Create all the files and directories needed by Gwendolyn.""" def makeJsonFile(path, content): """Create json file if it doesn't exist.""" if not os.path.isfile(path): logThis(path.split("/")[-1]+" didn't exist. Making it now.") with open(path, "w") as f: json.dump(content, f, indent=4) def makeTxtFile(path, content): """Create txt file if it doesn't exist.""" if not os.path.isfile(path): logThis(path.split("/")[-1]+" didn't exist. Making it now.") with open(path, "w") as f: f.write(content) def directory(path): """Create directory if it doesn't exist.""" if not os.path.isdir(path): os.makedirs(path) logThis("The "+path.split("/")[-1]+" directory didn't exist") with open("resources/startingFiles.json") as f: data = json.load(f) for path, content in data["json"].items(): makeJsonFile(path, content) for path, content in data["txt"].items(): makeTxtFile(path, content) for path in data["folder"]: directory(path) def replaceMultiple(mainString: str, toBeReplaced: list, newString: str): """ Replace multiple substrings in a string with the same substring. *Parameters* ------------ mainString: str The string to replace substrings in. toBeReplaced: list The substrings to replace. newString: str The string to replace the substrings with. *Returns* --------- mainString: str The string with the substrings replaced. """ # Iterate over the strings to be replaced for elem in toBeReplaced: # Check if string is in the main string if elem in mainString: # Replace the string mainString = mainString.replace(elem, newString) return mainString def emojiToCommand(emoji: str): """ Convert emoji to text. *Parameters* ------------ emoji: str The emoji to decipher. *Returns* --------- : str The deciphered string. """ if emoji == "1️⃣": return 1 elif emoji == "2️⃣": return 2 elif emoji == "3️⃣": return 3 elif emoji == "4️⃣": return 4 elif emoji == "5️⃣": return 5 elif emoji == "6️⃣": return 6 elif emoji == "7️⃣": return 7 elif emoji == "🎲": return "roll" elif emoji == "❌": return "none" elif emoji == "✔️": return 1 else: return ""