reworking a bunch of stuff 2.0

This commit is contained in:
Nikolaj
2024-10-28 14:38:41 +01:00
parent bc59bf9b05
commit eb2960aa10
9 changed files with 21 additions and 269 deletions

4
.gitignore vendored
View File

@ -150,9 +150,7 @@ static
.vscode/ .vscode/
token.txt .env
credentials.txt
options.txt
gwendolyn/resources/star_wars/destinyPoints.txt gwendolyn/resources/star_wars/destinyPoints.txt
gwendolyn/resources/plex/ gwendolyn/resources/plex/
gwendolyn/resources/games/hilo/ gwendolyn/resources/games/hilo/

View File

@ -1,11 +1,12 @@
from interactions import Client, Status from interactions import Client, Status
from gwendolyn.utils import get_options, get_credentials, long_strings, log from gwendolyn.utils import log
from dotenv import load_dotenv
from os import getenv
from pymongo import MongoClient # Used for database management from pymongo import MongoClient # Used for database management
class Gwendolyn(Client): class Gwendolyn(Client):
def __init__(self, testing: bool = True):
def __init__(self):
"""Initialize the bot.""" """Initialize the bot."""
initiation_parameters = { initiation_parameters = {
"status": Status.DND, "status": Status.DND,
@ -13,6 +14,8 @@ class Gwendolyn(Client):
} }
super().__init__(**initiation_parameters) super().__init__(**initiation_parameters)
self.testing = testing
self._add_clients_and_options() self._add_clients_and_options()
# self._add_util_classes() # self._add_util_classes()
# self._add_function_containers() # self._add_function_containers()
@ -20,16 +23,16 @@ class Gwendolyn(Client):
def _add_clients_and_options(self): def _add_clients_and_options(self):
"""Add all the client, option and credentials objects.""" """Add all the client, option and credentials objects."""
self.long_strings = long_strings() load_dotenv()
self.options = get_options() self.bot_token = getenv("DISCORD_TOKEN")
self.credentials = get_credentials()
mongo_user = self.credentials["mongo_db_user"] mongo_user = getenv("MONGODB_USER")
mongo_password = self.credentials["mongo_db_password"] mongo_password = getenv("MONGODB_PASSWORD")
mongo_url = f"mongodb+srv://{mongo_user}:{mongo_password}@gwendolyn" mongo_url = f"mongodb+srv://{mongo_user}:{mongo_password}@gwendolyn"
mongo_url += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority" mongo_url += ".qkwfy.mongodb.net/Gwendolyn?retryWrites=true&w=majority"
database_client = MongoClient(mongo_url) database_client = MongoClient(mongo_url)
if self.options["testing"]: if self.testing:
self.log("Testing mode") self.log("Testing mode")
self.database = database_client["Gwendolyn-Test"] self.database = database_client["Gwendolyn-Test"]
else: else:
@ -37,4 +40,7 @@ class Gwendolyn(Client):
def log(self, messages, channel: str = "", level: int = 20): # pylint:disable=no-self-use def log(self, messages, channel: str = "", level: int = 20): # pylint:disable=no-self-use
"""Log a message. Described in utils/util_functions.py.""" """Log a message. Described in utils/util_functions.py."""
log(messages, channel, level) log(messages, channel, level)
def start(self):
super().start(self.bot_token)

View File

@ -1,27 +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 the buttons or \"/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",
"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,36 +0,0 @@
{
"Astrogation" : "Intellect",
"Computers" : "Intellect",
"Cool" : "Presence",
"Vigilance" : "Willpower",
"Mechanics" : "Intellect",
"Melee" : "Brawn",
"Perception" : "Cunning",
"Piloting-space" : "Agility",
"Ranged-heavy" : "Agility",
"Ranged-light" : "Agility",
"Athletics" : "Brawn",
"Coercion" : "Willpower",
"Coordination" : "Agility",
"Charm" : "Presence",
"Medicine" : "Intellect",
"Negotiation" : "Presence",
"Piloting-planetary" : "Agility",
"Stealth" : "Agility",
"skulduggery" : "Cunning",
"Brawl" : "Brawn",
"Discipline" : "Willpower",
"Gunnery" : "Agility",
"Core-worlds" : "Intellect",
"Outer-rim" : "Intellect",
"Underworld" : "Intellect",
"Leadership" : "Presence",
"Lore" : "Intellect",
"Resilience" : "Brawn",
"Streetwise" : "Cunning",
"Survival" : "Cunning",
"Xenology" : "Intellect",
"Lightsaber" : "Brawn",
"Education" : "Intellect",
"Deception" : "Cunning"
}

View File

@ -1,82 +0,0 @@
{
"Character": {
"Name": "New Character",
"Species": "",
"Career": "",
"Specialization-trees": [],
"Soak": 0,
"Wound-threshold": 0,
"Wounds": 0,
"Strain-threshold": 0,
"Strain": 0,
"Defense-ranged": 0,
"Defense-melee": 0,
"Force-rating": 0,
"Characteristics": {
"Brawn": 2,
"Agility": 2,
"Intellect": 2,
"Cunning": 2,
"Willpower": 2,
"Presence": 2
},
"Skills": {
"Astrogation": 0,
"Athletics": 0,
"Brawl": 0,
"Charm": 0,
"Coercion": 0,
"Computers": 0,
"Cool": 0,
"Coordination": 0,
"Core-worlds": 0,
"Discipline": 0,
"Deception": 0,
"Education": 0,
"Gunnery": 0,
"Leadership": 0,
"Lightsaber": 0,
"Lore": 0,
"Mechanics": 0,
"Medicine": 0,
"Melee": 0,
"Negotiation": 0,
"Outer-rim": 0,
"Perception": 0,
"Piloting-planetary": 0,
"Piloting-space": 0,
"Ranged-heavy": 0,
"Ranged-light": 0,
"Resilience": 0,
"skulduggery": 0,
"Stealth": 0,
"Streetwise": 0,
"Survival": 0,
"Underworld": 0,
"Vigilance": 0,
"Xenology": 0
},
"Lightsaber-characteristic": "Brawn",
"Obligations": {},
"Morality": {
"Weakness": "",
"Strength": "",
"Conflict": "",
"Morality": ""
},
"Credits": 0,
"Equipment": [],
"Armor": "",
"Critical-injuries": {},
"Weapons": {},
"Talents": {},
"Force-powers": {}
},
"Weapon": {
"Skill" : "",
"Damage" : 0,
"Range" : "",
"Crit" : 0,
"Special" : []
}
}

View File

@ -56,11 +56,8 @@
] ]
}, },
"txt": { "txt": {
"gwendolyn/resources/star_wars/destinyPoints.txt": "",
"gwendolyn/resources/movies.txt": "The Room",
"gwendolyn/resources/names.txt": "Gandalf\n", "gwendolyn/resources/names.txt": "Gandalf\n",
"credentials.txt" : "Bot token: TOKEN\nWordnik API Key: KEY\nMongoDB user: USERNAME\nMongoDB password: PASSWORD\nWolframAlpha AppID: APPID\nRadarr API key: KEY\nSonarr API key: KEY\nqBittorrent username: USER\nqBittorrent password: PASSWORD", ".env" : "# Discord Bot Token\nDISCORD_TOKEN=TOKEN\n\n# Wordnik API Key\nWORDNIK_API_KEY=KEY\n\n# MongoDB Credentials\nMONGODB_USER=USERNAME\nMONGODB_PASSWORD=PASSWORD\n\n# WolframAlpha AppID\nWOLFRAM_APPID=APPID\n\n# Radarr API Key\nRADARR_API_KEY=KEY\n\n# Sonarr API Key\nSONARR_API_KEY=KEY\n\n# qBittorrent Credentials\nQBITTORRENT_USERNAME=USER\nQBITTORRENT_PASSWORD=PASSWORD\n\n# Admins (comma-separated list of Discord user IDs)\nADMINS="
"options.txt" : "Testing: True\nTesting guild ids:\nAdmins:"
}, },
"folder" : [ "folder" : [
"gwendolyn/resources/lookup", "gwendolyn/resources/lookup",
@ -68,7 +65,6 @@
"gwendolyn/resources/games/connect_four_boards", "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/plex",
"gwendolyn/resources/games/old_images" "gwendolyn/resources/games/old_images"
] ]
} }

View File

@ -1,5 +1,5 @@
"""A collections of utilities used by Gwendolyn and her functions.""" """A collections of utilities used by Gwendolyn and her functions."""
__all__ = ["make_files","get_options", "get_credentials", "long_strings", "log"] __all__ = ["make_files","log"]
from .util_functions import make_files, get_options, get_credentials, long_strings, log from .util_functions import make_files, log

View File

@ -23,109 +23,6 @@ handler.setFormatter(logging.Formatter(fmt=PRINTFORMAT, datefmt=DATEFORMAT))
printer.addHandler(handler) printer.addHandler(handler)
printer.propagate = False printer.propagate = False
def sanitize(data: str, lower_case_value: bool = False):
"""
Sanitize and create a dictionary from a string.
Each element is created from a line with a : in it. The key is left
of the :, the value is right of it.
*Parameters*
------------
data: str
The string to create a dict from.
lower_case_value: bool = False
Whether the value of each element should be lowercase.
*Returns*
---------
dct: dict
The sanitized dictionary of elements.
"""
data = data.splitlines()
dct = {}
for line in data:
if line[0] != "#" and ":" in line:
line_values = line.split(":")
line_values[0] = line_values[0].lower()
line_values[1] = line_values[1].replace(" ", "")
if lower_case_value:
line_values[1] = line_values[1].lower()
if line_values[0] in ["testing guild ids", "admins"]:
line_values[1] = line_values[1].split(",")
if all(i.isnumeric() for i in line_values[1]):
line_values[1] = [int(i) for i in line_values[1]]
if any(i == line_values[1] for i in ["true", "false"]):
line_values[1] = (line_values[1] == "true")
dct[line_values[0]] = line_values[1]
return dct
def get_options():
"""
Get the bot options as dict.
*Returns*
---------
options: dict
The options of the bot.
"""
with open("options.txt", "r", encoding="utf-8") as file_pointer:
data = sanitize(file_pointer.read(), True)
options = {}
options["testing"] = data["testing"]
options["guild_ids"] = data["testing guild ids"]
options["admins"] = data["admins"]
return options
def get_credentials():
"""
Returns the credentials used by the bot as a dict.
*Returns*
---------
credentials: dict
The credentials used by the bot.
"""
with open("credentials.txt", "r", encoding="utf-8") as file_pointer:
data = sanitize(file_pointer.read())
credentials = {}
credentials["token"] = data["bot token"]
credentials["wordnik_key"] = data["wordnik api key"]
credentials["mongo_db_user"] = data["mongodb user"]
credentials["mongo_db_password"] = data["mongodb password"]
credentials["wolfram_alpha_key"] = data["wolframalpha appid"]
credentials["radarr_key"] = data["radarr api key"]
credentials["sonarr_key"] = data["sonarr api key"]
credentials["qbittorrent_username"] = data["qbittorrent username"]
credentials["qbittorrent_password"] = data["qbittorrent password"]
return credentials
def long_strings():
"""
Get the data from gwendolyn/resources/long_strings.json.
*Returns*
---------
data: dict
The long strings and their keys.
"""
long_strings_path = "gwendolyn/resources/long_strings.json"
with open(long_strings_path, "r", encoding="utf-8") as file_pointer:
data = json.load(file_pointer)
return data
def log(messages, channel: str = "", level: int = 20): def log(messages, channel: str = "", level: int = 20):
""" """
Log something in Gwendolyn's logs. Log something in Gwendolyn's logs.

View File

@ -11,7 +11,7 @@ def main():
# Creates the Bot # Creates the Bot
bot = Gwendolyn() bot = Gwendolyn()
bot.load_extension("gwendolyn.ext.misc") bot.load_extension("gwendolyn.ext.misc")
bot.start("NzM4NzYwODkyNjczNTU2NTYy.GPjy55.xbYtH20UtCjOl87C-2DEPx2BwFWh2-xn1-9YnE") bot.start()
if __name__ == "__main__": if __name__ == "__main__":
main() main()