Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5eb637a3a8 | ||
|
|
f722eb1a83 | ||
|
|
7759bbc648 | ||
|
|
65de7baeda | ||
|
|
e243404480 | ||
|
|
1959e11e5c | ||
|
|
c25d354fc0 | ||
|
|
e5d90a71d9 | ||
|
|
785a4eff46 | ||
|
|
627112b114 | ||
|
|
9b3bd9d02c | ||
|
|
2c56c614f3 | ||
|
|
3ccaa7004e | ||
|
|
289113661f | ||
|
|
74ce22dd26 | ||
|
|
170ce1cbfb | ||
|
|
e1b761e848 | ||
|
|
68592a7df8 | ||
|
|
b28938f66a | ||
|
|
adab97f505 | ||
|
|
edf51aac2d | ||
|
|
dbc6474fc3 | ||
|
|
ed68c4174f | ||
|
|
3abbff13d5 | ||
|
|
304b089113 | ||
|
|
29a163ec46 | ||
|
|
76fbba739f | ||
|
|
7204e882f1 | ||
|
|
a8d775ca09 | ||
|
|
983b9b6f34 | ||
|
|
84c910b19c | ||
|
|
1fcb25193d | ||
|
|
4785271ebb | ||
|
|
f9d765ad92 | ||
|
|
50868988c0 | ||
|
|
81ae867a43 | ||
|
|
2649ceb6bb | ||
|
|
6e02bc877f | ||
|
|
f61ad83e11 | ||
|
|
feeb47d3da | ||
|
|
0ff1b07096 | ||
|
|
8674eed0c5 | ||
|
|
e2ddd5412a | ||
|
|
f37844c953 | ||
|
|
d703c76704 | ||
|
|
6e25d4e75a | ||
|
|
0702198f0a | ||
|
|
43df7aeda7 | ||
|
|
c8becb8203 | ||
|
|
44d813504a | ||
|
|
3fc8910c9a | ||
|
|
563b6ab888 | ||
|
|
d7e44d3a22 | ||
|
|
a99b488ae1 | ||
|
|
85d0077107 | ||
|
|
9510c9eddc | ||
|
|
9550d1a68b | ||
|
|
b04819aa36 | ||
|
|
f43dccb12d |
Vendored
+2
-1
@@ -5,11 +5,12 @@
|
||||
"highscore",
|
||||
"highscores",
|
||||
"imcompiling",
|
||||
"iterrows",
|
||||
"nextcord",
|
||||
"ondelete"
|
||||
],
|
||||
"python.analysis.diagnosticSeverityOverrides": {
|
||||
"reportOptionalMemberAccess": false,
|
||||
"reportOptionalMemberAccess": "warning",
|
||||
"reportArgumentType": "information",
|
||||
"reportAttributeAccessIssue": "warning"
|
||||
}
|
||||
|
||||
@@ -2,14 +2,15 @@
|
||||
|
||||
from nextcord.ext import commands
|
||||
|
||||
from .create import CreateCog
|
||||
from .delete import DeleteCog
|
||||
from .help import HelpCog
|
||||
from .refresh import RefreshCog
|
||||
from .set import SetCog
|
||||
from .submission import SubmissionCog
|
||||
from .update import UpdateCog
|
||||
from .view import ViewCog
|
||||
from cogs.commands.create import CreateCog
|
||||
from cogs.commands.delete import DeleteCog
|
||||
from cogs.commands.get import GetCog
|
||||
from cogs.commands.help import HelpCog
|
||||
from cogs.commands.refresh import RefreshCog
|
||||
from cogs.commands.set import SetCog
|
||||
from cogs.commands.submission import SubmissionCog
|
||||
from cogs.commands.update import UpdateCog
|
||||
from cogs.commands.view import ViewCog
|
||||
|
||||
|
||||
# This function will be called when this extension is loaded.
|
||||
@@ -18,6 +19,7 @@ def setup(bot: commands.Bot) -> None:
|
||||
"""Adds all command classes to bot."""
|
||||
bot.add_cog(CreateCog(bot))
|
||||
bot.add_cog(DeleteCog())
|
||||
bot.add_cog(GetCog())
|
||||
bot.add_cog(HelpCog())
|
||||
bot.add_cog(RefreshCog(bot))
|
||||
bot.add_cog(SetCog())
|
||||
|
||||
+17
-15
@@ -4,8 +4,10 @@ import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import exc, select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
from database.db import Category, CategoryGroup, engine
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup
|
||||
from utilities.utils import MAX_LINE_LENGTH, autofill_groups, send_highscore_message
|
||||
|
||||
|
||||
@@ -52,30 +54,30 @@ class CreateCog(commands.Cog, name="Create Cog"):
|
||||
size (int): How many sores to show in the category message. Is SlashOption.
|
||||
"""
|
||||
new_category = Category(
|
||||
CategoryName=category_name,
|
||||
GroupId=int(group_id),
|
||||
Size=size,
|
||||
IsAscending=is_ascending,
|
||||
IsTimeRecord=is_time_record,
|
||||
IsValidated=is_validated,
|
||||
name=category_name,
|
||||
group_id=int(group_id),
|
||||
size=size,
|
||||
is_ascending=is_ascending,
|
||||
is_time_record=is_time_record,
|
||||
is_validated=is_validated,
|
||||
)
|
||||
|
||||
# Open connection to engine and add new category.
|
||||
with Session(engine) as session:
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == int(group_id))
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == int(group_id))
|
||||
group = session.scalar(stmt)
|
||||
try:
|
||||
session.add(new_category)
|
||||
session.commit()
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
await interaction.response.send_message(
|
||||
f'"{category_name}" has been added to "{group.GroupName}"!', ephemeral=True
|
||||
f'"{category_name}" has been added to "{group.name}"!', ephemeral=True
|
||||
)
|
||||
except exc.IntegrityError:
|
||||
# Category name already exists in group
|
||||
session.rollback()
|
||||
await interaction.response.send_message(
|
||||
f'"{category_name}" already exists in "{group.GroupName}". Please rename.', ephemeral=True
|
||||
f'"{category_name}" already exists in "{group.name}". Please rename.', ephemeral=True
|
||||
)
|
||||
|
||||
@create.subcommand(description="Create a new Category Group. Must not exist already for Guild.")
|
||||
@@ -123,11 +125,11 @@ class CreateCog(commands.Cog, name="Create Cog"):
|
||||
channel_id: int = channel.id
|
||||
|
||||
new_group = CategoryGroup(
|
||||
GroupName=group_name,
|
||||
ChannelId=channel_id,
|
||||
GuildId=interaction.guild_id,
|
||||
PadLength=pad_length,
|
||||
UsernameLength=username_length,
|
||||
name=group_name,
|
||||
channel_id=channel_id,
|
||||
guild_id=interaction.guild_id,
|
||||
pad_length=pad_length,
|
||||
username_length=username_length,
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
|
||||
+34
-26
@@ -4,9 +4,10 @@ import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import distinct, select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import Category, CategoryGroup, Score, engine
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup, Score
|
||||
from utilities.utils import (
|
||||
autofill_categories,
|
||||
autofill_groups,
|
||||
@@ -36,10 +37,9 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
async def channel_messages(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
channel: nextcord.abc.GuildChannel | None = nextcord.SlashOption(
|
||||
channel: nextcord.TextChannel | None = nextcord.SlashOption(
|
||||
description="Channel to clear of messages.",
|
||||
required=False,
|
||||
channel_types=[nextcord.ChannelType.text],
|
||||
default=None,
|
||||
),
|
||||
) -> None:
|
||||
@@ -54,13 +54,18 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
Is a SlashOption. Limited to text channels. Defaults to None.
|
||||
"""
|
||||
if not channel:
|
||||
channel = interaction.channel
|
||||
if isinstance(interaction.channel, nextcord.TextChannel):
|
||||
channel = interaction.channel
|
||||
else:
|
||||
# This should never happen.
|
||||
await interaction.response.send_message("Channel is not a text channel somehow.", ephemeral=True)
|
||||
return
|
||||
|
||||
with Session(engine) as session:
|
||||
stmt = (
|
||||
select(CategoryGroup)
|
||||
.where(CategoryGroup.GuildId == interaction.guild_id)
|
||||
.where(CategoryGroup.ChannelId == channel.id)
|
||||
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
|
||||
.where(col(CategoryGroup.channel_id) == channel.id)
|
||||
)
|
||||
# TODO test when nothing in channel
|
||||
groups = session.scalars(stmt)
|
||||
@@ -68,12 +73,13 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
await interaction.response.defer(ephemeral=True)
|
||||
|
||||
for group in groups:
|
||||
try:
|
||||
message: nextcord.Message = await channel.fetch_message(group.MessageId)
|
||||
await message.delete()
|
||||
except nextcord.NotFound:
|
||||
# silently ignore that messages are not found. They got deleted already.
|
||||
pass
|
||||
if group.message_id is not None:
|
||||
try:
|
||||
message: nextcord.Message = await channel.fetch_message(group.message_id)
|
||||
await message.delete()
|
||||
except nextcord.NotFound:
|
||||
# silently ignore that messages are not found. They got deleted already.
|
||||
pass
|
||||
|
||||
await interaction.send("Highscore messages deleted.", ephemeral=True)
|
||||
|
||||
@@ -97,24 +103,24 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
user_name (str): User to remove from highscores
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = select(distinct(Score.CategoryId)).where(Score.UserName == user_name)
|
||||
stmt = select(distinct(col(Score.category_id))).where(col(Score.username) == user_name)
|
||||
category_ids: list[int] = list(session.scalars(stmt))
|
||||
|
||||
stmt = select(Score).where(Score.UserName == user_name)
|
||||
stmt = select(Score).where(col(Score.username) == user_name)
|
||||
for score in session.scalars(stmt):
|
||||
session.delete(score)
|
||||
session.commit()
|
||||
|
||||
group_ids = select(Category.GroupId).where(Category.CategoryId.in_(category_ids))
|
||||
group_ids = select(col(Category.group_id)).where(col(Category.id).in_(category_ids))
|
||||
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GroupId.in_(group_ids))
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id).in_(group_ids))
|
||||
|
||||
for group in session.scalars(stmt):
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
|
||||
await interaction.send(f'User "{user_name}" was removed from all Category Groups.', ephemeral=True)
|
||||
|
||||
@delete.subcommand(description="Delete a category from a group. Deletion is perminant.")
|
||||
@delete.subcommand(description="Delete a category from a group. Deletion is permanent.")
|
||||
async def category(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
@@ -133,7 +139,7 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
DeleteConfirmView(custom_id=create_delete_id(int(group_id), int(category_id)))
|
||||
)
|
||||
|
||||
@delete.subcommand(description="Delete a group. Deletion is perminant.")
|
||||
@delete.subcommand(description="Delete a group. Deletion is permanent.")
|
||||
async def group(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
@@ -172,13 +178,15 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
user_name (str): The user to remove. Is SlashOption.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == int(group_id))
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == int(group_id))
|
||||
group = session.scalar(stmt)
|
||||
|
||||
stmt = select(Category.CategoryName).where(Category.CategoryId == int(category_id))
|
||||
stmt = select(col(Category.name)).where(col(Category.id) == int(category_id))
|
||||
category_name = session.scalar(stmt)
|
||||
|
||||
stmt = select(Score).where(Score.CategoryId == int(category_id)).where(Score.UserName == user_name)
|
||||
stmt = (
|
||||
select(Score).where(col(Score.category_id) == int(category_id)).where(col(Score.username) == user_name)
|
||||
)
|
||||
|
||||
# there should only be one because category id and username are a composite primary key in score
|
||||
session.delete(session.scalar(stmt))
|
||||
@@ -205,10 +213,10 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
user_name (str): The user to remove. Is SlashOption.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == int(group_id))
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == int(group_id))
|
||||
group = session.scalar(stmt)
|
||||
category_ids = select(Category.CategoryId).where(Category.GroupId == int(group_id))
|
||||
stmt = select(Score).where(Score.CategoryId.in_(category_ids)).where(Score.UserName == user_name)
|
||||
category_ids = select(col(Category.id)).where(col(Category.group_id) == int(group_id))
|
||||
stmt = select(Score).where(col(Score.category_id).in_(category_ids)).where(col(Score.username) == user_name)
|
||||
|
||||
for score in session.scalars(stmt):
|
||||
session.delete(score)
|
||||
@@ -216,7 +224,7 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
|
||||
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
await interaction.response.send_message(
|
||||
f'User "{user_name}" removed from all categories in {group.GroupName}.', ephemeral=True
|
||||
f'User "{user_name}" removed from all categories in {group.name}.', ephemeral=True
|
||||
)
|
||||
|
||||
@from_category.on_autocomplete("group_id")
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Get command hierarchy."""
|
||||
|
||||
import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlmodel import Session, col, select
|
||||
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup
|
||||
from utilities.utils import autofill_categories, autofill_groups
|
||||
|
||||
|
||||
class GetCog(commands.Cog, name="Get command."):
|
||||
"""Class holds commands for setting variables in guild's database."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""Default constructor for SetCog class. Does nothing."""
|
||||
|
||||
@nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
|
||||
async def get(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash command for getting. Never called."""
|
||||
|
||||
@get.subcommand(description="Commands for getting category information.")
|
||||
async def category(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash subcommand for getting category information. Never called."""
|
||||
|
||||
@category.subcommand(description="Get whether a category is sorted in ascending or descending order.")
|
||||
async def is_ascending(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
category_id: str = nextcord.SlashOption(
|
||||
name="category", description="Category to information from.", required=True
|
||||
),
|
||||
) -> None:
|
||||
"""
|
||||
Command to view how a category is sorted.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id get information from. Is SlashOption.
|
||||
category_id (str): String representation of Category id to get information from. Is SlashOption.
|
||||
"""
|
||||
stmt = (
|
||||
select(Category).where(col(Category.group_id) == int(group_id)).where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group or Category was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await interaction.response.send_message(
|
||||
f"**{category.name}** is sorted in **{'ascending' if category.is_ascending else 'descending'}** order.",
|
||||
ephemeral=True,
|
||||
)
|
||||
|
||||
@category.subcommand(description="Get whether a category required validation.")
|
||||
async def is_validated(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
category_id: str = nextcord.SlashOption(
|
||||
name="category", description="Category to information from.", required=True
|
||||
),
|
||||
) -> None:
|
||||
"""
|
||||
Command to view if a category required photo validation.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id get information from. Is SlashOption.
|
||||
category_id (str): String representation of Category id to get information from. Is SlashOption.
|
||||
"""
|
||||
stmt = (
|
||||
select(Category).where(col(Category.group_id) == int(group_id)).where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group or Category was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await interaction.response.send_message(
|
||||
f"{category.name} does {'not ' if not category.is_validated else ''} require validation.",
|
||||
ephemeral=True,
|
||||
)
|
||||
|
||||
@category.subcommand(description="Get the size for a category.")
|
||||
async def size(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
category_id: str = nextcord.SlashOption(name="category", description="Category to get size of.", required=True),
|
||||
) -> None:
|
||||
"""
|
||||
Command to view a category's size.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id get information from. Is SlashOption.
|
||||
category_id (str): String representation of Category id to get information from. Is SlashOption.
|
||||
"""
|
||||
stmt = (
|
||||
select(Category).where(col(Category.group_id) == int(group_id)).where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group or Category was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await interaction.response.send_message(
|
||||
f"**{category.name}** has a size of **{category.size}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@get.subcommand(description="Commands for getting group information.")
|
||||
async def group(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash subcommand for getting group information. Never called."""
|
||||
|
||||
@group.subcommand(description="Get the pad length of a group.")
|
||||
async def pad_length(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group to get pad length of.", required=True),
|
||||
) -> None:
|
||||
"""
|
||||
Command to view a group's pad length.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id get information from. Is SlashOption.
|
||||
"""
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == int(group_id))
|
||||
|
||||
with Session(engine) as session:
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await interaction.response.send_message(
|
||||
f"**{group.name}** has a pad length of **{group.pad_length}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@group.subcommand(description="Get the username length of a group.")
|
||||
async def username_length(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(
|
||||
name="group", description="Group to get username length of.", required=True
|
||||
),
|
||||
) -> None:
|
||||
"""
|
||||
Command to view a group's username length.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id get information from. Is SlashOption.
|
||||
"""
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == int(group_id))
|
||||
|
||||
with Session(engine) as session:
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await interaction.response.send_message(
|
||||
f"**{group.name}** has a username length of **{group.username_length}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@is_ascending.on_autocomplete("category_id")
|
||||
@is_validated.on_autocomplete("category_id")
|
||||
@size.on_autocomplete("category_id")
|
||||
async def category_autocomplete(self, interaction: nextcord.Interaction, category_id: str, group_id: str) -> None:
|
||||
"""
|
||||
Autocomplete function for category names.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
category_id (str): String to be autocompleted with Category name.
|
||||
group_id (str): Group to find Category from.
|
||||
"""
|
||||
await interaction.response.send_autocomplete(
|
||||
autofill_categories(interaction.guild_id, int(group_id), category_id)
|
||||
)
|
||||
|
||||
@is_ascending.on_autocomplete("group_id")
|
||||
@is_validated.on_autocomplete("group_id")
|
||||
@pad_length.on_autocomplete("group_id")
|
||||
@size.on_autocomplete("group_id")
|
||||
@username_length.on_autocomplete("group_id")
|
||||
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str) -> None:
|
||||
"""
|
||||
Sends results from autofill_groups back to group_output_channel for autocompletion of group_id.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction with command.
|
||||
group_id (str): String to run autocompletion against.
|
||||
"""
|
||||
await interaction.response.send_autocomplete(autofill_groups(interaction.guild_id, group_id))
|
||||
@@ -11,7 +11,7 @@ class HelpCog(commands.Cog, name="Help commands."):
|
||||
"""Default constructor for HelpCog class. Does nothing."""
|
||||
|
||||
@nextcord.slash_command()
|
||||
async def help(self, interaction: nextcord.Interaction):
|
||||
async def help(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash command for help. Never called."""
|
||||
|
||||
@help.subcommand(description="Describes how to get started with Agon.")
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
"""
|
||||
Commands for refreshing highscore messages.
|
||||
"""
|
||||
"""Commands for refreshing highscore messages."""
|
||||
|
||||
import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import CategoryGroup, engine
|
||||
from database.db import engine
|
||||
from database.models import CategoryGroup
|
||||
from utilities.utils import autofill_groups, send_highscore_message
|
||||
|
||||
|
||||
@@ -44,13 +43,13 @@ class RefreshCog(commands.Cog, name="Refresh Cog"):
|
||||
with Session(engine) as session:
|
||||
stmt = (
|
||||
select(CategoryGroup)
|
||||
.where(CategoryGroup.GuildId == interaction.guild_id)
|
||||
.where(CategoryGroup.GroupId == int(group_id))
|
||||
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
|
||||
.where(col(CategoryGroup.id) == int(group_id))
|
||||
)
|
||||
group = session.scalar(stmt)
|
||||
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
await interaction.response.send_message(f"Updated group {group.GroupName}!", ephemeral=True)
|
||||
await interaction.response.send_message(f"Updated group {group.name}!", ephemeral=True)
|
||||
|
||||
@refresh.subcommand()
|
||||
async def all(self, interaction: nextcord.Interaction) -> None:
|
||||
@@ -68,7 +67,7 @@ class RefreshCog(commands.Cog, name="Refresh Cog"):
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GuildId == interaction.guild_id)
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.guild_id) == interaction.guild_id)
|
||||
|
||||
# awaiting response because posting scores takes a while
|
||||
await interaction.response.defer(ephemeral=True)
|
||||
|
||||
+294
-59
@@ -1,40 +1,240 @@
|
||||
"""
|
||||
Set command heirarchy.
|
||||
"""
|
||||
"""Set command hierarchy."""
|
||||
|
||||
import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import CategoryGroup, Guild, engine
|
||||
from utilities.utils import MAX_LINE_LENGTH, autofill_groups
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup, Guild
|
||||
from utilities.logger import agon_logger
|
||||
from utilities.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, send_highscore_message
|
||||
|
||||
|
||||
class SetCog(commands.Cog, name="Set command."):
|
||||
"""
|
||||
Class holds commands for setting variables in guild's database.
|
||||
"""
|
||||
"""Class holds commands for setting variables in guild's database."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
"""
|
||||
Default constructor for SetCog class. Does nothing.
|
||||
"""
|
||||
"""Default constructor for SetCog class. Does nothing."""
|
||||
|
||||
@nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
|
||||
async def set(self, interaction: nextcord.Interaction):
|
||||
"""
|
||||
Parent slash command for setting settings. Never called.
|
||||
"""
|
||||
async def set(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash command for setting settings. Never called."""
|
||||
|
||||
@set.subcommand(description="Registers the channel for a Category Group's messages.")
|
||||
async def group_output_channel(
|
||||
@set.subcommand(description="Commands for editing a category.")
|
||||
async def category(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash subcommand for setting category settings. Never called."""
|
||||
|
||||
@category.subcommand(description="Update the number of entries to show for a category.", name="size")
|
||||
async def category_size(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(
|
||||
name="group", description="Category Group to assign to channel.", required=True
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
category_id: str = nextcord.SlashOption(
|
||||
name="category", description="Category to update size of.", required=True
|
||||
),
|
||||
size: int = nextcord.SlashOption(description="Number of entries to show for the category.", required=True),
|
||||
) -> None:
|
||||
"""
|
||||
Command to update a category's size.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id to register channel to. Is SlashOption.
|
||||
category_id (str): String representation of Category id to register channel to. Is SlashOption.
|
||||
size (int): Size to set. Is SlashOption.
|
||||
"""
|
||||
stmt = (
|
||||
select(Category).where(col(Category.group_id) == int(group_id)).where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Category or Group was not found.", ephemeral=True)
|
||||
return
|
||||
category.size = size
|
||||
session.commit()
|
||||
|
||||
# Use the relationship to get group category is in.
|
||||
if (group := category.category_group) is None:
|
||||
agon_logger.warning(f"{category.name}:{category.id} group relationship was None.")
|
||||
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == group_id)
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
await interaction.response.send_message(
|
||||
f"**{category.name}** size has been updated to **{size}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@category.subcommand(description="Update the is_ascending value for a category.")
|
||||
async def is_ascending(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
category_id: str = nextcord.SlashOption(
|
||||
name="category", description="Category to update is_ascending of.", required=True
|
||||
),
|
||||
ascending: bool = nextcord.SlashOption( # noqa: FBT001
|
||||
description="Whether the scores are sorted ascending or not.", required=True
|
||||
),
|
||||
) -> None:
|
||||
"""
|
||||
Command to update a category's is_ascending boolean.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id to register channel to. Is SlashOption.
|
||||
category_id (str): String representation of Category id to register channel to. Is SlashOption.
|
||||
ascending (bool): Boolean to set. Determines whether scores are sorted ascending or not. Is SlashOption.
|
||||
"""
|
||||
stmt = (
|
||||
select(Category).where(col(Category.group_id) == int(group_id)).where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Category or Group was not found.", ephemeral=True)
|
||||
return
|
||||
category.is_ascending = ascending
|
||||
session.commit()
|
||||
|
||||
# Use the relationship to get group category is in.
|
||||
if (group := category.category_group) is None:
|
||||
agon_logger.warning(f"{category.name}:{category.id} group relationship was None.")
|
||||
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == group_id)
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
await interaction.response.send_message(
|
||||
f"**{category.name}** is_ascending has been updated to **{ascending}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@category.subcommand(description="Update the is_validated value for a category.")
|
||||
async def is_validated(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
category_id: str = nextcord.SlashOption(
|
||||
name="category", description="Category to update is_ascending of.", required=True
|
||||
),
|
||||
validated: bool = nextcord.SlashOption( # noqa: FBT001
|
||||
description="Whether the scores need to be validated.", required=True
|
||||
),
|
||||
) -> None:
|
||||
"""
|
||||
Command to update a category's is_validated boolean.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id to register channel to. Is SlashOption.
|
||||
category_id (str): String representation of Category id to register channel to. Is SlashOption.
|
||||
validated (bool): Boolean to set. Determines whether scores are validated or not. Is SlashOption.
|
||||
"""
|
||||
stmt = (
|
||||
select(Category).where(col(Category.group_id) == int(group_id)).where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Category or Group was not found.", ephemeral=True)
|
||||
return
|
||||
category.is_validated = validated
|
||||
session.commit()
|
||||
|
||||
await interaction.response.send_message(
|
||||
f"**{category.name}** is_validated has been updated to **{validated}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@category.subcommand(name="name", description="Change the name of a category.")
|
||||
async def category_name(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
category_id: str = nextcord.SlashOption(
|
||||
name="category", description="Category to update the name of.", required=True
|
||||
),
|
||||
name: str = nextcord.SlashOption(description="Name to update to.", required=True, min_length=1, max_length=30),
|
||||
) -> None:
|
||||
"""
|
||||
Command to update a category's name.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id to register channel to. Is SlashOption.
|
||||
category_id (str): String representation of Category id to register channel to. Is SlashOption.
|
||||
name (str): The name to update the category's name to. Is SlashOption.
|
||||
"""
|
||||
stmt = (
|
||||
select(Category).where(col(Category.group_id) == int(group_id)).where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
with Session(engine) as session:
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Category or Group was not found.", ephemeral=True)
|
||||
return
|
||||
old_name = category.name
|
||||
category.name = name
|
||||
session.commit()
|
||||
|
||||
# Use the relationship to get group category is in.
|
||||
if (group := category.category_group) is None:
|
||||
agon_logger.warning(f"{category.name}:{category.id} group relationship was None.")
|
||||
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == group_id)
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
await interaction.response.send_message(
|
||||
f"**{old_name}** has been updated to **{category.name}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@set.subcommand(description="Commands for editing a group.")
|
||||
async def group(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash subcommand for setting group settings. Never called."""
|
||||
|
||||
@group.subcommand(name="name", description="Change the name of a Group.")
|
||||
async def group_name(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group that Category is in.", required=True),
|
||||
name: str = nextcord.SlashOption(description="Name to update to.", required=True, min_length=1, max_length=50),
|
||||
) -> None:
|
||||
"""
|
||||
Command to update a group's name.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id to register channel to. Is SlashOption.
|
||||
name (str): The name to update the group's name to. Is SlashOption.
|
||||
"""
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == int(group_id))
|
||||
|
||||
with Session(engine) as session:
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group was not found.", ephemeral=True)
|
||||
return
|
||||
old_name = group.name
|
||||
group.name = name
|
||||
# session.add(group) test if this is needed. SQLAlchemy can do the update without adding.
|
||||
session.commit()
|
||||
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
await interaction.response.send_message(f"**{old_name}** has been updated to **{group.name}**.", ephemeral=True)
|
||||
|
||||
@group.subcommand(description="Registers the channel for a Group's messages.")
|
||||
async def output_channel(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group to assign to channel.", required=True),
|
||||
channel: nextcord.abc.GuildChannel | None = nextcord.SlashOption(
|
||||
description="Channel to register",
|
||||
required=False,
|
||||
@@ -48,32 +248,34 @@ class SetCog(commands.Cog, name="Set command."):
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
group_id (str): String representation of Group id to register channel to. Is SlashOption.
|
||||
channel (nextcord.abc.GuildChannel, optional): Channel to register
|
||||
channel (nextcord.abc.GuildChannel, optional): Channel to register.
|
||||
Is a SlashOption. Limited to text channels, Defaults to None.
|
||||
"""
|
||||
if not channel:
|
||||
channel = interaction.channel
|
||||
channel_id = channel.id
|
||||
channel_id = interaction.channel.id if not channel else channel.id
|
||||
|
||||
with Session(engine) as session:
|
||||
stmt = (
|
||||
select(CategoryGroup)
|
||||
.where(CategoryGroup.GuildId == interaction.guild_id)
|
||||
.where(CategoryGroup.GroupId == int(group_id))
|
||||
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
|
||||
.where(col(CategoryGroup.id) == int(group_id))
|
||||
)
|
||||
group = session.scalar(stmt)
|
||||
group.ChannelId = channel_id
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group or Category was not found.", ephemeral=True)
|
||||
return
|
||||
group.channel_id = channel_id
|
||||
session.commit()
|
||||
# TODO(imcompiling): delete the message and call send_highscore_message to send a new one. Bug needs fixed
|
||||
# first.
|
||||
# 082
|
||||
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
|
||||
|
||||
@set.subcommand(
|
||||
@group.subcommand(
|
||||
description="Set character length for a category. Can cut off username/score. Affects all categories."
|
||||
)
|
||||
async def pad_length(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(
|
||||
name="group", description="Category Group to assign pad length to.", required=True
|
||||
),
|
||||
group_id: str = nextcord.SlashOption(name="group", description="Group to assign pad length to.", required=True),
|
||||
length: int = nextcord.SlashOption(
|
||||
description="Number of characters alloted to a category.",
|
||||
required=True,
|
||||
@@ -93,17 +295,21 @@ class SetCog(commands.Cog, name="Set command."):
|
||||
with Session(engine) as session:
|
||||
stmt = (
|
||||
select(CategoryGroup)
|
||||
.where(CategoryGroup.GuildId == interaction.guild_id)
|
||||
.where(CategoryGroup.GroupId == int(group_id))
|
||||
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
|
||||
.where(col(CategoryGroup.id) == int(group_id))
|
||||
)
|
||||
group = session.scalar(stmt)
|
||||
group.PadLength = length
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
group.pad_length = length
|
||||
session.commit()
|
||||
await interaction.response.send_message(
|
||||
f"Category pad length set to {length} for {group.GroupName}", ephemeral=True
|
||||
f"Category pad length set to **{length}** for **{group.name}**.", ephemeral=True
|
||||
)
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
|
||||
@set.subcommand(
|
||||
@group.subcommand(
|
||||
description="Registers the channel for submission messages. Currently this information is deprecated."
|
||||
)
|
||||
async def submission_channel(
|
||||
@@ -121,21 +327,21 @@ class SetCog(commands.Cog, name="Set command."):
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command
|
||||
channel Optional[nextcord.abc.GuildChannel], optional): Channel to register
|
||||
channel (nextcord.abc.GuildChannel): Channel to register
|
||||
Is a SlashOption. Limited to text channels, Defaults to None.
|
||||
"""
|
||||
if not channel:
|
||||
channel = interaction.channel
|
||||
channel_id = interaction.channel.id if not channel else channel.id
|
||||
|
||||
with Session(engine) as session:
|
||||
channel_id = channel.id
|
||||
stmt = select(Guild).where(Guild.GuildId == interaction.guild_id)
|
||||
guild = session.scalar(stmt)
|
||||
guild.SubmissionChannel = channel_id
|
||||
stmt = select(Guild).where(col(Guild.id) == interaction.guild_id)
|
||||
if (guild := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Guild was not found.", ephemeral=True)
|
||||
return
|
||||
guild.submission_channel = channel_id
|
||||
session.commit()
|
||||
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
|
||||
|
||||
@set.subcommand(description="Set username length for a Group of Categories.")
|
||||
@group.subcommand(description="Set username length for a Group of Categories.")
|
||||
async def username_length(
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
@@ -151,18 +357,24 @@ class SetCog(commands.Cog, name="Set command."):
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command
|
||||
group_id (str): String representation of Group id to set username length in. Is SlashOption.
|
||||
length (int): Number of characters. Is SlashOption. Defaults to 12.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = (
|
||||
select(CategoryGroup)
|
||||
.where(CategoryGroup.GuildId == interaction.guild_id)
|
||||
.where(CategoryGroup.GroupId == int(group_id))
|
||||
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
|
||||
.where(col(CategoryGroup.id) == int(group_id))
|
||||
)
|
||||
group = session.scalar(stmt)
|
||||
group.UsernameLength = length
|
||||
if (group := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Group or Category was not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
group.username_length = length
|
||||
session.commit()
|
||||
await interaction.response.send_message(f"Username length set to {length}.", ephemeral=True)
|
||||
await interaction.response.send_message(
|
||||
f"Username length for **{group.name}** set to **{length}**.", ephemeral=True
|
||||
)
|
||||
|
||||
@set.subcommand(description="Registers the channel for verification messages.")
|
||||
async def verify_channel(
|
||||
@@ -183,20 +395,43 @@ class SetCog(commands.Cog, name="Set command."):
|
||||
channel (Optional[nextcord.abc.GuildChannel]): Channel to register
|
||||
Is a SlashOption. Limited to text channels, Defaults to None.
|
||||
"""
|
||||
if not channel:
|
||||
channel = interaction.channel
|
||||
channel_id = channel.id
|
||||
channel_id = interaction.channel.id if not channel else channel.id
|
||||
|
||||
with Session(engine) as session:
|
||||
stmt = select(Guild).where(Guild.GuildId == interaction.guild_id)
|
||||
guild = session.scalar(stmt)
|
||||
guild.VerificationChannel = channel_id
|
||||
stmt = select(Guild).where(col(Guild.id) == interaction.guild_id)
|
||||
if (guild := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Guild was not found.", ephemeral=True)
|
||||
return
|
||||
guild.verification_channel = channel_id
|
||||
session.commit()
|
||||
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
|
||||
|
||||
@group_output_channel.on_autocomplete("group_id")
|
||||
@category_name.on_autocomplete("category_id")
|
||||
@category_size.on_autocomplete("category_id")
|
||||
@is_ascending.on_autocomplete("category_id")
|
||||
@is_validated.on_autocomplete("category_id")
|
||||
async def category_autocomplete(self, interaction: nextcord.Interaction, category_id: str, group_id: str) -> None:
|
||||
"""
|
||||
Autocomplete function for category names.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command.
|
||||
category_id (str): String to be autocompleted with Category name.
|
||||
group_id (str): Group to find Category from.
|
||||
"""
|
||||
await interaction.response.send_autocomplete(
|
||||
autofill_categories(interaction.guild_id, int(group_id), category_id)
|
||||
)
|
||||
|
||||
@category_name.on_autocomplete("group_id")
|
||||
@category_size.on_autocomplete("group_id")
|
||||
@group_name.on_autocomplete("group_id")
|
||||
@is_ascending.on_autocomplete("group_id")
|
||||
@is_validated.on_autocomplete("group_id")
|
||||
@output_channel.on_autocomplete("group_id")
|
||||
@pad_length.on_autocomplete("group_id")
|
||||
@username_length.on_autocomplete("group_id")
|
||||
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str):
|
||||
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str) -> None:
|
||||
"""
|
||||
Sends results from autofill_groups back to group_output_channel for autocompletion of group_id.
|
||||
|
||||
|
||||
+40
-30
@@ -6,10 +6,12 @@ import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
from cogs.submission.verification_view import VerificationView
|
||||
from database.db import Category, CategoryGroup, Guild, Submission, engine
|
||||
from main import logger
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup, Guild, Submission
|
||||
from main import agon_logger
|
||||
from utilities.utils import autofill_categories, autofill_groups, submit_score
|
||||
|
||||
|
||||
@@ -19,8 +21,10 @@ class SubmissionCog(commands.Cog):
|
||||
def __init__(self) -> None:
|
||||
return
|
||||
|
||||
# TODO(imcompiling): fix too many return statements when reworking command.
|
||||
# https://gitea.cheezers.org/imcompiling/agon/issues/76
|
||||
@nextcord.slash_command()
|
||||
async def submit( # noqa: PLR0913
|
||||
async def submit( # noqa: PLR0911, PLR0913
|
||||
self,
|
||||
interaction: nextcord.Interaction,
|
||||
group_id: str = nextcord.SlashOption(name="group", required=True, description="Group to submit score to."),
|
||||
@@ -56,46 +60,52 @@ class SubmissionCog(commands.Cog):
|
||||
|
||||
with Session(engine) as session:
|
||||
stmt = (
|
||||
select(Category).where(Category.GroupId == int(group_id)).where(Category.CategoryId == int(category_id))
|
||||
select(Category)
|
||||
.where(col(Category.group_id) == int(group_id))
|
||||
.where(col(Category.id) == int(category_id))
|
||||
)
|
||||
|
||||
category: Category = session.scalar(stmt)
|
||||
if (category := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Category not found.", ephemeral=True)
|
||||
return
|
||||
|
||||
# check if verification is required. if no picture, deny
|
||||
if category.IsValidated and proof is None:
|
||||
if category.is_validated and proof is None:
|
||||
await interaction.response.send_message(
|
||||
"This category required verification. Please attach a picture and re-submit.", ephemeral=True
|
||||
)
|
||||
return
|
||||
|
||||
# check with regex if score is in correct format
|
||||
verified_score = await self.verify_score(interaction, score, is_time_record=category.IsTimeRecord)
|
||||
|
||||
# check if verify_score was successful. It replies with corrections required itself.
|
||||
if verified_score is None:
|
||||
if (
|
||||
verified_score := await self.verify_score(interaction, score, is_time_record=category.is_time_record)
|
||||
) is None:
|
||||
# This response message will be filled out better once command is split up to
|
||||
# know which type it expects...
|
||||
await interaction.response.send_message("Format was incorrect.", ephemeral=True)
|
||||
return
|
||||
|
||||
# Create submission verification request or submit score if verification not needed.
|
||||
if not category.IsValidated:
|
||||
if not category.is_validated:
|
||||
await submit_score(interaction, int(group_id), int(category_id), username, verified_score)
|
||||
await interaction.response.send_message("Score has been submitted!", ephemeral=True)
|
||||
return
|
||||
|
||||
stmt = select(Guild).where(Guild.GuildId == interaction.guild_id)
|
||||
verification_channel_id: int = session.scalar(stmt).VerificationChannel
|
||||
stmt = select(col(Guild.verification_channel)).where(col(Guild.id) == interaction.guild_id)
|
||||
|
||||
channel = interaction.guild.get_channel(verification_channel_id)
|
||||
if (verification_channel_id := session.scalar(stmt)) is None:
|
||||
error_response = "No verification channel was registered. Contact server admins."
|
||||
await interaction.response.send_message(error_response, ephemeral=True)
|
||||
return
|
||||
|
||||
if channel is None:
|
||||
error_response = (
|
||||
"Registered Verification channel does not exist or was never registered. Contact server admins."
|
||||
)
|
||||
if (channel := interaction.guild.get_channel(verification_channel_id)) is None:
|
||||
error_response = "Registered Verification channel does not exist. Contact server admins."
|
||||
await interaction.response.send_message(error_response, ephemeral=True)
|
||||
return
|
||||
|
||||
if not isinstance(channel, nextcord.TextChannel):
|
||||
await interaction.response.send_message("An error happened with submission.")
|
||||
logger.error(
|
||||
agon_logger.error(
|
||||
"Channel id %s in guild %s is does not correspond to a TextChannel.", channel.id, channel.guild.id
|
||||
)
|
||||
return
|
||||
@@ -111,13 +121,13 @@ class SubmissionCog(commands.Cog):
|
||||
|
||||
# Save the submission data for later use.
|
||||
submission: Submission = Submission(
|
||||
CategoryId=category_id,
|
||||
GroupId=group_id,
|
||||
GuildId=interaction.guild_id,
|
||||
MessageId=verification_message.id,
|
||||
Score=verified_score,
|
||||
UserId=interaction.user.id,
|
||||
UserName=username,
|
||||
category_id=int(category_id),
|
||||
group_id=int(group_id),
|
||||
guild_id=interaction.guild_id,
|
||||
message_id=verification_message.id,
|
||||
score=verified_score,
|
||||
user_id=interaction.user.id,
|
||||
username=username,
|
||||
)
|
||||
|
||||
session.add(submission)
|
||||
@@ -151,15 +161,15 @@ class SubmissionCog(commands.Cog):
|
||||
|
||||
# Get group name from database
|
||||
stmt = (
|
||||
select(CategoryGroup.GroupName)
|
||||
.where(CategoryGroup.GuildId == interaction.guild_id)
|
||||
.where(CategoryGroup.GroupId == group_id)
|
||||
select(col(CategoryGroup.name))
|
||||
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
|
||||
.where(col(CategoryGroup.id) == group_id)
|
||||
)
|
||||
embed.add_field(name="Group", value=session.scalar(stmt), inline=False)
|
||||
|
||||
# Get category name from database
|
||||
stmt = (
|
||||
select(Category.CategoryName).where(Category.GroupId == group_id).where(Category.CategoryId == category_id)
|
||||
select(col(Category.name)).where(col(Category.group_id) == group_id).where(col(Category.id) == category_id)
|
||||
)
|
||||
embed.add_field(name="Category", value=session.scalar(stmt), inline=False)
|
||||
embed.add_field(name="Score", value=score, inline=False)
|
||||
|
||||
+20
-22
@@ -1,23 +1,20 @@
|
||||
"""
|
||||
Commands for updating information/variables held in database.
|
||||
"""
|
||||
"""Commands for updating information/variables held in database."""
|
||||
|
||||
import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import Guild, engine
|
||||
from database.db import engine
|
||||
from database.models import Guild
|
||||
from utilities.utils import autofill_users_in_guild
|
||||
|
||||
from .views.update_username_verify import UpdateUsernameVerifyView
|
||||
|
||||
|
||||
class UpdateCog(commands.Cog, name="Update commands."):
|
||||
"""
|
||||
Class holds commands and views needed for updating things in bot.
|
||||
"""
|
||||
"""Class holds commands and views needed for updating things in bot."""
|
||||
|
||||
def __init__(self, bot: commands.Bot):
|
||||
"""
|
||||
@@ -29,17 +26,13 @@ class UpdateCog(commands.Cog, name="Update commands."):
|
||||
self._bot: commands.Bot = bot
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
"""
|
||||
Called when cog is loaded. Adds views required for DataManagement commands.
|
||||
"""
|
||||
async def on_ready(self) -> None:
|
||||
"""Called when cog is loaded. Adds views required for DataManagement commands."""
|
||||
self._bot.add_view(UpdateUsernameVerifyView())
|
||||
|
||||
@nextcord.slash_command()
|
||||
async def update(self, interaction: nextcord.Interaction):
|
||||
"""
|
||||
Parent slash command for updating things. Never called.
|
||||
"""
|
||||
async def update(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Parent slash command for updating things. Never called."""
|
||||
|
||||
@update.subcommand(description="Request a username update. Admins must approve.")
|
||||
async def username(
|
||||
@@ -47,10 +40,11 @@ class UpdateCog(commands.Cog, name="Update commands."):
|
||||
interaction: nextcord.Interaction,
|
||||
old_username: str = nextcord.SlashOption(description="Username currently stored in highscores.", required=True),
|
||||
new_username: str = nextcord.SlashOption(description="Username to update to.", required=True),
|
||||
):
|
||||
) -> None:
|
||||
"""
|
||||
Creates a request to send to admins for changing a username. Uses
|
||||
UpdateUsernameVerifyView to do the work.
|
||||
Creates a request to send to admins for changing a username.
|
||||
|
||||
Uses UpdateUsernameVerifyView to do the work.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction that invoked the command
|
||||
@@ -58,9 +52,13 @@ class UpdateCog(commands.Cog, name="Update commands."):
|
||||
new_username (str): Username to replace old with.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = select(Guild.VerificationChannel).where(Guild.GuildId == interaction.guild_id)
|
||||
stmt = select(col(Guild.verification_channel)).where(col(Guild.id) == interaction.guild_id)
|
||||
verify_channel = interaction.guild.get_channel(session.scalar(stmt))
|
||||
|
||||
if not isinstance(verify_channel, nextcord.TextChannel):
|
||||
await interaction.send("Verification channel not set. Cannot process request.", ephemeral=True)
|
||||
return
|
||||
|
||||
embed: nextcord.Embed = nextcord.Embed(title="Username change request.")
|
||||
embed.add_field(name="Old Username", value=old_username)
|
||||
embed.add_field(name="New Username", value=new_username)
|
||||
@@ -72,12 +70,12 @@ class UpdateCog(commands.Cog, name="Update commands."):
|
||||
await interaction.send("Request sent to admins for verification.", ephemeral=True)
|
||||
|
||||
@username.on_autocomplete("old_username")
|
||||
async def all_users_autocomplete(self, interaction: nextcord.Interaction, username: str):
|
||||
async def all_users_autocomplete(self, interaction: nextcord.Interaction, username: str) -> None:
|
||||
"""
|
||||
Sends response from autofill_users_in_guild back to update_username for autocompletion of old_username.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): Interaction with command.
|
||||
old_username (str): String to run autocompletion against.
|
||||
username (str): String to run autocompletion against.
|
||||
"""
|
||||
await interaction.response.send_autocomplete(autofill_users_in_guild(interaction.guild_id, username))
|
||||
|
||||
@@ -5,9 +5,10 @@ import pandas as pd
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import Category, CategoryGroup, Score, engine
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup, Score
|
||||
from utilities.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, format_score_string
|
||||
|
||||
|
||||
@@ -47,17 +48,17 @@ class ViewCog(commands.Cog, name="View Command"):
|
||||
|
||||
# get group, category, and all scores sorted correctly.
|
||||
with Session(engine) as session:
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == int(group_id))
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id) == int(group_id))
|
||||
group = session.scalar(stmt)
|
||||
|
||||
stmt = select(Category).where(Category.CategoryId == int(category_id))
|
||||
stmt = select(Category).where(col(Category.id) == int(category_id))
|
||||
category = session.scalar(stmt)
|
||||
|
||||
d_f = pd.read_sql_query(
|
||||
sql=session.query(Score).where(Score.CategoryId == category_id).statement, con=engine
|
||||
sql=session.query(Score).where(col(Score.category_id) == category_id).statement, con=engine
|
||||
)
|
||||
|
||||
scores = d_f.sort_values("Score", ascending=category.IsAscending).reset_index()
|
||||
scores = d_f.sort_values("Score", ascending=category.is_ascending).reset_index()
|
||||
|
||||
# get the longest string
|
||||
longest_str: int = scores.UserName.map(len).max()
|
||||
@@ -68,13 +69,13 @@ class ViewCog(commands.Cog, name="View Command"):
|
||||
row["UserName"],
|
||||
row["Score"],
|
||||
longest_str,
|
||||
category.IsTimeRecord,
|
||||
category.is_time_record,
|
||||
i + 1, # type: ignore[reportOperatorIssue]
|
||||
MAX_LINE_LENGTH,
|
||||
)
|
||||
)
|
||||
|
||||
message_str: str = f"**{group.GroupName} {category.CategoryName} Leaderboard!**\n```"
|
||||
message_str: str = f"**{group.name} {category.name} Leaderboard!**\n```"
|
||||
if len(str_list) == 0:
|
||||
message_str += "No Submissions!"
|
||||
else:
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""Package for views used in commands."""
|
||||
@@ -1,23 +1,19 @@
|
||||
"""
|
||||
Contains view and helper functions for confirming and processing deletes.
|
||||
"""
|
||||
"""Contains view and helper functions for confirming and processing deletes."""
|
||||
|
||||
import nextcord
|
||||
from sqlalchemy import delete, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import Category, CategoryGroup, engine
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup
|
||||
from utilities.utils import send_highscore_message
|
||||
|
||||
|
||||
class DeleteConfirmView(nextcord.ui.Modal):
|
||||
"""
|
||||
View modal popup for confirming deletions.
|
||||
"""
|
||||
"""View modal popup for confirming deletions."""
|
||||
|
||||
def __init__(self, custom_id: str):
|
||||
super().__init__(title="Warning, deletion is perminant.", custom_id=custom_id)
|
||||
super().__init__(title="Warning, deletion is permanent.", custom_id=custom_id)
|
||||
|
||||
self.checker = nextcord.ui.TextInput(
|
||||
label='Type "delete" to confirm deletion.',
|
||||
@@ -27,7 +23,12 @@ class DeleteConfirmView(nextcord.ui.Modal):
|
||||
)
|
||||
self.add_item(self.checker)
|
||||
|
||||
async def callback(self, interaction: nextcord.Interaction):
|
||||
async def callback(self, interaction: nextcord.Interaction) -> None:
|
||||
"""Action for confirming deletion.
|
||||
|
||||
Args:
|
||||
interaction (nextcord.Interaction): User interaction object with the modal.
|
||||
"""
|
||||
if self.checker.value.lower() != "delete":
|
||||
await interaction.response.send_message('Response was not "delete". Canceling delete.')
|
||||
return
|
||||
@@ -35,21 +36,23 @@ class DeleteConfirmView(nextcord.ui.Modal):
|
||||
del_vals = parse_delete_id(self.custom_id)
|
||||
|
||||
with Session(engine) as session:
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == del_vals["group_id"])
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.id == del_vals["group_id"])
|
||||
group = session.scalar(stmt)
|
||||
if del_vals["category_id"] is None:
|
||||
# delete entire group
|
||||
session.delete(group)
|
||||
# delete the message related to group
|
||||
channel: nextcord.TextChannel = interaction.guild.get_channel(group.ChannelId)
|
||||
message: nextcord.Message = await channel.fetch_message(group.MessageId)
|
||||
channel = interaction.guild.get_channel(group.channel_id)
|
||||
if not isinstance(channel, nextcord.TextChannel):
|
||||
return
|
||||
message: nextcord.Message = await channel.fetch_message(group.message_id)
|
||||
await message.delete()
|
||||
|
||||
else:
|
||||
stmt = (
|
||||
delete(Category)
|
||||
.where(Category.GroupId == del_vals["group_id"])
|
||||
.where(Category.CategoryId == del_vals["category_id"])
|
||||
.where(Category.group_id == del_vals["group_id"])
|
||||
.where(Category.id == del_vals["category_id"])
|
||||
)
|
||||
session.execute(stmt)
|
||||
# update the message
|
||||
@@ -78,7 +81,7 @@ def parse_delete_id(delete_id: str) -> dict:
|
||||
Returns a dict containing the values of a delete id.
|
||||
|
||||
Args:
|
||||
id (str): the delete id
|
||||
delete_id (str): the delete id
|
||||
|
||||
Returns:
|
||||
dict: dict containing values from a delete id.
|
||||
|
||||
@@ -3,23 +3,22 @@
|
||||
import nextcord
|
||||
from sqlalchemy import distinct, exc, select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import Category, CategoryGroup, Score, engine
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup, Score
|
||||
from utilities.utils import send_highscore_message
|
||||
|
||||
|
||||
class UpdateUsernameVerifyView(nextcord.ui.View):
|
||||
"""Defines view for allowing a username update."""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
Default constructor for UpdateUsernameVerifyView. Calls super constructor with no timeout.
|
||||
"""
|
||||
def __init__(self) -> None:
|
||||
"""Default constructor for UpdateUsernameVerifyView. Calls super constructor with no timeout."""
|
||||
super().__init__(timeout=None)
|
||||
|
||||
@nextcord.ui.button(label="Deny", style=nextcord.ButtonStyle.red, custom_id="deny-username-update")
|
||||
async def deny_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction): # pylint: disable=unused-argument
|
||||
async def deny_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None: # noqa: ARG002
|
||||
"""
|
||||
Button for denying username update. Deletes message.
|
||||
|
||||
@@ -30,10 +29,11 @@ class UpdateUsernameVerifyView(nextcord.ui.View):
|
||||
await interaction.message.delete()
|
||||
|
||||
@nextcord.ui.button(label="Approve", style=nextcord.ButtonStyle.green, custom_id="approve-username-update")
|
||||
async def approve_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction): # pylint: disable=unused-argument
|
||||
async def approve_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None: # noqa: ARG002
|
||||
"""
|
||||
Button for approving username update. Tells guild data to update username, then updates
|
||||
message to show it is complete.
|
||||
Button for approving username update.
|
||||
|
||||
Tells guild data to update username, then updates message to show it is complete.
|
||||
|
||||
Args:
|
||||
button (nextcord.ui.Button): unused
|
||||
@@ -42,20 +42,20 @@ class UpdateUsernameVerifyView(nextcord.ui.View):
|
||||
with Session(engine) as session:
|
||||
try:
|
||||
embed_content = interaction.message.embeds[0].to_dict()
|
||||
old_username: str = embed_content["fields"][0]["value"]
|
||||
new_username: str = embed_content["fields"][1]["value"]
|
||||
old_username: str = embed_content["fields"][0]["value"] # type: ignore reportTypedDictNotRequiredAccess
|
||||
new_username: str = embed_content["fields"][1]["value"] # type: ignore reportTypedDictNotRequiredAccess
|
||||
|
||||
stmt = select(distinct(Score.CategoryId)).where(Score.UserName == old_username)
|
||||
stmt = select(distinct(col(Score.category_id))).where(col(Score.username) == old_username)
|
||||
category_ids: list[int] = list(session.scalars(stmt))
|
||||
|
||||
stmt = select(Score).where(Score.UserName == old_username)
|
||||
stmt = select(Score).where(col(Score.username) == old_username)
|
||||
for score in session.scalars(stmt):
|
||||
score.UserName = new_username
|
||||
session.commit()
|
||||
|
||||
group_ids = select(Category.GroupId).where(Category.CategoryId.in_(category_ids))
|
||||
group_ids = select(col(Category.group_id)).where(col(Category.id).in_(category_ids))
|
||||
|
||||
stmt = select(CategoryGroup).where(CategoryGroup.GroupId.in_(group_ids))
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.id).in_(group_ids))
|
||||
|
||||
for group in session.scalars(stmt):
|
||||
await send_highscore_message(session, interaction.guild, group)
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
"""
|
||||
Defines cog for guild listeners. Contains functions for various guild events.
|
||||
"""
|
||||
"""Defines cog for guild listeners. Contains functions for various guild events."""
|
||||
|
||||
import nextcord
|
||||
from nextcord.ext import commands
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import Guild, engine
|
||||
from database.db import engine
|
||||
from database.models import Guild
|
||||
|
||||
|
||||
class GuildListener(commands.Cog, name="Guild Listener"):
|
||||
@@ -18,7 +17,7 @@ class GuildListener(commands.Cog, name="Guild Listener"):
|
||||
self.bot = bot
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_guild_join(self, guild: nextcord.Guild):
|
||||
async def on_guild_join(self, guild: nextcord.Guild) -> None:
|
||||
"""
|
||||
Listener for Guild Join. Adds guild to database.
|
||||
|
||||
@@ -26,12 +25,11 @@ class GuildListener(commands.Cog, name="Guild Listener"):
|
||||
guild (nextcord.Guild): Guild that was joined.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = select(Guild).where(Guild.GuildId == guild.id)
|
||||
guild_data = session.scalar(stmt)
|
||||
stmt = select(Guild).where(col(Guild.id == guild.id))
|
||||
|
||||
# just in case check if the guild already exists
|
||||
if guild_data is None:
|
||||
new_guild = Guild(GuildId=guild.id, GuildName=guild.name)
|
||||
if (guild_data := session.scalar(stmt)) is None:
|
||||
new_guild = Guild(id=guild.id, name=guild.name)
|
||||
session.add(new_guild)
|
||||
else:
|
||||
guild_data.GuildName = guild.name
|
||||
@@ -45,7 +43,7 @@ class GuildListener(commands.Cog, name="Guild Listener"):
|
||||
await imcompiling.send(f'Agon has joined server "{guild.name}"!')
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_guild_remove(self, guild: nextcord.Guild):
|
||||
async def on_guild_remove(self, guild: nextcord.Guild) -> None:
|
||||
"""
|
||||
Listens to when the bot has been removed from a guild. Update's the database to record the active flag as false.
|
||||
|
||||
@@ -53,7 +51,7 @@ class GuildListener(commands.Cog, name="Guild Listener"):
|
||||
guild (nextcord.Guild): Guild that was left.
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
stmt = select(Guild).where(Guild.GuildId == guild.id)
|
||||
stmt = select(Guild).where(col(Guild.id == guild.id))
|
||||
guild_data = session.scalar(stmt)
|
||||
guild_data.Active = False
|
||||
session.commit()
|
||||
@@ -66,6 +64,6 @@ class GuildListener(commands.Cog, name="Guild Listener"):
|
||||
|
||||
# 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"""
|
||||
def setup(bot: commands.Bot) -> None:
|
||||
"""Adds function to bot."""
|
||||
bot.add_cog(GuildListener(bot))
|
||||
|
||||
@@ -13,23 +13,22 @@ class BotPresence(commands.Cog, name="Bot Presence"):
|
||||
self.bot = bot
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_guild_join(self, guild: nextcord.Guild): # pylint: disable=unused-argument
|
||||
async def on_guild_join(self, guild: nextcord.Guild) -> None: # noqa: ARG002
|
||||
"""Listener for Guild Join. Updated presence on guild join."""
|
||||
await self.change_presence()
|
||||
|
||||
@commands.Cog.listener()
|
||||
async def on_ready(self):
|
||||
async def on_ready(self) -> None:
|
||||
"""Starts the loop when bot is ready."""
|
||||
await self.bot.wait_until_ready()
|
||||
# pylint doesn't recognize that periodic_change_presense is subclassed from tasks.loop.
|
||||
self.periodic_change_presence.start() # pylint: disable=no-member
|
||||
self.periodic_change_presence.start()
|
||||
|
||||
@tasks.loop(minutes=2)
|
||||
async def periodic_change_presence(self):
|
||||
async def periodic_change_presence(self) -> None:
|
||||
"""Loops every 2 minutes and changes presence."""
|
||||
await self.change_presence()
|
||||
|
||||
async def change_presence(self):
|
||||
async def change_presence(self) -> None:
|
||||
"""Randomly chooses a presence and updates bot's presence."""
|
||||
statuses = [
|
||||
"Now with slash commands!",
|
||||
@@ -39,7 +38,7 @@ class BotPresence(commands.Cog, name="Bot Presence"):
|
||||
"That's a lot of damage!",
|
||||
]
|
||||
|
||||
status = random.choice(statuses)
|
||||
status = random.choice(statuses) # noqa: S311
|
||||
|
||||
status += f" | {len(self.bot.guilds)} servers"
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
from nextcord.ext import commands, tasks
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlmodel import col
|
||||
|
||||
from database.db import engine
|
||||
from database.models import Guild
|
||||
@@ -11,7 +12,7 @@ from database.models import Guild
|
||||
class GuildData(commands.Cog, name="Guild Data"):
|
||||
"""Class to contain loop."""
|
||||
|
||||
def __init__(self, bot: commands.bot) -> None:
|
||||
def __init__(self, bot: commands.Bot) -> None:
|
||||
self.bot = bot
|
||||
|
||||
@commands.Cog.listener()
|
||||
@@ -30,7 +31,7 @@ class GuildData(commands.Cog, name="Guild Data"):
|
||||
with Session(engine) as session:
|
||||
for guild in self.bot.guilds:
|
||||
# update given guild name for guild id
|
||||
stmt = select(Guild).where(Guild.id == guild.id)
|
||||
stmt = select(Guild).where(col(Guild.id) == guild.id)
|
||||
guild_data = session.scalar(stmt)
|
||||
|
||||
# just in case checking if the guild doesn't exist.
|
||||
@@ -38,6 +39,6 @@ class GuildData(commands.Cog, name="Guild Data"):
|
||||
new_guild = Guild(id=guild.id, name=guild.name)
|
||||
session.add(new_guild)
|
||||
else:
|
||||
guild_data.GuildName = guild.name
|
||||
guild_data.name = guild.name
|
||||
|
||||
session.commit()
|
||||
|
||||
@@ -7,8 +7,6 @@ from sqlmodel import col
|
||||
|
||||
from database.db import engine
|
||||
from database.models import Submission
|
||||
|
||||
# pylint: disable=import-error
|
||||
from utilities.utils import submit_score
|
||||
|
||||
|
||||
@@ -41,9 +39,7 @@ class VerificationView(nextcord.ui.View):
|
||||
.where(col(Submission.message_id) == interaction.message.id)
|
||||
)
|
||||
|
||||
submission = session.scalar(stmt)
|
||||
|
||||
if submission is None:
|
||||
if (submission := session.scalar(stmt)) is None:
|
||||
await interaction.response.send_message("Could not find submission data in database.", ephemeral=True)
|
||||
await interaction.message.delete()
|
||||
return
|
||||
|
||||
@@ -2,13 +2,16 @@
|
||||
|
||||
from sqlmodel import SQLModel, create_engine
|
||||
from utilities import config
|
||||
from utilities.logger import agon_logger
|
||||
|
||||
from . import models # noqa: F401 - Need this import for creating the models.
|
||||
|
||||
if config.ENVIRONMENT == "prod":
|
||||
url = f"mysql+pymysql://{config.SQL_USER}:{config.SQL_PASS}@{config.SQL_HOST}/{config.SQL_DB}"
|
||||
agon_logger.info("Connected to prod database.")
|
||||
else:
|
||||
url = "sqlite:///database.db"
|
||||
agon_logger.info("Connected to local dev database.")
|
||||
engine = create_engine(url)
|
||||
|
||||
# Don't need to create all when connected to prod.
|
||||
|
||||
+1
-1
@@ -64,7 +64,7 @@ class CategoryGroup(SQLModel, table=True):
|
||||
nullable=False,
|
||||
)
|
||||
)
|
||||
message_id: int = Field(sa_column=Column("MessageId", BIGINT(unsigned=True)))
|
||||
message_id: int | None = Field(sa_column=Column("MessageId", BIGINT(unsigned=True)), default=None)
|
||||
pad_length: int = Field(default=12, sa_column=Column("PadLength", SMALLINT(unsigned=True)))
|
||||
username_length: int = Field(default=12, sa_column=Column("UsernameLength", SMALLINT(unsigned=True)))
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ import nextcord
|
||||
from nextcord.ext import commands
|
||||
|
||||
from utilities import config
|
||||
from utilities.logger import agon_logger
|
||||
|
||||
nextcord_logger = logging.getLogger("nextcord")
|
||||
nextcord_logger.setLevel(logging.DEBUG)
|
||||
@@ -15,18 +16,12 @@ nextcord_handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8"
|
||||
nextcord_handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
|
||||
nextcord_logger.addHandler(nextcord_handler)
|
||||
|
||||
logger = logging.getLogger("default")
|
||||
logger.setLevel(logging.INFO)
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
|
||||
logger.addHandler(handler)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""Main function for bot."""
|
||||
min_python_version = (3, 12)
|
||||
if sys.version_info < min_python_version:
|
||||
logger.error("ERROR: Python version must be >= 3.12")
|
||||
agon_logger.error("ERROR: Python version must be >= 3.12")
|
||||
sys.exit()
|
||||
|
||||
# Allows privileged intents for monitoring members joining, roles editing, and role assignments
|
||||
@@ -46,9 +41,9 @@ def main() -> None:
|
||||
async def on_ready() -> None:
|
||||
"""When Discord is connected."""
|
||||
if bot.user is None:
|
||||
logger.error("Discord connection failed.")
|
||||
agon_logger.error("Discord connection failed.")
|
||||
return
|
||||
logger.info("%s has connected to Discord!", bot.user.name)
|
||||
agon_logger.info("%s has connected to Discord!", bot.user.name)
|
||||
|
||||
# Run Discord bot
|
||||
bot.run(config.DISCORD_TOKEN)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Creates logger for Agon bot."""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
agon_logger = logging.getLogger("default")
|
||||
agon_logger.setLevel(logging.INFO)
|
||||
handler = logging.StreamHandler(sys.stdout)
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
|
||||
agon_logger.addHandler(handler)
|
||||
+16
-9
@@ -8,9 +8,9 @@ from sqlalchemy import distinct, select
|
||||
from sqlalchemy.orm import Session, aliased
|
||||
from sqlmodel import col
|
||||
|
||||
# pylint: disable=import-error
|
||||
from database.db import engine
|
||||
from database.models import Category, CategoryGroup, Guild, Score
|
||||
from main import agon_logger
|
||||
|
||||
MAX_LINE_LENGTH = 142
|
||||
|
||||
@@ -65,7 +65,7 @@ def autofill_groups(guild_id: int, group_begin: str) -> "dict[str, str]":
|
||||
"""
|
||||
with Session(engine) as session:
|
||||
# Select all groups in guild.
|
||||
stmt = select(CategoryGroup).wherecol((CategoryGroup.guild_id) == guild_id)
|
||||
stmt = select(CategoryGroup).where(col(CategoryGroup.guild_id) == guild_id)
|
||||
|
||||
# dict has to have key values of same type for discord.
|
||||
group_dict: dict[str, str] = {group.name: str(group.id) for group in session.scalars(stmt)}
|
||||
@@ -276,6 +276,8 @@ def format_highscore_message(session: Session, group: CategoryGroup) -> str:
|
||||
return ret_string + "```"
|
||||
|
||||
|
||||
# TODO(imcompiling): rework into two functions to remove the boolean and reduce function arguments.
|
||||
# 084
|
||||
def format_score_string(
|
||||
username: str,
|
||||
score: float,
|
||||
@@ -328,7 +330,7 @@ def get_time_str(time_in: float) -> str:
|
||||
return time.strftime(f"%-M:%S.{milliseconds}", time.gmtime(time_in))
|
||||
|
||||
|
||||
async def send_highscore_message(session: Session, guild: nextcord.Guild, group: CategoryGroup) -> nextcord.Message:
|
||||
async def send_highscore_message(session: Session, guild: nextcord.Guild, group: CategoryGroup) -> None:
|
||||
"""
|
||||
Function takes care of checking if a message exists for a group.
|
||||
|
||||
@@ -338,23 +340,28 @@ async def send_highscore_message(session: Session, guild: nextcord.Guild, group:
|
||||
session (Session): The sqlalchemy session being used for this function call.
|
||||
guild (nextcord.Guild): the nextcord.Guild object requesting this message.
|
||||
group (CategoryGroup): group to post to the message.
|
||||
|
||||
Returns:
|
||||
nextcord.Message: Message object that was posted with group contents.
|
||||
"""
|
||||
highscore_string = format_highscore_message(session, group)
|
||||
channel = guild.get_channel(group.channel_id)
|
||||
|
||||
if not isinstance(channel, nextcord.TextChannel):
|
||||
agon_logger.error(
|
||||
"Channel id %s in guild %s is does not correspond to a TextChannel.", channel.id, channel.guild.id
|
||||
)
|
||||
return
|
||||
|
||||
if group.message_id is None:
|
||||
# message doesn't exist.
|
||||
message: nextcord.Message = await channel.send(highscore_string)
|
||||
group.MessageId = message.id
|
||||
group.message_id = message.id
|
||||
session.commit()
|
||||
else:
|
||||
# TODO(imcompiling): check what happens when message is deleted.
|
||||
# https://gitea.cheezers.org/imcompiling/agon/issues/83
|
||||
message: nextcord.Message = await channel.fetch_message(group.message_id)
|
||||
await message.edit(content=highscore_string)
|
||||
|
||||
return message
|
||||
return
|
||||
|
||||
|
||||
async def submit_score(
|
||||
@@ -391,7 +398,7 @@ async def submit_score(
|
||||
existing_score = session.scalar(stmt)
|
||||
|
||||
if existing_score:
|
||||
existing_score.Score = score_f
|
||||
existing_score.score = score_f
|
||||
else:
|
||||
score_obj = Score(username=username, score=score_f, category_id=category_id)
|
||||
session.add(score_obj)
|
||||
|
||||
Reference in New Issue
Block a user