✨ reworking a bunch of stuff
This commit is contained in:
@ -1,37 +1,7 @@
|
||||
"""
|
||||
Contains utility functions used by parts of the bot.
|
||||
|
||||
*Functions*
|
||||
-----------
|
||||
sanitize(data: str, lower_case_value: bool = false) -> dict
|
||||
get_options() -> dict
|
||||
get_credentials() -> dict
|
||||
long_strings() -> dict
|
||||
get_params() -> dict
|
||||
log_this(messages: Union[str, list], channel: str = "",
|
||||
level: int = 20)
|
||||
cap(s: str) -> str
|
||||
make_files()
|
||||
replace_multiple(main_string: str, to_be_replaced: list,
|
||||
new_string: str) -> str
|
||||
emoji_to_command(emoji: str) -> str
|
||||
"""
|
||||
import string
|
||||
import json # Used by long_strings(), get_params() and make_files()
|
||||
import logging # Used for logging
|
||||
import os # Used by make_files() to check if files exist
|
||||
import sys # Used to specify printing for logging
|
||||
import imdb # Used to disable logging for the module
|
||||
|
||||
|
||||
BASE_37 = ":" + string.digits + string.ascii_uppercase
|
||||
BASE_128 = list(
|
||||
string.digits +
|
||||
string.ascii_letters +
|
||||
"!#$€£¢¥¤&%()*+,-./;:<=>?@[]_{|}~ `¦§©®«»±µ·¿əʒ" +
|
||||
"ÆØÅÐÉÈÊÇÑÖ" +
|
||||
"æøåðéèêçñö"
|
||||
)
|
||||
|
||||
# All of this is logging configuration
|
||||
FORMAT = " %(asctime)s | %(name)-16s | %(levelname)-8s | %(message)s"
|
||||
@ -53,10 +23,6 @@ handler.setFormatter(logging.Formatter(fmt=PRINTFORMAT, datefmt=DATEFORMAT))
|
||||
printer.addHandler(handler)
|
||||
printer.propagate = False
|
||||
|
||||
imdb._logging.setLevel("CRITICAL") # pylint: disable=protected-access
|
||||
# Basically disables imdbpy logging, since it's being printed to the
|
||||
# terminal.
|
||||
|
||||
def sanitize(data: str, lower_case_value: bool = False):
|
||||
"""
|
||||
Sanitize and create a dictionary from a string.
|
||||
@ -134,7 +100,6 @@ def get_credentials():
|
||||
credentials = {}
|
||||
|
||||
credentials["token"] = data["bot token"]
|
||||
credentials["finnhub_key"] = data["finnhub api key"]
|
||||
credentials["wordnik_key"] = data["wordnik api key"]
|
||||
credentials["mongo_db_user"] = data["mongodb user"]
|
||||
credentials["mongo_db_password"] = data["mongodb password"]
|
||||
@ -161,30 +126,7 @@ def long_strings():
|
||||
|
||||
return data
|
||||
|
||||
|
||||
def get_params():
|
||||
"""
|
||||
Get the slash command parameters.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
params: dict
|
||||
The parameters for every slash command.
|
||||
"""
|
||||
path = "gwendolyn/resources/slash_parameters.json"
|
||||
with open(path, "r", encoding="utf-8") as file_pointer:
|
||||
slash_parameters = json.load(file_pointer)
|
||||
|
||||
options = get_options()
|
||||
|
||||
if options["testing"]:
|
||||
for parameter in slash_parameters:
|
||||
slash_parameters[parameter]["guild_ids"] = options["guild_ids"]
|
||||
|
||||
return slash_parameters
|
||||
|
||||
|
||||
def log_this(messages, channel: str = "", level: int = 20):
|
||||
def log(messages, channel: str = "", level: int = 20):
|
||||
"""
|
||||
Log something in Gwendolyn's logs.
|
||||
|
||||
@ -222,49 +164,19 @@ def log_this(messages, channel: str = "", level: int = 20):
|
||||
for log_message in messages:
|
||||
logger.log(level, log_message)
|
||||
|
||||
|
||||
def cap(input_string: str):
|
||||
"""
|
||||
Capitalize a string like a movie title.
|
||||
|
||||
That means "of" and "the" are not capitalized.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
input_string: str
|
||||
The string to capitalized.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
return_string: str
|
||||
The capitalized string.
|
||||
"""
|
||||
no_caps_list = ["of", "the"]
|
||||
word_number = 0
|
||||
string_list = input_string.split()
|
||||
return_string = ''
|
||||
for word in string_list:
|
||||
word_number += 1
|
||||
if word not in no_caps_list or word_number == 1:
|
||||
word = word.capitalize()
|
||||
return_string += word+" "
|
||||
return_string = return_string[:-1]
|
||||
return return_string
|
||||
|
||||
|
||||
def make_files():
|
||||
"""Create all the files and directories needed by Gwendolyn."""
|
||||
def make_json_file(path, content):
|
||||
"""Create json file if it doesn't exist."""
|
||||
if not os.path.isfile(path):
|
||||
log_this(path.split("/")[-1]+" didn't exist. Making it now.")
|
||||
log(path.split("/")[-1]+" didn't exist. Making it now.")
|
||||
with open(path, "w", encoding="utf-8") as file_pointer:
|
||||
json.dump(content, file_pointer, indent=4)
|
||||
|
||||
def make_txt_file(path, content):
|
||||
"""Create txt file if it doesn't exist."""
|
||||
if not os.path.isfile(path):
|
||||
log_this(path.split("/")[-1]+" didn't exist. Making it now.")
|
||||
log(path.split("/")[-1]+" didn't exist. Making it now.")
|
||||
with open(path, "w", encoding="utf-8") as file_pointer:
|
||||
file_pointer.write(content)
|
||||
|
||||
@ -272,121 +184,18 @@ def make_files():
|
||||
"""Create directory if it doesn't exist."""
|
||||
if not os.path.isdir(path):
|
||||
os.makedirs(path)
|
||||
log_this("The "+path.split("/")[-1]+" directory didn't exist")
|
||||
log("The "+path.split("/")[-1]+" directory didn't exist")
|
||||
|
||||
file_path = "gwendolyn/resources/starting_files.json"
|
||||
with open(file_path, "r", encoding="utf-8") as file_pointer:
|
||||
data = json.load(file_pointer)
|
||||
|
||||
for path in data["folder"]:
|
||||
directory(path)
|
||||
|
||||
for path, content in data["json"].items():
|
||||
make_json_file(path, content)
|
||||
|
||||
for path, content in data["txt"].items():
|
||||
make_txt_file(path, content)
|
||||
|
||||
for path in data["folder"]:
|
||||
directory(path)
|
||||
|
||||
|
||||
def replace_multiple(main_string: str, to_be_replaced: list, new_string: str):
|
||||
"""
|
||||
Replace multiple substrings in a string with the same substring.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
main_string: str
|
||||
The string to replace substrings in.
|
||||
to_be_replaced: list
|
||||
The substrings to replace.
|
||||
new_string: str
|
||||
The string to replace the substrings with.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
main_string: str
|
||||
The string with the substrings replaced.
|
||||
"""
|
||||
# Iterate over the strings to be replaced
|
||||
for elem in to_be_replaced:
|
||||
# Check if string is in the main string
|
||||
if elem in main_string:
|
||||
# Replace the string
|
||||
main_string = main_string.replace(elem, new_string)
|
||||
|
||||
return main_string
|
||||
|
||||
|
||||
def emoji_to_command(emoji: str):
|
||||
"""
|
||||
Convert emoji to text.
|
||||
|
||||
*Parameters*
|
||||
------------
|
||||
emoji: str
|
||||
The emoji to decipher.
|
||||
|
||||
*Returns*
|
||||
---------
|
||||
: str
|
||||
The deciphered string.
|
||||
"""
|
||||
if emoji == "1️⃣":
|
||||
return_value = 1
|
||||
elif emoji == "2️⃣":
|
||||
return_value = 2
|
||||
elif emoji == "3️⃣":
|
||||
return_value = 3
|
||||
elif emoji == "4️⃣":
|
||||
return_value = 4
|
||||
elif emoji == "5️⃣":
|
||||
return_value = 5
|
||||
elif emoji == "6️⃣":
|
||||
return_value = 6
|
||||
elif emoji == "7️⃣":
|
||||
return_value = 7
|
||||
elif emoji == "🎲":
|
||||
return_value = "roll"
|
||||
elif emoji == "❌":
|
||||
return_value = "none"
|
||||
elif emoji == "✔️":
|
||||
return_value = 1
|
||||
else:
|
||||
return_value = ""
|
||||
|
||||
return return_value
|
||||
|
||||
def encode_id(info: list):
|
||||
letters = list(":".join(info))
|
||||
dec = 0
|
||||
for i, letter in enumerate(letters):
|
||||
try:
|
||||
dec += (37**i) * BASE_37.index(letter.upper())
|
||||
except ValueError:
|
||||
log_this(f"Could not encode letter {letter}", level=30)
|
||||
|
||||
custom_id = []
|
||||
|
||||
while dec:
|
||||
custom_id.append(BASE_128[dec % 128])
|
||||
dec = dec // 128
|
||||
|
||||
custom_id = ''.join(custom_id)
|
||||
log_this(f"Encoded {info} to {custom_id}")
|
||||
return custom_id
|
||||
|
||||
|
||||
def decode_id(custom_id: str):
|
||||
letters = list(custom_id)
|
||||
dec = 0
|
||||
for i, letter in enumerate(letters):
|
||||
dec += (128**i) * BASE_128.index(letter)
|
||||
|
||||
info_string = []
|
||||
|
||||
while dec:
|
||||
info_string.append(BASE_37[dec % 37])
|
||||
dec = dec // 37
|
||||
|
||||
info = ''.join(info_string).split(':')
|
||||
log_this(f"Decoded {custom_id} to be {info}")
|
||||
return ''.join(info_string).split(':')
|
||||
|
Reference in New Issue
Block a user