From c29194a30a08bec99dd055e2cad446293ccdf681 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Wed, 26 Feb 2025 21:35:25 -0500 Subject: [PATCH 01/51] Install sqlmodel --- pyproject.toml | 2 +- uv.lock | 79 ++++++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 0e1af9a..ec63d6a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ dependencies = [ "pymysql>=1.1.1", "python-dotenv>=1.0.1", "setuptools>=75.3.0", - "sqlalchemy>=2.0.35", + "sqlmodel>=0.0.22", ] requires-python = ">=3.12" diff --git a/uv.lock b/uv.lock index 8ee428b..7fa58c4 100644 --- a/uv.lock +++ b/uv.lock @@ -12,7 +12,7 @@ dependencies = [ { name = "pymysql" }, { name = "python-dotenv" }, { name = "setuptools" }, - { name = "sqlalchemy" }, + { name = "sqlmodel" }, ] [package.dev-dependencies] @@ -28,7 +28,7 @@ requires-dist = [ { name = "pymysql", specifier = ">=1.1.1" }, { name = "python-dotenv", specifier = ">=1.0.1" }, { name = "setuptools", specifier = ">=75.3.0" }, - { name = "sqlalchemy", specifier = ">=2.0.35" }, + { name = "sqlmodel", specifier = ">=0.0.22" }, ] [package.metadata.requires-dev] @@ -102,6 +102,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/76/ac/a7305707cb852b7e16ff80eaf5692309bde30e2b1100a1fcacdc8f731d97/aiosignal-1.3.1-py3-none-any.whl", hash = "sha256:f8376fb07dd1e86a584e4fcdec80b36b7f81aac666ebc724e2c090300dd83b17", size = 7617 }, ] +[[package]] +name = "annotated-types" +version = "0.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/67/531ea369ba64dcff5ec9c3402f9f51bf748cec26dde048a2f973a4eea7f5/annotated_types-0.7.0.tar.gz", hash = "sha256:aff07c09a53a08bc8cfccb9c85b05f1aa9a2a6f23728d790723543408344ce89", size = 16081 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/b6/6307fbef88d9b5ee7421e68d78a9f162e0da4900bc5f5793f6d3d0e34fb8/annotated_types-0.7.0-py3-none-any.whl", hash = "sha256:1f02e8b43a8fbbc3f3e0d4f0f4bfc8131bcb4eebe8849b8e5c773f3a1c582a53", size = 13643 }, +] + [[package]] name = "attrs" version = "24.2.0" @@ -425,6 +434,59 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/13/a3/a812df4e2dd5696d1f351d58b8fe16a405b234ad2886a0dab9183fb78109/pycparser-2.22-py3-none-any.whl", hash = "sha256:c3702b6d3dd8c7abc1afa565d7e63d53a1d0bd86cdc24edd75470f4de499cfcc", size = 117552 }, ] +[[package]] +name = "pydantic" +version = "2.10.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b7/ae/d5220c5c52b158b1de7ca89fc5edb72f304a70a4c540c84c8844bf4008de/pydantic-2.10.6.tar.gz", hash = "sha256:ca5daa827cce33de7a42be142548b0096bf05a7e7b365aebfa5f8eeec7128236", size = 761681 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f4/3c/8cc1cc84deffa6e25d2d0c688ebb80635dfdbf1dbea3e30c541c8cf4d860/pydantic-2.10.6-py3-none-any.whl", hash = "sha256:427d664bf0b8a2b34ff5dd0f5a18df00591adcee7198fbd71981054cef37b584", size = 431696 }, +] + +[[package]] +name = "pydantic-core" +version = "2.27.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/fc/01/f3e5ac5e7c25833db5eb555f7b7ab24cd6f8c322d3a3ad2d67a952dc0abc/pydantic_core-2.27.2.tar.gz", hash = "sha256:eb026e5a4c1fee05726072337ff51d1efb6f59090b7da90d30ea58625b1ffb39", size = 413443 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d6/74/51c8a5482ca447871c93e142d9d4a92ead74de6c8dc5e66733e22c9bba89/pydantic_core-2.27.2-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:9e0c8cfefa0ef83b4da9588448b6d8d2a2bf1a53c3f1ae5fca39eb3061e2f0b0", size = 1893127 }, + { url = "https://files.pythonhosted.org/packages/d3/f3/c97e80721735868313c58b89d2de85fa80fe8dfeeed84dc51598b92a135e/pydantic_core-2.27.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:83097677b8e3bd7eaa6775720ec8e0405f1575015a463285a92bfdfe254529ef", size = 1811340 }, + { url = "https://files.pythonhosted.org/packages/9e/91/840ec1375e686dbae1bd80a9e46c26a1e0083e1186abc610efa3d9a36180/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:172fce187655fece0c90d90a678424b013f8fbb0ca8b036ac266749c09438cb7", size = 1822900 }, + { url = "https://files.pythonhosted.org/packages/f6/31/4240bc96025035500c18adc149aa6ffdf1a0062a4b525c932065ceb4d868/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:519f29f5213271eeeeb3093f662ba2fd512b91c5f188f3bb7b27bc5973816934", size = 1869177 }, + { url = "https://files.pythonhosted.org/packages/fa/20/02fbaadb7808be578317015c462655c317a77a7c8f0ef274bc016a784c54/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:05e3a55d124407fffba0dd6b0c0cd056d10e983ceb4e5dbd10dda135c31071d6", size = 2038046 }, + { url = "https://files.pythonhosted.org/packages/06/86/7f306b904e6c9eccf0668248b3f272090e49c275bc488a7b88b0823444a4/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9c3ed807c7b91de05e63930188f19e921d1fe90de6b4f5cd43ee7fcc3525cb8c", size = 2685386 }, + { url = "https://files.pythonhosted.org/packages/8d/f0/49129b27c43396581a635d8710dae54a791b17dfc50c70164866bbf865e3/pydantic_core-2.27.2-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6fb4aadc0b9a0c063206846d603b92030eb6f03069151a625667f982887153e2", size = 1997060 }, + { url = "https://files.pythonhosted.org/packages/0d/0f/943b4af7cd416c477fd40b187036c4f89b416a33d3cc0ab7b82708a667aa/pydantic_core-2.27.2-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:28ccb213807e037460326424ceb8b5245acb88f32f3d2777427476e1b32c48c4", size = 2004870 }, + { url = "https://files.pythonhosted.org/packages/35/40/aea70b5b1a63911c53a4c8117c0a828d6790483f858041f47bab0b779f44/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:de3cd1899e2c279b140adde9357c4495ed9d47131b4a4eaff9052f23398076b3", size = 1999822 }, + { url = "https://files.pythonhosted.org/packages/f2/b3/807b94fd337d58effc5498fd1a7a4d9d59af4133e83e32ae39a96fddec9d/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_armv7l.whl", hash = "sha256:220f892729375e2d736b97d0e51466252ad84c51857d4d15f5e9692f9ef12be4", size = 2130364 }, + { url = "https://files.pythonhosted.org/packages/fc/df/791c827cd4ee6efd59248dca9369fb35e80a9484462c33c6649a8d02b565/pydantic_core-2.27.2-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:a0fcd29cd6b4e74fe8ddd2c90330fd8edf2e30cb52acda47f06dd615ae72da57", size = 2158303 }, + { url = "https://files.pythonhosted.org/packages/9b/67/4e197c300976af185b7cef4c02203e175fb127e414125916bf1128b639a9/pydantic_core-2.27.2-cp312-cp312-win32.whl", hash = "sha256:1e2cb691ed9834cd6a8be61228471d0a503731abfb42f82458ff27be7b2186fc", size = 1834064 }, + { url = "https://files.pythonhosted.org/packages/1f/ea/cd7209a889163b8dcca139fe32b9687dd05249161a3edda62860430457a5/pydantic_core-2.27.2-cp312-cp312-win_amd64.whl", hash = "sha256:cc3f1a99a4f4f9dd1de4fe0312c114e740b5ddead65bb4102884b384c15d8bc9", size = 1989046 }, + { url = "https://files.pythonhosted.org/packages/bc/49/c54baab2f4658c26ac633d798dab66b4c3a9bbf47cff5284e9c182f4137a/pydantic_core-2.27.2-cp312-cp312-win_arm64.whl", hash = "sha256:3911ac9284cd8a1792d3cb26a2da18f3ca26c6908cc434a18f730dc0db7bfa3b", size = 1885092 }, + { url = "https://files.pythonhosted.org/packages/41/b1/9bc383f48f8002f99104e3acff6cba1231b29ef76cfa45d1506a5cad1f84/pydantic_core-2.27.2-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:7d14bd329640e63852364c306f4d23eb744e0f8193148d4044dd3dacdaacbd8b", size = 1892709 }, + { url = "https://files.pythonhosted.org/packages/10/6c/e62b8657b834f3eb2961b49ec8e301eb99946245e70bf42c8817350cbefc/pydantic_core-2.27.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:82f91663004eb8ed30ff478d77c4d1179b3563df6cdb15c0817cd1cdaf34d154", size = 1811273 }, + { url = "https://files.pythonhosted.org/packages/ba/15/52cfe49c8c986e081b863b102d6b859d9defc63446b642ccbbb3742bf371/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71b24c7d61131bb83df10cc7e687433609963a944ccf45190cfc21e0887b08c9", size = 1823027 }, + { url = "https://files.pythonhosted.org/packages/b1/1c/b6f402cfc18ec0024120602bdbcebc7bdd5b856528c013bd4d13865ca473/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:fa8e459d4954f608fa26116118bb67f56b93b209c39b008277ace29937453dc9", size = 1868888 }, + { url = "https://files.pythonhosted.org/packages/bd/7b/8cb75b66ac37bc2975a3b7de99f3c6f355fcc4d89820b61dffa8f1e81677/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ce8918cbebc8da707ba805b7fd0b382816858728ae7fe19a942080c24e5b7cd1", size = 2037738 }, + { url = "https://files.pythonhosted.org/packages/c8/f1/786d8fe78970a06f61df22cba58e365ce304bf9b9f46cc71c8c424e0c334/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:eda3f5c2a021bbc5d976107bb302e0131351c2ba54343f8a496dc8783d3d3a6a", size = 2685138 }, + { url = "https://files.pythonhosted.org/packages/a6/74/d12b2cd841d8724dc8ffb13fc5cef86566a53ed358103150209ecd5d1999/pydantic_core-2.27.2-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bd8086fa684c4775c27f03f062cbb9eaa6e17f064307e86b21b9e0abc9c0f02e", size = 1997025 }, + { url = "https://files.pythonhosted.org/packages/a0/6e/940bcd631bc4d9a06c9539b51f070b66e8f370ed0933f392db6ff350d873/pydantic_core-2.27.2-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8d9b3388db186ba0c099a6d20f0604a44eabdeef1777ddd94786cdae158729e4", size = 2004633 }, + { url = "https://files.pythonhosted.org/packages/50/cc/a46b34f1708d82498c227d5d80ce615b2dd502ddcfd8376fc14a36655af1/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_aarch64.whl", hash = "sha256:7a66efda2387de898c8f38c0cf7f14fca0b51a8ef0b24bfea5849f1b3c95af27", size = 1999404 }, + { url = "https://files.pythonhosted.org/packages/ca/2d/c365cfa930ed23bc58c41463bae347d1005537dc8db79e998af8ba28d35e/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_armv7l.whl", hash = "sha256:18a101c168e4e092ab40dbc2503bdc0f62010e95d292b27827871dc85450d7ee", size = 2130130 }, + { url = "https://files.pythonhosted.org/packages/f4/d7/eb64d015c350b7cdb371145b54d96c919d4db516817f31cd1c650cae3b21/pydantic_core-2.27.2-cp313-cp313-musllinux_1_1_x86_64.whl", hash = "sha256:ba5dd002f88b78a4215ed2f8ddbdf85e8513382820ba15ad5ad8955ce0ca19a1", size = 2157946 }, + { url = "https://files.pythonhosted.org/packages/a4/99/bddde3ddde76c03b65dfd5a66ab436c4e58ffc42927d4ff1198ffbf96f5f/pydantic_core-2.27.2-cp313-cp313-win32.whl", hash = "sha256:1ebaf1d0481914d004a573394f4be3a7616334be70261007e47c2a6fe7e50130", size = 1834387 }, + { url = "https://files.pythonhosted.org/packages/71/47/82b5e846e01b26ac6f1893d3c5f9f3a2eb6ba79be26eef0b759b4fe72946/pydantic_core-2.27.2-cp313-cp313-win_amd64.whl", hash = "sha256:953101387ecf2f5652883208769a79e48db18c6df442568a0b5ccd8c2723abee", size = 1990453 }, + { url = "https://files.pythonhosted.org/packages/51/b2/b2b50d5ecf21acf870190ae5d093602d95f66c9c31f9d5de6062eb329ad1/pydantic_core-2.27.2-cp313-cp313-win_arm64.whl", hash = "sha256:ac4dbfd1691affb8f48c2c13241a2e3b60ff23247cbcf981759c768b6633cf8b", size = 1885186 }, +] + [[package]] name = "pymysql" version = "1.1.1" @@ -536,6 +598,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b8/49/21633706dd6feb14cd3f7935fc00b60870ea057686035e1a99ae6d9d9d53/SQLAlchemy-2.0.36-py3-none-any.whl", hash = "sha256:fddbe92b4760c6f5d48162aef14824add991aeda8ddadb3c31d56eb15ca69f8e", size = 1883787 }, ] +[[package]] +name = "sqlmodel" +version = "0.0.22" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pydantic" }, + { name = "sqlalchemy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/39/8641040ab0d5e1d8a1c2325ae89a01ae659fc96c61a43d158fb71c9a0bf0/sqlmodel-0.0.22.tar.gz", hash = "sha256:7d37c882a30c43464d143e35e9ecaf945d88035e20117bf5ec2834a23cbe505e", size = 116392 } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/b1/3af5104b716c420e40a6ea1b09886cae3a1b9f4538343875f637755cae5b/sqlmodel-0.0.22-py3-none-any.whl", hash = "sha256:a1ed13e28a1f4057cbf4ff6cdb4fc09e85702621d3259ba17b3c230bfb2f941b", size = 28276 }, +] + [[package]] name = "typing-extensions" version = "4.12.2" From de2542ece627b8a147386bc5fa7b66089d7f6a84 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Thu, 27 Feb 2025 09:42:49 -0500 Subject: [PATCH 02/51] Start testing with sqlmodel. --- .gitignore | 1 + database_setup/database_test.py | 14 +++++++++++ database_setup/sql_data_classes.py | 40 ++++++++++++++++++++---------- utilities/config.py | 5 ++-- 4 files changed, 44 insertions(+), 16 deletions(-) create mode 100644 database_setup/database_test.py diff --git a/.gitignore b/.gitignore index 4defef7..87899b1 100644 --- a/.gitignore +++ b/.gitignore @@ -135,3 +135,4 @@ deleted_backups/ highscores_data/ TODO.txt sql_tester.py +database.db diff --git a/database_setup/database_test.py b/database_setup/database_test.py new file mode 100644 index 0000000..ab3d577 --- /dev/null +++ b/database_setup/database_test.py @@ -0,0 +1,14 @@ +from sqlmodel import BigInteger, Column, Field, SQLModel, create_engine + + +class Guilds(SQLModel, table=True): + id: int = Field(sa_column=Column(BigInteger(), primary_key=True)) + name: str = Field(max_length=95) + submission_channel: int = Field(sa_column=Column(BigInteger())) + verification_channel: int = Field(sa_column=Column(BigInteger())) + active: bool = Field(default=True) + + +url = "sqlite:///database.db" +engine = create_engine(url) +SQLModel.metadata.create_all(engine) diff --git a/database_setup/sql_data_classes.py b/database_setup/sql_data_classes.py index 25d42d5..a9147b9 100644 --- a/database_setup/sql_data_classes.py +++ b/database_setup/sql_data_classes.py @@ -1,18 +1,32 @@ """Simple file to set up the sqlalchemy connection to database.""" -from sqlalchemy import create_engine -from sqlalchemy.ext.automap import automap_base +# from sqlalchemy import create_engine +# from sqlalchemy.ext.automap import automap_base +from sqlmodel import BigInteger, Column, Field, SQLModel, create_engine from utilities import config -# connect with sql alchemy and autoload schema -url = f"mysql+pymysql://{config.SQL_USER}:{config.SQL_PASS}@{config.SQL_HOST}/{config.SQL_DB}" -engine = create_engine(url) -Base = automap_base() -Base.prepare(autoload_with=engine) -# define the classes -Category = Base.classes.Categories -CategoryGroup = Base.classes.CategoryGroups -Guild = Base.classes.Guilds -Score = Base.classes.Scores -Submission = Base.classes.Submissions +class Guilds(SQLModel, table=True): + id: int = Field(sa_column=Column(BigInteger(), primary_key=True)) + name: str + submission_channel: int = Field(sa_column=Column(BigInteger())) + verification_channel: int = Field(sa_column=Column(BigInteger())) + active: bool = Field(default=True) + + +# connect with sql alchemy and autoload schema +if config.ENVIRONMENT == "prod": + url = f"mysql+pymysql://{config.SQL_USER}:{config.SQL_PASS}@{config.SQL_HOST}/{config.SQL_DB}" +else: + url = "sqlite:///database.db" +engine = create_engine(url) +SQLModel.metadata.create_all(engine) +# Base = automap_base() +# Base.prepare(autoload_with=engine) + +# # define the classes +# Category = Base.classes.Categories +# CategoryGroup = Base.classes.CategoryGroups +# Guild = Base.classes.Guilds +# Score = Base.classes.Scores +# Submission = Base.classes.Submissions diff --git a/utilities/config.py b/utilities/config.py index dcba7ca..baf0aac 100644 --- a/utilities/config.py +++ b/utilities/config.py @@ -1,6 +1,4 @@ -""" -Loads environment variables for use in bot. -""" +"""Loads environment variables for use in bot.""" import os @@ -15,3 +13,4 @@ SQL_DB = os.getenv("SQL_DB", "") SQL_HOST = os.getenv("SQL_HOST", "") SQL_PASS = os.getenv("SQL_PASS", "") SQL_USER = os.getenv("SQL_USER", "") +ENVIRONMENT: str = os.getenv("ENVIRONMENT", "prod") From 774e6ffedf38a21bd05124d25363c399588e7050 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Thu, 27 Feb 2025 16:28:00 -0500 Subject: [PATCH 03/51] Add CategoryGroup definition. Not working completely, the unique constraint is missing. --- database_setup/database_test.py | 68 ++++++++++++++++++++++++++++++--- 1 file changed, 63 insertions(+), 5 deletions(-) diff --git a/database_setup/database_test.py b/database_setup/database_test.py index ab3d577..2cfe522 100644 --- a/database_setup/database_test.py +++ b/database_setup/database_test.py @@ -1,14 +1,72 @@ -from sqlmodel import BigInteger, Column, Field, SQLModel, create_engine +from sqlalchemy.dialects.mysql import BIGINT, SMALLINT +from sqlmodel import Column, Field, ForeignKey, Relationship, Session, SQLModel, UniqueConstraint, create_engine -class Guilds(SQLModel, table=True): - id: int = Field(sa_column=Column(BigInteger(), primary_key=True)) +class Guild(SQLModel, table=True): + """ + Represents a Guild entity in the database. + + Attributes: + id (int): The unique identifier for the guild. + name (str): The name of the guild. + submission_channel (int): The ID of the submission channel associated with the guild. + verification_channel (int): The ID of the verification channel associated with the guild. + active (bool): Indicates whether the guild is active. Defaults to True. + category_groups (list[CategoryGroup]): A list of category groups associated with the guild. + """ + + __tablename__: str = "Guilds" + + id: int = Field(sa_column=Column(BIGINT(unsigned=True), primary_key=True)) name: str = Field(max_length=95) - submission_channel: int = Field(sa_column=Column(BigInteger())) - verification_channel: int = Field(sa_column=Column(BigInteger())) + submission_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) + verification_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) active: bool = Field(default=True) + category_groups: list["CategoryGroup"] = Relationship(back_populates="guild", cascade_delete=True) + + +class CategoryGroup(SQLModel, table=True): + """ + Represents a category group in the database. + + Attributes: + id (int | None): The primary key of the category group. + name (str): The name of the category group, with a maximum length of 50 characters. + channel_id (int): The ID of the channel associated with the category group. + guild_id (int): The ID of the guild associated with the category group. + message_id (int): The ID of the message associated with the category group. + pad_length (int): The padding length for the category group, default is 12. + username_length (int): The username length for the category group, default is 12. + guild (Guild | None): The guild relationship back-populated from the Guild model. + """ + + __tablename__: str = "CategoryGroups" + + id: int | None = Field(default=None, primary_key=True) + name: str = Field(max_length=50) + channel_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) + guild_id: int = Field(sa_column=Column(BIGINT(unsigned=True), ForeignKey("Guilds.id", ondelete="CASCADE"))) + message_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) + pad_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) + username_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) + + __table_args__ = (UniqueConstraint("guild_id", "name", name="UniqueGuildCategoryGroup"),) + + guild: Guild | None = Relationship(back_populates="category_groups") + url = "sqlite:///database.db" engine = create_engine(url) SQLModel.metadata.create_all(engine) + +with Session(engine) as session: + guild = Guild(id=1, name="test guild", submission_channel=1, verification_channel=2) + session.add(guild) + + group1 = CategoryGroup(name="group1", channel_id=1, guild_id=1, message_id=1) + group2 = CategoryGroup(name="group1", channel_id=2, guild_id=1, message_id=2) + session.add(group1) + session.add(group2) + + session.commit() From 0e262d5972c8d34fe76db4caa427ca3d9da948f3 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Fri, 28 Feb 2025 16:00:58 -0500 Subject: [PATCH 04/51] Add the rest of the tables as SQLModels. --- database_setup/database_test.py | 72 +++++++++++++++++++++++++++++++-- 1 file changed, 68 insertions(+), 4 deletions(-) diff --git a/database_setup/database_test.py b/database_setup/database_test.py index 2cfe522..c91c78f 100644 --- a/database_setup/database_test.py +++ b/database_setup/database_test.py @@ -1,4 +1,4 @@ -from sqlalchemy.dialects.mysql import BIGINT, SMALLINT +from sqlalchemy.dialects.mysql import BIGINT, INTEGER, SMALLINT from sqlmodel import Column, Field, ForeignKey, Relationship, Session, SQLModel, UniqueConstraint, create_engine @@ -17,7 +17,7 @@ class Guild(SQLModel, table=True): __tablename__: str = "Guilds" - id: int = Field(sa_column=Column(BIGINT(unsigned=True), primary_key=True)) + id: int = Field(sa_column=Column(BIGINT(unsigned=True), primary_key=True, nullable=False)) name: str = Field(max_length=95) submission_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) verification_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) @@ -46,7 +46,13 @@ class CategoryGroup(SQLModel, table=True): id: int | None = Field(default=None, primary_key=True) name: str = Field(max_length=50) channel_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) - guild_id: int = Field(sa_column=Column(BIGINT(unsigned=True), ForeignKey("Guilds.id", ondelete="CASCADE"))) + guild_id: int = Field( + sa_column=Column( + BIGINT(unsigned=True), + ForeignKey("Guilds.id", ondelete="CASCADE"), + nullable=False, + ) + ) message_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) pad_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) username_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) @@ -56,6 +62,64 @@ class CategoryGroup(SQLModel, table=True): guild: Guild | None = Relationship(back_populates="category_groups") +class Category(SQLModel, table=True): + __tablename__: str = "Categories" + + id: int | None = Field(default=None, primary_key=True) + name: str = Field(max_length=30) + group_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + ForeignKey("CategoryGroups.id", ondelete="CASCADE"), + nullable=False, + ) + ) + size: int = Field(sa_column=Column(SMALLINT(unsigned=True), default=3, nullable=False)) + is_ascending: bool = Field(default=True, nullable=False) + is_time_record: bool = Field(default=False, nullable=False) + is_validated: bool = Field(default=True, nullable=False) + + __table_args__ = (UniqueConstraint("group_id", "name", name="UniqueCategoryInGroup"),) + + +class Score(SQLModel, table=True): + __tablename__: str = "Scores" + + username: str = Field(max_length=30, nullable=False, primary_key=True) + score: float = Field(nullable=False) + category_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + ForeignKey("Categories.id", ondelete="CASCADE"), + nullable=False, + primary_key=True, + ), + ) + + +class Submission(SQLModel, table=True): + __tablename__: str = "Submissions" + + category_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + nullable=False, + primary_key=True, + ), + ) + group_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + nullable=False, + ) + ) + guild_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + message_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + score: str = Field(max_length=30, nullable=False) + user_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + username: str = Field(max_length=30, nullable=False, primary_key=True) + + url = "sqlite:///database.db" engine = create_engine(url) SQLModel.metadata.create_all(engine) @@ -65,7 +129,7 @@ with Session(engine) as session: session.add(guild) group1 = CategoryGroup(name="group1", channel_id=1, guild_id=1, message_id=1) - group2 = CategoryGroup(name="group1", channel_id=2, guild_id=1, message_id=2) + group2 = CategoryGroup(name="group2", channel_id=2, guild_id=1, message_id=2) session.add(group1) session.add(group2) From bd365d575f2edb32d037208c79f3bf98f74da7b0 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Fri, 28 Feb 2025 16:12:09 -0500 Subject: [PATCH 05/51] Add relationships. --- database_setup/database_test.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/database_setup/database_test.py b/database_setup/database_test.py index c91c78f..05e7090 100644 --- a/database_setup/database_test.py +++ b/database_setup/database_test.py @@ -60,6 +60,7 @@ class CategoryGroup(SQLModel, table=True): __table_args__ = (UniqueConstraint("guild_id", "name", name="UniqueGuildCategoryGroup"),) guild: Guild | None = Relationship(back_populates="category_groups") + categories: list["Category"] | None = Relationship(back_populates="category_group", cascade_delete=True) class Category(SQLModel, table=True): @@ -81,6 +82,9 @@ class Category(SQLModel, table=True): __table_args__ = (UniqueConstraint("group_id", "name", name="UniqueCategoryInGroup"),) + category_group: CategoryGroup | None = Relationship(back_populates="categories") + scores: list["Score"] | None = Relationship(back_populates="category", cascade_delete=True) + class Score(SQLModel, table=True): __tablename__: str = "Scores" @@ -96,6 +100,8 @@ class Score(SQLModel, table=True): ), ) + category: Category | None = Relationship(back_populates="scores") + class Submission(SQLModel, table=True): __tablename__: str = "Submissions" From 171a1b08406447009f4bd4306c4fe57ff8d25ddf Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 14:20:54 -0500 Subject: [PATCH 06/51] Move sql models into their own file. --- database_setup/create_database.py | 13 --- database_setup/database_test.py | 129 +----------------------------- database_setup/models.py | 128 +++++++++++++++++++++++++++++ 3 files changed, 130 insertions(+), 140 deletions(-) delete mode 100644 database_setup/create_database.py create mode 100644 database_setup/models.py diff --git a/database_setup/create_database.py b/database_setup/create_database.py deleted file mode 100644 index 612f614..0000000 --- a/database_setup/create_database.py +++ /dev/null @@ -1,13 +0,0 @@ -"""Small script to create the database if it doesn't already exist.""" - -import sqlite3 -from pathlib import Path - -if not Path("database/dakiny.db").exists(): - with sqlite3.connect("database/dakiny.db") as con: - cur = con.cursor() - - with Path("database_setup/database.sql", encoding="utf-8").open() as file: - database_script = file.read() - cur.executescript(database_script) - con.commit() diff --git a/database_setup/database_test.py b/database_setup/database_test.py index 05e7090..91e9d3e 100644 --- a/database_setup/database_test.py +++ b/database_setup/database_test.py @@ -1,130 +1,5 @@ -from sqlalchemy.dialects.mysql import BIGINT, INTEGER, SMALLINT -from sqlmodel import Column, Field, ForeignKey, Relationship, Session, SQLModel, UniqueConstraint, create_engine - - -class Guild(SQLModel, table=True): - """ - Represents a Guild entity in the database. - - Attributes: - id (int): The unique identifier for the guild. - name (str): The name of the guild. - submission_channel (int): The ID of the submission channel associated with the guild. - verification_channel (int): The ID of the verification channel associated with the guild. - active (bool): Indicates whether the guild is active. Defaults to True. - category_groups (list[CategoryGroup]): A list of category groups associated with the guild. - """ - - __tablename__: str = "Guilds" - - id: int = Field(sa_column=Column(BIGINT(unsigned=True), primary_key=True, nullable=False)) - name: str = Field(max_length=95) - submission_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) - verification_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) - active: bool = Field(default=True) - - category_groups: list["CategoryGroup"] = Relationship(back_populates="guild", cascade_delete=True) - - -class CategoryGroup(SQLModel, table=True): - """ - Represents a category group in the database. - - Attributes: - id (int | None): The primary key of the category group. - name (str): The name of the category group, with a maximum length of 50 characters. - channel_id (int): The ID of the channel associated with the category group. - guild_id (int): The ID of the guild associated with the category group. - message_id (int): The ID of the message associated with the category group. - pad_length (int): The padding length for the category group, default is 12. - username_length (int): The username length for the category group, default is 12. - guild (Guild | None): The guild relationship back-populated from the Guild model. - """ - - __tablename__: str = "CategoryGroups" - - id: int | None = Field(default=None, primary_key=True) - name: str = Field(max_length=50) - channel_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) - guild_id: int = Field( - sa_column=Column( - BIGINT(unsigned=True), - ForeignKey("Guilds.id", ondelete="CASCADE"), - nullable=False, - ) - ) - message_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) - pad_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) - username_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) - - __table_args__ = (UniqueConstraint("guild_id", "name", name="UniqueGuildCategoryGroup"),) - - guild: Guild | None = Relationship(back_populates="category_groups") - categories: list["Category"] | None = Relationship(back_populates="category_group", cascade_delete=True) - - -class Category(SQLModel, table=True): - __tablename__: str = "Categories" - - id: int | None = Field(default=None, primary_key=True) - name: str = Field(max_length=30) - group_id: int = Field( - sa_column=Column( - INTEGER(unsigned=True), - ForeignKey("CategoryGroups.id", ondelete="CASCADE"), - nullable=False, - ) - ) - size: int = Field(sa_column=Column(SMALLINT(unsigned=True), default=3, nullable=False)) - is_ascending: bool = Field(default=True, nullable=False) - is_time_record: bool = Field(default=False, nullable=False) - is_validated: bool = Field(default=True, nullable=False) - - __table_args__ = (UniqueConstraint("group_id", "name", name="UniqueCategoryInGroup"),) - - category_group: CategoryGroup | None = Relationship(back_populates="categories") - scores: list["Score"] | None = Relationship(back_populates="category", cascade_delete=True) - - -class Score(SQLModel, table=True): - __tablename__: str = "Scores" - - username: str = Field(max_length=30, nullable=False, primary_key=True) - score: float = Field(nullable=False) - category_id: int = Field( - sa_column=Column( - INTEGER(unsigned=True), - ForeignKey("Categories.id", ondelete="CASCADE"), - nullable=False, - primary_key=True, - ), - ) - - category: Category | None = Relationship(back_populates="scores") - - -class Submission(SQLModel, table=True): - __tablename__: str = "Submissions" - - category_id: int = Field( - sa_column=Column( - INTEGER(unsigned=True), - nullable=False, - primary_key=True, - ), - ) - group_id: int = Field( - sa_column=Column( - INTEGER(unsigned=True), - nullable=False, - ) - ) - guild_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) - message_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) - score: str = Field(max_length=30, nullable=False) - user_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) - username: str = Field(max_length=30, nullable=False, primary_key=True) - +from database_setup.models import CategoryGroup, Guild +from sqlmodel import Session, SQLModel, create_engine url = "sqlite:///database.db" engine = create_engine(url) diff --git a/database_setup/models.py b/database_setup/models.py new file mode 100644 index 0000000..cc6be82 --- /dev/null +++ b/database_setup/models.py @@ -0,0 +1,128 @@ +"""File holds all model definitions of SQL tables.""" + +from sqlalchemy.dialects.mysql import BIGINT, INTEGER, SMALLINT +from sqlmodel import Column, Field, ForeignKey, Relationship, SQLModel, UniqueConstraint + + +class Guild(SQLModel, table=True): + """ + Represents a Guild entity in the database. + + Attributes: + id (int): The unique identifier for the guild. + name (str): The name of the guild. + submission_channel (int): The ID of the submission channel associated with the guild. + verification_channel (int): The ID of the verification channel associated with the guild. + active (bool): Indicates whether the guild is active. Defaults to True. + category_groups (list[CategoryGroup]): A list of category groups associated with the guild. + """ + + __tablename__: str = "Guilds" + + id: int = Field(sa_column=Column(BIGINT(unsigned=True), primary_key=True, nullable=False)) + name: str = Field(max_length=95) + submission_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) + verification_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) + active: bool = Field(default=True) + + category_groups: list["CategoryGroup"] = Relationship(back_populates="guild", cascade_delete=True) + + +class CategoryGroup(SQLModel, table=True): + """ + Represents a category group in the database. + + Attributes: + id (int | None): The primary key of the category group. + name (str): The name of the category group, with a maximum length of 50 characters. + channel_id (int): The ID of the channel associated with the category group. + guild_id (int): The ID of the guild associated with the category group. + message_id (int): The ID of the message associated with the category group. + pad_length (int): The padding length for the category group, default is 12. + username_length (int): The username length for the category group, default is 12. + guild (Guild | None): The guild relationship back-populated from the Guild model. + """ + + __tablename__: str = "CategoryGroups" + + id: int | None = Field(default=None, primary_key=True) + name: str = Field(max_length=50) + channel_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) + guild_id: int = Field( + sa_column=Column( + BIGINT(unsigned=True), + ForeignKey("Guilds.id", ondelete="CASCADE"), + nullable=False, + ) + ) + message_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) + pad_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) + username_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) + + __table_args__ = (UniqueConstraint("guild_id", "name", name="UniqueGuildCategoryGroup"),) + + guild: Guild | None = Relationship(back_populates="category_groups") + categories: list["Category"] | None = Relationship(back_populates="category_group", cascade_delete=True) + + +class Category(SQLModel, table=True): + __tablename__: str = "Categories" + + id: int | None = Field(default=None, primary_key=True) + name: str = Field(max_length=30) + group_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + ForeignKey("CategoryGroups.id", ondelete="CASCADE"), + nullable=False, + ) + ) + size: int = Field(sa_column=Column(SMALLINT(unsigned=True), default=3, nullable=False)) + is_ascending: bool = Field(default=True, nullable=False) + is_time_record: bool = Field(default=False, nullable=False) + is_validated: bool = Field(default=True, nullable=False) + + __table_args__ = (UniqueConstraint("group_id", "name", name="UniqueCategoryInGroup"),) + + category_group: CategoryGroup | None = Relationship(back_populates="categories") + scores: list["Score"] | None = Relationship(back_populates="category", cascade_delete=True) + + +class Score(SQLModel, table=True): + __tablename__: str = "Scores" + + username: str = Field(max_length=30, nullable=False, primary_key=True) + score: float = Field(nullable=False) + category_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + ForeignKey("Categories.id", ondelete="CASCADE"), + nullable=False, + primary_key=True, + ), + ) + + category: Category | None = Relationship(back_populates="scores") + + +class Submission(SQLModel, table=True): + __tablename__: str = "Submissions" + + category_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + nullable=False, + primary_key=True, + ), + ) + group_id: int = Field( + sa_column=Column( + INTEGER(unsigned=True), + nullable=False, + ) + ) + guild_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + message_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + score: str = Field(max_length=30, nullable=False) + user_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + username: str = Field(max_length=30, nullable=False, primary_key=True) From e13790ba086c7417a78300ae0ae1424374f75776 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 14:27:26 -0500 Subject: [PATCH 07/51] Add rest of docstrings. --- database_setup/models.py | 49 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/database_setup/models.py b/database_setup/models.py index cc6be82..6c23d36 100644 --- a/database_setup/models.py +++ b/database_setup/models.py @@ -41,6 +41,9 @@ class CategoryGroup(SQLModel, table=True): pad_length (int): The padding length for the category group, default is 12. username_length (int): The username length for the category group, default is 12. guild (Guild | None): The guild relationship back-populated from the Guild model. + + Table Constraints: + __table_args__: Unique constraint on guild_id and name to ensure unique category groups within a guild. """ __tablename__: str = "CategoryGroups" @@ -66,9 +69,28 @@ class CategoryGroup(SQLModel, table=True): class Category(SQLModel, table=True): + """ + Represents a category in the database. + + Attributes: + id (int): The unique identifier for the category. Primary key. + name (str): The name of the category with a maximum length of 30 characters. + group_id (int): The identifier of the group to which the category belongs. + Foreign key referencing CategoryGroups.id. + size (int): The size attribute of the category, default is 3. + is_ascending (bool): Indicates if the category is in ascending order. Default is True. + is_time_record (bool): Indicates if the category is a time record. Default is False. + is_validated (bool): Indicates if the category is validated. Default is True. + category_group (CategoryGroup | None): The relationship to the CategoryGroup model. + scores (list["Score"] | None): The relationship to the Score model with cascade delete enabled. + + Table Constraints: + __table_args__: Unique constraint on group_id and name to ensure unique category names within a group. + """ + __tablename__: str = "Categories" - id: int | None = Field(default=None, primary_key=True) + id: int = Field(default=None, primary_key=True) name: str = Field(max_length=30) group_id: int = Field( sa_column=Column( @@ -89,6 +111,18 @@ class Category(SQLModel, table=True): class Score(SQLModel, table=True): + """ + Represents a score entry in the database. + + Attributes: + username (str): The username associated with the score. This is a primary key. + score (float): The score value. + category_id (int): The ID of the category this score belongs to. This is a primary key and a foreign key + referencing the Categories table. + category (Category | None): The relationship to the Category model, back-populated by the scores attribute + in the Category model. + """ + __tablename__: str = "Scores" username: str = Field(max_length=30, nullable=False, primary_key=True) @@ -106,6 +140,19 @@ class Score(SQLModel, table=True): class Submission(SQLModel, table=True): + """ + Represents a submission in the database. + + Attributes: + category_id (int): The ID of the category. This is a primary key. + group_id (int): The ID of the group. + guild_id (int): The ID of the guild. + message_id (int): The ID of the message. + score (str): The score of the submission, with a maximum length of 30 characters. + user_id (int): The ID of the user. + username (str): The username of the user. This is a primary key. + """ + __tablename__: str = "Submissions" category_id: int = Field( From 0ea9ef5b4188c9b9ea61e331c360e43cc8c1e438 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 14:29:50 -0500 Subject: [PATCH 08/51] Rename sql_data_classes to db. --- cogs/commands/create.py | 2 +- cogs/commands/delete.py | 2 +- cogs/commands/refresh.py | 2 +- cogs/commands/set.py | 2 +- cogs/commands/submission.py | 2 +- cogs/commands/update.py | 2 +- cogs/commands/view.py | 2 +- cogs/commands/views/delete_confirm.py | 2 +- cogs/commands/views/update_username_verify.py | 2 +- cogs/guild_listener/__init__.py | 2 +- cogs/loops/guild_data.py | 2 +- cogs/submission/verification_view.py | 2 +- database_setup/{sql_data_classes.py => db.py} | 0 utilities/utils.py | 2 +- 14 files changed, 13 insertions(+), 13 deletions(-) rename database_setup/{sql_data_classes.py => db.py} (100%) diff --git a/cogs/commands/create.py b/cogs/commands/create.py index 3b0208c..843dfe9 100644 --- a/cogs/commands/create.py +++ b/cogs/commands/create.py @@ -5,7 +5,7 @@ from nextcord.ext import commands from sqlalchemy import exc, select from sqlalchemy.orm import Session -from database_setup.sql_data_classes import Category, CategoryGroup, engine +from database_setup.db import Category, CategoryGroup, engine from utilities.utils import MAX_LINE_LENGTH, autofill_groups, send_highscore_message diff --git a/cogs/commands/delete.py b/cogs/commands/delete.py index bb5d936..616333b 100644 --- a/cogs/commands/delete.py +++ b/cogs/commands/delete.py @@ -6,7 +6,7 @@ from sqlalchemy import distinct, select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import Category, CategoryGroup, Score, engine +from database_setup.db import Category, CategoryGroup, Score, engine from utilities.utils import ( autofill_categories, autofill_groups, diff --git a/cogs/commands/refresh.py b/cogs/commands/refresh.py index 46f152c..020e66f 100644 --- a/cogs/commands/refresh.py +++ b/cogs/commands/refresh.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import CategoryGroup, engine +from database_setup.db import CategoryGroup, engine from utilities.utils import autofill_groups, send_highscore_message diff --git a/cogs/commands/set.py b/cogs/commands/set.py index 21a431b..0d66276 100644 --- a/cogs/commands/set.py +++ b/cogs/commands/set.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import CategoryGroup, Guild, engine +from database_setup.db import CategoryGroup, Guild, engine from utilities.utils import MAX_LINE_LENGTH, autofill_groups diff --git a/cogs/commands/submission.py b/cogs/commands/submission.py index 857d048..cc8ef24 100644 --- a/cogs/commands/submission.py +++ b/cogs/commands/submission.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session from cogs.submission.verification_view import VerificationView -from database_setup.sql_data_classes import Category, CategoryGroup, Guild, Submission, engine +from database_setup.db import Category, CategoryGroup, Guild, Submission, engine from main import logger from utilities.utils import autofill_categories, autofill_groups, submit_score diff --git a/cogs/commands/update.py b/cogs/commands/update.py index 4c1c853..ae46474 100644 --- a/cogs/commands/update.py +++ b/cogs/commands/update.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import Guild, engine +from database_setup.db import Guild, engine from utilities.utils import autofill_users_in_guild from .views.update_username_verify import UpdateUsernameVerifyView diff --git a/cogs/commands/view.py b/cogs/commands/view.py index 3c308a0..d53d6bf 100644 --- a/cogs/commands/view.py +++ b/cogs/commands/view.py @@ -7,7 +7,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import Category, CategoryGroup, Score, engine +from database_setup.db import Category, CategoryGroup, Score, engine from utilities.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, format_score_string diff --git a/cogs/commands/views/delete_confirm.py b/cogs/commands/views/delete_confirm.py index e950441..c1a0c06 100644 --- a/cogs/commands/views/delete_confirm.py +++ b/cogs/commands/views/delete_confirm.py @@ -7,7 +7,7 @@ from sqlalchemy import delete, select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import Category, CategoryGroup, engine +from database_setup.db import Category, CategoryGroup, engine from utilities.utils import send_highscore_message diff --git a/cogs/commands/views/update_username_verify.py b/cogs/commands/views/update_username_verify.py index 0e494d7..a13261d 100644 --- a/cogs/commands/views/update_username_verify.py +++ b/cogs/commands/views/update_username_verify.py @@ -5,7 +5,7 @@ from sqlalchemy import distinct, exc, select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import Category, CategoryGroup, Score, engine +from database_setup.db import Category, CategoryGroup, Score, engine from utilities.utils import send_highscore_message diff --git a/cogs/guild_listener/__init__.py b/cogs/guild_listener/__init__.py index 6838c28..0892ad2 100644 --- a/cogs/guild_listener/__init__.py +++ b/cogs/guild_listener/__init__.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import Guild, engine +from database_setup.db import Guild, engine class GuildListener(commands.Cog, name="Guild Listener"): diff --git a/cogs/loops/guild_data.py b/cogs/loops/guild_data.py index 0c6d227..3a47035 100644 --- a/cogs/loops/guild_data.py +++ b/cogs/loops/guild_data.py @@ -7,7 +7,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.sql_data_classes import Guild, engine +from database_setup.db import Guild, engine class GuildData(commands.Cog, name="Guild Data"): diff --git a/cogs/submission/verification_view.py b/cogs/submission/verification_view.py index df9b2ee..0acb654 100644 --- a/cogs/submission/verification_view.py +++ b/cogs/submission/verification_view.py @@ -4,7 +4,7 @@ import nextcord from sqlalchemy import delete, select from sqlalchemy.orm import Session -from database_setup.sql_data_classes import Submission, engine +from database_setup.db import Submission, engine # pylint: disable=import-error from utilities.utils import submit_score diff --git a/database_setup/sql_data_classes.py b/database_setup/db.py similarity index 100% rename from database_setup/sql_data_classes.py rename to database_setup/db.py diff --git a/utilities/utils.py b/utilities/utils.py index 855c24f..c85040a 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -8,7 +8,7 @@ from sqlalchemy import distinct, select from sqlalchemy.orm import Session, aliased # pylint: disable=import-error -from database_setup.sql_data_classes import Category, CategoryGroup, Guild, Score, engine +from database_setup.db import Category, CategoryGroup, Guild, Score, engine MAX_LINE_LENGTH = 142 From 7a57b75ca371bc9ede8a05ce865dad6e177dd683 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 14:41:24 -0500 Subject: [PATCH 09/51] Add comments to models. --- database_setup/models.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/database_setup/models.py b/database_setup/models.py index 6c23d36..f0fb0e9 100644 --- a/database_setup/models.py +++ b/database_setup/models.py @@ -21,6 +21,7 @@ class Guild(SQLModel, table=True): id: int = Field(sa_column=Column(BIGINT(unsigned=True), primary_key=True, nullable=False)) name: str = Field(max_length=95) + # deprecated, not currently used. submission_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) verification_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) active: bool = Field(default=True) @@ -170,6 +171,7 @@ class Submission(SQLModel, table=True): ) guild_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) message_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + # Score is stored as a string until converted during submission. score: str = Field(max_length=30, nullable=False) user_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) username: str = Field(max_length=30, nullable=False, primary_key=True) From 36eae177516d45c9c7dc123c9420787ca6281e25 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 15:16:24 -0500 Subject: [PATCH 10/51] Update db.py just contain engine and create database. --- database_setup/db.py | 27 +++++---------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/database_setup/db.py b/database_setup/db.py index a9147b9..8c3d97d 100644 --- a/database_setup/db.py +++ b/database_setup/db.py @@ -1,32 +1,15 @@ -"""Simple file to set up the sqlalchemy connection to database.""" +"""Simple file to set up the sqlmodel connection to database.""" -# from sqlalchemy import create_engine -# from sqlalchemy.ext.automap import automap_base -from sqlmodel import BigInteger, Column, Field, SQLModel, create_engine +from sqlmodel import SQLModel, create_engine from utilities import config +from . import models # noqa: F401 Need this import for creating the models. -class Guilds(SQLModel, table=True): - id: int = Field(sa_column=Column(BigInteger(), primary_key=True)) - name: str - submission_channel: int = Field(sa_column=Column(BigInteger())) - verification_channel: int = Field(sa_column=Column(BigInteger())) - active: bool = Field(default=True) - - -# connect with sql alchemy and autoload schema if config.ENVIRONMENT == "prod": url = f"mysql+pymysql://{config.SQL_USER}:{config.SQL_PASS}@{config.SQL_HOST}/{config.SQL_DB}" else: url = "sqlite:///database.db" engine = create_engine(url) -SQLModel.metadata.create_all(engine) -# Base = automap_base() -# Base.prepare(autoload_with=engine) -# # define the classes -# Category = Base.classes.Categories -# CategoryGroup = Base.classes.CategoryGroups -# Guild = Base.classes.Guilds -# Score = Base.classes.Scores -# Submission = Base.classes.Submissions +# Don't need to create all when connected to prod. +SQLModel.metadata.create_all(engine) From f1f0c0c6de496ced0448dc6514346045d0632f0e Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 15:18:31 -0500 Subject: [PATCH 11/51] Rename database_setup directory to database. --- cogs/commands/create.py | 2 +- cogs/commands/delete.py | 2 +- cogs/commands/refresh.py | 2 +- cogs/commands/set.py | 2 +- cogs/commands/submission.py | 2 +- cogs/commands/update.py | 2 +- cogs/commands/view.py | 2 +- cogs/commands/views/delete_confirm.py | 2 +- cogs/commands/views/update_username_verify.py | 2 +- cogs/guild_listener/__init__.py | 2 +- cogs/loops/guild_data.py | 2 +- cogs/submission/verification_view.py | 2 +- {database_setup => database}/database_test.py | 3 ++- {database_setup => database}/db.py | 0 {database_setup => database}/models.py | 0 {database_setup => database}/pyproject.toml | 0 utilities/utils.py | 2 +- 17 files changed, 15 insertions(+), 14 deletions(-) rename {database_setup => database}/database_test.py (90%) rename {database_setup => database}/db.py (100%) rename {database_setup => database}/models.py (100%) rename {database_setup => database}/pyproject.toml (100%) diff --git a/cogs/commands/create.py b/cogs/commands/create.py index 843dfe9..b5214f6 100644 --- a/cogs/commands/create.py +++ b/cogs/commands/create.py @@ -5,7 +5,7 @@ from nextcord.ext import commands from sqlalchemy import exc, select from sqlalchemy.orm import Session -from database_setup.db import Category, CategoryGroup, engine +from database.db import Category, CategoryGroup, engine from utilities.utils import MAX_LINE_LENGTH, autofill_groups, send_highscore_message diff --git a/cogs/commands/delete.py b/cogs/commands/delete.py index 616333b..d7325ef 100644 --- a/cogs/commands/delete.py +++ b/cogs/commands/delete.py @@ -6,7 +6,7 @@ from sqlalchemy import distinct, select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import Category, CategoryGroup, Score, engine +from database.db import Category, CategoryGroup, Score, engine from utilities.utils import ( autofill_categories, autofill_groups, diff --git a/cogs/commands/refresh.py b/cogs/commands/refresh.py index 020e66f..fef3415 100644 --- a/cogs/commands/refresh.py +++ b/cogs/commands/refresh.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import CategoryGroup, engine +from database.db import CategoryGroup, engine from utilities.utils import autofill_groups, send_highscore_message diff --git a/cogs/commands/set.py b/cogs/commands/set.py index 0d66276..6026ce8 100644 --- a/cogs/commands/set.py +++ b/cogs/commands/set.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import CategoryGroup, Guild, engine +from database.db import CategoryGroup, Guild, engine from utilities.utils import MAX_LINE_LENGTH, autofill_groups diff --git a/cogs/commands/submission.py b/cogs/commands/submission.py index cc8ef24..2d89bfb 100644 --- a/cogs/commands/submission.py +++ b/cogs/commands/submission.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session from cogs.submission.verification_view import VerificationView -from database_setup.db import Category, CategoryGroup, Guild, Submission, engine +from database.db import Category, CategoryGroup, Guild, Submission, engine from main import logger from utilities.utils import autofill_categories, autofill_groups, submit_score diff --git a/cogs/commands/update.py b/cogs/commands/update.py index ae46474..671eece 100644 --- a/cogs/commands/update.py +++ b/cogs/commands/update.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import Guild, engine +from database.db import Guild, engine from utilities.utils import autofill_users_in_guild from .views.update_username_verify import UpdateUsernameVerifyView diff --git a/cogs/commands/view.py b/cogs/commands/view.py index d53d6bf..f1b6f0a 100644 --- a/cogs/commands/view.py +++ b/cogs/commands/view.py @@ -7,7 +7,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import Category, CategoryGroup, Score, engine +from database.db import Category, CategoryGroup, Score, engine from utilities.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, format_score_string diff --git a/cogs/commands/views/delete_confirm.py b/cogs/commands/views/delete_confirm.py index c1a0c06..85b3145 100644 --- a/cogs/commands/views/delete_confirm.py +++ b/cogs/commands/views/delete_confirm.py @@ -7,7 +7,7 @@ from sqlalchemy import delete, select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import Category, CategoryGroup, engine +from database.db import Category, CategoryGroup, engine from utilities.utils import send_highscore_message diff --git a/cogs/commands/views/update_username_verify.py b/cogs/commands/views/update_username_verify.py index a13261d..3aefd27 100644 --- a/cogs/commands/views/update_username_verify.py +++ b/cogs/commands/views/update_username_verify.py @@ -5,7 +5,7 @@ from sqlalchemy import distinct, exc, select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import Category, CategoryGroup, Score, engine +from database.db import Category, CategoryGroup, Score, engine from utilities.utils import send_highscore_message diff --git a/cogs/guild_listener/__init__.py b/cogs/guild_listener/__init__.py index 0892ad2..c3df5a6 100644 --- a/cogs/guild_listener/__init__.py +++ b/cogs/guild_listener/__init__.py @@ -8,7 +8,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import Guild, engine +from database.db import Guild, engine class GuildListener(commands.Cog, name="Guild Listener"): diff --git a/cogs/loops/guild_data.py b/cogs/loops/guild_data.py index 3a47035..3760731 100644 --- a/cogs/loops/guild_data.py +++ b/cogs/loops/guild_data.py @@ -7,7 +7,7 @@ from sqlalchemy import select from sqlalchemy.orm import Session # pylint: disable=import-error -from database_setup.db import Guild, engine +from database.db import Guild, engine class GuildData(commands.Cog, name="Guild Data"): diff --git a/cogs/submission/verification_view.py b/cogs/submission/verification_view.py index 0acb654..7cdd522 100644 --- a/cogs/submission/verification_view.py +++ b/cogs/submission/verification_view.py @@ -4,7 +4,7 @@ import nextcord from sqlalchemy import delete, select from sqlalchemy.orm import Session -from database_setup.db import Submission, engine +from database.db import Submission, engine # pylint: disable=import-error from utilities.utils import submit_score diff --git a/database_setup/database_test.py b/database/database_test.py similarity index 90% rename from database_setup/database_test.py rename to database/database_test.py index 91e9d3e..b2ba0f0 100644 --- a/database_setup/database_test.py +++ b/database/database_test.py @@ -1,6 +1,7 @@ -from database_setup.models import CategoryGroup, Guild from sqlmodel import Session, SQLModel, create_engine +from database.models import CategoryGroup, Guild + url = "sqlite:///database.db" engine = create_engine(url) SQLModel.metadata.create_all(engine) diff --git a/database_setup/db.py b/database/db.py similarity index 100% rename from database_setup/db.py rename to database/db.py diff --git a/database_setup/models.py b/database/models.py similarity index 100% rename from database_setup/models.py rename to database/models.py diff --git a/database_setup/pyproject.toml b/database/pyproject.toml similarity index 100% rename from database_setup/pyproject.toml rename to database/pyproject.toml diff --git a/utilities/utils.py b/utilities/utils.py index c85040a..47f9abb 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -8,7 +8,7 @@ from sqlalchemy import distinct, select from sqlalchemy.orm import Session, aliased # pylint: disable=import-error -from database_setup.db import Category, CategoryGroup, Guild, Score, engine +from database.db import Category, CategoryGroup, Guild, Score, engine MAX_LINE_LENGTH = 142 From 0b2a1cd2936f6cc4a79f9f7ce7d98637e9428bdc Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 15:19:46 -0500 Subject: [PATCH 12/51] Organize import in db.py. --- database/db.py | 1 + 1 file changed, 1 insertion(+) diff --git a/database/db.py b/database/db.py index 8c3d97d..161db71 100644 --- a/database/db.py +++ b/database/db.py @@ -1,6 +1,7 @@ """Simple file to set up the sqlmodel connection to database.""" from sqlmodel import SQLModel, create_engine + from utilities import config from . import models # noqa: F401 Need this import for creating the models. From b72dd35e04eccaccf64ad838af8bb7e4155f8e97 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 15:28:00 -0500 Subject: [PATCH 13/51] Add init file to the database package. --- database/__init__.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 database/__init__.py diff --git a/database/__init__.py b/database/__init__.py new file mode 100644 index 0000000..920815a --- /dev/null +++ b/database/__init__.py @@ -0,0 +1 @@ +"""Package for database interaction.""" From 1c3fb231b771f7d4364aea46294dd6fb81b543ca Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 15:54:20 -0500 Subject: [PATCH 14/51] Add more cspell words. --- .vscode/settings.json | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 0ba4286..815a7fb 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,11 +1,8 @@ { - "cSpell.words": [ - "highscore", - "highscores" - ], + "cSpell.words": ["gmtime", "highscore", "highscores", "imcompiling", "nextcord"], "python.analysis.diagnosticSeverityOverrides": { "reportOptionalMemberAccess": false, "reportArgumentType": "information", "reportAttributeAccessIssue": "warning" } -} \ No newline at end of file +} From 157b8d4f3fe12ae4c6951639393575ad5706d5c2 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 15:54:28 -0500 Subject: [PATCH 15/51] Begin updating utils. --- utilities/utils.py | 59 ++++++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/utilities/utils.py b/utilities/utils.py index 47f9abb..c709320 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -8,7 +8,8 @@ from sqlalchemy import distinct, select from sqlalchemy.orm import Session, aliased # pylint: disable=import-error -from database.db import Category, CategoryGroup, Guild, Score, engine +from database.db import engine +from database.models import Category, CategoryGroup, Guild, Score MAX_LINE_LENGTH = 142 @@ -31,13 +32,13 @@ def autofill_categories(guild_id: int, group_id: int, category_begin: str) -> "d # search database for all category names subq = ( select(CategoryGroup) - .where(CategoryGroup.GuildId == guild_id) - .where(CategoryGroup.GroupId == group_id) + .where(CategoryGroup.guild_id == guild_id) + .where(CategoryGroup.id == group_id) .subquery() ) cat_group_alias = aliased(CategoryGroup, subq) - stmt = select(Category).where(Category.GroupId == cat_group_alias.GroupId) - categories_dict: dict[str, str] = {cat.CategoryName: str(cat.CategoryId) for cat in session.scalars(stmt)} + stmt = select(Category).where(Category.group_id == cat_group_alias.id) + categories_dict: dict[str, str] = {cat.name: str(cat.id) for cat in session.scalars(stmt)} # if string empty, return all category names if not category_begin: @@ -64,10 +65,10 @@ 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).where(CategoryGroup.GuildId == guild_id) + stmt = select(CategoryGroup).where(CategoryGroup.guild_id == guild_id) # dict has to have key values of same type for discord. - group_dict: dict[str, str] = {group.GroupName: str(group.GroupId) for group in session.scalars(stmt)} + group_dict: dict[str, str] = {group.name: str(group.id) for group in session.scalars(stmt)} # if string empty, return all group names if not group_begin: @@ -83,8 +84,10 @@ def autofill_groups(guild_id: int, group_begin: str) -> "dict[str, str]": def autofill_users_in_group_category(guild_id: int, group_id: int, category_id: int, user_begin: str) -> "list[str]": """ - Returns list of users that match user_begin. Either all users in group or just users in category if category is - not None. Might be expensive due to unioning all users in group. + Returns list of users that match user_begin. + + Either all users in group or just users in category if category is not None. Might be expensive due to union-ing all + users in group. Args: guild_id (int): Guild id corresponding to group and category. @@ -99,27 +102,27 @@ def autofill_users_in_group_category(guild_id: int, group_id: int, category_id: # get all categories in the group subq = ( select(CategoryGroup) - .where(CategoryGroup.GuildId == guild_id) - .where(CategoryGroup.GroupId == group_id) + .where(CategoryGroup.guild_id == guild_id) + .where(CategoryGroup.id == group_id) .subquery() ) category_group = aliased(CategoryGroup, subq) # If no category id, get all users in group. if category_id == 0: - subq = select(Category.CategoryId).where(Category.GroupId == category_group.GroupId) - stmt = select(distinct(Score.UserName)).where(Score.CategoryId.in_(subq)) + subq = select(Category.id).where(Category.group_id == category_group.id) + stmt = select(distinct(Score.username)).where(Score.category_id.in_(subq)) else: # get all users in category_id subq = ( select(Category) - .where(Category.GroupId == category_group.GroupId) - .where(Category.CategoryId == category_id) + .where(Category.group_id == category_group.id) + .where(Category.id == category_id) .subquery() ) category = aliased(Category, subq) - stmt = select(distinct(Score.UserName)).where(Score.CategoryId == category.CategoryId) + stmt = select(distinct(Score.username)).where(Score.category == category.id) users_list: list[str] = list(session.scalars(stmt)) @@ -145,9 +148,9 @@ def autofill_users_in_guild(guild_id: int, user_begin: str) -> "list[str]": list[str]: All users with submissions in the guild. """ with Session(engine) as session: - group_ids = select(CategoryGroup.GroupId).where(CategoryGroup.GuildId == guild_id) - category_ids = select(Category.CategoryId).where(Category.GroupId.in_(group_ids)) - stmt = select(distinct(Score.UserName)).where(Score.CategoryId.in_(category_ids)) + group_ids = select(CategoryGroup.id).where(CategoryGroup.guild_id == guild_id) + category_ids = select(Category.id).where(Category.group_id.in_(group_ids)) + stmt = select(distinct(Score.username)).where(Score.category_id.in_(category_ids)) users_list: list[str] = list(session.scalars(stmt)) # if string empty, return all users @@ -176,34 +179,34 @@ def format_highscore_message(session: Session, group: CategoryGroup) -> str: Returns: str: Formatted string for discord message """ - ret_string = f"**{group.GroupName}**\n```" + ret_string = f"**{group.name}**\n```" - stmt = select(Guild).where(Guild.GuildId == group.GuildId) + stmt = select(Guild).where(Guild.id == group.guild_id) # Get all categories in the group subq = ( select(CategoryGroup) - .where(CategoryGroup.GuildId == group.GuildId) - .where(CategoryGroup.GroupName == group.GroupName) + .where(CategoryGroup.guild_id == group.guild_id) + .where(CategoryGroup.name == group.name) .subquery() ) cat_group_alias = aliased(CategoryGroup, subq) - stmt = select(Category).where(Category.GroupId == cat_group_alias.GroupId) + stmt = select(Category).where(Category.group_id == cat_group_alias.id) # set up a map for the categories # also grab the max category size categories = [] category_ids = [] max_cat_size: int = 0 - pad_length = group.PadLength + pad_length = group.pad_length for cat in session.scalars(stmt): - max_cat_size = max(cat.Size, max_cat_size) + max_cat_size = max(cat.size, max_cat_size) categories.append(cat) - category_ids.append(cat.CategoryId) + category_ids.append(cat.id) # get all scores in category group, load into data frame. d_f = pd.read_sql_query( - sql=session.query(Score).where(Score.CategoryId.in_(category_ids)).statement, + sql=session.query(Score).where(Score.category_id.in_(category_ids)).statement, con=engine, ) From 37fb9c1abb7ead6d00ef9742438f9d7b887ad320 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 21:01:59 -0500 Subject: [PATCH 16/51] Use col to correct type hint errors. --- utilities/utils.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/utilities/utils.py b/utilities/utils.py index c709320..c3868b3 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -6,6 +6,7 @@ import nextcord import pandas as pd from sqlalchemy import distinct, select from sqlalchemy.orm import Session, aliased +from sqlmodel import col # pylint: disable=import-error from database.db import engine @@ -32,12 +33,12 @@ def autofill_categories(guild_id: int, group_id: int, category_begin: str) -> "d # search database for all category names subq = ( select(CategoryGroup) - .where(CategoryGroup.guild_id == guild_id) - .where(CategoryGroup.id == group_id) + .where(col(CategoryGroup.guild_id) == guild_id) + .where(col(CategoryGroup.id) == group_id) .subquery() ) cat_group_alias = aliased(CategoryGroup, subq) - stmt = select(Category).where(Category.group_id == cat_group_alias.id) + stmt = select(Category).where(col(Category.group_id) == cat_group_alias.id) categories_dict: dict[str, str] = {cat.name: str(cat.id) for cat in session.scalars(stmt)} # if string empty, return all category names @@ -45,7 +46,6 @@ def autofill_categories(guild_id: int, group_id: int, category_begin: str) -> "d return dict(list(categories_dict.items())[:25]) # else find all categories that start with category_begin - # TODO is it better to have sql handle the starts with or python? categories: dict[str, str] = { cat_name: cat_id for cat_name, cat_id in categories_dict.items() if category_begin.lower() in cat_name.lower() } @@ -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).where(CategoryGroup.guild_id == guild_id) + stmt = select(CategoryGroup).wherecol((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)} @@ -102,16 +102,16 @@ def autofill_users_in_group_category(guild_id: int, group_id: int, category_id: # get all categories in the group subq = ( select(CategoryGroup) - .where(CategoryGroup.guild_id == guild_id) - .where(CategoryGroup.id == group_id) + .where(col(CategoryGroup.guild_id) == guild_id) + .where(col(CategoryGroup.id) == group_id) .subquery() ) category_group = aliased(CategoryGroup, subq) # If no category id, get all users in group. if category_id == 0: - subq = select(Category.id).where(Category.group_id == category_group.id) - stmt = select(distinct(Score.username)).where(Score.category_id.in_(subq)) + subq = select(col(Category.id)).where(Category.group_id == category_group.id) + stmt = select(distinct(col(Score.username))).where(col(Score.category_id).in_(subq)) else: # get all users in category_id @@ -148,8 +148,8 @@ def autofill_users_in_guild(guild_id: int, user_begin: str) -> "list[str]": list[str]: All users with submissions in the guild. """ with Session(engine) as session: - group_ids = select(CategoryGroup.id).where(CategoryGroup.guild_id == guild_id) - category_ids = select(Category.id).where(Category.group_id.in_(group_ids)) + group_ids = select(col(CategoryGroup.id)).where(CategoryGroup.guild_id == guild_id) + category_ids = select(Category.id).where(col(Category.group_id).in_(group_ids)) stmt = select(distinct(Score.username)).where(Score.category_id.in_(category_ids)) users_list: list[str] = list(session.scalars(stmt)) From cf5629a6dd8b78be9a7b72c6e7b473842ce731b8 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 21:52:30 -0500 Subject: [PATCH 17/51] Finish updating utils to use new models. --- utilities/utils.py | 78 ++++++++++++++++++++++++---------------------- 1 file changed, 40 insertions(+), 38 deletions(-) diff --git a/utilities/utils.py b/utilities/utils.py index c3868b3..38faba8 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -110,19 +110,19 @@ def autofill_users_in_group_category(guild_id: int, group_id: int, category_id: # If no category id, get all users in group. if category_id == 0: - subq = select(col(Category.id)).where(Category.group_id == category_group.id) + subq = select(col(Category.id)).where(col(Category.group_id) == category_group.id) stmt = select(distinct(col(Score.username))).where(col(Score.category_id).in_(subq)) else: # get all users in category_id subq = ( select(Category) - .where(Category.group_id == category_group.id) - .where(Category.id == category_id) + .where(col(Category.group_id) == category_group.id) + .where(col(Category.id) == category_id) .subquery() ) category = aliased(Category, subq) - stmt = select(distinct(Score.username)).where(Score.category == category.id) + stmt = select(distinct(col(Score.username))).where(col(Score.category_id) == category.id) users_list: list[str] = list(session.scalars(stmt)) @@ -148,9 +148,9 @@ def autofill_users_in_guild(guild_id: int, user_begin: str) -> "list[str]": list[str]: All users with submissions in the guild. """ with Session(engine) as session: - group_ids = select(col(CategoryGroup.id)).where(CategoryGroup.guild_id == guild_id) - category_ids = select(Category.id).where(col(Category.group_id).in_(group_ids)) - stmt = select(distinct(Score.username)).where(Score.category_id.in_(category_ids)) + group_ids = select(col(CategoryGroup.id)).where(col(CategoryGroup.guild_id) == guild_id) + category_ids = select(col(Category.id)).where(col(Category.group_id).in_(group_ids)) + stmt = select(distinct(col(Score.username))).where(col(Score.category_id).in_(category_ids)) users_list: list[str] = list(session.scalars(stmt)) # if string empty, return all users @@ -181,21 +181,21 @@ def format_highscore_message(session: Session, group: CategoryGroup) -> str: """ ret_string = f"**{group.name}**\n```" - stmt = select(Guild).where(Guild.id == group.guild_id) + stmt = select(Guild).where(col(Guild.id) == group.guild_id) # Get all categories in the group subq = ( select(CategoryGroup) - .where(CategoryGroup.guild_id == group.guild_id) - .where(CategoryGroup.name == group.name) + .where(col(CategoryGroup.guild_id) == group.guild_id) + .where(col(CategoryGroup.name) == group.name) .subquery() ) cat_group_alias = aliased(CategoryGroup, subq) - stmt = select(Category).where(Category.group_id == cat_group_alias.id) + stmt = select(Category).where(col(Category.group_id) == cat_group_alias.id) # set up a map for the categories # also grab the max category size - categories = [] + categories: list[Category] = [] category_ids = [] max_cat_size: int = 0 pad_length = group.pad_length @@ -206,7 +206,7 @@ def format_highscore_message(session: Session, group: CategoryGroup) -> str: # get all scores in category group, load into data frame. d_f = pd.read_sql_query( - sql=session.query(Score).where(Score.category_id.in_(category_ids)).statement, + sql=session.query(Score).where(col(Score.category_id).in_(category_ids)).statement, con=engine, ) @@ -217,15 +217,15 @@ def format_highscore_message(session: Session, group: CategoryGroup) -> str: for category in categories: # category name string - str_list[0] += f"{category.CategoryName}".ljust(pad_length, " ") + str_list[0] += f"{category.name}".ljust(pad_length, " ") # ensure there is data to print - if category.CategoryId in groups_df.indices: - group_df = groups_df.get_group(category.CategoryId) + if category.id in groups_df.indices: + group_df = groups_df.get_group(category.id) # process data. Want each group sorted correctly and only top X results processed_group = ( - group_df.sort_values("Score", ascending=category.IsAscending).head(category.Size).reset_index() + group_df.sort_values("Score", ascending=category.is_ascending).head(category.size).reset_index() ) # add each score to list @@ -237,19 +237,19 @@ def format_highscore_message(session: Session, group: CategoryGroup) -> str: str_list[ind + 1] += format_score_string( username, score, - group.UsernameLength, - category.IsTimeRecord, + group.username_length, + category.is_time_record, ind + 1, pad_length, ) # if not enough entries, pad out - elif ind + 1 <= category.Size: + elif ind + 1 <= category.size: str_list[ind + 1] += f"{ind + 1}: ".ljust(pad_length, " ") else: str_list[ind + 1] += "".ljust(pad_length, " ") else: for ind in range(max_cat_size): - if ind + 1 <= category.Size: + if ind + 1 <= category.size: str_list[ind + 1] += f"{ind + 1}: ".ljust(pad_length, " ") else: str_list[ind + 1] += "".ljust(pad_length, " ") @@ -304,13 +304,13 @@ def format_score_string( if is_time_record: # MM:SS.ms is 7 characters long # if there are single digit minutes, add a space for formatting. - score = get_time_str(score) - if score.find(":") and len(score.split(":", maxsplit=1)[0]) < 2: - score = " " + score + formatted_score = get_time_str(score) + if formatted_score.find(":") and len(formatted_score.split(":", maxsplit=1)[0]) < 2: # noqa: PLR2004 + formatted_score = " " + formatted_score else: - score = str(int(score)).rjust(7, " ") + formatted_score = str(int(score)).rjust(7, " ") - return f"{rank}: {username} - {score}".ljust(pad_length, " ") + return f"{rank}: {username} - {formatted_score}".ljust(pad_length, " ") def get_time_str(time_in: float) -> str: @@ -331,6 +331,7 @@ def get_time_str(time_in: float) -> str: async def send_highscore_message(session: Session, guild: nextcord.Guild, group: CategoryGroup) -> nextcord.Message: """ Function takes care of checking if a message exists for a group. + Creates and sends/edits the message. Args: @@ -342,15 +343,15 @@ async def send_highscore_message(session: Session, guild: nextcord.Guild, group: nextcord.Message: Message object that was posted with group contents. """ highscore_string = format_highscore_message(session, group) - channel = guild.get_channel(group.ChannelId) + channel = guild.get_channel(group.channel_id) - if group.MessageId is None: + if group.message_id is None: # message doesn't exist. message: nextcord.Message = await channel.send(highscore_string) group.MessageId = message.id session.commit() else: - message: nextcord.Message = await channel.fetch_message(group.MessageId) + message: nextcord.Message = await channel.fetch_message(group.message_id) await message.edit(content=highscore_string) return message @@ -365,37 +366,38 @@ async def submit_score( ) -> None: """ Adds passed score to group. Then updates group message by calling send_highscore_message. + Ensures that a highscores channel exists. Args: interaction (nextcord.Interaction): Interaction that caused the score submission. - group (CategoryGroup): group to submit score to. - category_id (Category): Category to submit score to. + group_id (int): group id to submit score to. + category_id (int): Category id to submit score to. username (str): The user who submitted the score. score (str): Score to submit. Need to convert to correct type. """ with Session(engine) as session: - stmt = select(Category.IsTimeRecord).where(Category.CategoryId == category_id) + stmt = select(col(Category.is_time_record)).where(col(Category.id) == category_id) is_time_record = session.scalar(stmt) if is_time_record: minutes = float(score.split(":", maxsplit=1)[0]) seconds = float(score.split(":", maxsplit=1)[1]) - score = (minutes * 60) + seconds + score_f = (minutes * 60) + seconds else: - score = float(score) + score_f = float(score) - stmt = select(Score).where(Score.UserName == username).where(Score.CategoryId == category_id) + stmt = select(Score).where(col(Score.username) == username).where(col(Score.category_id) == category_id) existing_score = session.scalar(stmt) if existing_score: - existing_score.Score = score + existing_score.Score = score_f else: - score_obj = Score(UserName=username, Score=score, CategoryId=category_id) + score_obj = Score(username=username, score=score_f, category_id=category_id) session.add(score_obj) session.commit() - stmt = select(CategoryGroup).where(CategoryGroup.GroupId == group_id) + stmt = select(CategoryGroup).where(col(CategoryGroup.id) == group_id) group = session.scalar(stmt) await send_highscore_message(session, interaction.guild, group) From 0ad425b9828383817058078f221567e70ec3a4e4 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 21:52:54 -0500 Subject: [PATCH 18/51] Small lint adjustments. --- database/db.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/database/db.py b/database/db.py index 161db71..d86cd41 100644 --- a/database/db.py +++ b/database/db.py @@ -1,10 +1,9 @@ """Simple file to set up the sqlmodel connection to database.""" from sqlmodel import SQLModel, create_engine - from utilities import config -from . import models # noqa: F401 Need this import for creating the models. +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}" From ce3ed3c0015d60a076333d5f4fed8fdea684fa02 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 21:53:19 -0500 Subject: [PATCH 19/51] Just more testing. --- database/database_test.py | 29 ++++++++++++++++++++--------- 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/database/database_test.py b/database/database_test.py index b2ba0f0..1212c51 100644 --- a/database/database_test.py +++ b/database/database_test.py @@ -1,18 +1,29 @@ -from sqlmodel import Session, SQLModel, create_engine +from sqlmodel import Session, SQLModel, create_engine, select -from database.models import CategoryGroup, Guild +from models import Guild url = "sqlite:///database.db" engine = create_engine(url) SQLModel.metadata.create_all(engine) with Session(engine) as session: - guild = Guild(id=1, name="test guild", submission_channel=1, verification_channel=2) - session.add(guild) + # guild = Guild(id=1, name="test guild", submission_channel=1, verification_channel=2) + # 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() - 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) + # 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() - session.commit() + stmt = select(Guild).where(Guild.id == 1) + guild = session.scalar(stmt) + + print(guild.category_groups) From 6dfd3acad06a56834c1d60f023e9e84fe5580404 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 22:44:14 -0500 Subject: [PATCH 20/51] Add SnakeCase column names that are already in database. --- .vscode/settings.json | 11 +++++-- database/database_test.py | 35 ++++++++++++++-------- database/models.py | 61 +++++++++++++++++++++------------------ 3 files changed, 65 insertions(+), 42 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 815a7fb..368ef93 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,8 +1,15 @@ { - "cSpell.words": ["gmtime", "highscore", "highscores", "imcompiling", "nextcord"], + "cSpell.words": [ + "gmtime", + "highscore", + "highscores", + "imcompiling", + "nextcord", + "ondelete" + ], "python.analysis.diagnosticSeverityOverrides": { "reportOptionalMemberAccess": false, "reportArgumentType": "information", "reportAttributeAccessIssue": "warning" } -} +} \ No newline at end of file diff --git a/database/database_test.py b/database/database_test.py index 1212c51..5ef69be 100644 --- a/database/database_test.py +++ b/database/database_test.py @@ -1,19 +1,30 @@ -from sqlmodel import Session, SQLModel, create_engine, select +import os -from models import Guild +from dotenv import load_dotenv +from sqlmodel import Session, SQLModel, create_engine + +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", submission_channel=1, verification_channel=2) - # 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() + guild = Guild(id=1, name="test guild", submission_channel=1, verification_channel=2) + 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) @@ -23,7 +34,7 @@ with Session(engine) as session: # session.add(group2) # session.commit() - stmt = select(Guild).where(Guild.id == 1) - guild = session.scalar(stmt) + # stmt = select(Guild) + # guild = session.scalars(stmt) - print(guild.category_groups) +# print(guild) diff --git a/database/models.py b/database/models.py index f0fb0e9..7151656 100644 --- a/database/models.py +++ b/database/models.py @@ -1,6 +1,6 @@ """File holds all model definitions of SQL tables.""" -from sqlalchemy.dialects.mysql import BIGINT, INTEGER, SMALLINT +from sqlalchemy.dialects.mysql import BIGINT, BOOLEAN, FLOAT, INTEGER, SMALLINT, VARCHAR from sqlmodel import Column, Field, ForeignKey, Relationship, SQLModel, UniqueConstraint @@ -19,12 +19,12 @@ class Guild(SQLModel, table=True): __tablename__: str = "Guilds" - id: int = Field(sa_column=Column(BIGINT(unsigned=True), primary_key=True, nullable=False)) - name: str = Field(max_length=95) + id: int = Field(sa_column=Column("GuildId", BIGINT(unsigned=True), primary_key=True, nullable=False)) + name: str = Field(sa_column=Column("GuildName", VARCHAR), max_length=95) # deprecated, not currently used. - submission_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) - verification_channel: int = Field(sa_column=Column(BIGINT(unsigned=True))) - active: bool = Field(default=True) + submission_channel: int = Field(sa_column=Column("SubmissionChannel", BIGINT(unsigned=True))) + verification_channel: int = Field(sa_column=Column("VerificationChannel", BIGINT(unsigned=True))) + active: bool = Field(sa_column=Column("Active", BOOLEAN()), default=True) category_groups: list["CategoryGroup"] = Relationship(back_populates="guild", cascade_delete=True) @@ -49,19 +49,20 @@ class CategoryGroup(SQLModel, table=True): __tablename__: str = "CategoryGroups" - id: int | None = Field(default=None, primary_key=True) - name: str = Field(max_length=50) - channel_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) + id: int | None = Field(sa_column=Column("GroupId", INTEGER, primary_key=True), default=None) + name: str = Field(sa_column=Column("GroupName", VARCHAR), max_length=50) + channel_id: int = Field("ChannelId", sa_column=Column(BIGINT(unsigned=True))) guild_id: int = Field( sa_column=Column( + "GuildId", BIGINT(unsigned=True), - ForeignKey("Guilds.id", ondelete="CASCADE"), + ForeignKey("Guilds.GuildId", ondelete="CASCADE"), nullable=False, ) ) - message_id: int = Field(sa_column=Column(BIGINT(unsigned=True))) - pad_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) - username_length: int = Field(default=12, sa_column=Column(SMALLINT(unsigned=True))) + message_id: int = Field(sa_column=Column("MessageId", BIGINT(unsigned=True))) + 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))) __table_args__ = (UniqueConstraint("guild_id", "name", name="UniqueGuildCategoryGroup"),) @@ -91,19 +92,20 @@ class Category(SQLModel, table=True): __tablename__: str = "Categories" - id: int = Field(default=None, primary_key=True) - name: str = Field(max_length=30) + id: int = Field(sa_column=Column("CategoryId", INTEGER, primary_key=True), default=None) + name: str = Field(sa_column=Column("CategoryName", VARCHAR), max_length=30) group_id: int = Field( sa_column=Column( + "GroupId", INTEGER(unsigned=True), - ForeignKey("CategoryGroups.id", ondelete="CASCADE"), + ForeignKey("CategoryGroups.GroupId", ondelete="CASCADE"), nullable=False, ) ) - size: int = Field(sa_column=Column(SMALLINT(unsigned=True), default=3, nullable=False)) - is_ascending: bool = Field(default=True, nullable=False) - is_time_record: bool = Field(default=False, nullable=False) - is_validated: bool = Field(default=True, nullable=False) + size: int = Field(sa_column=Column("Size", SMALLINT(unsigned=True), nullable=False), default=3) + is_ascending: bool = Field(sa_column=Column("IsAscending", nullable=False), default=True) + is_time_record: bool = Field(sa_column=Column("IsTimeRecord", nullable=False), default=False) + is_validated: bool = Field(sa_column=Column("IsValidated", nullable=False), default=True) __table_args__ = (UniqueConstraint("group_id", "name", name="UniqueCategoryInGroup"),) @@ -126,12 +128,13 @@ class Score(SQLModel, table=True): __tablename__: str = "Scores" - username: str = Field(max_length=30, nullable=False, primary_key=True) - score: float = Field(nullable=False) + username: str = Field(sa_column=Column("UserName", VARCHAR, primary_key=True, nullable=False), max_length=30) + score: float = Field(sa_column=Column("Score", FLOAT, nullable=False)) category_id: int = Field( sa_column=Column( + "CategoryId", INTEGER(unsigned=True), - ForeignKey("Categories.id", ondelete="CASCADE"), + ForeignKey("Categories.CategoryId", ondelete="CASCADE"), nullable=False, primary_key=True, ), @@ -158,6 +161,7 @@ class Submission(SQLModel, table=True): category_id: int = Field( sa_column=Column( + "CategoryId", INTEGER(unsigned=True), nullable=False, primary_key=True, @@ -165,13 +169,14 @@ class Submission(SQLModel, table=True): ) group_id: int = Field( sa_column=Column( + "GroupId", INTEGER(unsigned=True), nullable=False, ) ) - guild_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) - message_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) + guild_id: int = Field(sa_column=Column("GuildId", BIGINT(unsigned=True), nullable=False)) + message_id: int = Field(sa_column=Column("MessageId", BIGINT(unsigned=True), nullable=False)) # Score is stored as a string until converted during submission. - score: str = Field(max_length=30, nullable=False) - user_id: int = Field(sa_column=Column(BIGINT(unsigned=True), nullable=False)) - username: str = Field(max_length=30, nullable=False, primary_key=True) + score: str = Field(sa_column=Column("Score", VARCHAR, nullable=False), max_length=30) + user_id: int = Field(sa_column=Column("UserId", BIGINT(unsigned=True), nullable=False)) + username: str = Field(sa_column=Column("UserName", VARCHAR, nullable=False, primary_key=True), max_length=30) From 37daa0e65718519b0342157255fb2bdf4623e0c0 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 22:46:33 -0500 Subject: [PATCH 21/51] Update names used in constraints. --- database/models.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/database/models.py b/database/models.py index 7151656..ee4673e 100644 --- a/database/models.py +++ b/database/models.py @@ -64,7 +64,7 @@ class CategoryGroup(SQLModel, table=True): 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))) - __table_args__ = (UniqueConstraint("guild_id", "name", name="UniqueGuildCategoryGroup"),) + __table_args__ = (UniqueConstraint("GuildId", "GroupName", name="UniqueGuildCategoryGroup"),) guild: Guild | None = Relationship(back_populates="category_groups") categories: list["Category"] | None = Relationship(back_populates="category_group", cascade_delete=True) @@ -107,7 +107,7 @@ class Category(SQLModel, table=True): is_time_record: bool = Field(sa_column=Column("IsTimeRecord", nullable=False), default=False) is_validated: bool = Field(sa_column=Column("IsValidated", nullable=False), default=True) - __table_args__ = (UniqueConstraint("group_id", "name", name="UniqueCategoryInGroup"),) + __table_args__ = (UniqueConstraint("GroupId", "CategoryName", name="UniqueCategoryInGroup"),) category_group: CategoryGroup | None = Relationship(back_populates="categories") scores: list["Score"] | None = Relationship(back_populates="category", cascade_delete=True) From 231c70094630bce231828f7dcd8b97f92d7fd940 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 22:57:48 -0500 Subject: [PATCH 22/51] Fix other errors with models. --- database/models.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/database/models.py b/database/models.py index ee4673e..5058126 100644 --- a/database/models.py +++ b/database/models.py @@ -51,7 +51,7 @@ class CategoryGroup(SQLModel, table=True): id: int | None = Field(sa_column=Column("GroupId", INTEGER, primary_key=True), default=None) name: str = Field(sa_column=Column("GroupName", VARCHAR), max_length=50) - channel_id: int = Field("ChannelId", sa_column=Column(BIGINT(unsigned=True))) + channel_id: int = Field(sa_column=Column("ChannelId", BIGINT(unsigned=True))) guild_id: int = Field( sa_column=Column( "GuildId", @@ -103,9 +103,9 @@ class Category(SQLModel, table=True): ) ) size: int = Field(sa_column=Column("Size", SMALLINT(unsigned=True), nullable=False), default=3) - is_ascending: bool = Field(sa_column=Column("IsAscending", nullable=False), default=True) - is_time_record: bool = Field(sa_column=Column("IsTimeRecord", nullable=False), default=False) - is_validated: bool = Field(sa_column=Column("IsValidated", nullable=False), default=True) + is_ascending: bool = Field(sa_column=Column("IsAscending", BOOLEAN, nullable=False), default=True) + is_time_record: bool = Field(sa_column=Column("IsTimeRecord", BOOLEAN, nullable=False), default=False) + is_validated: bool = Field(sa_column=Column("IsValidated", BOOLEAN, nullable=False), default=True) __table_args__ = (UniqueConstraint("GroupId", "CategoryName", name="UniqueCategoryInGroup"),) From 9dd07bef93beec69a286def2989c9bef374a2536 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:01:58 -0500 Subject: [PATCH 23/51] Add an init file for utilities. --- utilities/__init__.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 utilities/__init__.py diff --git a/utilities/__init__.py b/utilities/__init__.py new file mode 100644 index 0000000..3d3885f --- /dev/null +++ b/utilities/__init__.py @@ -0,0 +1 @@ +"""Package of utility functions and environment configuration variables.""" From f74b08b02ed0b6228d761ff2a7206328260c31e7 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:02:19 -0500 Subject: [PATCH 24/51] Add another word to cspell. --- .vscode/settings.json | 1 + 1 file changed, 1 insertion(+) diff --git a/.vscode/settings.json b/.vscode/settings.json index 368ef93..60a4c8c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,6 @@ { "cSpell.words": [ + "dotenv", "gmtime", "highscore", "highscores", From 43f51f7f074a1cbfc3737dadfd34d5f75f90641c Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:02:40 -0500 Subject: [PATCH 25/51] Test file after connecting to prod database and testing relationships. --- database/database_test.py | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/database/database_test.py b/database/database_test.py index 5ef69be..7e9218a 100644 --- a/database/database_test.py +++ b/database/database_test.py @@ -1,9 +1,9 @@ import os from dotenv import load_dotenv -from sqlmodel import Session, SQLModel, create_engine +from sqlmodel import Session, create_engine, select -from models import CategoryGroup, Guild +from models import Guild load_dotenv() @@ -12,19 +12,19 @@ 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}" +# 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) +# SQLModel.metadata.create_all(engine) with Session(engine) as session: - guild = Guild(id=1, name="test guild", submission_channel=1, verification_channel=2) - 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() + # guild = Guild(id=1, name="test guild", submission_channel=1, verification_channel=2) + # 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) @@ -34,7 +34,7 @@ with Session(engine) as session: # session.add(group2) # session.commit() - # stmt = select(Guild) - # guild = session.scalars(stmt) + stmt = select(Guild).where(Guild.name == "Dakiny") + guild = session.scalar(stmt) -# print(guild) + print(guild.category_groups) From 1658638938a8bb823048fdbd65ed1b67764eb4c7 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:08:41 -0500 Subject: [PATCH 26/51] Remove unneeded parenthesis. --- database/models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/models.py b/database/models.py index 5058126..2ec17b6 100644 --- a/database/models.py +++ b/database/models.py @@ -24,7 +24,7 @@ class Guild(SQLModel, table=True): # deprecated, not currently used. submission_channel: int = Field(sa_column=Column("SubmissionChannel", BIGINT(unsigned=True))) verification_channel: int = Field(sa_column=Column("VerificationChannel", BIGINT(unsigned=True))) - active: bool = Field(sa_column=Column("Active", BOOLEAN()), default=True) + active: bool = Field(sa_column=Column("Active", BOOLEAN), default=True) category_groups: list["CategoryGroup"] = Relationship(back_populates="guild", cascade_delete=True) From dbe652dcce52e392d0d98f69bd1c52ebb36c52a5 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:08:53 -0500 Subject: [PATCH 27/51] Fix smells in submission init file. --- cogs/submission/__init__.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/cogs/submission/__init__.py b/cogs/submission/__init__.py index d742ee3..48c3557 100644 --- a/cogs/submission/__init__.py +++ b/cogs/submission/__init__.py @@ -1,6 +1,4 @@ -""" -Cog for creating submission process. -""" +"""Cog for creating submission process.""" from nextcord.ext import commands @@ -15,14 +13,14 @@ class SubmissionCog(commands.Cog, name="Submission Cog"): self.bot = bot @commands.Cog.listener() - async def on_ready(self): - """Called when cog is loaded""" + async def on_ready(self) -> None: + """Called when cog is loaded.""" self.bot.add_view(SubmissionCreateButton(self.bot)) self.bot.add_view(VerificationView()) # This function will be called when this extension is loaded. # It is necessary to add these functions to the bot. -def setup(bot: commands.Bot): - """Adds function to bot""" +def setup(bot: commands.Bot) -> None: + """Adds function to bot.""" bot.add_cog(SubmissionCog(bot)) From 528af14e00156733524c0c5de4d63ef0d7f5f555 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:14:31 -0500 Subject: [PATCH 28/51] Update model usage in verification view. --- cogs/submission/verification_view.py | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/cogs/submission/verification_view.py b/cogs/submission/verification_view.py index 7cdd522..37ac2ef 100644 --- a/cogs/submission/verification_view.py +++ b/cogs/submission/verification_view.py @@ -3,8 +3,10 @@ import nextcord from sqlalchemy import delete, select from sqlalchemy.orm import Session +from sqlmodel import col -from database.db import Submission, engine +from database.db import engine +from database.models import Submission # pylint: disable=import-error from utilities.utils import submit_score @@ -22,8 +24,8 @@ class VerificationView(nextcord.ui.View): with Session(engine) as session: stmt = ( delete(Submission) - .where(Submission.GuildId == interaction.guild_id) - .where(Submission.MessageId == interaction.message.id) + .where(col(Submission.guild_id) == interaction.guild_id) + .where(col(Submission.message_id) == interaction.message.id) ) session.execute(stmt) session.commit() @@ -35,8 +37,8 @@ class VerificationView(nextcord.ui.View): with Session(engine) as session: stmt = ( select(Submission) - .where(Submission.GuildId == interaction.guild_id) - .where(Submission.MessageId == interaction.message.id) + .where(col(Submission.guild_id) == interaction.guild_id) + .where(col(Submission.message_id) == interaction.message.id) ) submission = session.scalar(stmt) @@ -47,11 +49,10 @@ class VerificationView(nextcord.ui.View): return await submit_score( - interaction, submission.GroupId, submission.CategoryId, submission.UserName, submission.Score + interaction, submission.group_id, submission.category_id, submission.username, submission.score ) session.delete(submission) session.commit() content = interaction.message.content content += f"\nApproved by <@{interaction.user.id}>." - # remove the bot information embed. it should always be the first one. await interaction.message.edit(content=content, view=None) From f6ae34c9e6eed95ee130761edf26f591c36c7be1 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:29:46 -0500 Subject: [PATCH 29/51] Started fixing smells and updating model calls. --- cogs/loops/__init__.py | 8 +++----- cogs/loops/bot_presence.py | 6 ++---- cogs/loops/guild_data.py | 25 ++++++++++--------------- 3 files changed, 15 insertions(+), 24 deletions(-) diff --git a/cogs/loops/__init__.py b/cogs/loops/__init__.py index 9ee014f..cec7fdb 100644 --- a/cogs/loops/__init__.py +++ b/cogs/loops/__init__.py @@ -1,6 +1,4 @@ -""" -Initializing code for all loops. -""" +"""Initializing code for all loops.""" from nextcord.ext import commands @@ -10,7 +8,7 @@ from .guild_data import GuildData # 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(BotPresence(bot)) bot.add_cog(GuildData(bot)) diff --git a/cogs/loops/bot_presence.py b/cogs/loops/bot_presence.py index d752396..f64cfd9 100644 --- a/cogs/loops/bot_presence.py +++ b/cogs/loops/bot_presence.py @@ -1,6 +1,4 @@ -""" -Functions for controlling the bot's presence. Also contains the loop. -""" +"""Functions for controlling the bot's presence. Also contains the loop.""" import random @@ -11,7 +9,7 @@ from nextcord.ext import commands, tasks class BotPresence(commands.Cog, name="Bot Presence"): """Class for bot presence functions.""" - def __init__(self, bot: commands.Bot): + def __init__(self, bot: commands.Bot) -> None: self.bot = bot @commands.Cog.listener() diff --git a/cogs/loops/guild_data.py b/cogs/loops/guild_data.py index 3760731..356a4c9 100644 --- a/cogs/loops/guild_data.py +++ b/cogs/loops/guild_data.py @@ -1,13 +1,11 @@ -""" -Contains a loop that updates guild data in the database periodically. -""" +"""Contains a loop that updates guild data in the database periodically.""" from nextcord.ext import commands, tasks from sqlalchemy import select from sqlalchemy.orm import Session -# pylint: disable=import-error -from database.db import Guild, engine +from database.db import engine +from database.models import Guild class GuildData(commands.Cog, name="Guild Data"): @@ -17,30 +15,27 @@ class GuildData(commands.Cog, name="Guild Data"): self.bot = bot @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_update_guild_data is subclassed from tasks.loop. - await self.periodic_update_guild_data.start() # pylint: disable=no-member + await self.periodic_update_guild_data.start() @tasks.loop(hours=24) - async def periodic_update_guild_data(self): + async def periodic_update_guild_data(self) -> None: """Loops every day, calls update_guild_data.""" self.update_guild_data() - def update_guild_data(self): - """ - Updates all known guild's data in the database. - """ + def update_guild_data(self) -> None: + """Updates all known guild's data in the database.""" with Session(engine) as session: for guild in self.bot.guilds: # update given guild name for guild id - stmt = select(Guild).where(Guild.GuildId == guild.id) + stmt = select(Guild).where(Guild.id == guild.id) guild_data = session.scalar(stmt) # just in case checking if the guild doesn't exist. if guild_data is None: - new_guild = Guild(GuildId=guild.id, GuildName=guild.name) + new_guild = Guild(id=guild.id, name=guild.name) session.add(new_guild) else: guild_data.GuildName = guild.name From 9cf05f44d02ee18ebb4b8311ee2fb69040c01a1d Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:32:03 -0500 Subject: [PATCH 30/51] Fix error in model. The two channel ids need to be NULL by default, don't know them on object creation. --- database/database_test.py | 24 ++++++++++++------------ database/models.py | 8 ++++++-- 2 files changed, 18 insertions(+), 14 deletions(-) diff --git a/database/database_test.py b/database/database_test.py index 7e9218a..5cf9343 100644 --- a/database/database_test.py +++ b/database/database_test.py @@ -1,9 +1,9 @@ import os from dotenv import load_dotenv -from sqlmodel import Session, create_engine, select +from sqlmodel import Session, SQLModel, create_engine, select -from models import Guild +from models import CategoryGroup, Guild load_dotenv() @@ -12,19 +12,19 @@ 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}" +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) +SQLModel.metadata.create_all(engine) with Session(engine) as session: - # guild = Guild(id=1, name="test guild", submission_channel=1, verification_channel=2) - # 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() + 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) diff --git a/database/models.py b/database/models.py index 2ec17b6..ff5fa0d 100644 --- a/database/models.py +++ b/database/models.py @@ -22,8 +22,12 @@ class Guild(SQLModel, table=True): id: int = Field(sa_column=Column("GuildId", BIGINT(unsigned=True), primary_key=True, nullable=False)) name: str = Field(sa_column=Column("GuildName", VARCHAR), max_length=95) # deprecated, not currently used. - submission_channel: int = Field(sa_column=Column("SubmissionChannel", BIGINT(unsigned=True))) - verification_channel: int = Field(sa_column=Column("VerificationChannel", BIGINT(unsigned=True))) + submission_channel: int | None = Field( + sa_column=Column("SubmissionChannel", BIGINT(unsigned=True), nullable=True), default=None + ) + verification_channel: int | None = Field( + sa_column=Column("VerificationChannel", BIGINT(unsigned=True), nullable=True), default=None + ) active: bool = Field(sa_column=Column("Active", BOOLEAN), default=True) category_groups: list["CategoryGroup"] = Relationship(back_populates="guild", cascade_delete=True) From f43dccb12d48daf71ef06c9148a15cfd4cc95606 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:36:07 -0500 Subject: [PATCH 31/51] Finish fixing lint smells in loops directory. --- cogs/loops/bot_presence.py | 13 ++++++------- cogs/loops/guild_data.py | 5 +++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/cogs/loops/bot_presence.py b/cogs/loops/bot_presence.py index f64cfd9..a236fb5 100644 --- a/cogs/loops/bot_presence.py +++ b/cogs/loops/bot_presence.py @@ -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" diff --git a/cogs/loops/guild_data.py b/cogs/loops/guild_data.py index 356a4c9..8ed6c83 100644 --- a/cogs/loops/guild_data.py +++ b/cogs/loops/guild_data.py @@ -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. From b04819aa36e9ba2e6ed4827d0195dc4a29df9737 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:40:49 -0500 Subject: [PATCH 32/51] Fix smells and model usage in guild listener. --- cogs/guild_listener/__init__.py | 23 +++++++++++------------ 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/cogs/guild_listener/__init__.py b/cogs/guild_listener/__init__.py index c3df5a6..9e6fc61 100644 --- a/cogs/guild_listener/__init__.py +++ b/cogs/guild_listener/__init__.py @@ -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,12 @@ 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) + 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: - new_guild = Guild(GuildId=guild.id, GuildName=guild.name) + new_guild = Guild(id=guild.id, name=guild.name) session.add(new_guild) else: guild_data.GuildName = guild.name @@ -45,7 +44,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 +52,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 +65,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)) From 9550d1a68b9b83dff1c3cb9a03b060f8e5cba12e Mon Sep 17 00:00:00 2001 From: imcompiling Date: Mon, 3 Mar 2025 23:41:58 -0500 Subject: [PATCH 33/51] Remove all pylint supressors. --- cogs/commands/delete.py | 1 - cogs/commands/refresh.py | 1 - cogs/commands/set.py | 1 - cogs/commands/update.py | 1 - cogs/commands/view.py | 1 - cogs/commands/views/delete_confirm.py | 1 - cogs/commands/views/update_username_verify.py | 5 ++--- cogs/submission/verification_view.py | 2 -- utilities/utils.py | 1 - 9 files changed, 2 insertions(+), 12 deletions(-) diff --git a/cogs/commands/delete.py b/cogs/commands/delete.py index d7325ef..efb30fc 100644 --- a/cogs/commands/delete.py +++ b/cogs/commands/delete.py @@ -5,7 +5,6 @@ from nextcord.ext import commands from sqlalchemy import distinct, select from sqlalchemy.orm import Session -# pylint: disable=import-error from database.db import Category, CategoryGroup, Score, engine from utilities.utils import ( autofill_categories, diff --git a/cogs/commands/refresh.py b/cogs/commands/refresh.py index fef3415..dd057e9 100644 --- a/cogs/commands/refresh.py +++ b/cogs/commands/refresh.py @@ -7,7 +7,6 @@ from nextcord.ext import commands from sqlalchemy import select from sqlalchemy.orm import Session -# pylint: disable=import-error from database.db import CategoryGroup, engine from utilities.utils import autofill_groups, send_highscore_message diff --git a/cogs/commands/set.py b/cogs/commands/set.py index 6026ce8..aea4b36 100644 --- a/cogs/commands/set.py +++ b/cogs/commands/set.py @@ -7,7 +7,6 @@ from nextcord.ext import commands from sqlalchemy import select from sqlalchemy.orm import Session -# pylint: disable=import-error from database.db import CategoryGroup, Guild, engine from utilities.utils import MAX_LINE_LENGTH, autofill_groups diff --git a/cogs/commands/update.py b/cogs/commands/update.py index 671eece..02c2d13 100644 --- a/cogs/commands/update.py +++ b/cogs/commands/update.py @@ -7,7 +7,6 @@ from nextcord.ext import commands from sqlalchemy import select from sqlalchemy.orm import Session -# pylint: disable=import-error from database.db import Guild, engine from utilities.utils import autofill_users_in_guild diff --git a/cogs/commands/view.py b/cogs/commands/view.py index f1b6f0a..ca45b20 100644 --- a/cogs/commands/view.py +++ b/cogs/commands/view.py @@ -6,7 +6,6 @@ from nextcord.ext import commands from sqlalchemy import select from sqlalchemy.orm import Session -# pylint: disable=import-error from database.db import Category, CategoryGroup, Score, engine from utilities.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, format_score_string diff --git a/cogs/commands/views/delete_confirm.py b/cogs/commands/views/delete_confirm.py index 85b3145..adf7578 100644 --- a/cogs/commands/views/delete_confirm.py +++ b/cogs/commands/views/delete_confirm.py @@ -6,7 +6,6 @@ import nextcord from sqlalchemy import delete, select from sqlalchemy.orm import Session -# pylint: disable=import-error from database.db import Category, CategoryGroup, engine from utilities.utils import send_highscore_message diff --git a/cogs/commands/views/update_username_verify.py b/cogs/commands/views/update_username_verify.py index 3aefd27..23725c6 100644 --- a/cogs/commands/views/update_username_verify.py +++ b/cogs/commands/views/update_username_verify.py @@ -4,7 +4,6 @@ import nextcord from sqlalchemy import distinct, exc, select from sqlalchemy.orm import Session -# pylint: disable=import-error from database.db import Category, CategoryGroup, Score, engine from utilities.utils import send_highscore_message @@ -19,7 +18,7 @@ class UpdateUsernameVerifyView(nextcord.ui.View): 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): """ Button for denying username update. Deletes message. @@ -30,7 +29,7 @@ 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): """ Button for approving username update. Tells guild data to update username, then updates message to show it is complete. diff --git a/cogs/submission/verification_view.py b/cogs/submission/verification_view.py index 37ac2ef..9a41e55 100644 --- a/cogs/submission/verification_view.py +++ b/cogs/submission/verification_view.py @@ -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 diff --git a/utilities/utils.py b/utilities/utils.py index 38faba8..3ad97cc 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -8,7 +8,6 @@ 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 9510c9eddc37f4df3915fe264cf60b00921396cc Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 09:47:39 -0500 Subject: [PATCH 34/51] Add init for views directory. Fix smells and update model usage in delete confirm. --- cogs/commands/views/__init__.py | 1 + cogs/commands/views/delete_confirm.py | 34 +++++++++++++++------------ 2 files changed, 20 insertions(+), 15 deletions(-) create mode 100644 cogs/commands/views/__init__.py diff --git a/cogs/commands/views/__init__.py b/cogs/commands/views/__init__.py new file mode 100644 index 0000000..1b5f260 --- /dev/null +++ b/cogs/commands/views/__init__.py @@ -0,0 +1 @@ +"""Package for views used in commands.""" diff --git a/cogs/commands/views/delete_confirm.py b/cogs/commands/views/delete_confirm.py index adf7578..c2d95ea 100644 --- a/cogs/commands/views/delete_confirm.py +++ b/cogs/commands/views/delete_confirm.py @@ -1,22 +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 -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.', @@ -26,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 @@ -34,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 @@ -77,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. From 85d007710719ae2eca89cd8fe924dc555df65079 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 09:53:09 -0500 Subject: [PATCH 35/51] Fix smells and update model uses for updating username verify. --- cogs/commands/views/update_username_verify.py | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/cogs/commands/views/update_username_verify.py b/cogs/commands/views/update_username_verify.py index 23725c6..3d04ac2 100644 --- a/cogs/commands/views/update_username_verify.py +++ b/cogs/commands/views/update_username_verify.py @@ -3,22 +3,22 @@ import nextcord from sqlalchemy import distinct, exc, select from sqlalchemy.orm import Session +from sqlmodel import col -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): + async def deny_button(self, button: nextcord.ui.Button, interaction: nextcord.Interaction) -> None: # noqa: ARG002 """ Button for denying username update. Deletes message. @@ -29,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): + 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 @@ -41,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) From a99b488ae1de399b5c83e493583cfb118be90036 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 11:03:45 -0500 Subject: [PATCH 36/51] Message id isn't known at object creation time. --- database/models.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/database/models.py b/database/models.py index ff5fa0d..4bbe2cf 100644 --- a/database/models.py +++ b/database/models.py @@ -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))) From d7e44d3a2263503b224a0376c172c94924b421a7 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 11:04:10 -0500 Subject: [PATCH 37/51] Fix lint smells and update model usage. --- cogs/commands/create.py | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/cogs/commands/create.py b/cogs/commands/create.py index b5214f6..08703cc 100644 --- a/cogs/commands/create.py +++ b/cogs/commands/create.py @@ -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: From 563b6ab8889ce6291ab4c4d04682ffa33eb501fa Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 11:18:40 -0500 Subject: [PATCH 38/51] Fix lint smells. Update model usage. --- cogs/commands/delete.py | 59 ++++++++++++++++++++++++----------------- 1 file changed, 34 insertions(+), 25 deletions(-) diff --git a/cogs/commands/delete.py b/cogs/commands/delete.py index efb30fc..98b67c0 100644 --- a/cogs/commands/delete.py +++ b/cogs/commands/delete.py @@ -4,8 +4,10 @@ import nextcord from nextcord.ext import commands from sqlalchemy import distinct, select from sqlalchemy.orm import Session +from sqlmodel import col -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, @@ -35,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: @@ -53,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) @@ -67,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) @@ -96,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, @@ -132,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, @@ -171,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)) @@ -204,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) @@ -215,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") From 3fc8910c9a2b16d4c2e400114fde901576af8fc6 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 11:19:06 -0500 Subject: [PATCH 39/51] Fix lint smell. --- cogs/commands/help.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cogs/commands/help.py b/cogs/commands/help.py index 3ed3b9e..39dc892 100644 --- a/cogs/commands/help.py +++ b/cogs/commands/help.py @@ -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.") From 44d813504ae23d43a4b85d26c1204f68a00f69c3 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 12:47:44 -0500 Subject: [PATCH 40/51] Fix lint smells and update model usage in refresh and set. --- cogs/commands/refresh.py | 16 +++++------ cogs/commands/set.py | 61 +++++++++++++++++----------------------- 2 files changed, 34 insertions(+), 43 deletions(-) diff --git a/cogs/commands/refresh.py b/cogs/commands/refresh.py index dd057e9..20e1064 100644 --- a/cogs/commands/refresh.py +++ b/cogs/commands/refresh.py @@ -1,13 +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 -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 @@ -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) diff --git a/cogs/commands/set.py b/cogs/commands/set.py index aea4b36..d2bd194 100644 --- a/cogs/commands/set.py +++ b/cogs/commands/set.py @@ -1,31 +1,25 @@ -""" -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 -from database.db import CategoryGroup, Guild, engine +from database.db import engine +from database.models import CategoryGroup, Guild 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. - """ + """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( @@ -50,14 +44,13 @@ class SetCog(commands.Cog, name="Set command."): 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 @@ -92,14 +85,14 @@ 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 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 ) @set.subcommand( @@ -120,17 +113,15 @@ 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) + stmt = select(Guild).where(col(Guild.id) == interaction.guild_id) guild = session.scalar(stmt) - guild.SubmissionChannel = channel_id + guild.submission_channel = channel_id session.commit() await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True) @@ -150,13 +141,14 @@ 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 @@ -182,11 +174,10 @@ 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) + stmt = select(Guild).where(col(Guild.id) == interaction.guild_id) guild = session.scalar(stmt) guild.VerificationChannel = channel_id session.commit() @@ -195,7 +186,7 @@ class SetCog(commands.Cog, name="Set command."): @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): + 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. From c8becb82039863c401fb26bb4f7b6dfd2593462c Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 13:15:20 -0500 Subject: [PATCH 41/51] Fix lint smells and update model usage in submission. --- cogs/commands/submission.py | 59 ++++++++++++++++++++++--------------- 1 file changed, 36 insertions(+), 23 deletions(-) diff --git a/cogs/commands/submission.py b/cogs/commands/submission.py index 2d89bfb..fab15dc 100644 --- a/cogs/commands/submission.py +++ b/cogs/commands/submission.py @@ -6,9 +6,11 @@ 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 database.db import engine +from database.models import Category, CategoryGroup, Guild, Submission from main import 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,40 +60,49 @@ 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) + category: Category | None = session.scalar(stmt) + + if category 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) + verified_score = await self.verify_score(interaction, score, is_time_record=category.is_time_record) # check if verify_score was successful. It replies with corrections required itself. if verified_score is None: 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) + verification_channel_id: int | None = session.scalar(stmt) + + if verification_channel_id is None: + error_response = "No verification channel was registered. Contact server admins." + await interaction.response.send_message(error_response, ephemeral=True) + return 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." - ) + error_response = "Registered Verification channel does not exist. Contact server admins." await interaction.response.send_message(error_response, ephemeral=True) return @@ -111,13 +124,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 +164,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) From 43df7aeda735fe84adaeae10a55738e2e4101c72 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 13:20:14 -0500 Subject: [PATCH 42/51] Fix lint smells and update model usage in update. --- cogs/commands/update.py | 41 ++++++++++++++++++++--------------------- 1 file changed, 20 insertions(+), 21 deletions(-) diff --git a/cogs/commands/update.py b/cogs/commands/update.py index 02c2d13..fc6aadd 100644 --- a/cogs/commands/update.py +++ b/cogs/commands/update.py @@ -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 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): """ @@ -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)) From 0702198f0ac2dc78057db7304dd33215e3a72349 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Tue, 4 Mar 2025 13:24:08 -0500 Subject: [PATCH 43/51] Fix lint smells and update model usage in view. --- .vscode/settings.json | 3 ++- cogs/commands/view.py | 16 +++++++++------- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 60a4c8c..47e3829 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -5,6 +5,7 @@ "highscore", "highscores", "imcompiling", + "iterrows", "nextcord", "ondelete" ], @@ -13,4 +14,4 @@ "reportArgumentType": "information", "reportAttributeAccessIssue": "warning" } -} \ No newline at end of file +} diff --git a/cogs/commands/view.py b/cogs/commands/view.py index ca45b20..88774dd 100644 --- a/cogs/commands/view.py +++ b/cogs/commands/view.py @@ -5,8 +5,10 @@ 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 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 @@ -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: From 3abbff13d5ff171c74ff89336f9ed96db808de29 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Wed, 12 Mar 2025 09:50:58 -0400 Subject: [PATCH 44/51] Use walrus operator when assigning and checking for None. --- cogs/commands/submission.py | 21 +++++++++------------ cogs/guild_listener/__init__.py | 3 +-- cogs/submission/verification_view.py | 4 +--- 3 files changed, 11 insertions(+), 17 deletions(-) diff --git a/cogs/commands/submission.py b/cogs/commands/submission.py index fab15dc..caa011d 100644 --- a/cogs/commands/submission.py +++ b/cogs/commands/submission.py @@ -64,10 +64,7 @@ class SubmissionCog(commands.Cog): .where(col(Category.group_id) == int(group_id)) .where(col(Category.id) == int(category_id)) ) - - category: Category | None = session.scalar(stmt) - - if category is None: + if (category := session.scalar(stmt)) is None: await interaction.response.send_message("Category not found.", ephemeral=True) return @@ -79,10 +76,13 @@ class SubmissionCog(commands.Cog): return # check with regex if score is in correct format - verified_score = await self.verify_score(interaction, score, is_time_record=category.is_time_record) - # 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. @@ -92,16 +92,13 @@ class SubmissionCog(commands.Cog): return stmt = select(col(Guild.verification_channel)).where(col(Guild.id) == interaction.guild_id) - verification_channel_id: int | None = session.scalar(stmt) - if verification_channel_id is None: + 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 - channel = interaction.guild.get_channel(verification_channel_id) - - if channel is None: + 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 diff --git a/cogs/guild_listener/__init__.py b/cogs/guild_listener/__init__.py index 9e6fc61..2707f6b 100644 --- a/cogs/guild_listener/__init__.py +++ b/cogs/guild_listener/__init__.py @@ -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: diff --git a/cogs/submission/verification_view.py b/cogs/submission/verification_view.py index 9a41e55..6a71e93 100644 --- a/cogs/submission/verification_view.py +++ b/cogs/submission/verification_view.py @@ -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 From b28938f66af1991ece42c2e113137b27d18a1412 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Wed, 12 Mar 2025 21:27:12 -0400 Subject: [PATCH 45/51] Had col around the wrong variables. --- cogs/loops/guild_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cogs/loops/guild_data.py b/cogs/loops/guild_data.py index 8ed6c83..f686d49 100644 --- a/cogs/loops/guild_data.py +++ b/cogs/loops/guild_data.py @@ -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. From 68592a7df8b3360ce8ff9972cdc7759008114a10 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Wed, 12 Mar 2025 21:27:29 -0400 Subject: [PATCH 46/51] Typo on col usage. --- utilities/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utilities/utils.py b/utilities/utils.py index 3ad97cc..dc24976 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -64,7 +64,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)} From e1b761e84867931856868c07883e1fcfb0e5ab34 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Wed, 12 Mar 2025 21:29:01 -0400 Subject: [PATCH 47/51] Use correct variable for guild name. --- cogs/loops/guild_data.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cogs/loops/guild_data.py b/cogs/loops/guild_data.py index f686d49..3ce385f 100644 --- a/cogs/loops/guild_data.py +++ b/cogs/loops/guild_data.py @@ -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() From 170ce1cbfb28964d0745cb36181c6419954ed38c Mon Sep 17 00:00:00 2001 From: imcompiling Date: Wed, 12 Mar 2025 21:30:56 -0400 Subject: [PATCH 48/51] Use correct message id reference. --- utilities/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utilities/utils.py b/utilities/utils.py index dc24976..6cd3fb2 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -347,7 +347,7 @@ async def send_highscore_message(session: Session, guild: nextcord.Guild, group: if group.message_id is None: # message doesn't exist. message: nextcord.Message = await channel.send(highscore_string) - group.MessageId = message.id + group.id = message.id session.commit() else: message: nextcord.Message = await channel.fetch_message(group.message_id) From 74ce22dd26f8406a723e403a14de90f9d957fab8 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Thu, 13 Mar 2025 00:39:47 -0400 Subject: [PATCH 49/51] Was saving the message id to the wrong spot. --- utilities/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utilities/utils.py b/utilities/utils.py index 6cd3fb2..6b703b1 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -347,7 +347,7 @@ async def send_highscore_message(session: Session, guild: nextcord.Guild, group: if group.message_id is None: # message doesn't exist. message: nextcord.Message = await channel.send(highscore_string) - group.id = message.id + group.message_id = message.id session.commit() else: message: nextcord.Message = await channel.fetch_message(group.message_id) From e5d90a71d9f5d321fe25275be79bfdf6d2564d0f Mon Sep 17 00:00:00 2001 From: imcompiling Date: Fri, 14 Mar 2025 16:02:18 -0400 Subject: [PATCH 50/51] Correct parameter usage. --- cogs/commands/set.py | 2 +- utilities/utils.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cogs/commands/set.py b/cogs/commands/set.py index d2bd194..7b4bdd5 100644 --- a/cogs/commands/set.py +++ b/cogs/commands/set.py @@ -179,7 +179,7 @@ class SetCog(commands.Cog, name="Set command."): with Session(engine) as session: stmt = select(Guild).where(col(Guild.id) == interaction.guild_id) guild = session.scalar(stmt) - guild.VerificationChannel = channel_id + guild.verification_channel = channel_id session.commit() await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True) diff --git a/utilities/utils.py b/utilities/utils.py index 6b703b1..8681a6b 100644 --- a/utilities/utils.py +++ b/utilities/utils.py @@ -390,7 +390,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) From c25d354fc09f8d5099bcd450789049b64450fbd5 Mon Sep 17 00:00:00 2001 From: imcompiling Date: Fri, 14 Mar 2025 16:09:52 -0400 Subject: [PATCH 51/51] Correct some parameter usage, handle errors if searches return nothing. --- .vscode/settings.json | 4 ++-- cogs/commands/set.py | 28 ++++++++++++++++++++-------- 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index 47e3829..1dc3b48 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -10,8 +10,8 @@ "ondelete" ], "python.analysis.diagnosticSeverityOverrides": { - "reportOptionalMemberAccess": false, + "reportOptionalMemberAccess": "warning", "reportArgumentType": "information", "reportAttributeAccessIssue": "warning" } -} +} \ No newline at end of file diff --git a/cogs/commands/set.py b/cogs/commands/set.py index 7b4bdd5..47e8d26 100644 --- a/cogs/commands/set.py +++ b/cogs/commands/set.py @@ -52,8 +52,10 @@ class SetCog(commands.Cog, name="Set command."): .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() await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True) @@ -88,8 +90,11 @@ class SetCog(commands.Cog, name="Set command."): .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 or Category 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 @@ -120,7 +125,9 @@ class SetCog(commands.Cog, name="Set command."): with Session(engine) as session: stmt = select(Guild).where(col(Guild.id) == interaction.guild_id) - guild = session.scalar(stmt) + 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) @@ -150,8 +157,11 @@ class SetCog(commands.Cog, name="Set command."): .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) @@ -178,7 +188,9 @@ class SetCog(commands.Cog, name="Set command."): with Session(engine) as session: stmt = select(Guild).where(col(Guild.id) == interaction.guild_id) - guild = session.scalar(stmt) + 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)