📝 Cogs and utils

Improved code style and added comments and docstrings to cogs and utils.
This commit is contained in:
NikolajDanger
2021-04-15 15:16:56 +02:00
parent 35b2446a10
commit 43f26ec383
11 changed files with 725 additions and 255 deletions

View File

@ -1,3 +1,18 @@
"""
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
import logging
import os
@ -5,22 +20,55 @@ import sys
import imdb
from .helperClasses import Options
# 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")
logging.basicConfig(format=FORMAT, datefmt=DATEFORMAT, level=logging.INFO, filename="gwendolyn.log")
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))
handler.setFormatter(logging.Formatter(fmt=PRINTFORMAT, datefmt=DATEFORMAT))
printer.addHandler(handler)
printer.propagate = False
imdb._logging.setLevel("CRITICAL")
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)
@ -32,8 +80,25 @@ def getParams():
return params
def logThis(messages, channel : str = "", level : int = 20):
channel = channel.replace("Direct Message with ","")
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]
@ -41,9 +106,11 @@ def logThis(messages, channel : str = "", level : int = 20):
for x, msg in enumerate(messages):
if channel != "":
messages[x] = f"{msg} - ({channel})"
messages[x] = f"{msg} - ({channel})" # Adds channel to log
# messages
if len(messages) > 1:
if len(messages) > 1: # Tells user to check the log if there are
# more messages there
printMessage += " (details in log)"
if level >= 25:
@ -52,10 +119,24 @@ def logThis(messages, channel : str = "", level : int = 20):
for logMessage in messages:
logger.log(level, logMessage)
# Capitalizes all words except some of them
def cap(s):
no_caps_list = ["of","the"]
# Capitalizes a strink like a movie title
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 = ''
@ -67,22 +148,25 @@ def cap(s):
res = res[:-1]
return res
def makeFiles():
def makeJsonFile(path,content):
# Creates 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):
# Creates txt file if it doesn't exist
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:
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")
@ -91,26 +175,57 @@ def makeFiles():
data = json.load(f)
for path, content in data["json"].items():
makeJsonFile(path,content)
makeJsonFile(path, content)
for path, content in data["txt"].items():
makeTxtFile(path,content)
makeTxtFile(path, content)
for path in data["folder"]:
directory(path)
# Replaces multiple things with the same thing
def replaceMultiple(mainString, toBeReplaces, newString):
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 toBeReplaces :
for elem in toBeReplaced:
# Check if string is in the main string
if elem in mainString :
if elem in mainString:
# Replace the string
mainString = mainString.replace(elem, newString)
return mainString
def emojiToCommand(emoji):
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":
@ -131,4 +246,5 @@ def emojiToCommand(emoji):
return "none"
elif emoji == "✔️":
return 1
else: return ""
else:
return ""