Compare commits

...
9 changed files with 104 additions and 70 deletions
+39 -6
View File
@@ -2,11 +2,14 @@
Defines cog for on message listener. Defines cog for on message listener.
""" """
import re
from nextcord.ext import commands from nextcord.ext import commands
import nextcord import nextcord
from cogs.submission.submission_views import SubmissionState # pylint: disable=import-error from cogs.submission.submission_views import SubmissionState # pylint: disable=import-error
from cogs.submission.submission_views import get_submission_embed # pylint: disable=import-error from cogs.submission.submission_views import get_submission_embed # pylint: disable=import-error
from highscores import highscores_config # pylint: disable=import-error
from highscores import highscores_data # pylint: disable=import-error from highscores import highscores_data # pylint: disable=import-error
from highscores import submission_objects # pylint: disable=import-error from highscores import submission_objects # pylint: disable=import-error
@@ -26,15 +29,43 @@ class SubmissionListener(commands.Cog, name="Message Listener"):
highscores_data["submission_channel_id"] highscores_data["submission_channel_id"]
).fetch_message(message_id) ).fetch_message(message_id)
# TODO want to regex score to ensure it is correct.
# # here is also where score can be standardized in look
# need check if correct user and correct channel # need check if correct user and correct channel
if message.channel.id == highscores_data["submission_channel_id"]: if message.channel.id == highscores_data["submission_channel_id"]:
state = submission_objects[message.author.id]["submission_state"] state = submission_objects[message.author.id]["submission_state"]
if state == SubmissionState.SCORE and message.content: if state == SubmissionState.SCORE and message.content:
submission_objects[message.author.id]["score"] = message.content
embed = get_submission_embed(message.author.id) # check with regex if score matches correctly
is_time_record = highscores_config["categories"][
submission_objects[message.author.id]["category"]
]["is_time_record"]
time_regex = re.search(
"([0-9]{2}:)?[0-9]{2}(\.[0-9])?", # pylint: disable=anomalous-backslash-in-string
message.content,
)
int_regex = re.search("[0-9]+", message.content)
if time_regex is None and is_time_record:
embed = submission_message.embeds[0]
embed.add_field(
name="Error",
value="Time record must follow format MM:SS.ms or SS.ms or SS.",
)
elif int_regex is None and not is_time_record:
embed = submission_message.embeds[0]
embed.add_field(name="Error", value="Number record must only be number.")
else:
score = message.content
if is_time_record:
# standardize time score format.
# add colon if its not there
if score.find(":") == -1:
score = "00:" + score
# add a 0 if there isn't 2 digits before a colon
elif len(score.split(":", maxsplit=1)[0]) < 2:
score = "0" + score
submission_objects[message.author.id]["score"] = score
embed = get_submission_embed(message.author.id)
await submission_message.edit( await submission_message.edit(
embed=embed, embed=embed,
) )
@@ -43,7 +74,9 @@ class SubmissionListener(commands.Cog, name="Message Listener"):
files=[await attch.to_file() for attch in message.attachments], files=[await attch.to_file() for attch in message.attachments],
) )
elif state == SubmissionState.NAME and message.content: elif state == SubmissionState.NAME and message.content:
submission_objects[message.author.id]["username"] = message.content[:12] submission_objects[message.author.id]["username"] = message.content[
: highscores_data["username_length"]
]
embed = get_submission_embed(message.author.id) embed = get_submission_embed(message.author.id)
await submission_message.edit( await submission_message.edit(
embed=embed, embed=embed,
+1
View File
@@ -43,6 +43,7 @@ class PostHighscores(commands.Cog, name="Post Highscores"):
message: nextcord.Message = await send_highscore_message(channel, boss) message: nextcord.Message = await send_highscore_message(channel, boss)
await message.edit(view=SubmissionCreateButton(self.bot)) await message.edit(view=SubmissionCreateButton(self.bot))
# Saving in case new message was sent.
save_highscores_data(highscores_data) save_highscores_data(highscores_data)
-1
View File
@@ -5,7 +5,6 @@ Bot command to submit a score
from nextcord.ext import commands from nextcord.ext import commands
from highscores import highscores_data # 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 from .verification_view import VerificationView
+7 -8
View File
@@ -7,9 +7,9 @@ import nextcord
from nextcord import Embed from nextcord import Embed
from nextcord.ext import commands from nextcord.ext import commands
from utilities.data_storage import open_message_map # pylint: disable=import-error
from highscores import highscores_data # pylint: disable=import-error from highscores import highscores_data # pylint: disable=import-error
from highscores import submission_objects # pylint: disable=import-error from highscores import submission_objects # pylint: disable=import-error
from highscores import highscores_message_map # pylint: disable=import-error
from .verification_view import VerificationView from .verification_view import VerificationView
@@ -55,7 +55,7 @@ def get_submission_embed(userid: int) -> nextcord.Embed:
def category_select_options(boss_name: str) -> "list[nextcord.SelectOption]": def category_select_options(boss_name: str) -> "list[nextcord.SelectOption]":
"""Returns list of categories for a given boss.""" """Returns list of categories for a given boss."""
options: "list[nextcord.SelectOption]" = [] options: "list[nextcord.SelectOption]" = []
boss_dict = highscores_data[boss_name] boss_dict = highscores_data["tables"][boss_name]
for category in boss_dict["categories"].items(): for category in boss_dict["categories"].items():
options.append(nextcord.SelectOption(label=category[0])) options.append(nextcord.SelectOption(label=category[0]))
@@ -186,22 +186,21 @@ class SubmissionCreateButton(nextcord.ui.View):
self, button: nextcord.ui.Button, interaction: nextcord.Interaction self, button: nextcord.ui.Button, interaction: nextcord.Interaction
): # pylint: disable=unused-argument ): # pylint: disable=unused-argument
"""Button for score submission.""" """Button for score submission."""
highscores_message_map = open_message_map() boss_name = highscores_message_map[interaction.message.id]
boss_name = highscores_message_map[str(interaction.message.id)]
# embed = nextcord.Embed(title="Highscores Submission")
# embed.add_field(name="Boss", value=boss_name, inline=False)
# embed.add_field(name="User", value=interaction.user.display_name, inline=False)
channel = self._bot.get_channel(highscores_data["submission_channel_id"]) channel = self._bot.get_channel(highscores_data["submission_channel_id"])
# a user should only have 1 submission active at once. # a user should only have 1 submission active at once.
# submitting with dummy message_id until message created # submitting with dummy message_id until message created
# split username on pipe.
submission_objects[interaction.user.id] = { submission_objects[interaction.user.id] = {
"message_id": 0, "message_id": 0,
"submission_state": SubmissionState.CATEGORY, "submission_state": SubmissionState.CATEGORY,
"boss_name": boss_name, "boss_name": boss_name,
"score": "", "score": "",
"category": "", "category": "",
"username": interaction.user.display_name.split("|")[0][:12], "username": interaction.user.display_name.split("|")[0][
: highscores_data["username_length"]
],
} }
embed = get_submission_embed(interaction.user.id) embed = get_submission_embed(interaction.user.id)
+9 -9
View File
@@ -10,6 +10,15 @@ class VerificationView(nextcord.ui.View):
def __init__(self): def __init__(self):
super().__init__(timeout=None) super().__init__(timeout=None)
@nextcord.ui.button(
label="Deny", style=nextcord.ButtonStyle.red, custom_id="deny-button-submission"
)
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()
@nextcord.ui.button( @nextcord.ui.button(
label="Approve", style=nextcord.ButtonStyle.green, custom_id="approve-button-submission" label="Approve", style=nextcord.ButtonStyle.green, custom_id="approve-button-submission"
) )
@@ -35,12 +44,3 @@ class VerificationView(nextcord.ui.View):
except UnboundLocalError: except UnboundLocalError:
await interaction.send("Instruct user to submit with all fields.") await interaction.send("Instruct user to submit with all fields.")
await interaction.message.edit(view=None) await interaction.message.edit(view=None)
@nextcord.ui.button(
label="Deny", style=nextcord.ButtonStyle.red, custom_id="deny-button-submission"
)
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()
+12 -4
View File
@@ -212,8 +212,8 @@
"Spooned Log" "Spooned Log"
], ],
"Taraket the Necromancer": [ "Taraket the Necromancer": [
"Kill Count", "Solo Kill Count",
"Kill Time", "Solo Kill Time",
"Group Kill Count", "Group Kill Count",
"Group Kill Time", "Group Kill Time",
"Spooned Log" "Spooned Log"
@@ -244,8 +244,8 @@
"Spooned Log" "Spooned Log"
], ],
"Verak Lith": [ "Verak Lith": [
"Kill Count", "Solo Kill Count",
"Kill Time", "Solo Kill Time",
"Group Kill Count", "Group Kill Count",
"Group Kill Time", "Group Kill Time",
"Spooned Log" "Spooned Log"
@@ -318,6 +318,14 @@
"ascending": true, "ascending": true,
"is_time_record": true "is_time_record": true
}, },
"Solo Kill Count": {
"ascending": false,
"is_time_record": false
},
"Solo Kill Time": {
"ascending": true,
"is_time_record": true
},
"Spooned Log": { "Spooned Log": {
"ascending": true, "ascending": true,
"is_time_record": false "is_time_record": false
+2 -2
View File
@@ -11,7 +11,7 @@ from nextcord.ext import commands
import config import config
from utilities.data_storage import open_highscores_config from utilities.data_storage import open_highscores_config
from utilities.data_storage import open_highscores_data from utilities.data_storage import open_highscores_data
from utilities.data_storage import open_message_map from utilities.data_storage import create_message_map
logger = logging.getLogger("nextcord") logger = logging.getLogger("nextcord")
logger.setLevel(logging.DEBUG) logger.setLevel(logging.DEBUG)
@@ -22,7 +22,7 @@ logger.addHandler(handler)
highscores_config = open_highscores_config() highscores_config = open_highscores_config()
highscores_data = open_highscores_data() highscores_data = open_highscores_data()
highscores_message_map = open_message_map() highscores_message_map = create_message_map(highscores_data)
submission_objects: dict = {} submission_objects: dict = {}
+13 -21
View File
@@ -5,7 +5,6 @@ import json
HIGHSCORES_CONFIG_FILE = "highscores_config.json" HIGHSCORES_CONFIG_FILE = "highscores_config.json"
HIGHSCORES_DATA_FILE = "highscores_data.json" HIGHSCORES_DATA_FILE = "highscores_data.json"
HIGHSCORES_MESSAGE_MAP_FILE = "highscores_message_map.json"
def open_highscores_config(): def open_highscores_config():
@@ -28,29 +27,31 @@ def open_highscores_data():
data = json.load(file) data = json.load(file)
else: else:
# create the json object # create the json object
data = {"highscore_channel_id": -1, "verification_channel_id": -1} data = {"highscore_channel_id": -1, "verification_channel_id": -1, "username_length": 12}
config: dict = open_highscores_config() config: dict = open_highscores_config()
for boss, categories in config["highscore_table"].items(): for boss, categories in config["highscore_table"].items():
data[boss] = {"message_id": 0} data["tables"][boss] = {"message_id": 0}
boss_categories = {} boss_categories = {}
for category in categories: # pylint: disable=unused-variable for category in categories: # pylint: disable=unused-variable
rank_list = [] rank_list = []
boss_categories[category] = rank_list boss_categories[category] = rank_list
data[boss]["categories"] = boss_categories data["tables"][boss]["categories"] = boss_categories
return data return data
def open_message_map(): def create_message_map(data: dict):
""" """
Opens a highscore_message_map.json file if one exists. Otherwise returns empty dict. Creates a message map from input highscores data.
@param data: highscores_data dict to create map from.
@return: dict message_map of message to boss. @return: dict message_map of message to boss.
""" """
if os.path.exists(HIGHSCORES_MESSAGE_MAP_FILE):
with open(HIGHSCORES_MESSAGE_MAP_FILE, encoding="utf-8", mode="r") as file: message_map = {}
message_map = json.load(file)
else: for boss, info in data["tables"].items():
# create the json object message_map[info["message_id"]] = boss
message_map = {}
return message_map return message_map
@@ -61,12 +62,3 @@ def save_highscores_data(data):
""" """
with open(HIGHSCORES_DATA_FILE, encoding="utf-8", mode="w") as file: with open(HIGHSCORES_DATA_FILE, encoding="utf-8", mode="w") as file:
file.write(json.dumps(data, indent=4)) file.write(json.dumps(data, indent=4))
def save_message_map(message_map):
"""
Saves the highscores message mao data dict into a json file.
@param map: dict map of message to boss.
"""
with open(HIGHSCORES_MESSAGE_MAP_FILE, encoding="utf-8", mode="w") as file:
file.write(json.dumps(message_map, indent=4))
+20 -18
View File
@@ -7,7 +7,6 @@ from highscores import highscores_config # pylint: disable=import-error
from highscores import highscores_data # pylint: disable=import-error from highscores import highscores_data # pylint: disable=import-error
from highscores import highscores_message_map # pylint: disable=import-error from highscores import highscores_message_map # pylint: disable=import-error
from utilities.data_storage import save_highscores_data # pylint: disable=import-error from utilities.data_storage import save_highscores_data # pylint: disable=import-error
from utilities.data_storage import save_message_map # pylint: disable=import-error
def format_highscore_message(boss_name: str): def format_highscore_message(boss_name: str):
@@ -17,11 +16,11 @@ def format_highscore_message(boss_name: str):
@return the formatted string @return the formatted string
""" """
ret_string = f"**{boss_name}**\n```" ret_string = f"**{boss_name}**\n```"
boss_data = highscores_data[boss_name] boss_data = highscores_data["tables"][boss_name]
# Gather all categories and add to string # Gather all categories and add to string
for key, value in boss_data["categories"].items(): for key, value in boss_data["categories"].items():
ret_string += f"{key}".ljust(25, " ") ret_string += f"{key}".ljust(26, " ")
ret_string += "\n" ret_string += "\n"
highscore_size = highscores_config["highscore_size"] highscore_size = highscores_config["highscore_size"]
@@ -30,10 +29,21 @@ def format_highscore_message(boss_name: str):
for i in range(highscore_size): for i in range(highscore_size):
for key, value in boss_data["categories"].items(): for key, value in boss_data["categories"].items():
if len(value) > i: if len(value) > i:
score = value[i] score_pair = value[i]
ret_string += f"{i+1}: {score[0]} - {score[1]}".ljust(25, " ")
# pad username to max length.
username: str = score_pair[0].ljust(highscores_data["username_length"], " ")
score: str = str(score_pair[1])
if highscores_config["categories"][key]["is_time_record"]:
# pad score to correct length
# MM:SS.ms is 7 characters long
score = score.ljust(7, " ")
line_str = f"{i+1}: {username} - "
ret_string += line_str + score.rjust(26 - len(line_str) - 1) + " "
else: else:
ret_string += f"{i+1}: submit your score".ljust(25, " ") ret_string += f"{i+1}: submit your score".ljust(26, " ")
ret_string += "\n" ret_string += "\n"
return ret_string + "```" return ret_string + "```"
@@ -48,7 +58,7 @@ async def send_highscore_message(channel, boss_name: str) -> nextcord.Message:
""" """
highscore_string = format_highscore_message(boss_name) highscore_string = format_highscore_message(boss_name)
message_id = highscores_data[boss_name]["message_id"] message_id = highscores_data["tables"][boss_name]["message_id"]
try: try:
message: nextcord.Message = await channel.fetch_message(message_id) message: nextcord.Message = await channel.fetch_message(message_id)
await message.edit(content=highscore_string) await message.edit(content=highscore_string)
@@ -56,10 +66,9 @@ async def send_highscore_message(channel, boss_name: str) -> nextcord.Message:
# message doesn't exist. # message doesn't exist.
message: nextcord.Message = await channel.send(highscore_string) message: nextcord.Message = await channel.send(highscore_string)
message_id = message.id message_id = message.id
highscores_data[boss_name]["message_id"] = message_id highscores_data["tables"][boss_name]["message_id"] = message_id
# save message -> boss_name in message_map # save message -> boss_name in message_map
highscores_message_map[str(message_id)] = boss_name highscores_message_map[str(message_id)] = boss_name
save_message_map(highscores_message_map)
return message return message
@@ -77,13 +86,6 @@ async def submit_score(
boss_category_config = highscores_config["categories"][category] boss_category_config = highscores_config["categories"][category]
# capping to 12 characters because runescape names are 12 characters long.
# Splitting on pipe. My discord has multiple names on account split by pipe.
user = user.split("|")[0][:12]
# strip leading zeros and colon from score
score = score.lstrip("0:")
# create score tuple for either time or int # create score tuple for either time or int
# define sort index # define sort index
if boss_category_config["is_time_record"]: if boss_category_config["is_time_record"]:
@@ -100,7 +102,7 @@ async def submit_score(
score_tuple = (user, int(score)) score_tuple = (user, int(score))
sort_index = 1 sort_index = 1
scores: "list[tuple]" = highscores_data[boss_name]["categories"][category] scores: "list[tuple]" = highscores_data["tables"][boss_name]["categories"][category]
# if user is in an existing tuple, delete it. # if user is in an existing tuple, delete it.
users_scores: "list[tuple]" = [score_tuple] users_scores: "list[tuple]" = [score_tuple]
@@ -134,7 +136,7 @@ async def submit_score(
# enforce highscore size # enforce highscore size
while len(scores) > highscores_config["highscore_size"]: while len(scores) > highscores_config["highscore_size"]:
scores.pop() scores.pop()
highscores_data[boss_name]["categories"][category] = scores highscores_data["tables"][boss_name]["categories"][category] = scores
# edit message # edit message
highscore_channel_id = highscores_data["highscore_channel_id"] highscore_channel_id = highscores_data["highscore_channel_id"]