Compare commits

...
13 changed files with 252 additions and 12 deletions
+3 -1
View File
@@ -131,4 +131,6 @@ dmypy.json
nextcord.log
# data file for bot
highscores_data.json
highscores_data.json
highscores_message_map.json
highscores_config.json
+1 -1
View File
@@ -22,5 +22,5 @@ class HelpCog(commands.Cog):
# setup functions for bot
def setup(bot: commands.Bot):
"""Adds functon to bot"""
"""Adds function to bot"""
bot.add_cog(HelpCog(bot))
+7 -3
View File
@@ -3,6 +3,9 @@ Bot command to post the highscores
"""
from nextcord.ext import commands
import nextcord
from cogs.submission.submission_views import SubmissionButton # pylint: disable=import-error
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
@@ -29,12 +32,13 @@ class PostHighscores(commands.Cog, name="Post Highscores"):
print(f"Printing out highscores information in channel {highscore_channel_id}")
channel = self.bot.get_channel(highscore_channel_id)
error_response = 'Registered Highscores channel does not exist or was never registered. \
error_response = 'Registered Highscores channel does not exist or was never registered. \n\
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"])
message: nextcord.Message = await send_highscore_message(channel, boss["boss"])
await message.edit(view=SubmissionButton())
save_highscores_data(highscores_data)
@@ -42,5 +46,5 @@ class PostHighscores(commands.Cog, name="Post Highscores"):
# 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"""
"""Adds function to bot"""
bot.add_cog(PostHighscores(bot))
+1 -1
View File
@@ -31,5 +31,5 @@ class RegisterHighscoreChannel(commands.Cog, name="Register HighScore Channel"):
# 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"""
"""Adds function to bot"""
bot.add_cog(RegisterHighscoreChannel(bot))
@@ -31,5 +31,5 @@ class RegisterVerificationChannel(commands.Cog, name="Register Verify Channel"):
# 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"""
"""Adds function to bot"""
bot.add_cog(RegisterVerificationChannel(bot))
+1 -1
View File
@@ -47,5 +47,5 @@ class Score(commands.Cog, name="Score"):
# 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"""
"""Adds function to bot"""
bot.add_cog(Score(bot))
+26
View File
@@ -0,0 +1,26 @@
"""
Cog for creating submission process.
"""
from nextcord.ext import commands
from .submission_views import SubmissionButton
class SubmissionCog(commands.Cog, name="Submission Cog"):
"""Constructs submission method."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
"""Called when cog is loaded"""
self.bot.add_view(SubmissionButton(self.bot))
# 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 function to bot"""
bot.add_cog(SubmissionCog(bot))
+129
View File
@@ -0,0 +1,129 @@
"""Views used for submission process."""
from typing import Optional
import nextcord
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 .verification_view import VerificationView
class SubmissionButton(nextcord.ui.View):
"""Defines view for score submission button."""
def __init__(self, bot: commands.Bot):
super().__init__(timeout=None)
self._bot = bot
@nextcord.ui.button(label="Submit", style=nextcord.ButtonStyle.primary, custom_id="submit")
async def submit_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
): # pylint: disable=unused-argument
"""Button for score submission."""
highscores_message_map = open_message_map()
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)
submission_message = await interaction.channel.send( # TODO change channel
f"<@{interaction.user.id}>",
view=SubmissionDropdownView(
self._bot, interaction, await self._category_select_options(boss_name)
),
embed=embed,
)
def wait_check(check_message: nextcord.Message):
return (
interaction.user.id == check_message.author.id
and interaction.channel == check_message.channel
)
proof_message = await self._bot.wait_for("message", check=wait_check)
embed = submission_message.embeds[0]
embed.add_field(name="Score", value=proof_message.content, inline=False)
await submission_message.edit(
files=[await attch.to_file() for attch in proof_message.attachments], embed=embed
)
await proof_message.delete()
async def _category_select_options(self, boss_name: str) -> "list[nextcord.SelectOption]":
options: list[nextcord.SelectOption] = [] # pylint: disable=unsubscriptable-object
boss_dict = highscores_data[boss_name]
for category in boss_dict["categories"].items():
options.append(nextcord.SelectOption(label=category[0]))
return options
class SubmissionDropdown(nextcord.ui.Select):
"""Defines dropdown menu for submission"""
def __init__(
self,
bot: commands.Bot,
options: "list[nextcord.SelectOption]",
):
super().__init__(
placeholder="Choose submission category.", min_values=1, max_values=1, options=options
)
self._bot = bot
async def callback(self, interaction: nextcord.Interaction):
embed = interaction.message.embeds[0]
embed.add_field(name="Category", value=self.values[0], inline=False)
await interaction.message.edit(
embed=embed, # TODO solve ordering issue. currently have to choose category after score submission.
)
class SubmissionDropdownView(nextcord.ui.View):
"""Defines submission dropdown process view"""
def __init__(
self,
bot: commands.Bot,
prev_interaction: nextcord.Interaction,
options: "list[nextcord.SelectOption]",
*,
timeout: Optional[float] = 180,
):
super().__init__(timeout=timeout)
self.add_item(SubmissionDropdown(bot, options))
self._prev_interaction = prev_interaction
self.bot = bot
async def interaction_check(self, interaction: nextcord.Interaction) -> bool:
return self._prev_interaction.user == interaction.user
@nextcord.ui.button(
label="Submit Score", style=nextcord.ButtonStyle.green, custom_id="submit-score"
)
async def submit_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
): # pylint: disable=unused-argument
"""Defines button to submit a user's 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 channel.send(error_response)
await channel.send(
files=[await attch.to_file() for attch in interaction.message.attachments],
view=VerificationView(),
embed=interaction.message.embeds[0],
)
await interaction.message.edit(content=f"<@{interaction.user.id}> Submitted!", view=None)
@nextcord.ui.button(
label="Cancel", style=nextcord.ButtonStyle.red, custom_id="cancel-submission"
)
async def cancel_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
): # pylint: disable=unused-argument
"""Deletes message to cancel interaction."""
await interaction.message.delete()
+42
View File
@@ -0,0 +1,42 @@
"""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.embeds[0].to_dict()
for field in content["fields"]:
if field["name"] == "Boss":
boss_name = field["value"]
elif field["name"] == "Category":
category = field["value"]
elif field["name"] == "Score":
score = field["value"]
elif field["name"] == "User":
user = field["value"]
try:
await submit_score(interaction, user, boss_name, category, score)
await interaction.message.edit("Approved.", view=None)
except UnboundLocalError:
await interaction.send("Instruct user to submit with all fields.")
await interaction.message.edit(view=None)
@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()
@@ -179,6 +179,10 @@
{
"boss": "Yakamaru",
"hardmode": false
},
{
"boss": "Zamorak, Lord of Chaos",
"hardmode": true
}
],
"categories": {
+3 -1
View File
@@ -11,6 +11,7 @@ from nextcord.ext import commands
import config
from utilities.data_storage import open_highscores_config
from utilities.data_storage import open_highscores_data
from utilities.data_storage import open_message_map
logger = logging.getLogger("nextcord")
logger.setLevel(logging.DEBUG)
@@ -21,6 +22,7 @@ logger.addHandler(handler)
highscores_config = open_highscores_config()
highscores_data = open_highscores_data()
highscores_message_map = open_message_map()
def main():
@@ -30,7 +32,7 @@ def main():
intents = nextcord.Intents.default()
# Required in order to read messages (eg. prefix commands)
intents.message_content = True
intents.message_content = True # pylint: disable=assigning-non-slot
# To enable the guilds priveleged intent:
# intents.guilds = True
+24
View File
@@ -5,6 +5,7 @@ import json
HIGHSCORES_CONFIG_FILE = "highscores_config.json"
HIGHSCORES_DATA_FILE = "highscores_data.json"
HIGHSCORES_MESSAGE_MAP_FILE = "highscores_message_map.json"
def open_highscores_config():
@@ -42,6 +43,20 @@ def open_highscores_data():
return data
def open_message_map():
"""
Opens a highscore_message_map.json file if one exists. Otherwise returns empty dict.
@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 = json.load(file)
else:
# create the json object
message_map = {}
return message_map
def save_highscores_data(data):
"""
Saves the highscores data dict into a json file.
@@ -49,3 +64,12 @@ def save_highscores_data(data):
"""
with open(HIGHSCORES_DATA_FILE, encoding="utf-8", mode="w") as file:
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))
+10 -3
View File
@@ -5,7 +5,9 @@ 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 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_message_map # pylint: disable=import-error
def format_highscore_message(boss_name: str):
@@ -37,7 +39,7 @@ def format_highscore_message(boss_name: str):
return ret_string + "```"
async def send_highscore_message(channel, boss_name: str):
async def send_highscore_message(channel, boss_name: str) -> nextcord.Message:
"""
Function takes care of checking if a message exists for a boss, then
creating and sending/editing the message
@@ -48,13 +50,18 @@ async def send_highscore_message(channel, boss_name: str):
message_id = highscores_data[boss_name]["message_id"]
try:
message = await channel.fetch_message(message_id)
message: nextcord.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: nextcord.Message = await channel.send(highscore_string)
message_id = message.id
highscores_data[boss_name]["message_id"] = message_id
# save message -> boss_name in message_map
highscores_message_map[str(message_id)] = boss_name
save_message_map(highscores_message_map)
return message
async def submit_score(