Compare commits

...
Author SHA1 Message Date
imcompiling 12893288f8 Use get_channel_or_thread so that threads can be found.
build_develop / build (push) Successful in 38s
2025-03-21 13:48:54 -04:00
imcompiling 0540f7a9eb Add thread as an option everywhere a textchannel is used.
build_develop / build (push) Successful in 35s
2025-03-20 11:04:00 -04:00
imcompiling a4aab09360 Use or instead of two isinstance calls. 2025-03-20 10:56:59 -04:00
imcompiling d82999b141 Check for channel being None. Allow groups to be posted in threads. 2025-03-20 09:50:31 -04:00
imcompiling 1ffb7fa9a7 Correct database ignore.
build_develop / build (push) Successful in 18s
build_latest / build (push) Successful in 18s
build_release / build (push) Successful in 19s
2025-03-19 09:51:38 -04:00
imcompiling 2566bee0ce Use home dir.
build_develop / build (push) Successful in 36s
2025-03-19 09:37:32 -04:00
imcompiling 3d113a06d4 Update workflows.
build_develop / build (push) Successful in 35s
2025-03-19 09:35:21 -04:00
imcompiling 2e3b8c86da Add more to dockerignore. 2025-03-19 09:30:44 -04:00
imcompiling 058e3aefa1 Update how agon is run. 2025-03-19 09:28:30 -04:00
imcompiling 7a4ba3a5af Update all imports with new file structure. 2025-03-19 09:22:29 -04:00
imcompiling 2f5f25ea75 Remove unneede file. 2025-03-19 09:17:43 -04:00
imcompiling fd476ce512 Move files from utilities to top level of module. 2025-03-19 09:17:07 -04:00
imcompiling 9588cdc8a0 Rename main.py to app.py, add init and main dunder files. 2025-03-19 09:11:02 -04:00
imcompiling 17769022bc Move all files into agon module. 2025-03-19 09:07:39 -04:00
imcompiling a46dc0388c Delete sql file. it is unneeded now. 2025-03-19 09:07:14 -04:00
imcompiling 553f79425f Delete database/pyproject.toml
build_develop / build (push) Successful in 36s
2025-03-19 08:49:17 -04:00
imcompiling 72cd6e9fd1 Merge pull request 'Update ghcr.io/astral-sh/uv Docker tag to v0.6.6' (#87) from renovate/ghcr.io-astral-sh-uv-0.x into main
build_develop / build (push) Successful in 56s
Reviewed-on: #87
Reviewed-by: imcompiling <[email protected]>
2025-03-16 11:09:44 -04:00
renovate-bot f63984e25a Update ghcr.io/astral-sh/uv Docker tag to v0.6.6 2025-03-16 04:01:28 +00:00
imcompiling 48a91dca3d Merge branch '41-editting-commands'
build_develop / build (push) Successful in 35s
build_release / build (push) Successful in 22s
2025-03-14 17:22:03 -04:00
imcompiling 5eb637a3a8 Indent so that a command can properly use session.
Remove commented out code. Also add work to an issue.
2025-03-14 17:20:50 -04:00
imcompiling f722eb1a83 Add to get's return messages. 2025-03-14 17:05:39 -04:00
imcompiling 7759bbc648 Add to set's return messages. 2025-03-14 17:04:20 -04:00
imcompiling 65de7baeda Added some log statements to provide helpful information. 2025-03-14 16:57:38 -04:00
imcompiling e243404480 Forgot to specify that is a description. 2025-03-14 16:53:15 -04:00
imcompiling f735e6d846 Merge branch '70-sqlmodel'
build_develop / build (push) Successful in 34s
build_release / build (push) Successful in 22s
2025-03-14 16:43:28 -04:00
imcompiling 9fbaf7bcf6 Merge branch 'main' of https://gitea.cheezers.org/imcompiling/agon
build_develop / build (push) Has been cancelled
2025-03-14 16:42:48 -04:00
imcompiling 1959e11e5c Merge branch '70-sqlmodel' into 41-editting-commands 2025-03-14 16:42:33 -04:00
imcompiling c25d354fc0 Correct some parameter usage, handle errors if searches return nothing. 2025-03-14 16:09:52 -04:00
imcompiling e5d90a71d9 Correct parameter usage. 2025-03-14 16:02:18 -04:00
imcompiling 785a4eff46 Was saving the message id to the wrong spot. 2025-03-13 09:21:10 -04:00
imcompiling 627112b114 Use correct message id reference. 2025-03-13 09:21:09 -04:00
imcompiling 9b3bd9d02c Use correct variable for guild name. 2025-03-13 09:21:09 -04:00
imcompiling 2c56c614f3 Typo on col usage. 2025-03-13 09:21:09 -04:00
imcompiling 3ccaa7004e Had col around the wrong variables. 2025-03-13 09:21:08 -04:00
imcompiling 289113661f Use walrus operator when assigning and checking for None. 2025-03-13 09:21:08 -04:00
imcompiling 74ce22dd26 Was saving the message id to the wrong spot. 2025-03-13 00:39:47 -04:00
imcompiling 170ce1cbfb Use correct message id reference. 2025-03-12 21:30:56 -04:00
imcompiling e1b761e848 Use correct variable for guild name. 2025-03-12 21:29:01 -04:00
imcompiling 68592a7df8 Typo on col usage. 2025-03-12 21:27:29 -04:00
imcompiling b28938f66a Had col around the wrong variables. 2025-03-12 21:27:12 -04:00
imcompiling adab97f505 Add another TODO 2025-03-12 10:18:16 -04:00
imcompiling edf51aac2d Add a todo regarding possible bug. 2025-03-12 10:12:54 -04:00
imcompiling dbc6474fc3 send highscore message doesn't need to return the message, its never used. 2025-03-12 10:02:32 -04:00
imcompiling ed68c4174f Update send highscore message to be more robust. 2025-03-12 09:57:17 -04:00
imcompiling 3abbff13d5 Use walrus operator when assigning and checking for None. 2025-03-12 09:50:58 -04:00
imcompiling 304b089113 Use the walrus operator when assigning and checking for None. 2025-03-12 09:35:44 -04:00
imcompiling 29a163ec46 correct some sql statement usages. Wasn't matching things properly. 2025-03-11 09:37:27 -04:00
imcompiling 76fbba739f Add command to view a group's username length. 2025-03-11 09:12:54 -04:00
imcompiling 7204e882f1 Forgot to do group autocomplete. 2025-03-11 09:10:17 -04:00
imcompiling a8d775ca09 Correct some doc strings. 2025-03-11 09:05:36 -04:00
imcompiling 983b9b6f34 Add command for getting group's pad length. 2025-03-11 09:03:54 -04:00
imcompiling 84c910b19c Add get is_validated command. 2025-03-10 16:06:28 -04:00
imcompiling 1fcb25193d Add get is_ascending command and autocomplete functions. 2025-03-10 14:27:24 -04:00
imcompiling f52b2fe49f Merge pull request 'Update ghcr.io/astral-sh/uv Docker tag to v0.6.5' (#81) from renovate/ghcr.io-astral-sh-uv-0.x into main
build_develop / build (push) Successful in 48s
Reviewed-on: #81
Reviewed-by: imcompiling <[email protected]>
2025-03-10 08:40:41 -04:00
renovate-bot 24a9fa998a Update ghcr.io/astral-sh/uv Docker tag to v0.6.5 2025-03-09 05:01:04 +00:00
imcompiling 4785271ebb Add command to get a category's size. 2025-03-07 16:10:42 -05:00
imcompiling f9d765ad92 Forgot to convert some ids to int. 2025-03-07 16:09:33 -05:00
imcompiling 50868988c0 Create teh get cog, add it to init for commands. 2025-03-07 15:59:13 -05:00
imcompiling 81ae867a43 Add set group and category name commands. 2025-03-07 12:56:45 -05:00
imcompiling 2649ceb6bb Add command to edit is_validated. 2025-03-07 11:45:05 -05:00
imcompiling 6e02bc877f Only want a warning as I can get the group another way. 2025-03-07 11:40:27 -05:00
imcompiling f61ad83e11 Make commands more robust against errors. 2025-03-07 11:39:39 -05:00
imcompiling feeb47d3da Update the message when updating pad length. 2025-03-07 11:24:45 -05:00
imcompiling 0ff1b07096 Add category and group subcommand structure. 2025-03-05 15:47:01 -05:00
imcompiling 8674eed0c5 Forgot a command description. 2025-03-05 15:32:20 -05:00
imcompiling e2ddd5412a Add set is_ascending command. 2025-03-05 15:27:57 -05:00
imcompiling f37844c953 Update error message. 2025-03-05 11:05:07 -05:00
imcompiling d703c76704 Add a command to set the category size. 2025-03-05 11:02:09 -05:00
imcompiling 6e25d4e75a Move the logger into own module for importing. 2025-03-05 10:50:37 -05:00
imcompiling 0702198f0a Fix lint smells and update model usage in view. 2025-03-04 13:24:08 -05:00
imcompiling 43df7aeda7 Fix lint smells and update model usage in update. 2025-03-04 13:20:14 -05:00
imcompiling c8becb8203 Fix lint smells and update model usage in submission. 2025-03-04 13:15:20 -05:00
imcompiling 44d813504a Fix lint smells and update model usage in refresh and set. 2025-03-04 12:47:44 -05:00
imcompiling 3fc8910c9a Fix lint smell. 2025-03-04 11:19:06 -05:00
imcompiling 63db4c1dd2 Merge pull request 'Update ghcr.io/astral-sh/uv Docker tag to v0.6.3' (#79) from renovate/ghcr.io-astral-sh-uv-0.x into main
build_develop / build (push) Successful in 51s
Reviewed-on: #79
Reviewed-by: imcompiling <[email protected]>
2025-03-03 23:03:42 -05:00
renovate-bot 8604ba2547 Update ghcr.io/astral-sh/uv Docker tag to v0.6.3 2025-03-02 05:01:27 +00:00
43 changed files with 908 additions and 508 deletions
+3
View File
@@ -1,2 +1,5 @@
.*
Dockerfile
LICENSE
README.md
renovate.json
+10 -4
View File
@@ -2,14 +2,18 @@ name: build_develop
on:
push:
branches: [main]
branches:
- "*"
- "!main"
paths-ignore:
- "README.md"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v4
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install Docker
@@ -20,7 +24,9 @@ jobs:
registry: gitea.cheezers.org
username: imcompiling
password: ${{ secrets.PASSWORD }}
- name: set env
run: echo "GIT_BRANCH=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}" >> $GITHUB_ENV
- name: Build Docker Image
run: docker build -t gitea.cheezers.org/imcompiling/agon:develop .
run: docker build -t gitea.cheezers.org/imcompiling/agon:${{env.GIT_BRANCH}} .
- name: Push Docker Image
run: docker push gitea.cheezers.org/imcompiling/agon:develop
run: docker push gitea.cheezers.org/imcompiling/agon:${{env.GIT_BRANCH}}
+28
View File
@@ -0,0 +1,28 @@
name: build_latest
on:
push:
branches: [main]
paths-ignore:
- "README.md"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install Docker
uses: https://github.com/papodaca/install-docker-action@v1
- name: Log into container registry
uses: docker/login-action@v3
with:
registry: gitea.cheezers.org
username: imcompiling
password: ${{ secrets.PASSWORD }}
- name: Build Docker Image
run: docker build -t gitea.cheezers.org/imcompiling/agon:latest .
- name: Push Docker Image
run: docker push gitea.cheezers.org/imcompiling/agon:latest
+1 -3
View File
@@ -23,8 +23,6 @@ jobs:
- name: Set env
run: echo "GIT_TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Build Docker Images
run: docker build -t gitea.cheezers.org/imcompiling/agon:latest -t gitea.cheezers.org/imcompiling/agon:${{env.GIT_TAG}} .
- name: Push Latest Image
run: docker push gitea.cheezers.org/imcompiling/agon:latest
run: docker build -t gitea.cheezers.org/imcompiling/agon:${{env.GIT_TAG}} .
- name: Push Tagged Image
run: docker push gitea.cheezers.org/imcompiling/agon:${{env.GIT_TAG}}
+1 -1
View File
@@ -135,4 +135,4 @@ deleted_backups/
highscores_data/
TODO.txt
sql_tester.py
database.db
/database
+2 -2
View File
@@ -8,8 +8,8 @@
"name": "Python: Module",
"type": "debugpy",
"request": "launch",
"module": "main",
"module": "agon",
"justMyCode": true
}
]
}
}
+2 -1
View File
@@ -5,11 +5,12 @@
"highscore",
"highscores",
"imcompiling",
"iterrows",
"nextcord",
"ondelete"
],
"python.analysis.diagnosticSeverityOverrides": {
"reportOptionalMemberAccess": false,
"reportOptionalMemberAccess": "warning",
"reportArgumentType": "information",
"reportAttributeAccessIssue": "warning"
}
+4 -4
View File
@@ -1,15 +1,15 @@
FROM python:3.12.3-slim
# install uv
COPY --from=ghcr.io/astral-sh/uv:0.6.2 /uv /uvx /bin/
COPY --from=ghcr.io/astral-sh/uv:0.6.6 /uv /uvx /bin/
RUN apt-get update && apt-get -y upgrade && apt-get -y install sqlite3
# Copy project to image
ADD . /agon
ADD . /home
# Sync the project into a new environment, using the frozen lockfile
WORKDIR /agon
WORKDIR /home
RUN uv sync --frozen --no-dev
CMD ["uv", "run", "./main.py"]
CMD ["uv", "run", "--frozen", "--no-dev", "-m", "agon"]
+1
View File
@@ -0,0 +1 @@
"""Empty init file for off_cooldown_bot module."""
+14
View File
@@ -0,0 +1,14 @@
"""Starts the app for agon."""
import logging
from .app import run
nextcord_logger = logging.getLogger("nextcord")
nextcord_logger.setLevel(logging.DEBUG)
nextcord_handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8", mode="w")
nextcord_handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
nextcord_logger.addHandler(nextcord_handler)
if __name__ == "__main__":
run()
+42
View File
@@ -0,0 +1,42 @@
"""Main file for Agon bot."""
import pathlib
import sys
import nextcord
from nextcord.ext import commands
from . import config
from .logger import agon_logger
def run() -> None:
"""Main function for bot."""
min_python_version = (3, 12)
if sys.version_info < min_python_version:
agon_logger.error("ERROR: Python version must be >= 3.12")
sys.exit()
# Allows privileged intents for monitoring members joining, roles editing, and role assignments
# These need to be enabled in the developer portal as well
intents = nextcord.Intents.default()
bot = commands.Bot(
commands.when_mentioned_or(config.BOT_PREFIX),
intents=intents,
)
# Get the modules of all cogs whose directory structure is ./cogs/<module_name>
for folder in pathlib.Path("./agon/cogs").iterdir():
bot.load_extension(f"agon.cogs.{folder.name}")
@bot.listen()
async def on_ready() -> None:
"""When Discord is connected."""
if bot.user is None:
agon_logger.error("Discord connection failed.")
return
agon_logger.info("%s has connected to Discord!", bot.user.name)
# Run Discord bot
bot.run(config.DISCORD_TOKEN)
@@ -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 agon.cogs.commands.create import CreateCog
from agon.cogs.commands.delete import DeleteCog
from agon.cogs.commands.get import GetCog
from agon.cogs.commands.help import HelpCog
from agon.cogs.commands.refresh import RefreshCog
from agon.cogs.commands.set import SetCog
from agon.cogs.commands.submission import SubmissionCog
from agon.cogs.commands.update import UpdateCog
from agon.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())
@@ -6,9 +6,9 @@ from sqlalchemy import exc, select
from sqlalchemy.orm import Session
from sqlmodel import col
from database.db import engine
from database.models import Category, CategoryGroup
from utilities.utils import MAX_LINE_LENGTH, autofill_groups, send_highscore_message
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup
from agon.utils import MAX_LINE_LENGTH, autofill_groups, send_highscore_message
class CreateCog(commands.Cog, name="Create Cog"):
@@ -99,7 +99,7 @@ class CreateCog(commands.Cog, name="Create Cog"):
min_value=1,
max_value=30,
),
channel: nextcord.TextChannel | None = nextcord.SlashOption(
channel: nextcord.TextChannel | nextcord.Thread | None = nextcord.SlashOption(
description="Channel to post Group in. If left empty, defaults to current channel.",
required=False,
default=None,
@@ -6,9 +6,9 @@ from sqlalchemy import distinct, select
from sqlalchemy.orm import Session
from sqlmodel import col
from database.db import engine
from database.models import Category, CategoryGroup, Score
from utilities.utils import (
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup, Score
from agon.utils import (
autofill_categories,
autofill_groups,
autofill_users_in_group_category,
@@ -37,7 +37,7 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
async def channel_messages(
self,
interaction: nextcord.Interaction,
channel: nextcord.TextChannel | None = nextcord.SlashOption(
channel: nextcord.TextChannel | nextcord.Thread | None = nextcord.SlashOption(
description="Channel to clear of messages.",
required=False,
default=None,
@@ -54,7 +54,7 @@ class DeleteCog(commands.Cog, name="Delete Cog"):
Is a SlashOption. Limited to text channels. Defaults to None.
"""
if not channel:
if isinstance(interaction.channel, nextcord.TextChannel):
if isinstance(interaction.channel, nextcord.TextChannel | nextcord.Thread):
channel = interaction.channel
else:
# This should never happen.
+199
View File
@@ -0,0 +1,199 @@
"""Get command hierarchy."""
import nextcord
from nextcord.ext import commands
from sqlmodel import Session, col, select
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup
from agon.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,14 @@
"""
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
from database.db import CategoryGroup, engine
from utilities.utils import autofill_groups, send_highscore_message
from agon.database.db import engine
from agon.database.models import CategoryGroup
from agon.utils import autofill_groups, send_highscore_message
class RefreshCog(commands.Cog, name="Refresh Cog"):
@@ -43,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:
@@ -67,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)
+442
View File
@@ -0,0 +1,442 @@
"""Set command hierarchy."""
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlmodel import col
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup, Guild
from agon.logger import agon_logger
from agon.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."""
def __init__(self) -> None:
"""Default constructor for SetCog class. Does nothing."""
@nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
async def set(self, interaction: nextcord.Interaction) -> None:
"""Parent slash command for setting settings. Never called."""
@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="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,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register a CategoryGroup's output channel.
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.
Is a SlashOption. Limited to text channels, Defaults to None.
"""
channel_id = interaction.channel.id if not channel else channel.id
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
.where(col(CategoryGroup.id) == int(group_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)
@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="Group to assign pad length to.", required=True),
length: int = nextcord.SlashOption(
description="Number of characters alloted to a category.",
required=True,
default=26,
min_value=7,
max_value=MAX_LINE_LENGTH,
),
) -> None:
"""
Changes guild's category pad length.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
group_id (str): String representation of Group id to set pad length in. Is SlashOption.
length (int): Number of characters. Is SlashOption. Defaults to 26.
"""
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(col(CategoryGroup.guild_id) == interaction.guild_id)
.where(col(CategoryGroup.id) == int(group_id))
)
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.name}**.", ephemeral=True
)
await send_highscore_message(session, interaction.guild, group)
@group.subcommand(
description="Registers the channel for submission messages. Currently this information is deprecated."
)
async def submission_channel(
self,
interaction: nextcord.Interaction,
channel: nextcord.abc.GuildChannel | None = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register the submission message channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
channel (nextcord.abc.GuildChannel): Channel to register
Is a SlashOption. Limited to text channels, Defaults to None.
"""
channel_id = interaction.channel.id if not channel else channel.id
with Session(engine) as session:
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)
@group.subcommand(description="Set username length for a Group of Categories.")
async def username_length(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(
name="group", description="Group to change username length of.", required=True
),
length: int = nextcord.SlashOption(
description="Number of characters.", required=True, default=12, min_value=1, max_value=30
),
) -> None:
"""
Changes guild's username length limit.
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(col(CategoryGroup.guild_id) == interaction.guild_id)
.where(col(CategoryGroup.id) == int(group_id))
)
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 for **{group.name}** set to **{length}**.", ephemeral=True
)
@set.subcommand(description="Registers the channel for verification messages.")
async def verify_channel(
self,
interaction: nextcord.Interaction,
channel: nextcord.abc.GuildChannel | None = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register the verification message channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
channel (Optional[nextcord.abc.GuildChannel]): Channel to register
Is a SlashOption. Limited to text channels, Defaults to None.
"""
channel_id = interaction.channel.id if not channel else channel.id
with Session(engine) as session:
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)
@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) -> 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))
@@ -6,11 +6,13 @@ 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 utilities.utils import autofill_categories, autofill_groups, submit_score
from agon.cogs.submission.verification_view import VerificationView
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup, Guild, Submission
from agon.logger import agon_logger
from agon.utils import autofill_categories, autofill_groups, submit_score
class SubmissionCog(commands.Cog):
@@ -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 channel is None:
error_response = (
"Registered Verification channel does not exist or was never registered. Contact server admins."
)
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 not isinstance(channel, nextcord.TextChannel):
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 | nextcord.Thread):
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)
@@ -1,22 +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
from database.db import Guild, engine
from utilities.utils import autofill_users_in_guild
from agon.database.db import engine
from agon.database.models import Guild
from agon.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):
"""
@@ -28,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(
@@ -46,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
@@ -57,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)
@@ -71,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,11 @@ import pandas as pd
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlmodel import col
from database.db import Category, CategoryGroup, Score, engine
from utilities.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, format_score_string
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup, Score
from agon.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, format_score_string
class ViewCog(commands.Cog, name="View Command"):
@@ -46,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()
@@ -67,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:
@@ -4,9 +4,9 @@ import nextcord
from sqlalchemy import delete, select
from sqlalchemy.orm import Session
from database.db import engine
from database.models import Category, CategoryGroup
from utilities.utils import send_highscore_message
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup
from agon.utils import send_highscore_message
class DeleteConfirmView(nextcord.ui.Modal):
@@ -43,7 +43,7 @@ class DeleteConfirmView(nextcord.ui.Modal):
session.delete(group)
# delete the message related to group
channel = interaction.guild.get_channel(group.channel_id)
if not isinstance(channel, nextcord.TextChannel):
if not isinstance(channel, nextcord.TextChannel | nextcord.Thread):
return
message: nextcord.Message = await channel.fetch_message(group.message_id)
await message.delete()
@@ -5,9 +5,9 @@ from sqlalchemy import distinct, exc, select
from sqlalchemy.orm import Session
from sqlmodel import col
from database.db import engine
from database.models import Category, CategoryGroup, Score
from utilities.utils import send_highscore_message
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup, Score
from agon.utils import send_highscore_message
class UpdateUsernameVerifyView(nextcord.ui.View):
@@ -6,8 +6,8 @@ from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlmodel import col
from database.db import engine
from database.models import Guild
from agon.database.db import engine
from agon.database.models import Guild
class GuildListener(commands.Cog, name="Guild Listener"):
@@ -26,10 +26,9 @@ class GuildListener(commands.Cog, name="Guild Listener"):
"""
with Session(engine) as session:
stmt = select(Guild).where(col(Guild.id == guild.id))
guild_data = session.scalar(stmt)
# just in case check if the guild already exists
if guild_data is None:
if (guild_data := session.scalar(stmt)) is None:
new_guild = Guild(id=guild.id, name=guild.name)
session.add(new_guild)
else:
@@ -5,8 +5,8 @@ from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlmodel import col
from database.db import engine
from database.models import Guild
from agon.database.db import engine
from agon.database.models import Guild
class GuildData(commands.Cog, name="Guild Data"):
@@ -31,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(col(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.
@@ -39,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()
@@ -5,9 +5,9 @@ from sqlalchemy import delete, select
from sqlalchemy.orm import Session
from sqlmodel import col
from database.db import engine
from database.models import Submission
from utilities.utils import submit_score
from agon.database.db import engine
from agon.database.models import Submission
from agon.utils import submit_score
class VerificationView(nextcord.ui.View):
@@ -39,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
+6 -2
View File
@@ -1,14 +1,18 @@
"""Simple file to set up the sqlmodel connection to database."""
from sqlmodel import SQLModel, create_engine
from utilities import config
from agon import config
from agon.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"
url = "sqlite:///database/database.db"
agon_logger.info("Connected to local dev database.")
engine = create_engine(url)
# Don't need to create all when connected to prod.
+10
View File
@@ -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)
+21 -11
View File
@@ -8,8 +8,9 @@ from sqlalchemy import distinct, select
from sqlalchemy.orm import Session, aliased
from sqlmodel import col
from database.db import engine
from database.models import Category, CategoryGroup, Guild, Score
from agon.database.db import engine
from agon.database.models import Category, CategoryGroup, Guild, Score
from agon.logger import agon_logger
MAX_LINE_LENGTH = 142
@@ -64,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)}
@@ -275,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,
@@ -327,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.
@@ -337,23 +340,30 @@ 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 (channel := guild.get_channel_or_thread(group.channel_id)) is None:
agon_logger.error("Channel id %s in guild %s does not exist.", group.channel_id, guild.id)
return
if not isinstance(channel, nextcord.TextChannel | nextcord.Thread):
agon_logger.error(
"Channel id %s in guild %s is does not correspond to a TextChannel or Thread.", 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(
@@ -390,7 +400,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)
-206
View File
@@ -1,206 +0,0 @@
"""
Set command heirarchy.
"""
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
from database.db import CategoryGroup, Guild, engine
from utilities.utils import MAX_LINE_LENGTH, autofill_groups
class SetCog(commands.Cog, name="Set 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 set(self, interaction: nextcord.Interaction):
"""
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(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(
name="group", description="Category Group to assign to channel.", required=True
),
channel: nextcord.abc.GuildChannel | None = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register a CategoryGroup's output channel.
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
Is a SlashOption. Limited to text channels, Defaults to None.
"""
if not channel:
channel = interaction.channel
channel_id = channel.id
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.GroupId == int(group_id))
)
group = session.scalar(stmt)
group.ChannelId = channel_id
session.commit()
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
@set.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
),
length: int = nextcord.SlashOption(
description="Number of characters alloted to a category.",
required=True,
default=26,
min_value=7,
max_value=MAX_LINE_LENGTH,
),
) -> None:
"""
Changes guild's category pad length.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
group_id (str): String representation of Group id to set pad length in. Is SlashOption.
length (int): Number of characters. Is SlashOption. Defaults to 26.
"""
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.GroupId == int(group_id))
)
group = session.scalar(stmt)
group.PadLength = length
session.commit()
await interaction.response.send_message(
f"Category pad length set to {length} for {group.GroupName}", ephemeral=True
)
@set.subcommand(
description="Registers the channel for submission messages. Currently this information is deprecated."
)
async def submission_channel(
self,
interaction: nextcord.Interaction,
channel: nextcord.abc.GuildChannel | None = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register the submission message channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
channel Optional[nextcord.abc.GuildChannel], optional): Channel to register
Is a SlashOption. Limited to text channels, Defaults to None.
"""
if not channel:
channel = interaction.channel
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
session.commit()
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
@set.subcommand(description="Set username length for a Group of Categories.")
async def username_length(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(
name="group", description="Group to change username length of.", required=True
),
length: int = nextcord.SlashOption(
description="Number of characters.", required=True, default=12, min_value=1, max_value=30
),
) -> None:
"""
Changes guild's username length limit.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
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))
)
group = session.scalar(stmt)
group.UsernameLength = length
session.commit()
await interaction.response.send_message(f"Username length set to {length}.", ephemeral=True)
@set.subcommand(description="Registers the channel for verification messages.")
async def verify_channel(
self,
interaction: nextcord.Interaction,
channel: nextcord.abc.GuildChannel | None = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register the verification message channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the 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
with Session(engine) as session:
stmt = select(Guild).where(Guild.GuildId == interaction.guild_id)
guild = session.scalar(stmt)
guild.VerificationChannel = channel_id
session.commit()
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
@group_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):
"""
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))
-40
View File
@@ -1,40 +0,0 @@
import os
from dotenv import load_dotenv
from sqlmodel import Session, SQLModel, create_engine, select
from models import CategoryGroup, Guild
load_dotenv()
SQL_DB = os.getenv("SQL_DB", "")
SQL_HOST = os.getenv("SQL_HOST", "")
SQL_PASS = os.getenv("SQL_PASS", "")
SQL_USER = os.getenv("SQL_USER", "")
url = "sqlite:///database.db"
# url = f"mysql+pymysql://{SQL_USER}:{SQL_PASS}@{SQL_HOST}/{SQL_DB}"
engine = create_engine(url)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
guild = Guild(id=1, name="test guild")
session.add(guild)
group1 = CategoryGroup(name="group1", channel_id=1, guild_id=1, message_id=1)
group2 = CategoryGroup(name="group2", channel_id=2, guild_id=1, message_id=2)
session.add(group1)
session.add(group2)
session.commit()
# anotherone = Guild(id=2, name="test guild 2", submission_channel=1, verification_channel=2)
# session.add(anotherone)
# group1 = CategoryGroup(name="group1", channel_id=1, guild_id=2, message_id=1)
# group2 = CategoryGroup(name="group2", channel_id=2, guild_id=2, message_id=2)
# session.add(group1)
# session.add(group2)
# session.commit()
stmt = select(Guild).where(Guild.name == "Dakiny")
guild = session.scalar(stmt)
print(guild.category_groups)
-7
View File
@@ -1,7 +0,0 @@
[tool.ruff]
# Extend the `pyproject.toml` file in the parent directory...
extend = "../pyproject.toml"
[tool.ruff.lint]
# ignore implicit-namespace-package in this directory.
ignore = ["INP001"]
-56
View File
@@ -1,56 +0,0 @@
CREATE DATABASE highscores;
use highscores;
CREATE TABLE Guilds(
GuildId bigint unsigned not null unique,
GuildName varchar(95) not null,
SubmissionChannel bigint unsigned, -- deprecated, is not used anymore.
VerificationChannel bigint unsigned,
Active boolean DEFAULT true,
PRIMARY KEY (GuildId)
);
CREATE TABLE CategoryGroups(
GroupId int unsigned not null unique AUTO_INCREMENT,
GroupName varchar(50) not null,
ChannelId bigint unsigned,
GuildId bigint unsigned not null,
MessageId bigint unsigned,
PadLength smallint not null DEFAULT 26,
UsernameLength smallint DEFAULT 12,
CONSTRAINT UniqueGuildCategoryGroup UNIQUE (GuildId, GroupName),
FOREIGN KEY (GuildId) REFERENCES Guilds(GuildId) ON DELETE CASCADE,
PRIMARY KEY (GroupId)
);
CREATE TABLE Categories(
CategoryId int unsigned not null unique AUTO_INCREMENT,
CategoryName varchar(30) not null,
GroupId int unsigned not null,
Size smallint not null DEFAULT 3,
IsAscending boolean not null DEFAULT true,
IsTimeRecord boolean not null DEFAULT false,
IsValidated boolean not null DEFAULT true,
CONSTRAINT UniqueCategoryInGroup UNIQUE (GroupId, CategoryName),
FOREIGN KEY (GroupId) REFERENCES CategoryGroups(GroupId) ON DELETE CASCADE,
PRIMARY Key (CategoryId)
);
CREATE TABLE Scores(
UserName varchar(30) not null,
Score float not null, -- Maybe should have time and int scores?? timestamp type?
CategoryId int unsigned not null,
FOREIGN KEY (CategoryId) REFERENCES Categories(CategoryId) ON DELETE CASCADE,
PRIMARY KEY (CategoryId, UserName)
);
CREATE TABLE Submissions(
CategoryId int unsigned not null,
GroupId int unsigned not null,
GuildId bigint unsigned not null,
MessageId bigint unsigned not null,
Score varchar(30) not null, -- Score is stored as a string until converted during submission
UserId bigint unsigned not null,
UserName varchar(30) not null,
PRIMARY KEY (CategoryId, UserName) -- one submission a category per user.
);
-58
View File
@@ -1,58 +0,0 @@
"""Main file for Agon bot."""
import logging
import os
import sys
import nextcord
from nextcord.ext import commands
from utilities import config
nextcord_logger = logging.getLogger("nextcord")
nextcord_logger.setLevel(logging.DEBUG)
nextcord_handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8", mode="w")
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")
sys.exit()
# Allows privileged intents for monitoring members joining, roles editing, and role assignments
# These need to be enabled in the developer portal as well
intents = nextcord.Intents.default()
bot = commands.Bot(
commands.when_mentioned_or(config.BOT_PREFIX),
intents=intents,
)
# Get the modules of all cogs whose directory structure is ./cogs/<module_name>
for folder in os.listdir("cogs"):
bot.load_extension(f"cogs.{folder}")
@bot.listen()
async def on_ready() -> None:
"""When Discord is connected."""
if bot.user is None:
logger.error("Discord connection failed.")
return
logger.info("%s has connected to Discord!", bot.user.name)
# Run Discord bot
bot.run(config.DISCORD_TOKEN)
if __name__ == "__main__":
main()
-1
View File
@@ -1 +0,0 @@
"""Package of utility functions and environment configuration variables."""