Compare commits
14
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a20c1f50a | ||
|
|
a8aad570d3 | ||
|
|
02ba90134e | ||
|
|
0834634cde | ||
|
|
445c77b012 | ||
|
|
b3af09f1c6 | ||
|
|
dc0fd694d3 | ||
|
|
6d41baef98 | ||
|
|
f29e459b2e | ||
|
|
35aa1f34f4 | ||
|
|
c046fa2c45 | ||
|
|
ffeb8119f7 | ||
|
|
a94ccdc425 | ||
|
|
04faff3bdb |
@@ -5,8 +5,8 @@ Bot command to post the highscores
|
||||
from nextcord.ext import commands
|
||||
from highscores import highscores_config # pylint: disable=import-error
|
||||
from highscores import highscores_data # pylint: disable=import-error
|
||||
from utils import data_storage # pylint: disable=import-error
|
||||
from utils import highscore_message # pylint: disable=import-error
|
||||
from utilities.data_storage import save_highscores_data # pylint: disable=import-error
|
||||
from utilities.utils import send_highscore_message # pylint: disable=import-error
|
||||
|
||||
|
||||
class PostHighscores(commands.Cog, name="Post Highscores"):
|
||||
@@ -25,18 +25,18 @@ class PostHighscores(commands.Cog, name="Post Highscores"):
|
||||
?post-scores
|
||||
```
|
||||
"""
|
||||
channel_id = highscores_data["channel_id"]
|
||||
print(f"Printing out highscores information in channel {channel_id}")
|
||||
channel = self.bot.get_channel(channel_id)
|
||||
if channel is None:
|
||||
response = 'Registered Highscores channel does not exist or was never registered. \
|
||||
Register with "?register" command.'
|
||||
await ctx.send(response)
|
||||
return
|
||||
for boss in highscores_config["bosses"]:
|
||||
await highscore_message.send_highscore_message(channel, boss["boss"])
|
||||
highscore_channel_id = highscores_data["highscore_channel_id"]
|
||||
print(f"Printing out highscores information in channel {highscore_channel_id}")
|
||||
channel = self.bot.get_channel(highscore_channel_id)
|
||||
|
||||
data_storage.save_highscores_data(highscores_data)
|
||||
error_response = 'Registered Highscores channel does not exist or was never registered. \
|
||||
Register with "?register" command.'
|
||||
assert channel is not None, await ctx.send(error_response)
|
||||
|
||||
for boss in highscores_config["bosses"]:
|
||||
await send_highscore_message(channel, boss["boss"])
|
||||
|
||||
save_highscores_data(highscores_data)
|
||||
|
||||
|
||||
# This function will be called when this extension is loaded.
|
||||
|
||||
@@ -4,7 +4,7 @@ Bot command to register the highscores channel
|
||||
|
||||
from nextcord.ext import commands
|
||||
from highscores import highscores_data # pylint: disable=import-error
|
||||
from utils import data_storage # pylint: disable=import-error
|
||||
from utilities.data_storage import save_highscores_data # pylint: disable=import-error
|
||||
|
||||
|
||||
class RegisterHighscoreChannel(commands.Cog, name="Register HighScore Channel"):
|
||||
@@ -13,19 +13,19 @@ class RegisterHighscoreChannel(commands.Cog, name="Register HighScore Channel"):
|
||||
def __init__(self, bot: commands.Bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command(name="register")
|
||||
@commands.command(name="register-highscore")
|
||||
async def register_highscores(self, ctx: commands.Context):
|
||||
"""A command which registers current channel as channel to post highscores in.
|
||||
Usage:
|
||||
```
|
||||
?register (in channel to post highscores in)
|
||||
?register-highscore (in channel to post highscores in)
|
||||
```
|
||||
"""
|
||||
print(f"Registering {ctx.channel.id}.")
|
||||
print(f"Registering {ctx.channel.id} for highscores.")
|
||||
# respond to the message
|
||||
await ctx.send(f"Registered <#{ctx.channel.id}> as channel to post highscores in.")
|
||||
highscores_data["channel_id"] = ctx.channel.id
|
||||
data_storage.save_highscores_data(highscores_data)
|
||||
highscores_data["highscore_channel_id"] = ctx.channel.id
|
||||
save_highscores_data(highscores_data)
|
||||
|
||||
|
||||
# This function will be called when this extension is loaded.
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""
|
||||
Bot command to register the verification channel
|
||||
"""
|
||||
|
||||
from nextcord.ext import commands
|
||||
from highscores import highscores_data # pylint: disable=import-error
|
||||
from utilities.data_storage import save_highscores_data # pylint: disable=import-error
|
||||
|
||||
|
||||
class RegisterVerificationChannel(commands.Cog, name="Register Verify Channel"):
|
||||
"""Registers Verification channel"""
|
||||
|
||||
def __init__(self, bot: commands.Bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.command(name="register-verify")
|
||||
async def register_highscores(self, ctx: commands.Context):
|
||||
"""A command which registers current channel as channel to post verifications in.
|
||||
Usage:
|
||||
```
|
||||
?register-verify (in channel to post highscores in)
|
||||
```
|
||||
"""
|
||||
print(f"Registering {ctx.channel.id} for verification.")
|
||||
# respond to the message
|
||||
await ctx.send(f"Registered <#{ctx.channel.id}> as channel to post verifications in.")
|
||||
highscores_data["verification_channel_id"] = ctx.channel.id
|
||||
save_highscores_data(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(RegisterVerificationChannel(bot))
|
||||
+24
-6
@@ -3,17 +3,22 @@ Bot command to submit a score
|
||||
"""
|
||||
|
||||
from nextcord.ext import commands
|
||||
from utils import highscore_manage # pylint: disable=import-error
|
||||
|
||||
# from utils import highscore_manage # pylint: disable=import-error
|
||||
from highscores import highscores_data # pylint: disable=import-error
|
||||
from utilities.utils import submit_score # pylint: disable=import-error
|
||||
from .verification_view import VerificationView
|
||||
|
||||
|
||||
class RegisterHighscoreChannel(commands.Cog, name="Score"):
|
||||
class Score(commands.Cog, name="Score"):
|
||||
"""Submits a score."""
|
||||
|
||||
def __init__(self, bot: commands.Bot):
|
||||
self.bot = bot
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
"""Called when the cog is loaded"""
|
||||
self.bot.add_view(VerificationView())
|
||||
|
||||
@commands.command(name="score")
|
||||
async def score(self, ctx: commands.Context, boss_name: str, category: str, score: str):
|
||||
"""A command which calls a function to submit the score to highscores.
|
||||
@@ -23,11 +28,24 @@ class RegisterHighscoreChannel(commands.Cog, name="Score"):
|
||||
?score "Boss Name" "Category" "score"
|
||||
```
|
||||
"""
|
||||
await highscore_manage.submit_score(self, ctx, boss_name, category, score)
|
||||
verification_channel_id = highscores_data["verification_channel_id"]
|
||||
channel = self.bot.get_channel(verification_channel_id)
|
||||
|
||||
error_response = "Registered Verification channel does not exist or was never registered. \
|
||||
Contact server admins."
|
||||
assert channel is not None, await ctx.send(error_response)
|
||||
|
||||
verification_string = f"{ctx.author.display_name}:{boss_name}:{category}:{score}"
|
||||
|
||||
await channel.send(
|
||||
content=verification_string,
|
||||
files=[await attch.to_file() for attch in ctx.message.attachments],
|
||||
view=VerificationView(),
|
||||
)
|
||||
|
||||
|
||||
# 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))
|
||||
bot.add_cog(Score(bot))
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""View for verification buttons"""
|
||||
|
||||
import nextcord
|
||||
from utilities.utils import submit_score # pylint: disable=import-error
|
||||
|
||||
|
||||
class VerificationView(nextcord.ui.View):
|
||||
"""Defines views for verifying score submissions"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(timeout=None)
|
||||
|
||||
@nextcord.ui.button(label="Approve", style=nextcord.ButtonStyle.green, custom_id="approve")
|
||||
async def approve_button(
|
||||
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
|
||||
): # pylint: disable=unused-argument
|
||||
"""Button for approving score submission."""
|
||||
content = interaction.message.content.split(":")
|
||||
user = content[0]
|
||||
boss_name = content[1]
|
||||
category = content[2]
|
||||
score = content[3]
|
||||
|
||||
await submit_score(interaction, user, boss_name, category, score)
|
||||
await interaction.message.delete()
|
||||
await interaction.channel.send(
|
||||
f"Approved: {boss_name} {category} {user} {score}",
|
||||
files=[await attch.to_file() for attch in interaction.message.attachments],
|
||||
)
|
||||
|
||||
@nextcord.ui.button(label="Deny", style=nextcord.ButtonStyle.red, custom_id="deny")
|
||||
async def deny_button(
|
||||
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
|
||||
): # pylint: disable=unused-argument
|
||||
"""Button for denying score submission."""
|
||||
await interaction.message.delete()
|
||||
+4
-3
@@ -9,7 +9,8 @@ import nextcord
|
||||
from nextcord.ext import commands
|
||||
|
||||
import config
|
||||
from utils import data_storage
|
||||
from utilities.data_storage import open_highscores_config
|
||||
from utilities.data_storage import open_highscores_data
|
||||
|
||||
logger = logging.getLogger("nextcord")
|
||||
logger.setLevel(logging.DEBUG)
|
||||
@@ -18,8 +19,8 @@ handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(me
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
highscores_config = data_storage.open_highscores_config()
|
||||
highscores_data = data_storage.open_highscores_data()
|
||||
highscores_config = open_highscores_config()
|
||||
highscores_data = open_highscores_data()
|
||||
|
||||
|
||||
def main():
|
||||
|
||||
@@ -1,14 +1,22 @@
|
||||
"""
|
||||
Contains functions for saving and loading highscore data and configs.
|
||||
"""
|
||||
"""Functions for retreiving and storing highscores data and configurations."""
|
||||
|
||||
import json
|
||||
import os
|
||||
import json
|
||||
|
||||
HIGHSCORES_CONFIG_FILE = "highscores_config.json"
|
||||
HIGHSCORES_DATA_FILE = "highscores_data.json"
|
||||
|
||||
|
||||
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 open_highscores_data():
|
||||
"""
|
||||
Opens a highscores_data.json file if one exists, otherwise creates a skeleton of the data.
|
||||
@@ -19,7 +27,7 @@ def open_highscores_data():
|
||||
data = json.load(file)
|
||||
else:
|
||||
# create the json object
|
||||
data = {"channel_id": -1}
|
||||
data = {"highscore_channel_id": -1, "verification_channel_id": -1}
|
||||
config = open_highscores_config()
|
||||
for boss in config["bosses"]:
|
||||
data[boss["boss"]] = {"message_id": 0}
|
||||
@@ -34,16 +42,6 @@ def open_highscores_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.
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
Contains various utlity functions for highscores bot
|
||||
"""
|
||||
|
||||
import nextcord
|
||||
from highscores import highscores_config # pylint: disable=import-error
|
||||
from highscores import highscores_data # pylint: disable=import-error
|
||||
from utilities.data_storage import save_highscores_data # pylint: disable=import-error
|
||||
|
||||
|
||||
def format_highscore_message(boss_name: str):
|
||||
"""
|
||||
returns a formatted string for a boss's highscore
|
||||
@param boss: the dictionary object for the boss
|
||||
@return the formatted string
|
||||
"""
|
||||
ret_string = f"**{boss_name}**\n```"
|
||||
boss_data = highscores_data[boss_name]
|
||||
|
||||
# Gather all categories and add to string
|
||||
for key, value in boss_data["categories"].items():
|
||||
ret_string += f"{key}".ljust(30, " ")
|
||||
ret_string += "\n"
|
||||
|
||||
highscore_size = highscores_config["highscore_size"]
|
||||
|
||||
# list rankings in a single line. Start with first place for each category and then continue
|
||||
for i in range(highscore_size):
|
||||
for key, value in boss_data["categories"].items():
|
||||
if len(value) > i:
|
||||
score = value[i]
|
||||
ret_string += f"{i+1}: {score[0]} - {score[1]}".ljust(30, " ")
|
||||
else:
|
||||
ret_string += f"{i+1}: submit your score".ljust(30, " ")
|
||||
ret_string += "\n"
|
||||
|
||||
return ret_string + "```"
|
||||
|
||||
|
||||
async def send_highscore_message(channel, boss_name: str):
|
||||
"""
|
||||
Function takes care of checking if a message exists for a boss, then
|
||||
creating and sending/editing the message
|
||||
@param channel: the channel to send the message in/search for message id
|
||||
@param boss: the boss to send the message about
|
||||
"""
|
||||
highscore_string = format_highscore_message(boss_name)
|
||||
|
||||
message_id = highscores_data[boss_name]["message_id"]
|
||||
try:
|
||||
message = await channel.fetch_message(message_id)
|
||||
await message.edit(content=highscore_string)
|
||||
except nextcord.NotFound:
|
||||
# message doesn't exist.
|
||||
message = await channel.send(highscore_string)
|
||||
message_id = message.id
|
||||
highscores_data[boss_name]["message_id"] = message_id
|
||||
|
||||
|
||||
async def submit_score(
|
||||
interaction: nextcord.Interaction, user: str, boss_name: str, category: str, score: str
|
||||
):
|
||||
"""
|
||||
Adds a score to the high scores and sorts. Removes a score if larger than size limit.
|
||||
@param boss: the boss to add score to
|
||||
@param category: the category to add score to
|
||||
@param user: user who submitted score
|
||||
@param score: score (int) to add
|
||||
"""
|
||||
# TODO update user submission to not have dupe users
|
||||
|
||||
# create score tuple for either time or int
|
||||
# define sort index
|
||||
if highscores_config["categories"][category]["is_time_record"]:
|
||||
minutes = score.split(":")[0]
|
||||
seconds = score.split(":")[1]
|
||||
score_seconds = int(minutes) * 60 + int(seconds)
|
||||
score_tuple = (user, score, score_seconds)
|
||||
sort_index = 2
|
||||
|
||||
else:
|
||||
score_tuple = (user, int(score))
|
||||
sort_index = 1
|
||||
|
||||
scores = highscores_data[boss_name]["categories"][category]
|
||||
scores.append(score_tuple)
|
||||
|
||||
# sort scores.
|
||||
scores.sort(
|
||||
key=lambda x: x[sort_index],
|
||||
reverse=not highscores_config["categories"][category]["ascending"],
|
||||
)
|
||||
|
||||
# enforce highscore size
|
||||
while len(scores) > highscores_config["highscore_size"]:
|
||||
scores.pop()
|
||||
highscores_data[boss_name]["categories"][category] = scores
|
||||
|
||||
# edit message
|
||||
highscore_channel_id = highscores_data["highscore_channel_id"]
|
||||
print(f"Editting message {highscore_channel_id}")
|
||||
channel = interaction.guild.get_channel(highscore_channel_id)
|
||||
|
||||
error_response = 'Registered Highscores channel does not exist or was never registered. \
|
||||
Register with "?register" command.'
|
||||
assert channel is not None, await interaction.send(error_response)
|
||||
|
||||
await send_highscore_message(channel, boss_name)
|
||||
|
||||
# save data
|
||||
save_highscores_data(highscores_data)
|
||||
@@ -1,60 +0,0 @@
|
||||
"""
|
||||
Contains various functions for managing the highscores data
|
||||
"""
|
||||
|
||||
from nextcord.ext import commands
|
||||
from highscores import highscores_config # pylint: disable=import-error
|
||||
from highscores import highscores_data # pylint: disable=import-error
|
||||
from utils import highscore_message # pylint: disable=import-error
|
||||
from utils import data_storage # pylint: disable=import-error
|
||||
|
||||
|
||||
async def submit_score(self, ctx: commands.Context, boss_name: str, category: str, score: str):
|
||||
"""
|
||||
Adds a score to the high scores and sorts. Removes a score if larger than size limit.
|
||||
@param boss: the boss to add score to
|
||||
@param category: the category to add score to
|
||||
@param user: user who submitted score
|
||||
@param score: score (int) to add
|
||||
"""
|
||||
# TODO update user submission to not have dupe users
|
||||
|
||||
# create score tuple for either time or int
|
||||
# define sort index
|
||||
if highscores_config["categories"][category]["is_time_record"]:
|
||||
score_list = score.split(":")
|
||||
minutes = score_list[0]
|
||||
seconds = score_list[1]
|
||||
score_seconds = int(minutes) * 60 + int(seconds)
|
||||
score_tuple = (ctx.author.display_name, score, score_seconds)
|
||||
sort_index = 2
|
||||
|
||||
else:
|
||||
score_tuple = (ctx.author.display_name, int(score))
|
||||
sort_index = 1
|
||||
|
||||
scores = highscores_data[boss_name]["categories"][category]
|
||||
scores.append(score_tuple)
|
||||
|
||||
# sort scores.
|
||||
ascending = highscores_config["categories"][category]["ascending"]
|
||||
scores.sort(key=lambda x: x[sort_index], reverse=not ascending)
|
||||
|
||||
# enforce highscore size
|
||||
while len(scores) > highscores_config["highscore_size"]:
|
||||
scores.pop()
|
||||
highscores_data[boss_name]["categories"][category] = scores
|
||||
|
||||
# edit message
|
||||
channel_id = highscores_data["channel_id"]
|
||||
print(f"Editting message {channel_id}")
|
||||
channel = self.bot.get_channel(channel_id)
|
||||
if channel is None:
|
||||
response = 'Registered Highscores channel does not exist or was never registered. \
|
||||
Register with "?register" command.'
|
||||
await ctx.send(response)
|
||||
return
|
||||
await highscore_message.send_highscore_message(channel, boss_name)
|
||||
|
||||
# save data
|
||||
data_storage.save_highscores_data(highscores_data)
|
||||
@@ -1,56 +0,0 @@
|
||||
"""
|
||||
Contains various functions for sending/editing the highscore messages.
|
||||
"""
|
||||
|
||||
import nextcord
|
||||
from highscores import highscores_config # pylint: disable=import-error
|
||||
from highscores import highscores_data # pylint: disable=import-error
|
||||
|
||||
|
||||
def format_highscore_message(boss_name: str):
|
||||
"""
|
||||
returns a formatted string for a boss's highscore
|
||||
@param boss: the dictionary object for the boss
|
||||
@return the formatted string
|
||||
"""
|
||||
ret_string = f"**{boss_name}**\n```"
|
||||
boss_data = highscores_data[boss_name]
|
||||
|
||||
# Gather all categories and add to string
|
||||
for key, value in boss_data["categories"].items():
|
||||
ret_string += f"{key}".ljust(30, " ")
|
||||
ret_string += "\n"
|
||||
|
||||
highscore_size = highscores_config["highscore_size"]
|
||||
|
||||
# list rankings in a single line. Start with first place for each category and then continue
|
||||
for i in range(highscore_size):
|
||||
for key, value in boss_data["categories"].items():
|
||||
if len(value) > i:
|
||||
score = value[i]
|
||||
ret_string += f"{i+1}: {score[0]} - {score[1]}".ljust(30, " ")
|
||||
else:
|
||||
ret_string += f"{i+1}: submit your score".ljust(30, " ")
|
||||
ret_string += "\n"
|
||||
|
||||
return ret_string + "```"
|
||||
|
||||
|
||||
async def send_highscore_message(channel, boss_name: str):
|
||||
"""
|
||||
Function takes care of checking if a message exists for a boss, then
|
||||
creating and sending/editing the message
|
||||
@param channel: the channel to send the message in/search for message id
|
||||
@param boss: the boss to send the message about
|
||||
"""
|
||||
highscore_string = format_highscore_message(boss_name)
|
||||
|
||||
message_id = highscores_data[boss_name]["message_id"]
|
||||
try:
|
||||
message = await channel.fetch_message(message_id)
|
||||
await message.edit(content=highscore_string)
|
||||
except nextcord.NotFound:
|
||||
# message doesn't exist.
|
||||
message = await channel.send(highscore_string)
|
||||
message_id = message.id
|
||||
highscores_data[boss_name]["message_id"] = message_id
|
||||
Reference in New Issue
Block a user