Correcting data storage and creating global variables for data and config. Post and register commands tested for theory.

This commit is contained in:
alwayscompiling
2022-06-26 16:20:05 -04:00
parent 3afa052a2b
commit 7152fe6d2c
5 changed files with 104 additions and 38 deletions
+4 -1
View File
@@ -128,4 +128,7 @@ dmypy.json
.vscode/
# logging
nextcord.log
nextcord.log
# data file for bot
highscores_data.json
+43
View File
@@ -0,0 +1,43 @@
"""
Bot command to post the highscores
"""
from nextcord.ext import commands
import highscores # pylint: disable=import-error
class PostHighscores(commands.Cog, name="Post Highscores"):
"""Actions of bot command"""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name="post-scores")
async def post_highscores(self, ctx: commands.Context):
"""A command which posts the highscore in the designated channel. Sends warning if no channel has been registered.
Usage:
```
?post-scores
```
"""
# temporarily sending config data...
channel_id = highscores.highscores_data["channel_id"]
if (channel_id != -1):
print(
f"Printing out highscores information in channel {channel_id}")
channel = self.bot.get_channel(channel_id)
for boss in highscores.highscores_config["bosses"]:
print(boss)
boss_name = boss["boss"]
highscore_string = f"**{boss_name}**"
await channel.send(highscore_string)
else:
response = "Highscores channel is not registered. Register with \"?register\" command."
await ctx.send(response)
# This function will be called when this extension is loaded.
# It is necessary to add these functions to the bot.
def setup(bot: commands.Bot):
"""Adds functon to bot"""
bot.add_cog(PostHighscores(bot))
+7 -3
View File
@@ -4,28 +4,32 @@ Bot command to register the highscores channel
from nextcord.ext import commands
import highscores # pylint: disable=import-error
from utils import data_storage # pylint: disable=import-error
class RegisterHighscoreChannel(commands.Cog, name="Register HighScore Channel"):
"""Actions of bot command"""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name="register")
async def ping(self, ctx: commands.Context):
async def register_highscores(self, ctx: commands.Context):
"""A command which registers the channel command is sent in as channel to post highscores in
Usage:
```
?register (in channel to post highscores in)
```
"""
# log in console that a ping was received
print(f"Registering {ctx.channel.id}.")
print(highscores.open_highscores_data())
# respond to the message
await ctx.send(f"Registered <#{ctx.channel.id}> as channel to post highscores in.")
highscores.highscores_data["channel_id"] = ctx.channel.id
data_storage.save_highscores_data(highscores.highscores_data)
# This function will be called when this extension is loaded.
# It is necessary to add these functions to the bot.
def setup(bot: commands.Bot):
"""Adds functon to bot"""
bot.add_cog(RegisterHighscoreChannel(bot))
+7 -34
View File
@@ -2,14 +2,15 @@
main file for pvm-highscores bot
"""
import os
import logging
import json
import logging
import os
import nextcord
from nextcord.ext import commands
import config
from utils import data_storage
logger = logging.getLogger('nextcord')
logger.setLevel(logging.DEBUG)
@@ -19,8 +20,9 @@ handler.setFormatter(logging.Formatter(
'%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)
highscores_config_file = "highscores_config.json"
highscores_data_file = "highscores_data.json"
highscores_config = data_storage.open_highscores_config()
highscores_data = data_storage.open_highscores_data()
def main():
@@ -63,34 +65,5 @@ def main():
bot.run(config.DISCORD_TOKEN)
def open_highscores_data():
"""Opens a highscores_data.json file if one exists, otherwise creates a skeleton of the data."""
if (os.path.exists(highscores_data_file)):
with open(highscores_data_file, encoding='utf-8', mode="r") as file:
data = json.load(file)
else:
# create the json object
x = {
"channel_id": 0
}
data = json.dumps(x)
return data
def open_highscores_config():
"""Opens the highscores config file as a json object and returns."""
# Load bot config
with open(highscores_config_file, encoding='utf-8', mode='r') as file:
highscores_config = json.load(file)
return highscores_config
def save_highscores_data(data):
"""Saves the highscores data into a json file."""
with open(highscores_data_file, encoding='utf-8', mode='w') as file:
file.write(json.dumps(data, indent=4))
if __name__ == "__main__":
main()
+43
View File
@@ -0,0 +1,43 @@
"""
Contains functions for saving and loading highscore data and configs.
"""
import json
import os
HIGHSCORES_CONFIG_FILE = "highscores_config.json"
HIGHSCORES_DATA_FILE = "highscores_data.json"
def open_highscores_data():
"""
Opens a highscores_data.json file if one exists, otherwise creates a skeleton of the data.
@return: dict of highscores data.
"""
if (os.path.exists(HIGHSCORES_DATA_FILE)):
with open(HIGHSCORES_DATA_FILE, encoding='utf-8', mode="r") as file:
data = json.load(file)
else:
# create the json object
data = {}
return data
def open_highscores_config():
"""
Opens the highscores config file and returns.
@return: dict of highscores config.
"""
# Load bot config
with open(HIGHSCORES_CONFIG_FILE, encoding='utf-8', mode='r') as file:
return json.load(file)
def save_highscores_data(data):
"""
Saves the highscores data dict into a json file.
@param: dict of highscores data.
"""
with open(HIGHSCORES_DATA_FILE, encoding='utf-8', mode='w') as file:
file.write(json.dumps(data, indent=4))