generated from InValidFire/discord-bot-template
50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
|
import json
|
||
|
from pathlib import Path
|
||
|
from typing import Tuple
|
||
|
import logging
|
||
|
import discord
|
||
|
import random
|
||
|
|
||
|
logger = logging.getLogger(__name__)
|
||
|
|
||
|
|
||
|
def load_config(conf_file) -> Tuple[dict, Path]:
|
||
|
"""Load data from a config file.\n
|
||
|
Returns a tuple containing the data as a dict, and the file as a Path"""
|
||
|
config_file = Path(conf_file)
|
||
|
config_file.touch(exist_ok=True)
|
||
|
if config_file.read_text() == "":
|
||
|
config_file.write_text("{}")
|
||
|
logger.debug("config file created.")
|
||
|
with config_file.open("r") as f:
|
||
|
config = json.load(f)
|
||
|
logger.debug("config file loaded.")
|
||
|
return config, config_file
|
||
|
|
||
|
|
||
|
def prompt_config(conf_file, msg, key):
|
||
|
"""Ensure a value exists in the config file, if it doesn't prompt the bot owner to input via the console."""
|
||
|
logger.debug(f"checking if {key} is in config.")
|
||
|
config, config_file = load_config(conf_file)
|
||
|
if key not in config:
|
||
|
logger.debug(f"{key} not found in config file.")
|
||
|
config[key] = input(msg)
|
||
|
with config_file.open("w+") as f:
|
||
|
json.dump(config, f, indent=4)
|
||
|
logger.debug(f"'{config[key]}' saved to config file under '{key}'.")
|
||
|
|
||
|
|
||
|
def update_config(conf_file, key, value):
|
||
|
logger.debug(f"updating config file '{conf_file}' key '{key}' to '{value}'")
|
||
|
config, config_file = load_config(conf_file)
|
||
|
config[key] = value
|
||
|
with config_file.open("w+") as f:
|
||
|
json.dump(config, f, indent=4)
|
||
|
logger.debug(f"config file '{conf_file}' key '{key}' has been updated to '{value}'")
|
||
|
|
||
|
|
||
|
def random_rgb(seed=None):
|
||
|
if seed is not None:
|
||
|
random.seed(seed)
|
||
|
return discord.Colour.from_rgb(random.randrange(0, 255), random.randrange(0, 255), random.randrange(0, 255))
|