Compare commits

..
Author SHA1 Message Date
imcompiling e2e8d8de30 Don't need to print the help string.
build_develop / build (push) Successful in 1m20s
build_release / build (push) Successful in 20s
2024-09-29 23:31:49 -04:00
imcompiling 7f007ffa1f Merge commit '02e7a6df3a13bb19056f31f616101980b668ae43'
build_develop / build (push) Successful in 2m20s
2023-08-30 09:04:36 -04:00
imcompiling 913f915bf0 Clarify create category option description. 2023-08-30 09:04:24 -04:00
imcompiling 02e7a6df3a Comment out troublesome code. I believe that this causes users to have trouble submitting multiple in a row over 5 minutes. 2023-08-29 21:01:13 -04:00
imcompiling 7be869b2b6 Update registry location.
build_develop / build (push) Successful in 1m14s
2023-07-29 18:34:56 -04:00
imcompiling 15c4776918 its async. must await.
build_develop / build (push) Failing after 1m29s
2023-07-25 13:38:48 -04:00
imcompiling d3102b57cc Add new birthday action.
build_develop / build (push) Has been cancelled
2023-07-25 11:19:56 -04:00
imcompiling 9bef20de5b Clarify wording in submission process.
build
2023-04-30 21:54:02 -04:00
imcompiling 9231c04c6a Merge branch '61-guild-active-in-database'
build
2023-03-29 20:14:47 -04:00
imcompiling 36ba4d35e0 Update table definition. Add on_guild_remove listener. 2023-03-29 20:13:39 -04:00
imcompiling b80959866a Merge branch '44-limit-autofill-choices'
build
2023-03-29 19:19:20 -04:00
imcompiling de1eba025a Limit results from autofill functions.
Also define some types.
2023-03-29 19:19:04 -04:00
imcompiling 28e575f364 Remove docker-compose from repo.
build
2023-03-29 16:43:11 -04:00
imcompiling d8368b4b92 Merge branch '62-dm-on-join'
build
2023-03-29 16:42:41 -04:00
imcompiling cc10bb518c Add comment. 2023-03-29 16:42:25 -04:00
imcompiling 90131f6395 Add message to myself on join. Edit adding guild just in case they already exist in database. 2023-03-28 15:06:48 -04:00
imcompiling 1814867c09 Merge branch '58-guild-name-in-database'
build
2023-03-28 13:55:40 -04:00
imcompiling 390bf8a489 rename variable. 2023-03-28 13:55:18 -04:00
imcompiling 74aa78c748 Add loop for updating guild data. 2023-03-28 13:44:03 -04:00
imcompiling 379f280c11 Refactor presence to loops. 2023-03-28 13:02:07 -04:00
imcompiling 7d1e69c007 Don't need this import. 2023-03-28 12:56:50 -04:00
imcompiling b905ce7216 Change tag to v. 2023-03-28 12:51:39 -04:00
imcompiling 4bb7db3f71 Set push for specific tag only, set GIT_TAG env var. 2023-03-28 12:51:39 -04:00
imcompiling b3f48d4603 Correct on push. 2023-03-28 12:51:39 -04:00
imcompiling 90763c73a7 Add release workflow. 2023-03-28 12:51:39 -04:00
imcompiling 635419dc7c Change to operate on the main branch. No need for dev branch. 2023-03-28 12:51:39 -04:00
imcompiling 2356d5edbf Change workflow back to develop branch. 2023-03-28 12:51:39 -04:00
imcompiling 9eed0a1f4e Don't use action due to using local repo. 2023-03-28 12:51:39 -04:00
imcompiling a9a6ab4520 correct github address. 2023-03-28 12:51:39 -04:00
imcompiling e08a764591 Install docker onto image. 2023-03-28 12:51:39 -04:00
imcompiling 8b43f766b3 try https url 2023-03-28 12:51:39 -04:00
imcompiling cb9cad9783 maybe need buildx to set up docker 2023-03-28 12:51:39 -04:00
imcompiling 216becff6e try with docker commands instead of action. 2023-03-28 12:51:39 -04:00
imcompiling 836673198a try localhost for repo. 2023-03-28 12:51:39 -04:00
imcompiling e34739a0b1 Need buildx, don't understand why. 2023-03-28 12:51:39 -04:00
imcompiling 7c592e6acc correct http url, try again without buildx. 2023-03-28 12:51:39 -04:00
imcompiling 0f8637be23 try adding buildx to fix missing token. 2023-03-28 12:51:39 -04:00
imcompiling 3b597aeac7 delete unneeded files. 2023-03-28 12:51:39 -04:00
imcompiling c43b2297a4 Change runs-on, use action to build docker image. 2023-03-28 12:51:39 -04:00
imcompiling 1b337a291d add demo workflow 2023-03-28 12:51:39 -04:00
imcompiling 16b662875f Add build_develop workflow. 2023-03-28 12:51:39 -04:00
imcompiling 307f61934e Merge branch '59-gitea-action'
build
2023-03-23 16:52:15 -04:00
imcompiling 00265f2f58 Change tag to v. 2023-03-23 16:50:39 -04:00
imcompiling 93d558edbc Merge commit '0f2b1aa2e655a66c777a71c3917cd61147c9d754' into 59-gitea-action
build
2023-03-23 16:45:52 -04:00
imcompiling 0f2b1aa2e6 Set push for specific tag only, set GIT_TAG env var.
build
2023-03-23 16:44:08 -04:00
imcompiling 3f6bac99ab Merge branch '59-gitea-action'
build
2023-03-23 09:30:16 -04:00
imcompiling 46e2955642 Correct on push.
build
2023-03-23 09:30:00 -04:00
imcompiling ac9bf6b35f Merge branch 'develop' 2023-03-23 09:19:47 -04:00
imcompiling 869b2ccb82 Merge branch '59-gitea-action' into develop 2023-03-23 09:19:29 -04:00
imcompiling 3ddfdfe9b0 Add release workflow. 2023-03-23 09:16:01 -04:00
imcompiling 3860e74579 Change to operate on the main branch. No need for dev branch. 2023-03-23 09:09:41 -04:00
imcompiling 3b49a6ec2a Change workflow back to develop branch. 2023-03-22 23:25:26 -04:00
imcompiling 2f89588358 Don't use action due to using local repo.
build
2023-03-22 23:14:15 -04:00
imcompiling 0513df944f correct github address.
build
2023-03-22 22:31:42 -04:00
imcompiling ddf319b9d5 Install docker onto image.
build
2023-03-22 22:27:05 -04:00
imcompiling 13f5bc0aab try https url
build
2023-03-22 21:47:28 -04:00
imcompiling e6f3fcb604 maybe need buildx to set up docker
build
2023-03-22 19:35:11 -04:00
imcompiling eaa342d479 try with docker commands instead of action.
build
2023-03-22 19:34:27 -04:00
imcompiling ac11f3e462 try localhost for repo.
build
2023-03-22 19:22:18 -04:00
imcompiling 106b394c44 Need buildx, don't understand why.
build
2023-03-22 19:16:54 -04:00
imcompiling 6c1505685b correct http url, try again without buildx.
build
2023-03-22 19:15:15 -04:00
imcompiling 2e681be690 try adding buildx to fix missing token.
build
2023-03-22 19:12:03 -04:00
imcompiling 5448f2a426 delete unneeded files. 2023-03-22 19:11:22 -04:00
imcompiling 7647c355af Change runs-on, use action to build docker image.
Explore-GitHub-Actions
build
2023-03-22 18:56:20 -04:00
imcompiling a95fca40f9 add demo workflow
Explore-GitHub-Actions
build_develop
2023-03-21 22:06:46 -04:00
imcompiling 148ba253cf Add build_develop workflow.
build_develop
2023-03-21 21:53:04 -04:00
imcompiling 640d481018 Add guild name to database on join. 2023-03-21 21:41:51 -04:00
imcompiling 4c18513661 Merge branch '35-show-leaderboard-command' into develop 2023-03-11 15:12:59 -05:00
imcompiling 37b4d2d62e correct usage of format_score_string. Make format of view message better. 2023-03-11 15:12:36 -05:00
imcompiling 9c762fb346 Add on delete cascade to sql definition. 2023-03-10 17:56:49 -05:00
imcompiling 2c9e9e246a Create view leaderboard command. 2023-03-10 17:37:59 -05:00
imcompiling ab721c1625 create format_score_string function. 2023-03-10 16:27:40 -05:00
imcompiling 2864f342cc need to push tags separately. 2023-03-10 16:01:54 -05:00
imcompiling 92511db446 Merge branch '35-show-leaderboard-command' of https://gitea.cheezers.net/imcompiling/agon into 35-show-leaderboard-command 2023-03-10 12:18:25 -05:00
imcompiling 44c2720f80 Add new view file. 2023-03-10 12:17:58 -05:00
imcompiling 35cebdebce correct develop builder. 2023-03-10 11:57:28 -05:00
imcompiling e4437cc654 Correct the build scripts. 2023-03-10 11:56:45 -05:00
imcompiling fe2c400a2a Add build script. 2023-03-09 16:22:31 -05:00
imcompiling 39875585ef Change sqlalchemy version requirement. 2023-02-12 21:46:25 -05:00
imcompiling 7796ead644 Revert "Make command for admin only."
This reverts commit 8595a12f7f.
2023-02-12 21:37:12 -05:00
imcompiling 531d2f3a0e Merge commit '63e77958fb09c6849d48263994b69fcd92f46277' 2023-02-12 21:30:22 -05:00
imcompiling 8595a12f7f Make command for admin only. 2023-02-12 21:27:54 -05:00
imcompiling f76171ac84 Create simple help command for setting up. 2023-02-12 20:52:28 -05:00
imcompiling 1605c8ad50 Add new view file. 2023-02-12 13:33:05 -05:00
alwayscompiling 63e77958fb Do need to expose port for test bot. 2022-12-10 16:54:49 -05:00
alwayscompiling 0bae0ea5ff Remove custom mysqldb image, just use latest public. Move bot docker to base directory. 2022-12-10 16:12:56 -05:00
alwayscompiling c67e9ae617 Use pymysql for sql connection. 2022-12-10 16:12:21 -05:00
alwayscompiling 7e23ac14ff Create dockerfile for bot. Add bot to compose. 2022-12-10 12:46:12 -05:00
alwayscompiling a0a7e37921 Remove guild join stuff again. 2022-12-09 16:43:56 -05:00
alwayscompiling c01c888503 Merge branch '21-allow-users-to-modify-tablescategories' into develop 2022-12-08 23:17:21 -05:00
alwayscompiling 58dbe547bb Add submit button on group create. 2022-12-08 23:16:56 -05:00
alwayscompiling 3cf4fc6b33 Merge branch '21-allow-users-to-modify-tablescategories' into develop 2022-12-08 23:09:07 -05:00
alwayscompiling 411f8ab275 Add a deletion confirmation. 2022-12-08 22:59:00 -05:00
alwayscompiling 8952c4a352 Remove onjoin message. 2022-12-08 13:44:34 -05:00
alwayscompiling 93248797a0 Fill out rest of group and category command. Fill out doc strings. 2022-12-08 13:41:15 -05:00
alwayscompiling dace72f5cc Correct empty message id handling. 2022-12-08 13:28:13 -05:00
alwayscompiling f468a028d0 Changed send_highscore_message to take guild rather than channel. 2022-12-08 13:02:39 -05:00
alwayscompiling a9b889234a Start filling out create category. 2022-12-07 22:40:47 -05:00
alwayscompiling 88cec73644 Create command skeletons. Update set to conform to min and max values decided in create. 2022-12-07 22:24:38 -05:00
alwayscompiling 91e57c6555 Standardize autocomplete function names. 2022-12-07 21:52:36 -05:00
alwayscompiling 6c5f40f788 Refractor command files into single command files. 2022-12-07 21:46:04 -05:00
alwayscompiling a9920db381 Don't auto add runescape groups on join. 2022-12-07 20:54:49 -05:00
alwayscompiling d04b8c5e32 Squashed commit of the following:
commit 3627419e12
Merge: 2db744d 3446ce9
Author: alwayscompiling <[email protected]>
Date:   Tue Dec 6 22:36:51 2022 -0500

    Merge branch '45-sql-connection-timing-out' into develop

commit 3446ce9ca2
Author: alwayscompiling <[email protected]>
Date:   Tue Dec 6 22:27:05 2022 -0500

    Change session usage to on use basis.

commit 2db744d170
Author: alwayscompiling <[email protected]>
Date:   Sun Dec 4 21:44:54 2022 -0500

    Add restart policy.

commit fa33be1b4a
Author: alwayscompiling <[email protected]>
Date:   Sun Dec 4 21:25:57 2022 -0500

    Renamed docker compose file.
2022-12-06 23:02:01 -05:00
alwayscompiling 3627419e12 Merge branch '45-sql-connection-timing-out' into develop 2022-12-06 22:36:51 -05:00
alwayscompiling 3446ce9ca2 Change session usage to on use basis. 2022-12-06 22:28:53 -05:00
alwayscompiling 582b88e248 Create set command over Settings Management. 2022-12-04 22:42:55 -05:00
alwayscompiling 2db744d170 Add restart policy. 2022-12-04 21:44:54 -05:00
alwayscompiling fa33be1b4a Renamed docker compose file. 2022-12-04 21:25:57 -05:00
alwayscompiling 296e14f0f6 Add docker compose file. 2022-12-04 11:57:23 -05:00
alwayscompiling 4c8444d077 Move config file into utilities. 2022-12-04 11:00:22 -05:00
alwayscompiling 2e2030a533 Move mysql docker stuff into own dir. 2022-12-04 10:56:44 -05:00
alwayscompiling f4ec272567 Update functions for username length being in group. 2022-12-04 10:54:54 -05:00
alwayscompiling b7dd44a028 Change database structure. UsernameLength belong in CategoryGroup. 2022-12-03 20:56:57 -05:00
alwayscompiling 081e406d51 Allow user to update score. 2022-12-03 20:49:17 -05:00
alwayscompiling e3a937649f Fix string formatting for splitting categories into multiple rows. 2022-12-02 22:08:01 -05:00
alwayscompiling d09c9b2b03 Clean up username update verify message on approval. 2022-12-02 20:57:42 -05:00
alwayscompiling 8624285d09 Remove another subquery. Enforce username length. 2022-12-02 20:41:10 -05:00
alwayscompiling f1cbe81699 Missed incorrect subquery. 2022-12-02 18:29:23 -05:00
alwayscompiling aea2e0beb3 Remove subqueries when sending to IN call. 2022-12-02 18:27:50 -05:00
alwayscompiling fdd08bc1a2 bug fixes in from_group and autocomplete user. 2022-12-02 18:17:06 -05:00
alwayscompiling 98dbd30327 Only delete specified user. cat_name is already the string. 2022-12-02 17:49:11 -05:00
alwayscompiling 2565b7689f Correct arg names. 2022-12-02 17:42:59 -05:00
alwayscompiling 52305c0107 Clarify parameter name for users, correct id usage for autofills. 2022-12-02 17:02:44 -05:00
alwayscompiling bed07d440b Merge branch '13-use-a-database' of github.com:alwayscompiling/pvm-highscores into 13-use-a-database 2022-12-02 16:53:51 -05:00
alwayscompiling 4e832a084f Corrected autofill function return structures. 2022-12-02 16:32:22 -05:00
alwayscompiling cc20868bde Corrected autofill function return structures. 2022-12-02 16:08:36 -05:00
alwayscompiling 14602282e9 Clarify optional SlashOptions 2022-12-02 15:28:53 -05:00
alwayscompiling 2e3f298036 Correct score submission value. Parse times correctly. 2022-12-01 23:30:21 -05:00
alwayscompiling 44cb9025b0 Edit embeds to provide bot information for submission. 2022-12-01 23:26:04 -05:00
alwayscompiling 02145ba244 Create new python file for handling sqlalchemy. Removes circular import. 2022-12-01 22:58:39 -05:00
alwayscompiling 58e616ea47 Put pandas group into separate variable to remove warning. 2022-12-01 22:42:43 -05:00
alwayscompiling 2ec7296c0f Bug fixes from testing post_highscore_groups. Command name change. 2022-12-01 20:34:12 -05:00
alwayscompiling d0f328dd2d Variable name changes for clarification and fixing runtime issues. 2022-12-01 20:21:36 -05:00
alwayscompiling 2154d713cb Update username verify view to use new database. 2022-12-01 18:14:23 -05:00
alwayscompiling ea0ebcc2e9 Update data management to use new database. 2022-12-01 18:06:43 -05:00
alwayscompiling b9cc3b46bb Add autofill to get all users in guild. 2022-12-01 17:42:29 -05:00
alwayscompiling 439ad539a8 Updated message management to use new database. 2022-12-01 17:07:50 -05:00
alwayscompiling 10e8e5a446 Update settings management to new database. 2022-12-01 16:40:06 -05:00
alwayscompiling 34e55b962d Change autofill functions to return dicts of name id pairs. 2022-12-01 16:39:32 -05:00
alwayscompiling 1fdb9ff1b6 Update the verification view to use database. 2022-11-30 22:58:27 -05:00
alwayscompiling 4f255a32e2 Change submission to use database. Also use ids rather than names. 2022-11-30 22:36:45 -05:00
alwayscompiling 814baa27d6 Update message listener to new database. 2022-11-30 21:54:05 -05:00
alwayscompiling 9531dca892 Update guild listener to use new database. Add default config function to utils. 2022-11-30 21:45:46 -05:00
alwayscompiling 18df783d86 Update utils to use new database. 2022-11-30 20:54:06 -05:00
alwayscompiling 03d7485037 ignore the todo text file 2022-11-29 22:46:13 -05:00
alwayscompiling 1a55ae0ac5 Move category size to Categories table. 2022-11-29 21:11:44 -05:00
alwayscompiling 76d6ba7969 Change to sqlalchemy and orm scheme. Remove classes due to orm. Edit requirements. 2022-11-27 22:20:29 -05:00
alwayscompiling f95d3130ff Updating requirements. 2022-11-27 09:26:44 -05:00
alwayscompiling 09696071ef Correct guild id property name. 2022-11-27 00:43:24 -05:00
alwayscompiling e5d11d200c Update score to mainly hold sql query information. 2022-11-27 00:35:42 -05:00
alwayscompiling 6a87622b58 Update category class to just hold sql data. 2022-11-27 00:23:15 -05:00
alwayscompiling 9bc88a7e03 Do not need highscores_data class. 2022-11-27 00:07:42 -05:00
alwayscompiling 4c0e6a6209 Change table class to guild class. Change to just store sql table information. 2022-11-27 00:07:15 -05:00
alwayscompiling 017cb7c9df Update Guild class to hold sql Guilds table information. 2022-11-27 00:02:30 -05:00
alwayscompiling 17867671f1 Change order of database columns for easier reading. 2022-11-26 23:49:02 -05:00
alwayscompiling 8896e41726 Revert "Remove all data storage classes."
This reverts commit 77a32b3adc.
2022-11-26 23:20:35 -05:00
alwayscompiling 12a55dd626 Connect to db on bot start. Remove message map. 2022-11-26 21:36:38 -05:00
alwayscompiling 77a32b3adc Remove all data storage classes. 2022-11-26 20:59:44 -05:00
alwayscompiling 2f10a1c7e6 Final changes to correct primary key and uniqueness rules. 2022-11-26 20:52:54 -05:00
alwayscompiling a3bed52479 Remove password in dockerfile, change guild/channel ids to bigint unsigned. 2022-11-26 17:29:04 -05:00
alwayscompiling 6b7dd6042d Add files for docker sql server. 2022-11-25 14:15:55 -05:00
alwayscompiling c4d5477f8b Merge branch '1-add-more-administrative-commands' into develop 2022-11-24 17:55:06 -05:00
alwayscompiling f5342f1541 Fill functionality for delete user from_table and from_category. 2022-11-24 17:47:21 -05:00
alwayscompiling 1e336e290d Catching AttributeError in autofill functions when invalid variables are sent. 2022-11-24 17:45:40 -05:00
alwayscompiling 9ebbca2557 Fill out docstrings. 2022-11-24 17:05:45 -05:00
alwayscompiling 8a2108fc14 Create shell commands and autofill functions. Fix set initializer in utils.autofill_users. 2022-11-22 17:12:26 -05:00
alwayscompiling 03c7a9303a Small rewrite to consolidate autofill_user function. Sort imports in message_management.py. 2022-11-22 17:02:18 -05:00
alwayscompiling a0c5527bf6 Create autofill functions for users in category and in table. Add function in category class to return a list of all users. 2022-11-22 16:26:31 -05:00
alwayscompiling 8155fb0c8f Reorganized commands to facilitate new commands. 2022-11-22 16:01:55 -05:00
alwayscompiling 06b46ef27c Create general autofill table and category util functions. Update table class to have get categories function. 2022-11-17 14:50:48 -05:00
alwayscompiling 1858f0c37d Add refresh table command. 2022-11-16 16:30:34 -05:00
alwayscompiling 792a225987 Correct docstring 2022-11-15 16:17:22 -05:00
alwayscompiling 2e324dc9c5 Use the new category pad length variable. 2022-11-15 15:52:58 -05:00
alwayscompiling 09f7a4323c Correct category pad default. 2022-11-15 15:50:12 -05:00
alwayscompiling dd73e9b472 Add commands to edit username length and category pad. 2022-11-15 15:48:17 -05:00
alwayscompiling b4f5ddc822 Update to nextcord 2.3.2. 2022-11-12 01:16:04 -05:00
alwayscompiling d2f33959ed Create remove_user command. 2022-08-13 21:46:41 -04:00
alwayscompiling 652533d071 Should have handled username updating code in the command, didn't need to create new functions for the command. 2022-08-13 21:26:50 -04:00
alwayscompiling 73e350c845 Save takes guild object, not id. 2022-08-13 20:46:59 -04:00
alwayscompiling 9dec15dbfa Correct table update_username. 2022-08-13 20:45:29 -04:00
alwayscompiling 41ba4dc23c Save data after modified. 2022-08-13 20:40:06 -04:00
alwayscompiling 790cff3406 Clear view on approval. 2022-08-13 20:33:14 -04:00
alwayscompiling 7fb87ae12f Add username setter. 2022-08-13 20:30:21 -04:00
alwayscompiling 2407e61913 Correcting embed access. 2022-08-13 20:30:03 -04:00
alwayscompiling 6147263647 Add UpdateUsernameVerify view to MessageManagementCog. 2022-08-13 20:23:56 -04:00
alwayscompiling cb71cbe1d5 Create update_username functions for category and table. 2022-08-13 20:08:57 -04:00
alwayscompiling 080356fe9c Create Guild.update_username(). 2022-08-13 19:48:29 -04:00
alwayscompiling d4e19284f0 Create view for verifyng username update request. 2022-08-12 23:18:21 -04:00
alwayscompiling ae9153b78e Change submission views to be more informative. 2022-08-12 22:49:54 -04:00
alwayscompiling ca58e9ac26 Create initial update_username command. 2022-08-12 22:39:12 -04:00
alwayscompiling 432888e468 Tag user on submission verify. 2022-08-12 22:28:14 -04:00
alwayscompiling c918b9492b Renamed to data_management. Better description. 2022-08-11 23:02:44 -04:00
alwayscompiling caef6a3652 Created command to clear table messages. 2022-08-11 23:00:11 -04:00
alwayscompiling b2acafd6e7 Changed design to be one class per file. 2022-08-11 22:44:22 -04:00
alwayscompiling 349fdfe18d Renamed python files to more describe their contents. Intend on having more than 1 class per file. 2022-08-11 22:17:52 -04:00
alwayscompiling efed6e001f Moved all commands into single commands cog. 2022-08-11 21:55:06 -04:00
alwayscompiling 6b0e61cdf7 Update nextcord. 2022-08-08 22:12:41 -04:00
alwayscompiling 0acfa77492 Change delete_scores to a slash command. 2022-08-08 22:07:12 -04:00
alwayscompiling ffefd08761 Updated presense to account for slash commands. 2022-08-08 21:54:27 -04:00
alwayscompiling a61662429a Remove help command. Doesn't work with slash commands. 2022-08-08 21:51:25 -04:00
alwayscompiling 57244bcbfe Update post highscores command to slash command. 2022-08-08 21:51:06 -04:00
alwayscompiling 3fd9ff46a3 imports cleanup. 2022-08-08 21:36:45 -04:00
alwayscompiling d4ad727f2a Correcting error statement. 2022-08-06 22:58:43 -04:00
alwayscompiling 516ff7feeb Update minimum python version. Nextcord v2.0 requires python 3.8. 2022-08-06 22:26:55 -04:00
alwayscompiling 0eb332aefd Added verify and submission register subcommands. Removed bot argument from Register class. 2022-08-06 22:21:08 -04:00
alwayscompiling ff07787a9a Create register group and highscore slash subcommand. 2022-08-06 20:14:30 -04:00
39 changed files with 2096 additions and 1454 deletions
+26
View File
@@ -0,0 +1,26 @@
name: build_develop
on:
push:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install Docker
uses: https://github.com/papodaca/install-docker-action@v1
- name: Log into container registry
uses: docker/login-action@v2
with:
registry: gitea.cheezers.org
username: imcompiling
password: ${{ secrets.PASSWORD }}
- name: Build Docker Image
run: docker build -t gitea.cheezers.org/imcompiling/agon:develop .
- name: Push Docker Image
run: docker push gitea.cheezers.org/imcompiling/agon:develop
+30
View File
@@ -0,0 +1,30 @@
name: build_release
on:
push:
tags: ["v[0-9].[0-9].[0-9]"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Install Docker
uses: https://github.com/papodaca/install-docker-action@v1
- name: Log into container registry
uses: docker/login-action@v2
with:
registry: gitea.cheezers.org
username: imcompiling
password: ${{ secrets.PASSWORD }}
- name: Set env
run: echo "GIT_TAG=${GITHUB_REF#refs/*/}" >> $GITHUB_ENV
- name: Build Docker Images
run: docker build -t gitea.cheezers.org/imcompiling/agon:latest -t gitea.cheezers.org/imcompiling/agon:${{env.GIT_TAG}} .
- name: Push Latest Image
run: docker push gitea.cheezers.org/imcompiling/agon:latest
- name: Push Tagged Image
run: docker push gitea.cheezers.org/imcompiling/agon:${{env.GIT_TAG}}
+3 -1
View File
@@ -134,4 +134,6 @@ nextcord.log
highscores_data.json
highscores_config.json
deleted_backups/
highscores_data/
highscores_data/
TODO.txt
sql_tester.py
+21
View File
@@ -0,0 +1,21 @@
FROM python:3.8.10-slim
# install dependencies for mysqlclient
# RUN apt-get update && apt-get -y upgrade && apt-get -y install python3-dev default-libmysqlclient-dev build-essential
RUN pip install --upgrade pip
WORKDIR /home
COPY classes classes/
COPY cogs cogs/
COPY utilities utilities/
COPY highscores.py highscores.py
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
# remove build deps that aren't needed to run
# RUN apt-get -y remove python3-dev build-essential && apt-get -y autoremove
CMD ["python3", "./highscores.py"]
-190
View File
@@ -1,190 +0,0 @@
"""File for Category class."""
import json
from classes.score import Score, ScoreTime # pylint: disable=import-error
class Category:
"""Stores a category's information and relative scores."""
def __init__(self, name: str) -> None:
"""
Default constructor for Category class. Creates empty category and populates with defaults.
Args:
name (str): Category's name
"""
self._name: str = name
self._ascending: bool = False
self._time_record: bool = False
self._scores_map: dict = {}
def __str__(self) -> str:
"""
Returns Category class as a string for printing.
Returns:
str: Category class as a string
"""
return self.to_str()
@classmethod
def from_dict(cls, name: str, data: dict):
"""
Creates a Category class from the passed data.
Args:
name (str): Category name
data (dict): Rest of Category data in dictionary format
Returns:
Category: Populated Category object
"""
category = cls(name)
category.ascending = data["ascending"]
category.time_record = data["time_record"]
for user, score in data["scores"].items():
if category.time_record:
score_obj: ScoreTime = ScoreTime(user)
score_obj.value = float(score)
category.add_score(score_obj)
else:
score_obj: Score = Score(user)
score_obj.value = int(score)
category.add_score(score_obj)
return category
@property
def ascending(self) -> bool:
"""
Getter for is ascending.
Returns:
bool: is ascending
"""
return self._ascending
@ascending.setter
def ascending(self, ascending: bool) -> None:
"""
Setter for is ascending.
Args:
ascending (bool): is ascending
"""
self._ascending = ascending
@property
def name(self) -> str:
"""
Getter for name.
Returns:
str: name
"""
return self._name
@property
def time_record(self) -> bool:
"""
Getter for is time record.
Returns:
bool: is time record
"""
return self._time_record
@time_record.setter
def time_record(self, time_record: bool) -> None:
"""
Setter for is time record.
Args:
time_record (bool): is time record
"""
self._time_record = time_record
@property
def scores(self) -> "list[Score]":
"""
Getter for Scores list.
Returns:
list[Score]: List of Scores in this Category
"""
return self._scores_map.values()
def add_score(self, score: Score) -> None:
"""
Adds score to dictionary storage map. Sorts dictionary by score value.
Args:
score (Score): Score to be added
"""
if score.user in self._scores_map:
self._scores_map[score.user].value = score.value
else:
self._scores_map[score.user] = score
self._scores_map = dict(
sorted(self._scores_map.items(), key=lambda x: x[1].value, reverse=not self.ascending)
)
def clear(self) -> None:
"""
Clears all Scores tracked in score map.
This is a test function and shouldn't really be used.
"""
self._scores_map.clear()
def get_user_score(self, user: str) -> Score:
"""
Gets a user's score. Returns None if user is not found.
Args:
user (str): Name of score to find
Returns:
Score: User's Score or None
"""
if user in self._scores_map:
return self._scores_map[user]
return None
def remove_score(self, score: str) -> None:
"""
Removes a user's score from dictionary storage.
Args:
score (str): user whose score to remove
"""
score = self._scores_map.pop(score)
del score
def to_dict(self) -> dict:
"""
Saves category data as a python dictionary.
Does not include category name. It should be the key of above data structure.
Returns:
dict: Category class in dictionary format
"""
data = {}
data["ascending"] = self.ascending
data["time_record"] = self.time_record
data["scores"] = {}
for score in self.scores:
data["scores"][score.user] = score.value
return data
def to_str(self) -> str:
"""
Returns Category object as a string.
Returns:
str: string of json representation of Category
"""
return json.dumps(self.to_dict(), indent=4)
-211
View File
@@ -1,211 +0,0 @@
"""File for Guild class."""
import json
from classes.table import Table # pylint: disable=import-error
class Guild:
"""Stores a guild's information."""
def __init__(self, guild_id: int) -> None:
"""
Default constructor for Guild class. Initializes channel ids as 0 as they won't be
registered yet. Sets default username length of 12. Default highscores size to 3.
Args:
guild_id (int): Discord Guild id of new Guild
"""
self._guild_id: int = guild_id
self._highscore_channel_id: int = 0
self._submission_channel_id: int = 0
self._table_map: dict = {}
self._username_length: int = 12
self._verification_channel_id: int = 0
def __str__(self) -> str:
"""
Returns Guild class as a string for printing.
Returns:
str: Guild class as a string
"""
return self.to_str()
@classmethod
def from_dict(cls, guild_id: int, data: dict):
"""
Creates a Guild class from the passed data.
Args:
guild_id (int): Guild's id
data (dict): Rest of Guild data in dictionary format
Returns:
Guild: Populated Guild object
"""
guild = cls(guild_id)
guild.highscore_channel = data["highscore_channel_id"]
guild.submission_channel = data["submission_channel_id"]
guild.username_length = data["username_length"]
guild.verification_channel = data["verification_channel_id"]
for table_name, table_data in data["tables"].items():
table = Table.from_dict(table_name, table_data)
guild.add_table(table)
return guild
@property
def guild_id(self) -> int:
"""
Getter for Guild id
Returns:
int: Guild id
"""
return self._guild_id
@property
def highscore_channel(self) -> int:
"""
Getter for highscore channel id.
Returns:
int: highscore channel id
"""
return self._highscore_channel_id
@highscore_channel.setter
def highscore_channel(self, channel: int) -> None:
"""
Setter for highscore channel id.
Args:
channel (int): highscore channel id
"""
self._highscore_channel_id = channel
@property
def submission_channel(self) -> int:
"""
Getter for submission channel id.
Returns:
int: submission channel id
"""
return self._submission_channel_id
@submission_channel.setter
def submission_channel(self, channel: id) -> None:
"""
Setter fro submission channel id.
Args:
channel (id): submission channel id
"""
self._submission_channel_id = channel
@property
def tables(self) -> "list[Table]":
"""
Getter for Tables list.
Returns:
list[Table]: List of Tables in this Guild
"""
return self._table_map.values()
@property
def username_length(self) -> int:
"""
Getter for username length.
Returns:
int: username length
"""
return self._username_length
@username_length.setter
def username_length(self, length: int) -> None:
"""
Setter for username length.
Args:
length (int): username length
"""
self._username_length = length
@property
def verification_channel(self) -> int:
"""
Getter for verification channel id.
Returns:
int: verification channel id
"""
return self._verification_channel_id
@verification_channel.setter
def verification_channel(self, channel: int) -> None:
"""
Setter for verification channel id
Args:
channel (int): verification channel id
"""
self._verification_channel_id = channel
def add_table(self, table: Table) -> None:
"""
Adds a Table to table map. Shouldn't exist already.
Args:
table (Table): new Table to add
"""
if table.name not in self._table_map:
self._table_map[table.name] = table
def get_table(self, table_name: str) -> Table:
"""
Getter for specific Table. Returns None if Table is not found.
Args:
table_name (str): Name of Table to find
Returns:
Table: Table corresponding to Name. None if not found.
"""
if table_name in self._table_map:
return self._table_map[table_name]
return None
def to_dict(self) -> dict:
"""
Creates python dictionary object from class data.
Does not include guild_id in dict, it should be the key of above data structure.
Returns:
dict: Guild class in dictionary format
"""
data: dict = {}
data["highscore_channel_id"] = self.highscore_channel
data["submission_channel_id"] = self.submission_channel
data["tables"] = {}
data["username_length"] = self.username_length
data["verification_channel_id"] = self.verification_channel
for table in self.tables:
data["tables"][table.name] = table.to_dict()
return data
def to_str(self) -> str:
"""
Returns Guild object as a string.
Returns:
str: string of json representation of Guild
"""
return json.dumps(self.to_dict(), indent=4)
-153
View File
@@ -1,153 +0,0 @@
"""Class and functions for storing and retrieving highscores data."""
import os
import json
from classes.guild import Guild # pylint: disable=import-error
from classes.table import Table # pylint: disable=import-error
from classes.category import Category # pylint: disable=import-error
HIGHSCORES_BACKUP_DIR = "deleted_backups"
HIGHSCORES_CONFIG_DIR = "example_config"
HIGHSCORES_DATA_DIR = "highscores_data"
class HighscoresData:
"""Class for storing and retrieving highscores data."""
def __init__(self) -> None:
"""
Default constructor for Highscores Data. Opens up known highscores data on creation.
"""
self._guild_map: dict = {}
# Ensure that data directories exist.
if not os.path.exists(HIGHSCORES_BACKUP_DIR):
os.mkdir(HIGHSCORES_BACKUP_DIR)
if not os.path.exists(HIGHSCORES_DATA_DIR):
os.mkdir(HIGHSCORES_DATA_DIR)
self.open_highscores_data()
def __str__(self) -> str:
"""
Returns Highscores class as a string for printing.
Returns:
str: Highscores class as a string
"""
data: dict = {}
for guild_id, guild_obj in self._guild_map.items():
data[guild_id] = guild_obj.to_dict()
return "Highscores Data\n" + json.dumps(data, indent=4)
@property
def guilds(self) -> "list[Guild]":
"""
Getter for Guilds list.
Returns:
list[Guild]: List of Guilds tracked by Highscores Bot
"""
return self._guild_map.values()
def add_configuration(self, guild_id: int, config_str: str) -> None:
"""
Adds an example configuration to a Guild. Uses guild id to know which guild and
config name to open a file in example_config.
Args:
guild_id (int): Guild id to add config to
config_str (str): Config name to add
"""
config = self._open_highscores_config(config_str)
guild = self.get_guild(guild_id)
for table_name, categorys in config["tables"].items():
table_obj = Table(table_name)
table_obj.size = config["table_size"]
for category_name in categorys:
category = Category(category_name)
category.ascending = config["categories"][category.name]["ascending"]
category.time_record = config["categories"][category.name]["is_time_record"]
table_obj.add_category(category)
guild.add_table(table_obj)
def add_guild(self, guild_id: int) -> None:
"""
Creates a new Guild and adds to Guild map.
Args:
guild_id (int): Guild Id to add
"""
guild: Guild = Guild(guild_id)
self._guild_map[guild_id] = guild
def get_guild(self, guild_id: int) -> Guild:
"""
Getter for Guild object that corresponds with the guild_id.
Args:
guild_id (int): id of Guild to retrieve.
Returns:
Guild: Guild object for guild_id
"""
return self._guild_map[guild_id]
def remove_guild(self, guild_id: int) -> None:
"""
Removes a guild's data from object. Saves backup.
Args:
guild_id (int): guild id to remove
"""
self._guild_map.pop(guild_id)
os.rename(
f"{HIGHSCORES_DATA_DIR}/{guild_id}.json", f"{HIGHSCORES_BACKUP_DIR}/{guild_id}.json"
)
def _open_highscores_config(self, config: str) -> dict:
"""
Opens the highscores config file and returns in dictionary format.
Will be replaced when config class is created.
Args:
config (str): Name of config to load.
Returns:
dict: dict of highscores config
"""
with open(f"{HIGHSCORES_CONFIG_DIR}/{config}.json", encoding="utf-8", mode="r") as file:
return json.load(file)
def open_highscores_data(self):
"""
Opens all saved highscores data in the HIGHSCORES_DATA_DIR dir. Creates a Guild object from
each file and adds to guild map.
"""
for data_file in os.listdir(HIGHSCORES_DATA_DIR):
guild_id: int = int(data_file.split(".", maxsplit=1)[0])
with open(f"{HIGHSCORES_DATA_DIR}/{data_file}", encoding="utf-8", mode="r") as file:
guild_obj: Guild = Guild.from_dict(guild_id, json.load(file))
self._guild_map[guild_obj.guild_id] = guild_obj
def save_all_data(self) -> None:
"""
Calls save_guild_data for each guild tracked in guild map.
"""
for guild in self.guilds:
self.save_guild_data(guild)
def save_guild_data(self, guild: Guild) -> None:
"""
Saves a guild to its own json file.
Args:
guild (Guild): Guild to save
"""
with open(
f"{HIGHSCORES_DATA_DIR}/{guild.guild_id}.json", encoding="utf-8", mode="w"
) as file:
file.write(guild.to_str()) # should use str function
-144
View File
@@ -1,144 +0,0 @@
"""File for Score classes"""
import time
class Score:
"""Parent class for Scores. Stores common information for a Score."""
# no user setter, it should never change.
def __init__(self, user: str) -> None:
"""
Default constructor for Score class.
Args:
user (str): Score's user
value (int): Score's value
"""
self._user: str = user
self._value: int = -1
def __str__(self) -> str:
"""
Returns Score class as a string for printing.
Returns:
str: Score class as a string
"""
return self.to_str()
@property
def user(self) -> str:
"""
Getter for score user.
Returns:
str: user
"""
return self._user
@property
def value(self) -> int:
"""
Getter for score value.
Returns:
int: value
"""
return self._value
@value.setter
def value(self, value: int) -> None:
"""
Setter for score value.
Args:
value (int): score value input
"""
self._value = value
def get_str(self) -> str:
"""
Gets score's value as string.
Returns:
str: Score's value
"""
return str(self._value)
def set_value_str(self, value: str) -> None:
"""
Setter for score value from string.
Args:
value (str): int as a string
"""
self._value = int(value)
def to_str(self) -> str:
"""
Returns Score object as a string.
Returns:
str: string of json representation of Score
"""
return f"{self.user}: {self.get_str()}"
class ScoreTime(Score):
"""Class for a time based score. Inherits from Score."""
def __init__(self, user: str) -> None: # pylint: disable=super-init-not-called
"""
Default constructor for ScoreTime class.
Args:
user (str): Score's user
score (float): Score's value
"""
# store time score as seconds.
self._user: str = user
self._score: float = -1.0
@property
def value(self) -> float:
"""
Getter for score value.
Returns:
float: value
"""
return self._score
@value.setter
def value(self, value: float) -> None:
"""
Setter for score value.
Args:
value (float): value
"""
self._score = value
def get_str(self) -> str:
"""
Gets score's value as string. Turns seconds into MM:SS.ms format.
Returns:
str: value in time format.
"""
milliseconds = round((self.value - int(self.value)) * 10)
return time.strftime(f"%-M:%S.{milliseconds}", time.gmtime(self.value))
def set_value_str(self, value: str) -> None:
"""
Setter for score value from a string.
Args:
value (str): string representation of time
"""
if value.find(":"):
self._score = int(value.split(":")[0]) * 60 + float(value.split(":")[1])
else:
self._score = float(value)
+53 -29
View File
@@ -4,8 +4,12 @@ Contains classes and enum for tracking data on submissions.
from enum import Enum
from nextcord import Embed
from sqlalchemy import select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from utilities.sql_data_classes import Category, CategoryGroup, engine
class SubmissionState(Enum):
@@ -21,45 +25,46 @@ class SubmissionState(Enum):
VERIFY = 6
# TODO remake into a data class
class Submission:
"""
Class for an individual submission. Contains submission information such as
guild id, message id, table, category, username, score and submission state.
"""
def __init__(self, guild_id: int, table: str, username: str) -> None:
def __init__(self, guild_id: int, group_id: int, username: str) -> None:
"""
Default constructor for Submission. Just need to know guild_id, table, and username.
Score and category are defaulted at empty, message id is 0, and submission state
is SubmissionState.CATEGORY.
"""
self._category: str = ""
self._category_id: int = 0
self._guild_id: int = guild_id
self._message_id: int = 0
self._score: str = ""
self._submission_state: SubmissionState = SubmissionState.CATEGORY
self._table: str = table
self._group_id: int = group_id
self._username: str = username
@property
def category(self) -> str:
def category_id(self) -> int:
"""
Getter for Submission's Category name.
Getter for Submission's Category id.
Returns:
str: Category name.
int: Category id.
"""
return self._category
return self._category_id
@category.setter
def category(self, category: str) -> None:
@category_id.setter
def category_id(self, category: int) -> None:
"""
Setter for Submission's Category name.
Setter for Submission's Category id.
Args:
category (str): Category name
category (int): Category id
"""
self._category = category
self._category_id = category
@property
def guild_id(self) -> int:
@@ -132,24 +137,24 @@ class Submission:
self._submission_state = state
@property
def table(self) -> str:
def group_id(self) -> str:
"""
Getter for table Submission is for.
Getter for group Submission is for.
Returns:
str: table name
str: group id
"""
return self._table
return self._group_id
@table.setter
def table(self, table: str) -> None:
@group_id.setter
def group_id(self, table: str) -> None:
"""
Getter for table Submission is for.
Args:
table (str): table name
table (str): group id
"""
self._table = table
self._group_id = table
@property
def username(self) -> str:
@@ -171,19 +176,19 @@ class Submission:
"""
self._username = username
def get_embed(self) -> Embed:
def get_embeds(self) -> "list[Embed]":
"""Creates an embed based off of the submission state and fields filled out."""
state: SubmissionState = self.submission_state
if state is SubmissionState.CATEGORY:
description = "Step 1: Choose your category!"
elif state is SubmissionState.SCORE:
description = "Step 2: Input your score!"
description = "Step 2: Send a message to input your score!"
elif state is SubmissionState.PROOF:
description = "Step 3: Submit your proof!"
description = "Step 3: Send a message with a picture attached to submit your proof!"
elif state is SubmissionState.NAME:
description = (
"Step 4 (Optional): Change name on submission! (proceed to next if skipping)"
"Step 4 (Optional): Send a message to change name on submission! (proceed to next if skipping)"
)
elif state is SubmissionState.SUBMIT:
description = "Step 5: Submit if everything looks correct!"
@@ -192,12 +197,31 @@ class Submission:
embed = Embed(title="Highscores Submission", description=description)
embed.add_field(name="User Name", value=self.username, inline=False)
embed.add_field(name="Table", value=self.table, inline=False)
if self.category:
embed.add_field(name="Category", value=self.category, inline=False)
stmt = (
select(CategoryGroup.GroupName)
.where(CategoryGroup.GuildId == self.guild_id)
.where(CategoryGroup.GroupId == self.group_id)
)
with Session(engine) as session:
embed.add_field(name="Group", value=session.scalar(stmt), inline=False)
if self.category_id:
stmt = (
select(Category.CategoryName)
.where(Category.GroupId == self.group_id)
.where(Category.CategoryId == self.category_id)
)
embed.add_field(name="Category", value=session.scalar(stmt), inline=False)
if self.score:
embed.add_field(name="Score", value=self.score, inline=False)
return embed
embeds = [embed]
if state is SubmissionState.VERIFY:
embed = Embed(title="Bot Information", description="Please disregard.")
embed.add_field(name="GroupId", value=self.group_id)
embed.add_field(name="CategoryId", value=self.category_id)
embeds.append(embed)
return embeds
class SubmissionMap:
-164
View File
@@ -1,164 +0,0 @@
"""File for Table class."""
import json
from classes.category import Category # pylint: disable=import-error
class Table:
"""Stores a table's information a list of categories."""
def __init__(self, name: str) -> None:
"""
Default constructor for Table class.
Creates object and fills out class variables with defaults.
Args:
name (str): Table's name
"""
self._name: str = name
self._message_id: int = 0
self._categories_map: dict = {}
self._size = 3
def __str__(self) -> str:
"""
Returns Table class as a string for printing.
Returns:
str: Table class as a string
"""
return self.to_str()
@classmethod
def from_dict(cls, table_name: str, data: dict):
"""
Creates a Table class from the passed data.
Args:
table_name (str): Table name
data (dict): Rest of Table data in dictionary format
Returns:
Table: Populated Table object
"""
table = cls(table_name)
table.message_id = data["message_id"]
table.size = data["table_size"]
for cat_name, cat in data["categories"].items():
category = Category.from_dict(cat_name, cat)
table.add_category(category)
return table
@property
def categories(self) -> "list[Category]":
"""
Getter for Categories list.
Returns:
list[Category]: List of Categories in this Table
"""
return self._categories_map.values()
@property
def message_id(self) -> int:
"""
Getter for message id
Returns:
int: message id
"""
return self._message_id
@message_id.setter
def message_id(self, m_id: int) -> None:
"""
Setter for message id.
Args:
m_id (int): message id
"""
self._message_id = m_id
@property
def name(self) -> str:
"""
Getter for name.
Returns:
str: name
"""
return self._name
@property
def size(self) -> int:
"""
Getter for size of table.
Returns:
int: Size of table
"""
return self._size
@size.setter
def size(self, size: int) -> None:
"""
Setter for size of table.
Args:
size (int): New size of table
"""
self._size = size
def add_category(self, category: Category) -> None:
"""
Adds a Category to categories map. Shouldn't exist already.
Args:
category (Category): New Category to add
"""
if category.name not in self._categories_map:
self._categories_map[category.name] = category
def get_category(self, category_name: str) -> Category:
"""
Getter for specific category. Returns None if not found.
Args:
category_name (str): name of category to return
Returns:
Category: Category corresponding to name. None if not found.
"""
if category_name in self._categories_map:
return self._categories_map[category_name]
return None
def to_dict(self) -> dict:
"""
Saves Table as a python dictionary.
Does not include table name. It should be the key of above data structure.
Returns:
dict: Table class in dictionary format
"""
data = {}
data["message_id"] = self.message_id
data["table_size"] = self.size
data["categories"] = {}
for category in self.categories:
data["categories"][category.name] = category.to_dict()
return data
def to_str(self) -> str:
"""
Returns Table object as a string.
Returns:
str: string of json representation of Table
"""
return json.dumps(self.to_dict(), indent=4)
+28
View File
@@ -0,0 +1,28 @@
"""
Cog loader. Adds all command cogs to the bot.
"""
from nextcord.ext import commands
from .create import CreateCog
from .delete import DeleteCog
from .help import HelpCog
from .refresh import RefreshCog
from .set import SetCog
from .update import UpdateCog
from .view import ViewCog
# 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 all command classes to bot.
"""
bot.add_cog(CreateCog(bot))
bot.add_cog(DeleteCog())
bot.add_cog(HelpCog())
bot.add_cog(RefreshCog(bot))
bot.add_cog(SetCog())
bot.add_cog(UpdateCog(bot))
bot.add_cog(ViewCog())
+172
View File
@@ -0,0 +1,172 @@
"""
Commands for creating items in bot.
"""
from typing import Optional
import nextcord
from nextcord.ext import commands
from sqlalchemy import exc, select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from cogs.submission.submission_views import SubmissionCreateButton
from utilities.sql_data_classes import Category, CategoryGroup, engine
from utilities.utils import MAX_LINE_LENGTH, autofill_groups, send_highscore_message
class CreateCog(commands.Cog, name="Create Cog"):
"""
Class holds commands for creating things.
"""
def __init__(self, bot: commands.Bot) -> None:
"""
Default constructor for CreateCog class.
"""
self._bot = bot
@nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
async def create(self, interaction: nextcord.Interaction):
"""
Parent slash command for creating things. Never called.
"""
# need all these arguments because discord command.
# pylint: disable=too-many-arguments
@create.subcommand(description="Create a new Category. Must not exist already in Group.")
async def category(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(name="group", description="Group to add Category to.", required=True),
category_name: str = nextcord.SlashOption(description="Name of new Category.", required=True),
is_ascending: bool = nextcord.SlashOption(description="If lower value is a better score.", required=True),
is_time_record: bool = nextcord.SlashOption(
description="If the score should be shown in time format. Cannot be changed.", required=True
),
is_validated: bool = nextcord.SlashOption(
description="If scores need to be validated before posted.", required=True
),
size: int = nextcord.SlashOption(
description="How many scores to post in Category. Default is 3.", required=False, default=3, min_value=1
),
) -> None:
"""
Creates a new category to be placed into group_id group. Fails if the category name already exists within the
group. Then calls send_highscore_message().
Args:
interaction (nextcord.Interaction): Interaction for the command.
group_id (str): Id of group to add category to. Is SlashOption.
category_name (str): Name of new category. Is SlashOption.
is_ascending (bool): If the scores are sorted ascending or not. Is SlashOption.
is_time_record (bool): If the scores are a time record or not. Is SlashOption.
is_validated (bool): If the scores should be validated or not. Is SlashOption.
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,
)
# Open connection to engine and add new category.
with Session(engine) as session:
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == 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
)
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
)
# need all these arguments because discord command.
# pylint: disable=too-many-arguments
@create.subcommand(description="Create a new Category Group. Must not exist already for Guild.")
async def group(
self,
interaction: nextcord.Interaction,
group_name: str = nextcord.SlashOption(description="Name of new Group.", required=True),
pad_length: int = nextcord.SlashOption(
description="Number of characters wide a category is printed. Default is 26.",
required=False,
default=26,
min_value=7,
max_value=MAX_LINE_LENGTH,
),
username_length: int = nextcord.SlashOption(
description="Number of characters of a username to display. Default is 12.",
required=False,
default=12,
min_value=1,
max_value=30,
),
channel: Optional[nextcord.abc.GuildChannel] = nextcord.SlashOption(
description="Channel to post Group in. If left empty, defaults to current channel.",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Creates a new category group to be placed into the database with the guild's id. Fails if the category group
name already exists within the guild. Then calls send_highscore_message().
Args:
interaction (nextcord.Interaction): Interaction for the command.
group_name (str): Name of new Group. Is SlashOption.
pad_length (int): Number of characters wide a category is printed. Is SlashOption.
username_length (int): Number of characters of a username to display. Is SlashOption.
channel (Optional[nextcord.abc.GuildChannel]): Channel to post group in. If None, defaults to current
channel. Is SlashOption.
"""
# if no channel provided, use current channel.
if channel is None:
channel = interaction.channel
new_group = CategoryGroup(
GroupName=group_name,
ChannelId=channel.id,
GuildId=interaction.guild_id,
PadLength=pad_length,
UsernameLength=username_length,
)
with Session(engine) as session:
try:
session.add(new_group)
session.commit()
message: nextcord.Message = await send_highscore_message(session, interaction.guild, new_group)
await message.edit(view=SubmissionCreateButton(self._bot))
await interaction.response.send_message(f'"{group_name}" has been created!', ephemeral=True)
except exc.IntegrityError:
# Category Group already exists in guild
session.rollback()
await interaction.response.send_message(
f'"{group_name}" already exists in "{interaction.guild.name}". Please rename.', ephemeral=True
)
@category.on_autocomplete("group_id")
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str):
"""
Collects list of table names and compares to input table name for autocomplete assistance.
Args:
interaction (nextcord.Interaction): Interaction with command.
group_id (str): String to run autocomplete compared to.
"""
await interaction.response.send_autocomplete(autofill_groups(interaction.guild_id, group_id))
+297
View File
@@ -0,0 +1,297 @@
"""
Commands for deleting groups/categories/scores in database and messages in discord..
"""
from typing import Optional
import nextcord
from nextcord.ext import commands
from sqlalchemy import distinct, select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from utilities.sql_data_classes import Category, CategoryGroup, Score, engine
from utilities.utils import (
autofill_categories,
autofill_groups,
autofill_users_in_group_category,
autofill_users_in_guild,
send_highscore_message,
)
from .views.delete_confirm import DeleteConfirmView, create_delete_id
class DeleteCog(commands.Cog, name="Table Management"):
"""
Class holds commands for deleting.
"""
def __init__(self) -> None:
"""
Default constructor for DeleteCog class.
"""
@nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
async def delete(self, interaction: nextcord.Interaction):
"""
Parent slash command for deleting things. Never called.
"""
@delete.subcommand()
async def all(self, interaction: nextcord.Interaction):
"""
Subcommand parent for deleting all of a thing. Never called.
"""
@all.subcommand(description="Clears highscores channel of all table messages. Does not change data.")
async def channel_messages(
self,
interaction: nextcord.Interaction,
channel: Optional[nextcord.abc.GuildChannel] = nextcord.SlashOption(
description="Channel to clear of messages.",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Deletes all group messages from channel. Does not change data.
Does not delete highscores channel id. Uses current channel if not supplied a channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
channel (Optional[nextcord.abc.GuildChannel]): Channel to clear of messages.
Is a SlashOption. Limited to text channels. Defaults to None.
"""
if not channel:
channel = interaction.channel
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.ChannelId == channel.id)
)
# TODO test when nothing in channel
groups = session.scalars(stmt)
await interaction.response.defer(ephemeral=True)
for group in groups:
try:
table_message: nextcord.Message = await channel.fetch_message(group.MessageId)
await table_message.delete()
except nextcord.NotFound:
# silently ignore that messages are not found. They got deleted already.
pass
await interaction.send("Table messages deleted.", ephemeral=True)
@all.subcommand(
description="Removes all of a user's scores. Warning: data is destroyed, use with case.",
)
async def users(
self,
interaction: nextcord.Interaction,
user_name: str = nextcord.SlashOption(
description="User to remove scores for. Note: This is not always a user's discord name.", required=True
),
):
"""
Searches all of guild's scores data for any score from the user. Removes. Updates table
message is user was removed from that table.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
user_name (str): User to remove from highscores
"""
with Session(engine) as session:
stmt = select(distinct(Score.CategoryId)).where(Score.UserName == user_name)
category_ids: "list[int]" = list(session.scalars(stmt))
stmt = select(Score).where(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))
stmt = select(CategoryGroup).where(CategoryGroup.GroupId.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 tables.', ephemeral=True)
@delete.subcommand(description="Delete a category from a group. Deletion is perminant.")
async def category(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(name="group", description="Group to delete from.", required=True),
category_id: str = nextcord.SlashOption(name="category", description="Category to delete.", required=True),
) -> None:
"""
Calls the delete confirmation view for the given group and category.
Args:
interaction (nextcord.Interaction): Interaction of command.
group_id (str): Group to delete from. Is SlashOption.
category_id (str): Category to delete. Is SlashOption.
"""
await interaction.response.send_modal(
DeleteConfirmView(custom_id=create_delete_id(int(group_id), int(category_id)))
)
@delete.subcommand(description="Delete a group. Deletion is perminant.")
async def group(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(name="group", description="Group to delete.", required=True),
) -> None:
"""
Calls the delete confirmation view for the given group.
Args:
interaction (nextcord.Interaction): Interaction of command.
group_id (str): Group to delete from. Is SlashOption.
"""
await interaction.response.send_modal(DeleteConfirmView(custom_id=create_delete_id(int(group_id))))
@delete.subcommand()
async def user(self, interaction: nextcord.Interaction):
"""
Subcommand parent for deleting user information. Never called.
"""
@user.subcommand(description="Deletes a user's scores from a category.")
async def from_category(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(name="group", description="Group to delete user from.", required=True),
category_id: str = nextcord.SlashOption(
name="category", description="Category to delete user from.", required=True
),
user_name: str = nextcord.SlashOption(description="User to delete.", required=True),
):
"""
Removes a user from a category. Uses autofill functions to fill out group_id, category_id, and user_name.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
group_id (str): String representation of Group id to remove user from. Is SlashOption.
category_id (str): String representation of Category id to remove user from. Is SlashOption.
user_name (str): The user to remove. Is SlashOption.
"""
with Session(engine) as session:
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == int(group_id))
group = session.scalar(stmt)
stmt = select(Category.CategoryName).where(Category.CategoryId == int(category_id))
category_name = session.scalar(stmt)
stmt = select(Score).where(Score.CategoryId == int(category_id)).where(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))
session.commit()
await send_highscore_message(session, interaction.guild, group)
await interaction.response.send_message(
f'User "{user_name}" removed from "{category_name}".', ephemeral=True
)
@user.subcommand(description="Deletes a user's scores from entire group.")
async def from_group(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(name="group", description="Group to delete user from.", required=True),
user_name: str = nextcord.SlashOption(description="User to delete.", required=True),
):
"""
Removes user from a goup. Uses autofill functions to fill out group_id and user_name.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
group_id (str): String representation of Group id to remove user from. Is SlashOption.
user_name (str): The user to remove. Is SlashOption.
"""
with Session(engine) as session:
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == 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)
for score in session.scalars(stmt):
session.delete(score)
session.commit()
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
)
@from_category.on_autocomplete("group_id")
@from_group.on_autocomplete("group_id")
@category.on_autocomplete("group_id")
@group.on_autocomplete("group_id")
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str):
"""
Autocomplete function for table names.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
group_id (str): String to be autocompleted with Group name.
"""
await interaction.response.send_autocomplete(autofill_groups(interaction.guild_id, group_id))
@from_category.on_autocomplete("category_id")
@category.on_autocomplete("category_id")
async def category_autocomplete(self, interaction: nextcord.Interaction, category_id: str, group_id: str):
"""
Autocomplete function for category names.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
category_id (str): String to be autocompleted with Category name.
group_id (str): Group to find Category from.
"""
await interaction.response.send_autocomplete(
autofill_categories(interaction.guild_id, int(group_id), category_id)
)
@from_category.on_autocomplete("user_name")
@from_group.on_autocomplete("user_name")
async def user_autocomplete(
self, interaction: nextcord.Interaction, user_name: str, group_id: str, category_id: Optional[str] = None
):
"""
Autocomplete functions for user names.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
user_name (str): String to be autocompleted with User name.
group_id (str): String representation of Group id to find category from.
category_id (Optional[str]): String representation of Category id to find User from, can be None.
"""
await interaction.response.send_autocomplete(
autofill_users_in_group_category(
interaction.guild_id, int(group_id), category_id if category_id else 0, user_name
)
)
@users.on_autocomplete("user_name")
async def all_users_autocomplete(self, interaction: nextcord.Interaction, username: str):
"""
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.
"""
await interaction.response.send_autocomplete(autofill_users_in_guild(interaction.guild_id, username))
+46
View File
@@ -0,0 +1,46 @@
"""
Commands for helping a user.
"""
import nextcord
from nextcord.ext import commands
class HelpCog(commands.Cog, name="Help commands."):
"""
Class holds commands for getting help.
"""
def __init__(self) -> None:
"""
Default constructor for HelpCog class. Does nothing.
"""
@nextcord.slash_command()
async def help(self, interaction: nextcord.Interaction):
"""
Parent slash command for help. Never called.
"""
@help.subcommand(description="Describes how to get started with Agon.")
async def setup(self, interaction: nextcord.Interaction):
"""
Sends a message describing how to get started with Agon.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
"""
# I hate this but don't want indents in the string.
# pylint: disable=line-too-long
help_str: str = """Welcome to Agon! Three simple steps are needed to get started.
1.) Set a channel to recieve submission verifications with "/set verify_channel."
This channel is used to allow moderators to check if a submission is real/valid.
2.) Set a channel for submissions to be posted in with "/set submission_channel."
This channel will be where all user submission messages are sent.
3.) Set up your highscore tables! Use "/create group" to first create a group message in the channel you would like and then use "/create category" to create a category in that group message!"""
# pylint: enable=line-too-long
await interaction.response.send_message(content=help_str)
+104
View File
@@ -0,0 +1,104 @@
"""
Commands for refreshing highscore messages.
"""
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from cogs.submission.submission_views import SubmissionCreateButton
from utilities.sql_data_classes import CategoryGroup, engine
from utilities.utils import autofill_groups, send_highscore_message
class RefreshCog(commands.Cog, name="Refresh Cog"):
"""
Class holds commands for refreshing.
"""
def __init__(self, bot: commands.Bot) -> None:
"""
Default constructor for RefreshCog class
Args:
bot (commands.Bot): Bot object. Required to register submission button view.
"""
self._bot = bot
@nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
async def refresh(self, interaction: nextcord.Interaction):
"""
Parent slash command for refreshing things. Never called.
"""
@refresh.subcommand(description="Manually refresh a table. Use when changing settings or data manually changed.")
async def group(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(name="group", description="Name of Group.", required=True),
) -> None:
"""
Refreshes a table given by user.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
group_id (str): Str representation of Group id to refresh. Is SlashOption.
"""
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.GroupId == int(group_id))
)
group = session.scalar(stmt)
message: nextcord.Message = await send_highscore_message(session, interaction.guild, group)
await message.edit(view=SubmissionCreateButton(self._bot))
await interaction.response.send_message(f"Updated table {group.GroupName}!", ephemeral=True)
@refresh.subcommand()
async def all(self, interaction: nextcord.Interaction):
"""
Subcommand parent for refreshing all things. Never called.
"""
@all.subcommand(description="Triggers post/update of highscores to registered highscore channels.")
async def groups(self, interaction: nextcord.Interaction) -> None:
"""
A command which posts the highscore in the registered channel.
Sends warning if no channel has been registered.
Either creates new messages for each table if one doesn't exist
or edits the existing message.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
"""
with Session(engine) as session:
stmt = select(CategoryGroup).where(CategoryGroup.GuildId == interaction.guild_id)
# awaiting response because posting scores takes a while
await interaction.response.defer(ephemeral=True)
for group in session.scalars(stmt):
message: nextcord.Message = await send_highscore_message(session, interaction.guild, group)
await message.edit(view=SubmissionCreateButton(self._bot))
await interaction.send(f"Posted all groups in {interaction.guild.name}'s highscores.", ephemeral=True)
@group.on_autocomplete("group_id")
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str):
"""
Collects list of table names and compares to input table name for autocomplete assistance.
Args:
interaction (nextcord.Interaction): Interaction with command.
group_id (str): String to run autocomplete compared to.
"""
await interaction.response.send_autocomplete(autofill_groups(interaction.guild_id, group_id))
+212
View File
@@ -0,0 +1,212 @@
"""
Set command heirarchy.
"""
from typing import Optional
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from utilities.sql_data_classes import CategoryGroup, Guild, engine
from utilities.utils import MAX_LINE_LENGTH, autofill_groups
class SetCog(commands.Cog, name="Set command."):
"""
Class holds commands for setting variables in guild's database.
"""
def __init__(self) -> None:
"""
Default constructor for SetCog class. Does nothing.
"""
@nextcord.slash_command(default_member_permissions=nextcord.Permissions(administrator=True))
async def set(self, interaction: nextcord.Interaction):
"""
Parent slash command for setting settings. Never called.
"""
@set.subcommand(description="Registers the channel for a Category Group's messages.")
async def group_output_channel(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(
name="group", description="Category Group to assign to channel.", required=True
),
channel: Optional[nextcord.abc.GuildChannel] = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register a CategoryGroup's output channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
group_id (str): String representation of Group id to register channel to. Is SlashOption.
channel (nextcord.abc.GuildChannel, optional): Channel to register
Is a SlashOption. Limited to text channels, Defaults to None.
"""
if not channel:
channel = interaction.channel
channel_id = channel.id
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.GroupId == int(group_id))
)
group = session.scalar(stmt)
group.ChannelId = channel_id
session.commit()
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
@set.subcommand(
description="Set character length for a category. Can cut off username/score. Affects all categories."
)
async def pad_length(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(
name="group", description="Category Group to assign pad length to.", required=True
),
length: int = nextcord.SlashOption(
description="Number of characters alloted to a category.",
required=True,
default=26,
min_value=7,
max_value=MAX_LINE_LENGTH,
),
) -> None:
"""
Changes guild's category pad length.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
group_id (str): String representation of Group id to set pad length in. Is SlashOption.
length (int): Number of characters. Is SlashOption. Defaults to 26.
"""
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.GroupId == int(group_id))
)
group = session.scalar(stmt)
group.PadLength = length
session.commit()
await interaction.response.send_message(
f"Category pad length set to {length} for {group.GroupName}", ephemeral=True
)
@set.subcommand(description="Registers the channel for submission messages.")
async def submission_channel(
self,
interaction: nextcord.Interaction,
channel: Optional[nextcord.abc.GuildChannel] = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register the submission message channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
channel Optional[nextcord.abc.GuildChannel], optional): Channel to register
Is a SlashOption. Limited to text channels, Defaults to None.
"""
if not channel:
channel = interaction.channel
with Session(engine) as session:
channel_id = channel.id
stmt = select(Guild).where(Guild.GuildId == interaction.guild_id)
guild = session.scalar(stmt)
guild.SubmissionChannel = channel_id
session.commit()
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
@set.subcommand(description="Set username length for a Group of Categories.")
async def username_length(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(
name="group", description="Group to change username length of.", required=True
),
length: int = nextcord.SlashOption(
description="Number of characters.", required=True, default=12, min_value=1, max_value=30
),
) -> None:
"""
Changes guild's username length limit.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
length (int): Number of characters. Is SlashOption. Defaults to 12.
"""
with Session(engine) as session:
stmt = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.GroupId == int(group_id))
)
group = session.scalar(stmt)
group.UsernameLength = length
session.commit()
await interaction.response.send_message(f"Username length set to {length}.", ephemeral=True)
@set.subcommand(description="Registers the channel for verification messages.")
async def verify_channel(
self,
interaction: nextcord.Interaction,
channel: Optional[nextcord.abc.GuildChannel] = nextcord.SlashOption(
description="Channel to register",
required=False,
channel_types=[nextcord.ChannelType.text],
default=None,
),
) -> None:
"""
Command function to register the verification message channel.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command
channel (Optional[nextcord.abc.GuildChannel]): Channel to register
Is a SlashOption. Limited to text channels, Defaults to None.
"""
if not channel:
channel = interaction.channel
channel_id = channel.id
with Session(engine) as session:
stmt = select(Guild).where(Guild.GuildId == interaction.guild_id)
guild = session.scalar(stmt)
guild.VerificationChannel = channel_id
session.commit()
await interaction.send(f"Registered <#{channel_id}>.", ephemeral=True)
@group_output_channel.on_autocomplete("group_id")
@pad_length.on_autocomplete("group_id")
@username_length.on_autocomplete("group_id")
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str):
"""
Sends results from autofill_groups back to group_output_channel for autocompletion of group_id.
Args:
interaction (nextcord.Interaction): Interaction with command.
group_id (str): String to run autocompletion against.
"""
await interaction.response.send_autocomplete(autofill_groups(interaction.guild_id, group_id))
+84
View File
@@ -0,0 +1,84 @@
"""
Commands for updating information/variables held in database.
"""
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from utilities.sql_data_classes import Guild, engine
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.
"""
def __init__(self, bot: commands.Bot):
"""
Default constructor for Update class. Sets internal bot variable.
Args:
bot (commands.Bot): Bot object. Required to register update username button view.
"""
self._bot: commands.Bot = bot
@commands.Cog.listener()
async def on_ready(self):
"""
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.
"""
@update.subcommand(description="Request a username update. Admins must approve.")
async def username(
self,
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),
):
"""
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
old_username (str): Username to replace.
new_username (str): Username to replace old with.
"""
with Session(engine) as session:
stmt = select(Guild.VerificationChannel).where(Guild.GuildId == interaction.guild_id)
verify_channel = interaction.guild.get_channel(session.scalar(stmt))
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)
await verify_channel.send(
content=f"Username change request from <@{interaction.user.id}>.",
embed=embed,
view=UpdateUsernameVerifyView(),
)
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):
"""
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.
"""
await interaction.response.send_autocomplete(autofill_users_in_guild(interaction.guild_id, username))
+112
View File
@@ -0,0 +1,112 @@
"""
View command heirarchy.
"""
import nextcord
import pandas as pd
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from utilities.sql_data_classes import Category, CategoryGroup, Score, engine
from utilities.utils import MAX_LINE_LENGTH, autofill_categories, autofill_groups, format_score_string
class ViewCog(commands.Cog, name="View Command"):
"""
Class holds commands for viewing data.
"""
def __init__(self) -> None:
"""
Default constructor for ViewCog class. Does nothing.
"""
@nextcord.slash_command()
async def view(self, interaction: nextcord.Interaction):
"""
Parent slash command for view. Never called.
"""
@view.subcommand(description="Lists all scores for a given category.")
async def leaderboard(
self,
interaction: nextcord.Interaction,
group_id: str = nextcord.SlashOption(
name="group", description="Group to show leaderboard from.", required=True
),
category_id: str = nextcord.SlashOption(
name="category", description="Category to show leaderboard.", required=True
),
):
"""
Gathers all users that have a submission in the group/category combo and returns a message with them
in ranked order.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
group_id (str): String representation of Group id to search from. Is SlashOption.
category_id (str): String representation of Category id to show leaderboard. Is SlashOption.
"""
str_list: "list[str]" = []
# get group, category, and all scores sorted correctly.
with Session(engine) as session:
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == int(group_id))
group = session.scalar(stmt)
stmt = select(Category).where(Category.CategoryId == 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
)
scores = d_f.sort_values("Score", ascending=category.IsAscending).reset_index()
# get the longest string
longest_str: int = scores.UserName.map(len).max()
for i, row in scores.iterrows():
str_list.append(
format_score_string(
row["UserName"], row["Score"], longest_str, category.IsTimeRecord, i + 1, MAX_LINE_LENGTH
)
)
message_str: str = f"**{group.GroupName} {category.CategoryName} Leaderboard!**\n```"
if len(str_list) == 0:
message_str += "No Submissions!"
else:
for line in str_list:
message_str += f"{line}\n"
message_str += "```"
await interaction.response.send_message(content=message_str)
@leaderboard.on_autocomplete("group_id")
async def group_autocomplete(self, interaction: nextcord.Interaction, group_id: str):
"""
Autocomplete function for table names.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
group_id (str): String to be autocompleted with Group name.
"""
await interaction.response.send_autocomplete(autofill_groups(interaction.guild_id, group_id))
@leaderboard.on_autocomplete("category_id")
async def category_autocomplete(self, interaction: nextcord.Interaction, category_id: str, group_id: str):
"""
Autocomplete function for category names.
Args:
interaction (nextcord.Interaction): Interaction that invoked the command.
category_id (str): String to be autocompleted with Category name.
group_id (str): Group to find Category from.
"""
await interaction.response.send_autocomplete(
autofill_categories(interaction.guild_id, int(group_id), category_id)
)
+97
View File
@@ -0,0 +1,97 @@
"""
Contains view and helper functions for confirming and processing deletes.
"""
from typing import Optional
import nextcord
from sqlalchemy import delete, select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from utilities.sql_data_classes import Category, CategoryGroup, engine
from utilities.utils import send_highscore_message
class DeleteConfirmView(nextcord.ui.Modal):
"""
View modal popup for confirming deletions.
"""
def __init__(self, custom_id: str):
super().__init__(title="Warning, deletion is perminant.", custom_id=custom_id)
self.checker = nextcord.ui.TextInput(
label='Type "delete" to confirm deletion.',
required=True,
placeholder="delete",
style=nextcord.TextInputStyle.short,
)
self.add_item(self.checker)
async def callback(self, interaction: nextcord.Interaction):
if self.checker.value.lower() != "delete":
await interaction.response.send_message('Response was not "delete". Canceling delete.')
return
del_vals = parse_delete_id(self.custom_id)
with Session(engine) as session:
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == 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)
await message.delete()
else:
stmt = (
delete(Category)
.where(Category.GroupId == del_vals["group_id"])
.where(Category.CategoryId == del_vals["category_id"])
)
session.execute(stmt)
# update the message
await send_highscore_message(session, interaction.guild, group)
session.commit()
await interaction.response.send_message("Deletion complete.", ephemeral=True)
def create_delete_id(group_id: int, category_id: Optional[int] = None) -> str:
"""
Creates a delete id string to tell the view what to delete.
Args:
group_id (int): group id to delete
category_id (Optional[int]): category id to delete. Can be None.
Returns:
str: string representation of the delete id.
"""
return f"delete-{group_id}-{category_id}"
def parse_delete_id(delete_id: str) -> dict:
"""
Returns a dict containing the values of a delete id.
Args:
id (str): the delete id
Returns:
dict: dict containing values from a delete id.
"""
vals = {}
group_id = delete_id.split("-")[1]
category_id = delete_id.split("-")[2]
vals["group_id"] = group_id
if category_id == "None":
vals["category_id"] = None
else:
vals["category_id"] = category_id
return vals
@@ -0,0 +1,76 @@
"""View for allowing a username update."""
import nextcord
from sqlalchemy import distinct, exc, select
from sqlalchemy.orm import Session
# pylint: disable=import-error
from utilities.sql_data_classes import Category, CategoryGroup, Score, engine
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.
"""
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
"""
Button for denying username update. Deletes message.
Args:
button (nextcord.ui.Button): unused
interaction (nextcord.Interaction): Interaction with the button
"""
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
"""
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
interaction (nextcord.Interaction): Interaction with the button
"""
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"]
stmt = select(distinct(Score.CategoryId)).where(Score.UserName == old_username)
category_ids: "list[int]" = list(session.scalars(stmt))
stmt = select(Score).where(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))
stmt = select(CategoryGroup).where(CategoryGroup.GroupId.in_(group_ids))
for group in session.scalars(stmt):
await send_highscore_message(session, interaction.guild, group)
content = interaction.message.content
content += f"\nApproved by <@{interaction.user.id}>."
await interaction.message.edit(content=content, embeds=interaction.message.embeds, view=None)
except exc.DataError:
session.rollback()
content = interaction.message.content
content += "\nError, UserName is too long."
await interaction.message.edit(content=content, embeds=interaction.message.embeds, view=None)
await interaction.response.send_message(content="User must resubmit with shorter name.", ephemeral=True)
-42
View File
@@ -1,42 +0,0 @@
"""
Bot command for deleting the guild's scores.
"""
from nextcord import Embed
from nextcord.ext import commands
from highscores import highscores_data # pylint: disable=import-error
class DeleteScores(commands.Cog, name="Delete Scores"):
"""
Warning: This command only works for developers.
Deletes this guild's scores.
"""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name="delete-scores")
@commands.has_permissions(administrator=True)
async def delete_scores(self, ctx: commands.Context):
"""A command which deletes all scores for this guild.
Usage:
```
?delete_scores
```
"""
# only allow AlwaysCompiling to use.
# If you are a developer and want to use command, can add name to list
if ctx.author.id == 206602713511886849:
for table in highscores_data.get_guild(ctx.guild.id).tables:
for category in table.categories:
category.clear()
highscores_data.save_guild_data(highscores_data.get_guild(ctx.guild.id))
# This function will be called when this extension is loaded.
# It is necessary to add these functions to the bot.
def setup(bot: commands.Bot):
"""Adds function to bot"""
bot.add_cog(DeleteScores(bot))
+45 -15
View File
@@ -2,10 +2,13 @@
Defines cog for guild listeners. Contains functions for various guild events.
"""
from nextcord.ext import commands
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
from highscores import highscores_data # pylint: disable=import-error
# pylint: disable=import-error
from utilities.sql_data_classes import Guild, engine
class GuildListener(commands.Cog, name="Guild Listener"):
@@ -16,24 +19,51 @@ class GuildListener(commands.Cog, name="Guild Listener"):
@commands.Cog.listener()
async def on_guild_join(self, guild: nextcord.Guild):
"""Listener for Guild Join. Creates skeleton for new guild joined and saves it."""
highscores_data.add_guild(guild.id)
# This add config will be removed eventually. Config adding will have to be controlled by commands.
highscores_data.add_configuration(guild.id, "runescape")
highscores_data.save_guild_data(highscores_data.get_guild(guild.id))
"""
Listener for Guild Join. Adds guild to database.
welcome_message: str = "Hello, I keep track of Highscores for you!"
welcome_message += " Currently only supporting RuneScape boss highscores,"
welcome_message += " but will be more dynamic support in future."
welcome_message += ' For assistance on getting started, use "?register help".'
Args:
guild (nextcord.Guild): Guild that was joined.
"""
await guild.system_channel.send(content=welcome_message)
with Session(engine) as session:
stmt = select(Guild).where(Guild.GuildId == 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)
session.add(new_guild)
else:
guild_data.GuildName = guild.name
guild_data.Active = True
session.commit()
# let imcompiling#2272 know about a new server joining!
# staying with fetch due to intents not being set up correctly. Maybe change to get eventually.
imcompiling: nextcord.User = await self.bot.fetch_user(206602713511886849)
await imcompiling.send(f'Agon has joined server "{guild.name}"!')
@commands.Cog.listener()
async def on_guild_remove(self, guild: nextcord.Guild):
"""Listener for Guild Remove. Removes data from highscores_data."""
print(f"Removing data for guild {guild.name} (id {guild.id}).")
highscores_data.remove_guild(guild.id)
"""
Listens to when the bot has been removed from a guild. Update's the database to record the active flag as false.
Args:
guild (nextcord.Guild): Guild that was left.
"""
with Session(engine) as session:
stmt = select(Guild).where(Guild.GuildId == guild.id)
guild_data = session.scalar(stmt)
guild_data.Active = False
session.commit()
# let imcompiling#2272 know about leaving a server.
# staying with fetch due to intents not being set up correctly. Maybe change to get eventually.
imcompiling: nextcord.User = await self.bot.fetch_user(206602713511886849)
await imcompiling.send(f'Agon has been removed from "{guild.name}".')
# This function will be called when this extension is loaded.
-26
View File
@@ -1,26 +0,0 @@
"""
Help command
"""
from nextcord.ext import commands
from .help_command import NewHelpCommand
class HelpCog(commands.Cog):
"""Help Command"""
def __init__(self, bot: commands.Bot):
self.bot = bot
self._original_help_command = bot.help_command
bot.help_command = NewHelpCommand()
bot.help_command.cog = self
def cog_unload(self):
self.bot.help_command = self._original_help_command
# setup functions for bot
def setup(bot: commands.Bot):
"""Adds function to bot"""
bot.add_cog(HelpCog(bot))
-84
View File
@@ -1,84 +0,0 @@
"""
Help command. Copied from discord-bot-template.
"""
import nextcord
from nextcord.embeds import EmptyEmbed
from nextcord.ext import commands
import config # pylint: disable=import-error
class NewHelpCommand(commands.MinimalHelpCommand):
"""Custom help command override using embeds"""
COLOUR = nextcord.Colour.blurple()
def get_ending_note(self):
"""Returns note to display at the bottom"""
invoked_with = self.invoked_with
return f"Use {config.BOT_PREFIX}{invoked_with} [command] for more info on a command."
def get_command_signature(self, command: commands.core.Command):
"""Retrieves the signature portion of the help page."""
return f"{command.qualified_name} {command.signature}"
async def send_bot_help(self, mapping: dict):
"""implements bot command help page"""
embed = nextcord.Embed(title="Bot Commands", colour=self.COLOUR)
avatar = self.context.bot.user.avatar
avatar_url = avatar.url if avatar else EmptyEmbed
embed.set_author(name=self.context.bot.user.name, icon_url=avatar_url)
description = self.context.bot.description
if description:
embed.description = description
for cog, commands in mapping.items(): # pylint: disable=redefined-outer-name
name = "No Category" if cog is None else cog.qualified_name
filtered = await self.filter_commands(commands, sort=True)
if filtered:
# \u2002 = middle dot
value = "\u2002".join(f"{config.BOT_PREFIX}{c.name}" for c in filtered)
if cog and cog.description:
value = f"{cog.description}\n{value}"
embed.add_field(name=name, value=value)
embed.set_footer(text=self.get_ending_note())
await self.get_destination().send(embed=embed)
async def send_cog_help(self, cog: commands.Cog):
"""implements cog help page"""
embed = nextcord.Embed(title=f"{cog.qualified_name} Commands", colour=self.COLOUR)
if cog.description:
embed.description = cog.description
filtered = await self.filter_commands(cog.get_commands(), sort=True)
for command in filtered:
embed.add_field(
name=self.get_command_signature(command),
value=command.short_doc or "...",
inline=False,
)
embed.set_footer(text=self.get_ending_note())
await self.get_destination().send(embed=embed)
async def send_group_help(self, group: commands.Group):
"""implements group help page and command help page"""
embed = nextcord.Embed(title=group.qualified_name, colour=self.COLOUR)
if group.help:
embed.description = group.help
if isinstance(group, commands.Group):
filtered = await self.filter_commands(group.commands, sort=True)
for command in filtered:
embed.add_field(
name=self.get_command_signature(command),
value=command.short_doc or "...",
inline=False,
)
embed.set_footer(text=self.get_ending_note())
await self.get_destination().send(embed=embed)
# Use the same function as group help for command help
send_command_help = send_group_help # type: ignore
+16
View File
@@ -0,0 +1,16 @@
"""
Initializing code for all loops.
"""
from nextcord.ext import commands
from .bot_presence import BotPresence
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"""
bot.add_cog(BotPresence(bot))
bot.add_cog(GuildData(bot))
@@ -1,12 +1,11 @@
"""
Functions for controlling the bot's presence.
Functions for controlling the bot's presence. Also contains the loop.
"""
import random
from nextcord.ext import commands
from nextcord.ext import tasks
import nextcord
from nextcord.ext import commands, tasks
class BotPresence(commands.Cog, name="Bot Presence"):
@@ -35,19 +34,15 @@ class BotPresence(commands.Cog, name="Bot Presence"):
async def change_presence(self):
"""Randomly chooses a presence and updates bot's presence."""
statuses = [
f"?help | {len(self.bot.guilds)} servers",
f"Vuln Pls. | {len(self.bot.guilds)} servers",
f"All your base are belong to us. | {len(self.bot.guilds)} servers",
f"Double plus good. | {len(self.bot.guilds)} servers",
"Now with slash commands!",
"Vuln Pls.",
"All your base are belong to us.",
"Double plus good.",
"That's a lot of damage!",
]
status = random.choice(statuses)
status += f" | {len(self.bot.guilds)} servers"
await self.bot.change_presence(activity=nextcord.Game(status))
# This function will be called when this extension is loaded.
# It is necessary to add these functions to the bot.
def setup(bot: commands.Bot):
"""Adds function to bot"""
bot.add_cog(BotPresence(bot))
+48
View File
@@ -0,0 +1,48 @@
"""
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 utilities.sql_data_classes import Guild, engine
class GuildData(commands.Cog, name="Guild Data"):
"""Class to contain loop."""
def __init__(self, bot: commands.bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
"""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
@tasks.loop(hours=24)
async def periodic_update_guild_data(self):
"""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.
"""
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)
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)
session.add(new_guild)
else:
guild_data.GuildName = guild.name
session.commit()
+82 -75
View File
@@ -2,15 +2,18 @@
Defines cog for on message listener.
"""
from datetime import date
import random
import re
from datetime import datetime
from nextcord.ext import commands
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session
from classes.submission import SubmissionState # pylint: disable=import-error
from highscores import highscores_data, submission_objects # pylint: disable=import-error
# pylint: disable=import-error
from classes.submission import SubmissionState
from highscores import submission_objects
from utilities.sql_data_classes import Category, Guild, engine
class SubmissionListener(commands.Cog, name="Message Listener"):
@@ -26,86 +29,74 @@ class SubmissionListener(commands.Cog, name="Message Listener"):
if message.author.id == self.bot.user.id:
return
guild_id = message.guild.id
await birthday_action(message)
# troll addition for friends birthday
if guild_id == 239758371358638080 and date.today() == date(2022, 7, 31):
# 5% chance to send the message
chance = random.randint(1, 20)
if chance == 1:
await message.channel.send("Happy Birthday Chris <@642330132958281750>")
guild_id = message.guild.id
if submission_objects.has_user(message.author.id):
submission = submission_objects.get_user_submission(message.author.id)
message_id = submission.message_id
submission_channel_id = highscores_data.get_guild(guild_id).submission_channel
submission_message: nextcord.Message = (
await self.bot.get_guild(guild_id)
.get_channel(submission_channel_id)
.fetch_message(message_id)
)
# need check if correct user and correct channel
if message.channel.id == submission_channel_id:
state = submission.submission_state
if state == SubmissionState.SCORE and message.content:
with Session(engine) as session:
stmt = select(Guild.SubmissionChannel).where(Guild.GuildId == guild_id)
submission_channel_id = session.scalar(stmt)
submission_message: nextcord.Message = (
await self.bot.get_guild(guild_id).get_channel(submission_channel_id).fetch_message(message_id)
)
# check with regex if score matches correctly
is_time_record = (
highscores_data.get_guild(guild_id)
.get_table(submission.table)
.get_category(submission.category)
.time_record
)
# need check if correct user and correct channel
if message.channel.id == submission_channel_id:
state = submission.submission_state
if state == SubmissionState.SCORE and message.content:
stmt = select(Category.IsTimeRecord).where(Category.CategoryId == submission.category_id)
time_regex = re.search(
"^([0-9]{1,2}:[0-9]|[0-9])?[0-9](\\.[0-9])?$", message.content
)
int_regex = re.search("^[0-9]+$", message.content)
if time_regex is None and is_time_record:
embed = submission_message.embeds[0]
embed.add_field(
name="Error",
value="Time record must follow format MM:SS.ms, SS.ms, or SS.",
# check with regex if score matches correctly
is_time_record = session.scalar(stmt)
time_regex = re.search("^([0-9]{1,2}:[0-9]|[0-9])?[0-9](\\.[0-9])?$", message.content)
int_regex = re.search("^[0-9]+$", message.content)
if time_regex is None and is_time_record:
embeds = submission_message.embeds[0]
embeds.add_field(
name="Error",
value="Time record must follow format MM:SS.ms, SS.ms, or SS.",
)
elif int_regex is None and not is_time_record:
embeds = submission_message.embeds[0]
embeds.add_field(name="Error", value="Number record must only be number.")
else:
score = message.content
if is_time_record:
# standardize time score format.
if re.search("^[1-9]?[0-9]:[0-9]{2}(\\.[0-9])?$", score):
# score is already fine.
pass
elif re.search("^[0-9]{2}(\\.[0-9])?$", score):
# need to add leading colon and 0
score = "0:" + score
elif re.search("^[0-9](\\.[0-9])?$", score):
# need to add 0 in seconds and leading colon and 0
score = "0:0" + score
elif re.search("^[0]?[0-9]:[0-9]{2}(\\.[0-9])?$", score):
# if there is a minute 10ths place 0, remove
score = score.lstrip("0")
submission.score = score
embeds = submission.get_embeds()
await submission_message.edit(
embeds=embeds,
)
elif state == SubmissionState.PROOF and len(message.attachments) > 0:
await submission_message.edit(
files=[await attch.to_file() for attch in message.attachments],
)
elif state == SubmissionState.NAME and message.content:
submission.username = message.content
embeds = submission.get_embeds()
await submission_message.edit(
embeds=embeds,
)
elif int_regex is None and not is_time_record:
embed = submission_message.embeds[0]
embed.add_field(name="Error", value="Number record must only be number.")
else:
score = message.content
if is_time_record:
# standardize time score format.
if re.search("^[1-9]?[0-9]:[0-9]{2}(\\.[0-9])?$", score):
# score is already fine.
pass
elif re.search("^[0-9]{2}(\\.[0-9])?$", score):
# need to add leading colon and 0
score = "0:" + score
elif re.search("^[0-9](\\.[0-9])?$", score):
# need to add 0 in seconds and leading colon and 0
score = "0:0" + score
elif re.search("^[0]?[0-9]:[0-9]{2}(\\.[0-9])?$", score):
# if there is a minute 10ths place 0, remove
score = score.lstrip("0")
submission.score = score
embed = submission.get_embed()
await submission_message.edit(
embed=embed,
)
elif state == SubmissionState.PROOF and len(message.attachments) > 0:
await submission_message.edit(
files=[await attch.to_file() for attch in message.attachments],
)
elif state == SubmissionState.NAME and message.content:
submission.username = message.content[
: highscores_data.get_guild(guild_id).username_length
]
embed = submission.get_embed()
await submission_message.edit(
embed=embed,
)
await message.delete()
await message.delete()
# This function will be called when this extension is loaded.
@@ -113,3 +104,19 @@ class SubmissionListener(commands.Cog, name="Message Listener"):
def setup(bot: commands.Bot):
"""Adds function to bot"""
bot.add_cog(SubmissionListener(bot))
async def birthday_action(message: nextcord.Message) -> None:
"""
Does the birthday thing, currently for chris only.
Args:
message (nextcord.Message): The message to check for birthday thing.
"""
today = datetime.today()
birthday = datetime(today.year, 7, 31)
chris = 642330132958281750
if today.date() == birthday.date():
if message.author.id == chris or chris in message.raw_mentions:
await message.add_reaction("🎂")
-57
View File
@@ -1,57 +0,0 @@
"""
Bot command to post the highscores
"""
from nextcord.ext import commands
import nextcord
from cogs.submission.submission_views import SubmissionCreateButton # pylint: disable=import-error
from highscores import highscores_data # pylint: disable=import-error
from utilities.utils import send_highscore_message # pylint: disable=import-error
class PostHighscores(commands.Cog, name="Post Highscores"):
"""Posts Highscores."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.command(name="post-scores")
@commands.has_permissions(administrator=True)
async def post_highscores(self, ctx: commands.Context):
"""
A command which posts the highscore in the designated channel.
Sends warning if no channel has been registered.
Usage:
```
?post-scores
```
"""
guild = highscores_data.get_guild(ctx.guild.id)
print(f"Printing out highscores information in channel {guild.highscore_channel}")
channel = ctx.guild.get_channel(guild.highscore_channel)
error_response = "Registered Highscores channel does not exist or was never registered. "
error_response += 'Register with "?register" command.'
assert channel is not None, await ctx.send(error_response)
if len(highscores_data.get_guild(ctx.guild.id).tables) < 1:
await channel.send(
"No tables have been created for this guild. Please create some tables."
)
return
for table in highscores_data.get_guild(ctx.guild.id).tables:
message: nextcord.Message = await send_highscore_message(channel, guild, table)
await message.edit(view=SubmissionCreateButton(self.bot))
# have to save data here in case message id was changed. rather save here after all
# messages have been sent.
highscores_data.save_guild_data(guild)
# This function will be called when this extension is loaded.
# It is necessary to add these functions to the bot.
def setup(bot: commands.Bot):
"""Adds function to bot"""
bot.add_cog(PostHighscores(bot))
-69
View File
@@ -1,69 +0,0 @@
"""
Bot command for registering various channels to the bot.
"""
from nextcord import Embed
from nextcord.ext import commands
from highscores import highscores_data # pylint: disable=import-error
class RegisterVerificationChannel(commands.Cog, name="Register"):
"""Bot command for registering various channels to the bot."""
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.command(name="register")
@commands.has_permissions(administrator=True)
async def register_highscores(self, ctx: commands.Context, registration_type: str) -> None:
"""A command which registers current channel as for various uses.
Usage:
```
?register verify (Use in channel you want to verify submissions in.)
?register highscore (Use in channel you want to show highscore messages in.)
?register submission (Use in channel you want submission messages to be send it.)
?register help (Shows help message.)
```
"""
# respond to the message
channel_id = ctx.channel.id
guild = highscores_data.get_guild(ctx.guild.id)
if registration_type == "verify":
await ctx.send(f"Registered <#{channel_id}> as channel to post verifications in.")
guild.verification_channel = channel_id
elif registration_type == "highscore":
await ctx.send(f"Registered <#{channel_id}> as channel to post highscores in.")
guild.highscore_channel = channel_id
elif registration_type == "submission":
await ctx.send(f"Registered <#{channel_id}> as channel to post submissions in.")
guild.submission_channel = channel_id
else:
embed = Embed(
title="Register command help", description="How to use the register command."
)
embed.add_field(
name="?register verify", value="Use in channel you want to verify submissions in."
)
embed.add_field(
name="?register highscore",
value="Use in channel you want to show highscore messages in.",
)
embed.add_field(
name="?register submission",
value="Use in channel you want submission messages to be send it.",
)
embed.add_field(name="?register help", value="Use to show this message.")
await ctx.reply(embed=embed)
# return, don't need to save data
return
highscores_data.save_guild_data(guild)
# 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) -> None:
"""Adds function to bot"""
bot.add_cog(RegisterVerificationChannel(bot))
+53 -48
View File
@@ -4,22 +4,28 @@ from typing import Optional
import nextcord
from nextcord.ext import commands
from sqlalchemy import select
from sqlalchemy.orm import Session, aliased
# pylint: disable=import-error
from classes.submission import Submission, SubmissionState
from highscores import submission_objects
from utilities.sql_data_classes import Category, CategoryGroup, Guild, engine
from classes.submission import Submission, SubmissionState # pylint: disable=import-error
from highscores import ( # pylint: disable=import-error
highscores_data,
highscores_message_map,
submission_objects,
)
from .verification_view import VerificationView
def category_select_options(guild_id: int, boss_name: str) -> "list[nextcord.SelectOption]":
def category_select_options(group_id: int) -> "list[nextcord.SelectOption]":
"""Returns list of categories for a given boss."""
options: "list[nextcord.SelectOption]" = []
category_list = highscores_data.get_guild(guild_id).get_table(boss_name).categories
for category in category_list:
options.append(nextcord.SelectOption(label=category.name))
with Session(engine) as session:
subq = select(CategoryGroup).where(CategoryGroup.GroupId == group_id).subquery()
cat_group_alias = aliased(CategoryGroup, subq)
stmt = select(Category).where(Category.GroupId == cat_group_alias.GroupId)
categories_list = session.scalars(stmt)
for category in categories_list:
options.append(nextcord.SelectOption(label=category.CategoryName, value=str(category.CategoryId)))
return options
@@ -35,17 +41,15 @@ class SubmissionDropdown(nextcord.ui.Select):
bot: commands.Bot,
options: "list[nextcord.SelectOption]",
):
super().__init__(
placeholder="Choose submission category.", min_values=1, max_values=1, options=options
)
super().__init__(placeholder="Choose submission category.", min_values=1, max_values=1, options=options)
self._bot = bot
async def callback(self, interaction: nextcord.Interaction):
submission = submission_objects.get_user_submission(interaction.user.id)
submission.category = self.values[0]
embed = submission.get_embed()
submission.category_id = self.values[0]
embeds = submission.get_embeds()
await interaction.message.edit(
embed=embed,
embeds=embeds,
)
@@ -61,8 +65,8 @@ class BackButton(nextcord.ui.Button):
state: SubmissionState = submission.submission_state
state = SubmissionState(state.value - 1)
submission.submission_state = state
embed = submission.get_embed()
await interaction.edit(embed=embed, view=SubmissionView(self._bot, interaction.user.id))
embeds = submission.get_embeds()
await interaction.edit(embeds=embeds, view=SubmissionView(self._bot, interaction.user.id))
class CancelButton(nextcord.ui.Button):
@@ -87,7 +91,7 @@ class NextButton(nextcord.ui.Button):
# check if fields have been filled out for each state
submission = submission_objects.get_user_submission(interaction.user.id)
state: SubmissionState = submission.submission_state
if state == SubmissionState.CATEGORY and not submission.category:
if state == SubmissionState.CATEGORY and not submission.category_id:
await interaction.send("Please choose a category.", ephemeral=True)
elif state == SubmissionState.SCORE and not submission.score:
await interaction.send("Please send a score.", ephemeral=True)
@@ -96,8 +100,8 @@ class NextButton(nextcord.ui.Button):
else:
state = SubmissionState(state.value + 1)
submission.submission_state = state
embed = submission.get_embed()
await interaction.edit(embed=embed, view=SubmissionView(self._bot, interaction.user.id))
embeds = submission.get_embeds()
await interaction.edit(embeds=embeds, view=SubmissionView(self._bot, interaction.user.id))
class SubmitButton(nextcord.ui.Button):
@@ -108,9 +112,9 @@ class SubmitButton(nextcord.ui.Button):
self._bot = bot
async def callback(self, interaction: nextcord.Interaction):
verification_channel_id = highscores_data.get_guild(
interaction.guild_id
).verification_channel
with Session(engine) as session:
stmt = select(Guild.VerificationChannel).where(Guild.GuildId == interaction.guild_id)
verification_channel_id = session.scalar(stmt)
channel = interaction.guild.get_channel(verification_channel_id)
submission = submission_objects.get_user_submission(interaction.user.id)
@@ -120,13 +124,13 @@ class SubmitButton(nextcord.ui.Button):
submission.submission_state = SubmissionState.VERIFY
embed = submission.get_embed()
embeds = submission.get_embeds()
await channel.send(
files=[await attch.to_file() for attch in interaction.message.attachments],
view=VerificationView(),
embed=embed,
content=f"Submission from {interaction.user.display_name}",
embeds=embeds,
content=f"Submission from <@{interaction.user.id}>.",
)
await interaction.message.edit(content=f"<@{interaction.user.id}> Submitted!", view=None)
submission_objects.remove_user_submission(interaction.user.id)
@@ -142,33 +146,36 @@ class SubmissionCreateButton(nextcord.ui.View):
super().__init__(timeout=None)
self._bot = bot
@nextcord.ui.button(
label="Submit", style=nextcord.ButtonStyle.primary, custom_id="submitcreate"
)
@nextcord.ui.button(label="Submit", style=nextcord.ButtonStyle.primary, custom_id="submitcreate")
async def submitcreate_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
): # pylint: disable=unused-argument
"""Button for score submission."""
# Don't allow a user to start a new submission if one already exists
if submission_objects.has_user(interaction.user.id):
await interaction.send("Please finish in progress submission first.", ephemeral=True)
return
table = highscores_message_map[interaction.guild.id][interaction.message.id]
channel = interaction.guild.get_channel(
highscores_data.get_guild(interaction.guild_id).submission_channel
)
with Session(engine) as session:
stmt = (
select(CategoryGroup.GroupId)
.where(CategoryGroup.GuildId == interaction.guild_id)
.where(CategoryGroup.MessageId == interaction.message.id)
)
group_id = session.scalar(stmt)
stmt = select(Guild.SubmissionChannel).where(Guild.GuildId == interaction.guild_id)
channel = interaction.guild.get_channel(session.scalar(stmt))
# a user should only have 1 submission active at once.
# split username on pipe then limit length.
username: str = interaction.user.display_name.split("|")[0][
: highscores_data.get_guild(interaction.guild_id).username_length
]
submission: Submission = Submission(interaction.guild_id, table, username)
# split username on pipe. Decided to store whole username...
username: str = interaction.user.display_name.split("|")[0]
submission: Submission = Submission(interaction.guild_id, group_id, username)
submission_objects.add_submission(interaction.user.id, submission)
embed = submission.get_embed()
embeds = submission.get_embeds()
submission_message = await channel.send(
f"<@{interaction.user.id}>",
@@ -176,7 +183,7 @@ class SubmissionCreateButton(nextcord.ui.View):
self._bot,
interaction.user.id,
),
embed=embed,
embeds=embeds,
)
# update the message_id once its created
@@ -197,14 +204,12 @@ class SubmissionView(nextcord.ui.View):
self._submission_user = submission_user
self._bot = bot
self._state = submission_objects.get_user_submission(self._submission_user).submission_state
self._boss_name = submission_objects.get_user_submission(self._submission_user).table
self._group_id = submission_objects.get_user_submission(self._submission_user).group_id
self._guild_id = submission_objects.get_user_submission(self._submission_user).guild_id
# add items depending on given state
if self._state is SubmissionState.CATEGORY:
self.add_item(
SubmissionDropdown(bot, category_select_options(self._guild_id, self._boss_name))
)
self.add_item(SubmissionDropdown(bot, category_select_options(self._group_id)))
self.add_item(CancelButton())
self.add_item(NextButton(self._bot))
elif (
@@ -226,6 +231,6 @@ class SubmissionView(nextcord.ui.View):
return check
async def on_timeout(self) -> None:
# remove user from submission objects after time out. Allows user to start new submission.
submission_objects.remove_user_submission(self._submission_user)
# async def on_timeout(self) -> None:
# # remove user from submission objects after time out. Allows user to start new submission.
# submission_objects.remove_user_submission(self._submission_user)
+20 -36
View File
@@ -1,10 +1,9 @@
"""View for verification buttons"""
import nextcord
from classes.score import Score, ScoreTime # pylint: disable=import-error
from highscores import highscores_data # pylint: disable=import-error
from utilities.utils import submit_score # pylint: disable=import-error
# pylint: disable=import-error
from utilities.utils import submit_score
class VerificationView(nextcord.ui.View):
@@ -13,53 +12,38 @@ class VerificationView(nextcord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@nextcord.ui.button(
label="Deny", style=nextcord.ButtonStyle.red, custom_id="deny-button-submission"
)
@nextcord.ui.button(label="Deny", style=nextcord.ButtonStyle.red, custom_id="deny-button-submission")
async def deny_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
): # pylint: disable=unused-argument
"""Button for denying score submission."""
await interaction.message.delete()
@nextcord.ui.button(
label="Approve", style=nextcord.ButtonStyle.green, custom_id="approve-button-submission"
)
@nextcord.ui.button(label="Approve", style=nextcord.ButtonStyle.green, custom_id="approve-button-submission")
async def approve_button(
self, button: nextcord.ui.Button, interaction: nextcord.Interaction
): # pylint: disable=unused-argument
"""Button for approving score submission."""
content = interaction.message.embeds[0].to_dict()
for embed in interaction.message.embeds:
content = embed.to_dict()
for field in content["fields"]:
if field["name"] == "Table":
table = field["value"]
elif field["name"] == "Category":
category = field["value"]
elif field["name"] == "Score":
score = field["value"]
elif field["name"] == "User Name":
user = field["value"]
for field in content["fields"]:
if field["name"] == "GroupId":
group_id = int(field["value"])
elif field["name"] == "CategoryId":
category_id = int(field["value"])
elif field["name"] == "Score":
score = field["value"]
elif field["name"] == "User Name":
user = field["value"]
try:
submission_guild = highscores_data.get_guild(interaction.guild_id)
submission_table = submission_guild.get_table(table)
submission_category = submission_table.get_category(category)
if submission_category.time_record:
submission_score: ScoreTime = ScoreTime(user)
submission_score.set_value_str(score)
else:
submission_score: Score = Score(user)
submission_score.set_value_str(score)
await submit_score(
interaction,
submission_guild,
submission_table,
submission_category,
submission_score,
)
await interaction.message.edit(f"Approved by <@{interaction.user.id}>.", view=None)
await submit_score(interaction, group_id, category_id, user, score)
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, embed=interaction.message.embeds[0])
except UnboundLocalError:
await interaction.send("Instruct user to submit with all fields.")
await interaction.message.edit(view=None)
-9
View File
@@ -1,9 +0,0 @@
import os
from dotenv.main import load_dotenv
load_dotenv()
# Discord config
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN", "")
BOT_PREFIX = "?"
+5 -14
View File
@@ -1,5 +1,5 @@
"""
main file for pvm-highscores bot
main file for highscores bot
"""
import logging
@@ -9,8 +9,8 @@ import sys
import nextcord
from nextcord.ext import commands
import config
from classes.highscores_data import HighscoresData
# pylint: disable=import-error
from utilities import config
from classes.submission import SubmissionMap
logger = logging.getLogger("nextcord")
@@ -19,23 +19,14 @@ handler = logging.FileHandler(filename="nextcord.log", encoding="utf-8", mode="w
handler.setFormatter(logging.Formatter("%(asctime)s:%(levelname)s:%(name)s: %(message)s"))
logger.addHandler(handler)
highscores_data: HighscoresData = HighscoresData()
highscores_message_map = {}
for guild in highscores_data.guilds:
highscores_message_map[guild.guild_id] = {}
for table in guild.tables:
highscores_message_map[guild.guild_id][table.message_id] = table.name
submission_objects: SubmissionMap = SubmissionMap()
def main():
"""Main function for bot."""
min_python_version = (3, 7)
min_python_version = (3, 8)
if sys.version_info < min_python_version:
print("ERROR: Python version must be >= 3.7")
print("ERROR: Python version must be >= 3.8")
sys.exit()
# Allows privledged intents for monitoring members joining, roles editing, and role assignments
+45
View File
@@ -0,0 +1,45 @@
CREATE DATABASE highscores;
use highscores;
CREATE TABLE Guilds(
GuildId bigint unsigned not null unique,
GuildName varchar(95) not null,
SubmissionChannel bigint unsigned,
VerificationChannel bigint unsigned,
Active boolean DEFAULT true,
PRIMARY KEY (GuildId)
);
CREATE TABLE CategoryGroups(
GroupId int unsigned not null unique AUTO_INCREMENT,
GroupName varchar(50) not null,
ChannelId bigint unsigned,
GuildId bigint unsigned not null,
MessageId bigint unsigned,
PadLength smallint not null DEFAULT 26,
UsernameLength smallint DEFAULT 12,
CONSTRAINT UniqueGuildCategoryGroup UNIQUE (GuildId, GroupName),
FOREIGN KEY (GuildId) REFERENCES Guilds(GuildId) ON DELETE CASCADE,
PRIMARY KEY (GroupId)
);
CREATE TABLE Categories(
CategoryId int unsigned not null unique AUTO_INCREMENT,
CategoryName varchar(30) not null,
GroupId int unsigned not null,
Size smallint not null DEFAULT 3,
IsAscending boolean not null DEFAULT true,
IsTimeRecord boolean not null DEFAULT false,
IsValidated boolean not null DEFAULT true,
CONSTRAINT UniqueCategoryInGroup UNIQUE (GroupId, CategoryName),
FOREIGN KEY (GroupId) REFERENCES CategoryGroups(GroupId) ON DELETE CASCADE,
PRIMARY Key (CategoryId)
);
CREATE TABLE Scores(
UserName varchar(30) not null,
Score float not null, -- Maybe should have time and int scores?? timestamp type?
CategoryId int unsigned not null,
FOREIGN KEY (CategoryId) REFERENCES Categories(CategoryId) ON DELETE CASCADE,
PRIMARY KEY (CategoryId, UserName)
);
+6 -2
View File
@@ -1,2 +1,6 @@
nextcord>=2.0.0rc1
python-dotenv>=0.20.0
nextcord>=2.3.2
python-dotenv>=0.20.0
pandas>=1.5.2
sqlalchemy<2.0
pymysql>=1.0.2
cryptography>=2.8
+17
View File
@@ -0,0 +1,17 @@
"""
Loads environment variables for use in bot.
"""
import os
from dotenv.main import load_dotenv
load_dotenv()
# Discord config
BOT_PREFIX = "?"
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN", "")
SQL_DB = os.getenv("SQL_DB", "")
SQL_HOST = os.getenv("SQL_HOST", "")
SQL_PASS = os.getenv("SQL_PASS", "")
SQL_USER = os.getenv("SQL_USER", "")
+20
View File
@@ -0,0 +1,20 @@
"""
Simple file to set up the sqlalchemy connection to database.
"""
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
# pylint: disable=import-error
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
Guild = Base.classes.Guilds
CategoryGroup = Base.classes.CategoryGroups
Category = Base.classes.Categories
Score = Base.classes.Scores
+369 -71
View File
@@ -2,122 +2,420 @@
Contains various utlity functions for highscores bot
"""
import json
import time
import nextcord
from highscores import highscores_data, highscores_message_map # pylint: disable=import-error
from classes.score import Score # pylint: disable=import-error
from classes.guild import Guild # pylint: disable=import-error
from classes.category import Category # pylint: disable=import-error
from classes.table import Table # pylint: disable=import-error
import pandas as pd
from sqlalchemy import distinct, select
from sqlalchemy.orm import Session, aliased
# pylint: disable=import-error
from utilities.sql_data_classes import Category, CategoryGroup, Guild, Score, engine
MAX_LINE_LENGTH = 142
def format_highscore_message(guild: Guild, table: Table) -> str:
def autofill_categories(guild_id: int, group_id: int, category_begin: str) -> "dict[str, str]":
"""
Returns all category names that start with category_begin.
If category_begin is empty, returns list of all category names.
Args:
guild_id (int): Guild id that holds the group and categories.
group_id (int): Group id to search in.
category_begin (str): The beginning of a category name to search with. Can be empty.
Returns:
dict[str, str]: List of all category names that start with category_begin.
"""
with Session(engine) as session:
# search database for all category names
subq = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == guild_id)
.where(CategoryGroup.GroupId == 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)}
# if string empty, return all category names
if not category_begin:
return dict(list(category_begin.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()
}
return dict(list(categories.items())[:25])
def autofill_groups(guild_id: int, group_begin: str) -> "dict[str, str]":
"""
Returns all group names that start with group_begin. If group_begin is empty, returns list of all group names.
Args:
guild_id (int): Guild id that holds the groups.
group_begin (str): The beginning of a group name to search with. Can be empty.
Returns:
dict[str, str]: Dict of group names and ids where group name start with group_begin. Key is name, value is id.
"""
with Session(engine) as session:
# Select all groups in guild.
stmt = select(CategoryGroup).where(CategoryGroup.GuildId == 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)}
# if string empty, return all group names
if not group_begin:
return dict(list(group_dict.items())[:25])
# else find all groups that start with group_begin
groups: "dict[str, str]" = {
group_name: group_id for group_name, group_id in group_dict.items() if group_begin.lower() in group_name.lower()
}
return dict(list(groups.items())[:25])
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.
Args:
guild_id (int): Guild id corresponding to group and category.
group_id (str): group to look in for category.
category_id (str): Category to look in for users. Can be None if not looking for category.
user_begin (str): Beginning of user name to search with. Can be empty.
Returns:
list[str]: List of users that start with user_begin.
"""
with Session(engine) as session:
# get all categories in the group
subq = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == guild_id)
.where(CategoryGroup.GroupId == 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))
else:
# get all users in category_id
subq = (
select(Category)
.where(Category.GroupId == category_group.GroupId)
.where(Category.CategoryId == category_id)
.subquery()
)
category = aliased(Category, subq)
stmt = select(distinct(Score.UserName)).where(Score.CategoryId == category.CategoryId)
users_list: "list[str]" = list(session.scalars(stmt))
# if string empty, return all users
if not user_begin:
return users_list[:25]
# else find all users that start with user_begin
users: "list[str]" = [user for user in users_list if user_begin.lower() in user.lower()]
return users[:25]
def autofill_users_in_guild(guild_id: int, user_begin: str) -> "list[str]":
"""
Obtains and returns a list of all the users who have submitted to the guild's highscores.
Args:
guild_id (int): Id of the guild.
user_begin (str): Beginning of user name to search with. Can be empty.
Returns:
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))
users_list: "list[str]" = list(session.scalars(stmt))
# if string empty, return all users
if not user_begin:
return users_list[:25]
# else find all users that start with user_begin
users: "list[str]" = [user for user in users_list if user_begin.lower() in user.lower()]
return users[:25]
def format_highscore_message(session: Session, group: CategoryGroup) -> str:
"""
Creates a formatted string for a boss's highscore discord message.
This formatted string is in discord's code block to ensure monospace text.
Loops through each category to build the message one place at a time.
Args:
guild (Guild): Guild object that is posting the message.
table (Table): Table object that contains the contents of the message.
session (Session): the sqlalchemy session used for this function call.
group (CategoryGroup): group object that contains the contents of the message.
Returns:
str: Formatted string for discord message
"""
ret_string = f"**{table.name}**\n```"
# Gather all categories and add to string
for category in table.categories:
ret_string += f"{category.name}".ljust(26, " ")
ret_string += "\n"
ret_string = f"**{group.GroupName}**\n```"
# list rankings in a single line. Start with first place for each category and then continue
for i in range(table.size):
for category in table.categories:
if len(category.scores) > i:
# pad username to max length.
# have to convert category.scores into list to make it subscriptable. no idea why.
username: str = list(category.scores)[i].user.ljust(guild.username_length, " ")
stmt = select(Guild).where(Guild.GuildId == group.GuildId)
score: str = list(category.scores)[i].get_str()
# Get all categories in the group
subq = (
select(CategoryGroup)
.where(CategoryGroup.GuildId == group.GuildId)
.where(CategoryGroup.GroupName == group.GroupName)
.subquery()
)
cat_group_alias = aliased(CategoryGroup, subq)
stmt = select(Category).where(Category.GroupId == cat_group_alias.GroupId)
# pad score to correct length
# MM:SS.ms is 7 characters long
if category.time_record:
# if there are single digit minutes, add a space for formatting.
if score.find(":") and len(score.split(":", maxsplit=1)[0]) < 2:
score = " " + score
# 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
for cat in session.scalars(stmt):
if cat.Size > max_cat_size:
max_cat_size = cat.Size
categories.append(cat)
category_ids.append(cat.CategoryId)
# 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, con=engine)
# this list is what will be printed in the discord message
# first string will be category list, others will be score printouts
str_list: "list[str]" = ["" for i in range(max_cat_size + 1)]
groups_df = d_f.groupby("CategoryId")
# TODO figure out how to have less nests.
for category in categories:
# category name string
str_list[0] += f"{category.CategoryName}".ljust(pad_length, " ")
# ensure there is data to print
if category.CategoryId in groups_df.indices:
group_df = groups_df.get_group(category.CategoryId)
# 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()
)
# add each score to list
for ind in range(max_cat_size): # need to subtract to deal with category name string
if ind in processed_group.index:
username = processed_group["UserName"][ind]
score = processed_group["Score"][ind]
str_list[ind + 1] += format_score_string(
username, score, group.UsernameLength, category.IsTimeRecord, ind + 1, pad_length
)
else:
score = score.rjust(7, " ")
# if not enough entries, pad out
if 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:
str_list[ind + 1] += f"{ind + 1}: ".ljust(pad_length, " ")
else:
str_list[ind + 1] += "".ljust(pad_length, " ")
ret_string += f"{i+1}: {username} - {score}".ljust(26, " ")
else:
ret_string += f"{i+1}: submit your score".ljust(26, " ")
ret_string += "\n"
# next step is to cut down on the length of each line if required
# need to use index to allow for modifying the list
for ind, line in enumerate(str_list):
if len(line) > MAX_LINE_LENGTH:
split_loc = int(MAX_LINE_LENGTH / pad_length) * pad_length
new_line = line[split_loc:]
str_list[ind] = line[:split_loc]
str_list.append(new_line)
# this list can now be placed into the format message function in the bot
for ind, string in enumerate(str_list):
# rstrip to clear unneeded spaces
# add newline here for each string
ret_string += string.rstrip() + "\n"
# add extra newline at category split unless there is already a space.
if ((ind + 1) % (max_cat_size + 1)) == 0:
# checking inside the other if to ensure called as little as possible.
if not ret_string.endswith("\n\n"):
ret_string += "\n"
return ret_string + "```"
async def send_highscore_message(
channel: nextcord.TextChannel, guild: Guild, table: Table
) -> nextcord.Message:
def format_score_string(
username: str, score: float, username_length: int, is_time_record: bool, rank: int, pad_length: int
) -> str:
"""
Function takes care of checking if a message exists for a table.
Builds the string to show a user's score.
Args:
username (str): username.
score (int): score in int form.
username_length (float): limit to how long username is allowed to be.
is_time_record (bool): if the score represents an number or a time record.
rank (int): the user's rank.
pad_length (int): limit to how long the string can be.
Returns:
str: string to show user's score.
"""
username = username[:username_length].ljust(username_length, " ")
# get score, pad to correct length
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
else:
score = str(int(score)).rjust(7, " ")
return f"{rank}: {username} - {score}".ljust(pad_length, " ")
def get_time_str(time_in: float) -> str:
"""
Formats a float value into the desired string format for a timestamp.
Args:
time_in (float): A time record in seconds
Returns:
str: Describes the time record in string format.
"""
# TODO see if theres a better way to do this
milliseconds = round((time_in - int(time_in)) * 10)
return time.strftime(f"%-M:%S.{milliseconds}", time.gmtime(time_in))
async def send_highscore_message(session: Session, guild: nextcord.Guild, group: CategoryGroup) -> nextcord.Message:
"""
Function takes care of checking if a message exists for a group.
Creates and sends/edits the message.
Args:
channel (nextcord.TextChannel): Discord channel object where message is sent
guild (Guild): Guild object for Guild that is posting the message
table (Table): Table to post to the message
session (Session): The sqlalchemy session being used for this function call.
guild (nextcord.Guild): the nextcord.Guild object requesting this message.
group (CategoryGroup): group to post to the message.
Returns:
nextcord.Message: Message object that was posted with table contents
nextcord.Message: Message object that was posted with group contents.
"""
highscore_string = format_highscore_message(guild, table)
message_id = table.message_id
try:
message: nextcord.Message = await channel.fetch_message(message_id)
await message.edit(content=highscore_string)
except nextcord.NotFound:
highscore_string = format_highscore_message(session, group)
channel = guild.get_channel(group.ChannelId)
if group.MessageId is None:
# message doesn't exist.
message: nextcord.Message = await channel.send(highscore_string)
message_id = message.id
table.message_id = message_id
# save message -> boss_name in message_map
# get guild id from channel
# channel should come from the guild that is requesting this highscores message anyways.
# check if guild is in message map already
if not channel.guild.id in highscores_message_map:
highscores_message_map[channel.guild.id] = {}
highscores_message_map[channel.guild.id][message_id] = table.name
group.MessageId = message.id
session.commit()
else:
message: nextcord.Message = await channel.fetch_message(group.MessageId)
await message.edit(content=highscore_string)
return message
async def submit_score(
interaction: nextcord.Interaction, guild: Guild, table: Table, category: Category, score: Score
interaction: nextcord.Interaction, group_id: int, category_id: int, username: str, score: str
) -> None:
"""
Adds passed score to table. Then updates table message by calling send_highscore_message.
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
guild (Guild): Guild to submit score to
table (Table): Table to submit score to
category (Category): Category to submit score to
score (Score): Score to submit
interaction (nextcord.Interaction): Interaction that caused the score submission.
group (CategoryGroup): group to submit score to.
category_id (Category): Category to submit score to.
username (str): The user who submitted the score.
score (str): Score to submit. Need to convert to correct type.
"""
category.add_score(score)
highscores_data.save_guild_data(guild)
with Session(engine) as session:
stmt = select(Category.IsTimeRecord).where(Category.CategoryId == category_id)
is_time_record = session.scalar(stmt)
# edit message
print(f"Editting message {guild.highscore_channel}")
channel = interaction.guild.get_channel(guild.highscore_channel)
if is_time_record:
minutes = float(score.split(":", maxsplit=1)[0])
seconds = float(score.split(":", maxsplit=1)[1])
score = (minutes * 60) + seconds
else:
score = float(score)
error_response = "Registered Highscores channel does not exist or was never registered."
error_response += 'Register with "?register" command.'
assert channel is not None, await interaction.send(error_response, ephemeral=True)
stmt = select(Score).where(Score.UserName == username).where(Score.CategoryId == category_id)
existing_score = session.scalar(stmt)
await send_highscore_message(channel, guild, table)
if existing_score:
existing_score.Score = score
else:
score_obj = Score(UserName=username, Score=score, CategoryId=category_id)
session.add(score_obj)
session.commit()
stmt = select(CategoryGroup).where(CategoryGroup.GroupId == group_id)
group = session.scalar(stmt)
await send_highscore_message(session, interaction.guild, group)
def add_preset_configuration(guild_id: int, config_str: str) -> None:
"""
Adds an example configuration to a Guild. Uses guild id to know which guild and
config name to open a file in example_config.
Args:
guild_id (int): Guild id to add config to
config_str (str): Config name to add
"""
with Session(engine) as session:
with open(f"example_config/{config_str}.json", encoding="utf-8", mode="r") as file:
config = json.load(file)
for group_name, categorys in config["tables"].items():
group_obj = CategoryGroup(GroupName=group_name, GuildId=guild_id)
session.add(group_obj)
for category_name in categorys:
cat_obj = Category(
CategoryName=category_name,
Size=config["table_size"],
IsTimeRecord=config["categories"][category_name]["is_time_record"],
IsAscending=config["categories"][category_name]["ascending"],
)
session.add(cat_obj)
session.commit()