diff --git a/.env.example b/.env.example index 54235e593..585f859ec 100644 --- a/.env.example +++ b/.env.example @@ -40,10 +40,15 @@ CUSTOM_DISCORD_INVITE_URL=[Replace with your group\'s Discord server invite link # One of: DEBUG, INFO, WARNING, ERROR, CRITICAL CONSOLE_LOG_LEVEL=INFO +# The minimum level that logs from the Discord library (Pycord) must meet in order to be logged to the `discord.log` file +# If this is not set, logs from the Discord library will not be saved to a file +# One of: DEBUG, INFO, WARNING, ERROR, CRITICAL +DISCORD_LOG_LEVEL= + # !!REQUIRED!! -# The URL to retrieve the list of IDs of people that have purchased a membership to your community group -# Ensure that all members are visible without pagination. For example, if your members-list is found on the UoB Guild of Students website, ensure the URL includes the "sort by groups" option -# Must be a valid URL +# The ID of your community group's organisation on your Student Union's online (MSL) platform +# This is used to create the URL of your group's members-list, along with any other required SU platform URLs +# Must be an integer, 4 to 5 digits long ORGANISATION_ID=[Replace with your group\'s MSL Organisation ID] # !!REQUIRED!! @@ -52,6 +57,17 @@ ORGANISATION_ID=[Replace with your group\'s MSL Organisation ID] # This can be extracted from your web-browser, after logging in to view your members-list yourself. It will probably be listed as a cookie named `.AspNet.SharedCookie` SU_PLATFORM_ACCESS_COOKIE=[Replace with your .AspNet.SharedCookie cookie] +# Whether the SU_PLATFORM_ACCESS_COOKIE will be automatically checked at a set interval, to ensure it is still valid +# The result of each check will be logged +# Must be a boolean (True or False) +AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING=False + +# The interval of time between each automatic check of the SU_PLATFORM_ACCESS_COOKIE +# Is ignored if AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING=False +# Must be a string of the seconds, minutes or hours between checks (format: "smh") +# The interval must be longer than 3 seconds +AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL=24h + # The probability that the more rare ping command response will be sent instead of the normal one # Must be a float between & including 0 to 1 PING_COMMAND_EASTER_EGG_PROBABILITY=0.01 @@ -107,9 +123,15 @@ MODERATION_DOCUMENT_URL=[Replace with your group\'s moderation document URL] # The name of the channel, that warning messages will be sent to when a committee-member manually applies a moderation action (instead of using the `/strike` command) # Must be the name of a Discord channel in your group's Discord guild, or the value "DM" (which indicates that the messages will be sent in the committee-member's DMs) # This can be the name of ANY Discord channel (so the offending person *will* be able to see these messages if a public channel is chosen) +# Note that the value "DM" will always send the messages to the committee-member's DMs, so a Discord channel named "DM" cannot be used MANUAL_MODERATION_WARNING_MESSAGE_LOCATION=DM # The set of roles that are tied to the membership of your community group # These roles will be removed along with the membership role upon annual handover/reset +# If this is not set, no extra roles will be removed (the example value below is not the default) # Must be a comma seperated list of strings of role names MEMBERSHIP_DEPENDENT_ROLES=member-red,member-blue,member-green,member-yellow,member-purple,member-pink,member-orange,member-grey,member-black,member-white + +# Whether the @Committee & @Committee-Elect roles will be automatically added to any new threads created within a channel category that has "committee" in its name +# Must be a boolean (True or False) +AUTO_ADD_COMMITTEE_TO_THREADS=True diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f5c8ef420..07ccaf50f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -9,6 +9,7 @@ We welcome anybody who wants to contribute, and we actively encourage everyone t * [Using the Issue Tracker](#using-the-issue-tracker) * [Repository Structure](#repository-structure) * [Making Your First Contribution](#making-your-first-contribution) +* [Guides](#guides) * [License](#license) * [Guidance](#guidance) @@ -34,8 +35,8 @@ We recommend also reading the following if you're unsure or not confident: * [How To Make A Pull Request](https://makeapullrequest.com) * [Contributing To An Open Source Project For The First Time](https://firsttimersonly.com) -TeX-Bot is written in [Python](https://python.org) using [Pycord](https://pycord.dev) and uses Discord's [slash-commands](https://support.discord.com/hc/articles/1500000368501-Slash-Commands-FAQ) & [user-commands](https://guide.pycord.dev/interactions/application-commands/context-menus). -We would recommend being somewhat familiar with the [Pycord library](https://docs.pycord.dev), [Python language](https://docs.python.org/3/reference/index) & [project terminology](README.md#terminology) before contributing. +TeX-Bot is written in [Python](https://python.org) using [Pycord](https://pycord.dev) and uses Discord's [slash commands](TERMINOLOGY.md#slash-commands) & [user commands](TERMINOLOGY.md#user-commands). +We would recommend being somewhat familiar with the [Pycord library](https://docs.pycord.dev), [Python language](https://docs.python.org/3/reference/index) & [project terminology](TERMINOLOGY.md) before contributing. ## Using the Issue Tracker @@ -51,8 +52,11 @@ If you are submitting a feature request, please include the steps to implement t ### Top level files -* [`main.py`](main.py): is the main entrypoint to instantiate the [`Bot` object](https://docs.pycord.dev/stable/api/clients.html#discord.Bot) & run it -* [`config.py`](config.py): retrieves the [environment variables](README.md#setting-environment-variables) & populates the correct values into the `settings` object +* [`main.py`](main.py): is the main entrypoint to instantiate the [`Bot` object](https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot) & run it +* [`config.py`](config.py): retrieves the [environment variables](DEPLOYMENT.md#setting-environment-variables) & populates the correct values into the `settings` object +* [`messages.json`](messages.json): contains the common messages sent by TeX-Bot (the welcome messages & the opt-in roles messages) +* [`TERMINOLOGY.md`](TERMINOLOGY.md): contains the definitions of the terms used throughout this project's documentation +* [`DEPLOYMENT.md`](DEPLOYMENT.md): contains the guide on how to deploy TeX-Bot, both in production & locally ### Other significant directories @@ -61,6 +65,7 @@ If you are submitting a feature request, please include the steps to implement t * [`utils/`](utils): contains common utility classes & functions used by the top-level modules & cogs * [`db/core/models/`](db/core/models): contains all the [database ORM models](https://docs.djangoproject.com/en/stable/topics/db/models) to interact with storing information longer-term (between individual command events) * [`tests/`](tests): contains the complete test suite for this project, based on the [Pytest framework](https://pytest.org) +* [`stubs/`](stubs): contains [type stubs](https://typing.python.org/en/latest/spec/distributing.html#stub-files) for third-party libraries that do not provide their own complete type hints ### Cogs @@ -73,18 +78,32 @@ There are separate cog files for each activity, and one [`__init__.py`](cogs/__i * [`cogs/__init__.py`](cogs/__init__.py): instantiates all the cog classes within this directory +* [`cogs/add_users_to_threads_and_channels.py`](cogs/add_users_to_threads_and_channels.py): cogs for adding users & roles to channels and threads, including automatically adding the committee roles to new committee threads + +* [`cogs/annual_handover_and_reset.py`](cogs/annual_handover_and_reset.py): cogs for annual handover procedures and role resets + * [`cogs/archive.py`](cogs/archive.py): cogs for archiving categories of channels within your group's Discord guild +* [`cogs/check_su_platform_authorisation.py`](cogs/check_su_platform_authorisation.py): cogs for checking the current status of the supplied SU platform access cookie + * [`cogs/command_error.py`](cogs/command_error.py): cogs for sending error messages when commands fail to complete/execute +* [`cogs/committee_actions_tracking.py`](cogs/committee_actions_tracking.py): cogs for creating, assigning & tracking actions for committee members + * [`cogs/delete_all.py`](cogs/delete_all.py): cogs for deleting all permanent data stored in a specific object's table in the database * [`cogs/edit_message.py`](cogs/edit_message.py): cogs for editing messages that were previously sent by TeX-Bot +* [`cogs/everest.py`](cogs/everest.py): cog to calculate how many steps of Mount Everest an assignment is worth + * [`cogs/induct.py`](cogs/induct.py): cogs for inducting people into your group's Discord guild +* [`cogs/invite_link.py`](cogs/invite_link.py): cog to display the invite link to your group's Discord guild + * [`cogs/kill.py`](cogs/kill.py): cogs related to the shutdown of TeX-Bot +* [`cogs/make_applicant.py`](cogs/make_applicant.py): cogs related to making users into applicants + * [`cogs/make_member.py`](cogs/make_member.py): cogs related to making guests into members * [`cogs/ping.py`](cogs/ping.py): cog to request a [ping](https://wikipedia.org/wiki/Ping-pong_scheme#Internet) response @@ -110,14 +129,22 @@ There are separate cog files for each activity, and one [`__init__.py`](cogs/__i After you have found an issue which needs solving, it's time to start working on a fix! However, there are a few guidelines we would like you to follow first. -### Installing pre-commit +### Installing pre-commit Hooks -[pre-commit](https://pre-commit.com) is a selection of checks and reformatting scripts that run before your changes are committed to git. +[pre-commit hooks](https://pre-commit.com) are a selection of checks and reformatting scripts that run before your changes are committed to git. This ensures common formatting mistakes (see [the section on Code Style](#code-style)) and errors can be reported to you early, rather than having to wait for them to show in the CI/CD pipeline. +This project uses [prek](https://prek.j178.dev) to install & run the hooks, which is installed automatically along with this project's other development dependencies. The hooks can be installed with the following command: ```shell -uv run pre-commit install --install-hooks +uv run prek install --prepare-hooks +``` + +The hooks will then run automatically on your changed files every time you make a commit. +To run all the hooks against every file in the repository, use the following command: + +```shell +uv run prek run --all-files ``` ### Running tests @@ -148,6 +175,16 @@ uv run ruff check There are many additional flags to provide more advanced linting help (E.g. `--fix`). See [ruff's documentation](https://docs.astral.sh/ruff/configuration#command-line-interface) for additional configuration options. +#### flake8 + +[flake8](https://flake8.pycqa.org) is another [static analysis code linter](https://wikipedia.org/wiki/Lint_(software)). +It is used alongside [ruff](#ruff) to check this project's own custom linting rules (provided by the [flake8-carrot](https://github.com/CarrotManMatt/flake8-carrot) plugin). +It can be run with the following command: + +```shell +uv run flake8 +``` + #### mypy [Mypy](https://mypy-lang.org) is a [static type checker](https://realpython.com/python-type-checking#static-type-checking), which will alert you to possible [typing](https://realpython.com/python-type-checking#type-systems) errors in your Python code. @@ -172,8 +209,9 @@ Commit messages should be written in the imperative present tense. For example, Commit subjects should start with a capital letter and **not** end in a full-stop. -Additionally, we request that you keep the commit subject under 80 characters for a comfortable viewing experience on GitHub and other git tools. -If you need more, please use the body of the commit. +Additionally, the commit subject must be 72 characters or fewer for a comfortable viewing experience on GitHub and other git tools. +If you need more, please use the body of the commit, keeping each line of the body to 80 characters or fewer. +(These rules are checked by [gitlint](https://jorisroovers.com/gitlint), which is installed as one of the [pre-commit hooks](#installing-pre-commit-hooks).) (See [Robert Painsi's Commit Message Guidelines](https://gist.github.com/robertpainsi/b632364184e70900af4ab688decf6f53) for how to write good commit messages.) For example: @@ -192,6 +230,451 @@ We may ask you to change a few things, so please do check GitHub or your emails After that, that's it! You've made your first contribution. 🎉 +## Guides + +### Creating a New Cog + +Cogs are modular components of TeX-Bot that group related [commands](TERMINOLOGY.md#application-commands) and [event listeners](TERMINOLOGY.md#event-listeners) into a single class. +To create a new cog, follow these steps: + +1. Create the Cog File + * Navigate to the `cogs/` directory. + * Create a new Python file with a name that reflects the purpose of the cog (E.g. `example.py`). + +2. Define the Cog Class + * Define a class that inherits from `TeXBotBaseCog` (found within the `utils` module). + * Name the class after the functionality it provides, ending in `Cog` (E.g. `PingCommandCog` or `SendIntroductionRemindersTaskCog`). + * Add a docstring to describe the purpose of the cog. + * Add the name of the cog class to the `__all__` sequence at the top of the file. + +3. Add Commands and Event Listeners + * Define a method within the class for each [command](TERMINOLOGY.md#application-commands) & [event listener](TERMINOLOGY.md#event-listeners). + * Use the `@discord.slash_command()` decorator for [slash commands](TERMINOLOGY.md#slash-commands), the `@discord.user_command()` or `@discord.message_command()` decorators for [context commands](TERMINOLOGY.md#context-commands), or the `@TeXBotBaseCog.listener()` decorator for [event listeners](TERMINOLOGY.md#event-listeners). + * Include any necessary checks using the `CommandChecks` decorators (found within the `utils` module). + E.g. `@CommandChecks.check_interaction_user_in_main_guild` ensures that the user is a member of your group's main [Discord guild](TERMINOLOGY.md#guild-vs-server), and `@CommandChecks.check_interaction_user_has_committee_role` ensures that the user has the "@**Committee**" role. + + Example: + + ```python + """Contains cog classes for any example interactions.""" + + __all__: Sequence[str] = ("ExampleCommandCog",) + + import logging + lazy from collections.abc import Sequence + lazy from logging import Logger + lazy from typing import Final + + import discord + + from utils import CommandChecks, TeXBotBaseCog + lazy from utils import TeXBotApplicationContext + + logger: Final[Logger] = logging.getLogger("TeX-Bot") + + + class ExampleCommandCog(TeXBotBaseCog): + """Cog class that defines the "/example" command and its call-back method.""" + + @discord.slash_command(name="example", description="Replies with an example message.") + @CommandChecks.check_interaction_user_in_main_guild + async def example(self, ctx: TeXBotApplicationContext) -> None: + """Definition & callback response of the "example" command.""" + await ctx.respond(content="This is an example message.", ephemeral=True) + + @TeXBotBaseCog.listener() + async def on_member_join(self, member: discord.Member) -> None: + """Log the name of every new member that joins your group's Discord guild.""" + logger.debug("%s joined your group's Discord guild.", member) + ``` + +4. Register the Cog + * Edit `cogs/__init__.py` to import your new cog class, and add it to the list of cogs in the `setup` function. + * Also, include the cog class in the `__all__` sequence to ensure it is properly exported. + * Keep the `__all__` sequence & the imports in alphabetical order. + + Example: + + ```python + __all__: Sequence[str] = ( + ..., + "EverestCommandCog", + "ExampleCommandCog", + ..., + ) + + # ... + from .everest import EverestCommandCog + from .example import ExampleCommandCog + # ... + + + def setup(bot: TeXBot) -> None: + """Add all the cogs to the bot, at bot startup.""" + cogs: Iterable[type[TeXBotBaseCog]] = ( + ..., + EverestCommandCog, + ExampleCommandCog, + ..., + ) + Cog: type[TeXBotBaseCog] + for Cog in cogs: + bot.add_cog(Cog(bot)) + ``` + +5. Test the Cog + * Run the bot with your changes and ensure the new cog is loaded without errors. + * Test the [commands](TERMINOLOGY.md#application-commands) and [event listeners](TERMINOLOGY.md#event-listeners) to verify they work as expected. + +6. Document the Cog + * Every class & method requires a docstring (this is checked by [ruff](#ruff)). + Only add extra comments where the functionality may be unexpected or surprising. + * Add your new cog file to [the list of cogs](#cogs) within this document. + * If your cog adds any new functionality, add it to [the "Features" section](README.md#features) of the `README.md` file. + +### Creating a New Environment Variable + +To add a new [environment variable](https://wikipedia.org/wiki/Environment_variable) to the project, follow these steps: + +1. Define the Variable in your development `.env` file + * Open the `.env` file in the project root directory (or create one if it doesn't exist). + * Add the new variable in the format `VARIABLE_NAME=value`. + * Ensure the variable name is descriptive and uses uppercase letters with underscores. + +2. Update `config.py` + * Open the `config.py` file. + * Add a new private setup class method in the `Settings` class (named `_setup_`) to validate and load the variable. + * Raise an `ImproperlyConfiguredError` with a helpful message if the value of the variable is invalid. + * Store the final value in `cls._settings` under the variable's key (this is usually the same as the variable's name). + * Every key that is retrieved from `settings` must be present in `cls._settings` once setup has completed, in every circumstance. + So, if an optional variable has not been set, either store its default value or `None` as the value. + (The only exceptions are variables that just configure logging & are never retrieved from `settings`, such as `DISCORD_LOG_LEVEL`.) + + Example: + + ```python + @classmethod + def _setup_example_limit(cls) -> None: + raw_example_limit: str = os.getenv("EXAMPLE_LIMIT", default="3").strip() + + if not re.fullmatch(pattern=r"\A\d{1,3}\Z", string=raw_example_limit): + INVALID_EXAMPLE_LIMIT_MESSAGE: Final[str] = ( + "EXAMPLE_LIMIT must be an integer between 0 and 999." + ) + raise ImproperlyConfiguredError(INVALID_EXAMPLE_LIMIT_MESSAGE) + + cls._settings["EXAMPLE_LIMIT"] = int(raw_example_limit) + ``` + + * If the variable is required, raise an `ImproperlyConfiguredError` when it has not been set (see `_setup_discord_guild_id` for an example). + * If the variable is optional & has no default value, store `None` when it has not been set (see `_setup_group_full_name` for an example). + +3. Call the Setup Method + * Add a call to your new setup method within the `try` block of the `_setup_env_variables` method in `config.py`. + * If your setup method depends upon the value of another variable, it must be called after that variable's setup method. + (E.g. `_setup_auto_su_platform_access_cookie_checking_interval` must be called after `_setup_auto_su_platform_access_cookie_checking`.) + + Example: + + ```python + @classmethod + def _setup_env_variables(cls) -> None: + ... + + try: + cls._setup_console_logging() + ... + cls._setup_auto_add_committee_to_threads() + cls._setup_example_limit() + except ImproperlyConfiguredError as improper_config_error: + webhook_config_logger.error(improper_config_error.message) # noqa: TRY400 + raise improper_config_error from improper_config_error + + cls._is_env_variables_setup = True + ``` + +4. Use the Variable + * Import the `settings` object from `config.py`, then retrieve the value of your variable using its key. + + Example: + + ```python + lazy from config import settings + + example_limit: int = settings["EXAMPLE_LIMIT"] + ``` + +5. Document the Variable + * Add the variable to `.env.example`, along with comments describing its purpose & any valid values. + The example value should be the variable's default value (if it has one). + * If the variable is required, mark it with `# !!REQUIRED!!` in `.env.example`, and add it to the list of required variables in [the "Setting Environment Variables" section](DEPLOYMENT.md#setting-environment-variables) of `DEPLOYMENT.md`. + +6. Test the Variable + * Run the bot with your changes and ensure the new variable is loaded correctly. + * Test edge cases, such as missing, blank or invalid values in the `.env` file, to confirm that error handling functions correctly. + +### Creating a Response Button + +Response buttons are interactive [message components](TERMINOLOGY.md#interactions) that allow users to respond to bot messages with predefined actions. +To create a response button, follow these steps: + +1. Define the View Class + * Create a new class in your cog file that inherits from `discord.ui.View`. + * Add a button callback response method for each button, using the `@discord.ui.button()` decorator. + * Each button should define its label, style and a unique custom ID. + + Example: + + ```python + import discord + from discord.ui import View + + + class ConfirmActionView(View): + """A discord.View containing two buttons to confirm or cancel an action.""" + + @discord.ui.button(label="Yes", style=discord.ButtonStyle.green, custom_id="confirm_yes") + async def confirm_yes_button_callback( + self, _: discord.ui.Button[ConfirmActionView], interaction: discord.Interaction + ) -> None: + """When the "Yes" button is pressed, confirm the action.""" + await interaction.response.send_message(content="Action confirmed.", ephemeral=True) + + @discord.ui.button(label="No", style=discord.ButtonStyle.red, custom_id="confirm_no") + async def confirm_no_button_callback( + self, _: discord.ui.Button[ConfirmActionView], interaction: discord.Interaction + ) -> None: + """When the "No" button is pressed, cancel the action.""" + await interaction.response.send_message(content="Action cancelled.", ephemeral=True) + ``` + +2. Send the View with a Message + * Use the `view` parameter of the `send` or `respond` method to attach the buttons to a message. + * This could be sent in response to a [command](TERMINOLOGY.md#application-commands), [event](TERMINOLOGY.md#events) or [task](TERMINOLOGY.md#tasks). + + Example: + + ```python + await ctx.respond(content="Do you want to proceed?", view=ConfirmActionView()) + ``` + +3. Handle Button Interactions + * Define the logic within each button callback method to handle the user's [interaction](TERMINOLOGY.md#interactions). + * Use `interaction.response` to send feedback or perform actions based on the button that was pressed. + * The `button` argument of the callback method can be used to retrieve information about the button that was pressed. + + Example: + + ```python + @discord.ui.button(label="Yes", style=discord.ButtonStyle.green, custom_id="confirm_yes") + async def confirm_yes_button_callback( + self, button: discord.ui.Button[ConfirmActionView], interaction: discord.Interaction + ) -> None: + """When the "Yes" button is pressed, tell the user which button they pressed.""" + if interaction.user is None: + await interaction.response.send_message( + content="No user information was provided.", ephemeral=True + ) + return + + await interaction.response.send_message( + content=f"{interaction.user.mention} pressed the {button.label!r} button.", + ephemeral=True, + ) + ``` + + Alternatively, the button callback methods can be kept lightweight, with processing continuing inside the original cog method that sent the buttons. + In this case, each button callback method only removes the buttons from the message, while the original cog method waits for the button [interaction](TERMINOLOGY.md#interactions) using `self.bot.wait_for()`. + The value of `button_interaction.data["custom_id"]` can then be checked to decide how to continue. + + Example button callback method: + + ```python + @discord.ui.button(label="Yes", style=discord.ButtonStyle.green, custom_id="confirm_yes") + async def confirm_yes_button_callback( + self, _: discord.ui.Button[ConfirmActionView], interaction: discord.Interaction + ) -> None: + """ + Remove the buttons from the message when the "Yes" button is pressed. + + The actual handling of the event is done by the command that sent the view, + so all that is required is to remove the buttons from the original message. + """ + await interaction.response.edit_message(view=None) + ``` + + Example of waiting for the button interaction within the original cog method: + + ```python + button_interaction: discord.Interaction = await self.bot.wait_for( + "interaction", + check=lambda interaction: ( + interaction.type == discord.InteractionType.component + and interaction.user == ctx.user + and interaction.channel == ctx.channel + and "custom_id" in interaction.data + and interaction.data["custom_id"] in {"confirm_yes", "confirm_no"} + ), + ) + + if button_interaction.data["custom_id"] == "confirm_no": # type: ignore[index, typeddict-item] + await button_interaction.edit_original_response(content="Action cancelled.", view=None) + return + ``` + + See the `/strike` [command](TERMINOLOGY.md#application-commands) for a full example ([command handler](https://github.com/CSSUoB/TeX-Bot-Py-V2/blob/9376f67561cbdd7016fba7ea0c84372e1782f0e6/cogs/strike.py#L110-L145), [follow-up handling](https://github.com/CSSUoB/TeX-Bot-Py-V2/blob/9376f67561cbdd7016fba7ea0c84372e1782f0e6/cogs/strike.py#L296-L323)). + +4. Test the Button + * Run the bot with your changes and ensure the buttons appear and function as expected. + * Test edge cases, such as multiple users interacting with the buttons simultaneously. + +5. Document the Button + * Every class & method requires a docstring (this is checked by [ruff](#ruff)). + Only add extra comments where the functionality may be unexpected or surprising. + +### Creating and Interacting with Django Models + +> [!IMPORTANT] +> When making changes to the database models, it is essential to consider the data protection implications of these changes. +> If personal data is being collected, stored or processed, it is essential that this is in compliance with the law. +> In the UK, the relevant law is the [Data Protection Act 2018](https://www.legislation.gov.uk/ukpga/2018/12/contents). +> As a general rule, any changes that have data protection implications should be checked and approved by the organisation responsible for running the application. + +[Django models](https://docs.djangoproject.com/en/stable/topics/db/models) are used to interact with the database in this project. +They allow you to define the structure of your data and provide an API to query and manipulate it. +To create and interact with Django models, follow these steps: + +1. Define a Model + * Open the `db/core/models/__init__.py` file, which contains all of TeX-Bot's models. + * Define a new class that inherits from `AsyncBaseModel` (found within the `.utils` module in `db/core/models/`). + * Add the name of the class to the `__all__` sequence at the top of the file (keeping it in alphabetical order). + * Add your Django fields to the class to represent the model's data structure. + * If your model stores information related to each [Discord member](TERMINOLOGY.md#discord-objects), you **must** declare a field called `discord_member`, which links to the `DiscordMember` model (also found within the `.utils` module in `db/core/models/`). + The field must be either a Django `ForeignKey` field or a `OneToOneField`, depending upon the relationship between your model and each Discord member. + * Define the static class string holding the display name for multiple instances of your class (E.g. `INSTANCES_NAME_PLURAL: str = "Discord Members' Smiley Faces"`). + * Define a `Meta` class holding the human-readable names of your model. + + Example: + + ```python + class MemberSmileyFaces(AsyncBaseModel): + """Model to represent the number of smiley faces of each Discord member.""" + + INSTANCES_NAME_PLURAL: str = "Discord Members' Smiley Faces" + + discord_member = models.OneToOneField( + DiscordMember, + on_delete=models.CASCADE, + related_name="smiley_faces", + verbose_name="Discord Member", + blank=False, + null=False, + primary_key=True, + ) + count = models.PositiveIntegerField( + "Number of smiley faces", + null=False, + blank=True, + default=0, + ) + + class Meta(TypedModelMeta): # noqa: D106 + verbose_name: ClassVar[StrOrPromise] = _("Discord Member's Smiley Faces") + verbose_name_plural: ClassVar[StrOrPromise] = _("Discord Members' Smiley Faces") + ``` + +2. Create Migrations + * Run the following command to create a migration file for your changes to the models: + + ```shell + uv run python -m django makemigrations --settings=db._settings + ``` + + * Commit the new migration file (found within `db/core/migrations/`) along with the rest of your changes. + Existing migration files must not be deleted. + * You do not need to apply the migrations yourself, because any pending migrations are applied automatically every time TeX-Bot starts up. + +3. Query the Model + * Use Django's [asynchronous ORM methods](https://docs.djangoproject.com/en/stable/topics/async#queries-the-orm) (E.g. `acreate()`, `aget_or_create()`, `afirst()`, `asave()` & `adelete()`), because all of TeX-Bot's [commands](TERMINOLOGY.md#application-commands), [event listeners](TERMINOLOGY.md#event-listeners) & [tasks](TERMINOLOGY.md#tasks) are asynchronous. + * Models related to each Discord member can be filtered using the Discord member's ID (E.g. `MemberSmileyFaces.objects.filter(discord_member__discord_id=member.id)`). + * It is unlikely that you will need to query the `DiscordMember` model directly, other than to retrieve (or create) the `DiscordMember` object to link to a new instance of your model. + Instead, the attributes of each Discord member can be accessed through the relationship between your model and the `DiscordMember` model. + * The example below shows a single [slash command](TERMINOLOGY.md#slash-commands) that creates, filters, updates & deletes instances of a model, based upon the given command option. + + ```python + """Contains cog classes for any smiley faces interactions.""" + + __all__: Sequence[str] = ("SmileyFacesCommandCog",) + + lazy from collections.abc import Sequence + + import discord + + from utils import CommandChecks, TeXBotBaseCog + lazy from db.core.models import DiscordMember, MemberSmileyFaces + lazy from utils import TeXBotApplicationContext + + + class SmileyFacesCommandCog(TeXBotBaseCog): + """Cog class that defines the "/smiley-faces" command and its call-back method.""" + + @discord.slash_command( + name="smiley-faces", description="Add, view or reset your number of smiley faces." + ) + @discord.option( + name="action", + description="The action to perform on your smiley faces.", + input_type=str, + choices={"add", "view", "reset"}, + required=True, + parameter_name="action", + ) + @CommandChecks.check_interaction_user_in_main_guild + async def smiley_faces(self, ctx: TeXBotApplicationContext, action: str) -> None: + """ + Definition & callback response of the "smiley_faces" command. + + The "smiley_faces" command creates, retrieves, updates or deletes + the MemberSmileyFaces object of the user that ran the command. + """ + if action == "add": + member_smiley_faces: MemberSmileyFaces = ( + await MemberSmileyFaces.objects.aget_or_create( + discord_member=( + await DiscordMember.objects.aget_or_create(discord_id=ctx.user.id) + )[0] + ) + )[0] + member_smiley_faces.count += 1 + await member_smiley_faces.asave() + + await ctx.respond( + content=f"You now have {member_smiley_faces.count} smiley faces!", + ephemeral=True, + ) + return + + found_smiley_faces: MemberSmileyFaces | None = await MemberSmileyFaces.objects.filter( + discord_member__discord_id=ctx.user.id + ).afirst() + + if found_smiley_faces is None: + await ctx.respond(content="You do not have any smiley faces yet.", ephemeral=True) + return + + if action == "view": + await ctx.respond( + content=f"You have {found_smiley_faces.count} smiley faces.", + ephemeral=True, + ) + return + + await found_smiley_faces.adelete() + await ctx.respond(content="Your smiley faces have been reset.", ephemeral=True) + ``` + + * If the data stored by your model may need to be completely deleted in the future, add a matching sub-command to the `/delete-all` [command](TERMINOLOGY.md#application-commands) group within `cogs/delete_all.py`. + ## License Please note that any contributions you make will be made under the terms of the [Apache Licence 2.0](LICENSE). diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md new file mode 100644 index 000000000..7f6dbfe32 --- /dev/null +++ b/DEPLOYMENT.md @@ -0,0 +1,83 @@ +# TeX-Bot-Py-V2 Deployment + +> [!NOTE] +> Please familiarise yourself with all the terms defined in [TERMINOLOGY.md](TERMINOLOGY.md) before continuing, to prevent any confusion. + +## Deploying in Production + +The only supported way to deploy TeX-Bot in production is by using our pre-built [docker container](https://docker.com/resources/what-container). +It can be pulled from the [GitHub Container Registry](https://docs.github.com/packages/working-with-a-github-packages-registry/working-with-the-container-registry) with this identifier: [`ghcr.io/CSSUoB/tex-bot-py-v2:latest`](https://github.com/CSSUoB/TeX-Bot-Py-V2/pkgs/container/tex-bot-py-v2). +([Here is an introduction](https://docs.docker.com/compose/gettingstarted) on how to use a [docker-compose deployment](https://docs.docker.com/compose).) +See [**Versioning**](README.md#versioning) for the full list of available version tags for each release. + +Before running the [container](https://docker.com/resources/what-container), some [environment variables](https://wikipedia.org/wiki/Environment_variable) will need to be set. +These can be defined in your [`compose.yaml`](https://docs.docker.com/compose/compose-application-model#the-compose-file) file. +The required [environment variables](https://wikipedia.org/wiki/Environment_variable) are explained within [the "Setting Environment Variables" section](#setting-environment-variables). + +## Local Deployment + +### Installing Dependencies + +1. Ensure that you have [uv](https://docs.astral.sh/uv/getting-started/installation) installed +2. Navigate to this project's repository root folder +3. To install the required dependencies, execute the following command: + +```shell +uv sync +``` + +> [!TIP] +> Syncing the dependencies is not required. uv performs this automatically every time the `uv run` command is used + +### Creating Your [Bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) + +A full guide on how to create your bot's account can be found [here; on Pycord's wiki](https://docs.pycord.dev/en/stable/discord.html). + +You'll need to create a [Discord bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) of your own in the [Discord Developer Portal](https://discord.com/developers/applications). +It's also handy if you have an empty [Discord guild](TERMINOLOGY.md#guild-vs-server) for you to test in. + +The correct [invite URL](https://docs.pycord.dev/en/stable/discord.html#inviting-your-bot) will be displayed to you in the console the first time you run the bot (or if you set a high verbosity log level) + +### Setting [Environment Variables](https://wikipedia.org/wiki/Environment_variable) + +You'll also need to set a number of [environment variables](https://wikipedia.org/wiki/Environment_variable) before running TeX-Bot: + +* `DISCORD_BOT_TOKEN`: The [Discord bot secret token](https://docs.pycord.dev/en/stable/discord.html) for the [instance of TeX-Bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) you created. + * The [Discord bot token](https://docs.pycord.dev/en/stable/discord.html) is available on [your bot's page in the Discord Developer Portal](https://discord.com/developers/applications). + +* `DISCORD_GUILD_ID`: The [ID](https://discord.com/developers/docs/reference#snowflakes) of your community group's [Discord guild](TERMINOLOGY.md#guild-vs-server). + +* `DISCORD_LOG_CHANNEL_WEBHOOK_URL`: The [webhook URL](https://support.discord.com/hc/articles/228383668-Intro-to-Webhooks) of the [Discord text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) where error log messages should be sent. + * This setting is optional. + Error logs will **always** be sent to the [console](https://wikipedia.org/wiki/Terminal_emulator), this setting just allows them to also be sent to a [Discord log channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel). + +* `ORGANISATION_ID`: Your SU platform organisation ID. + This is used to dynamically create the members list and other needed URLs. + +* `SU_PLATFORM_ACCESS_COOKIE`: The SU platform [access session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie). + * This [session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie) will [authenticate](https://wikipedia.org/wiki/Authentication) TeX-Bot to view your group's members list on the SU platform, as if it were [logged in to the website](https://wikipedia.org/wiki/Login_session) as a Committee member. + * This can be [extracted from your web-browser](https://wikihow.com/View-Cookies), after logging in to view your members list yourself. + It will most likely be listed as a [cookie](https://wikipedia.org/wiki/HTTP_cookie) named `.AspNet.SharedCookie`. + * If you wish to test TeX-Bot with the SU platform-access disabled, a dummy value of 512 `0` characters can be used. + Note that this will cause many commands and scheduled tasks to fail when they are used at runtime. + +* `MODERATION_DOCUMENT_URL`: The URL of your group's [Discord guild](TERMINOLOGY.md#guild-vs-server) moderation document. + +You can put these [variables](https://wikipedia.org/wiki/Environment_variable) in a [`.env` file](https://blog.bitsrc.io/a-gentle-introduction-to-env-files-9ad424cc5ff4) in the root folder, as [python-dotenv](https://saurabh-kumar.com/python-dotenv) is used to collect all [environment variables](https://wikipedia.org/wiki/Environment_variable). +There is an [`.env.example` file](.env.example) in the repo that you can rename and populate. + +There are also many other configuration settings that can be changed to alter the behaviour of TeX-Bot. +These are all listed in [the `.env.example` file](.env.example), along with the behaviours that will be affected. + +Any [variables](https://wikipedia.org/wiki/Environment_variable), in [the `.env.example` file](.env.example), marked with `# !!REQUIRED!!` must be set before running TeX-Bot. +All other [variables](https://wikipedia.org/wiki/Environment_variable) are optional and their default values are shown as the example value for each variable in [the `.env.example` file](.env.example). + +### Running The Bot + +Once everything is set up, you should be able to execute the following command to automatically run TeX-Bot & connect it to your [Discord guild](TERMINOLOGY.md#guild-vs-server): + +```shell +uv run -m main +``` + +Any pending database migrations are applied automatically each time TeX-Bot starts up. diff --git a/README.md b/README.md index 60ca570e7..8f82389b7 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # TeX-Bot-Py-V2 -[![Python Version](https://img.shields.io/badge/Python-3.15-blue?&logo=Python&logoColor=white)](https://python.org/downloads/release/python-3139) +[![Python Version](https://img.shields.io/badge/Python-3.15-blue?&logo=Python&logoColor=white)](https://python.org/downloads/release/python-3150) [![Pycord Version](https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Ftoml-version-finder.carrotmanmatt.com%2Flock%2FCSSUoB%2FTeX-Bot-Py-V2%2Fpy-cord&query=%24.package_version&logo=data:image/svg%2bxml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM6dj0iaHR0cHM6Ly92ZWN0YS5pby9uYW5vIj48cGF0aCBkPSJNMTQuMjUuMThsLjkuMi43My4yNi41OS4zLjQ1LjMyLjM0LjM0LjI1LjM0LjE2LjMzLjEuMy4wNC4yNi4wMi4yLS4wMS4xM1Y4LjVsLS4wNS42My0uMTMuNTUtLjIxLjQ2LS4yNi4zOC0uMy4zMS0uMzMuMjUtLjM1LjE5LS4zNS4xNC0uMzMuMS0uMy4wNy0uMjYuMDQtLjIxLjAySDguNzdsLS42OS4wNS0uNTkuMTQtLjUuMjItLjQxLjI3LS4zMy4zMi0uMjcuMzUtLjIuMzYtLjE1LjM3LS4xLjM1LS4wNy4zMi0uMDQuMjctLjAyLjIxdjMuMDZIMy4xN2wtLjIxLS4wMy0uMjgtLjA3LS4zMi0uMTItLjM1LS4xOC0uMzYtLjI2LS4zNi0uMzYtLjM1LS40Ni0uMzItLjU5LS4yOC0uNzMtLjIxLS44OC0uMTQtMS4wNS0uMDUtMS4yMy4wNi0xLjIyLjE2LTEuMDQuMjQtLjg3LjMyLS43MS4zNi0uNTcuNC0uNDQuNDItLjMzLjQyLS4yNC40LS4xNi4zNi0uMS4zMi0uMDUuMjQtLjAxaC4xNmwuMDYuMDFoOC4xNnYtLjgzSDYuMThsLS4wMS0yLjc1LS4wMi0uMzcuMDUtLjM0LjExLS4zMS4xNy0uMjguMjUtLjI2LjMxLS4yMy4zOC0uMi40NC0uMTguNTEtLjE1LjU4LS4xMi42NC0uMS43MS0uMDYuNzctLjA0Ljg0LS4wMiAxLjI3LjA1IDEuMDcuMTN6bS02LjMgMS45OGwtLjIzLjMzLS4wOC40MS4wOC40MS4yMy4zNC4zMy4yMi40MS4wOS40MS0uMDkuMzMtLjIyLjIzLS4zNC4wOC0uNDEtLjA4LS40MS0uMjMtLjMzLS4zMy0uMjItLjQxLS4wOS0uNDEuMDktLjMzLjIyeiIgZmlsbD0iIzVlNmRmMCIvPjxwYXRoIGQ9Ik0xNC41NyAyMC4zNmwtLjIzLjMzLS4wOC40MS4wOC40MS4yMy4zMy4zMy4yMy40MS4wOC40MS0uMDguMzMtLjIzLjIzLS4zMy4wOC0uNDEtLjA4LS40MS0uMjMtLjMzLS4zMy0uMjMtLjQxLS4wOC0uNDEuMDgtLjMzLjIzem02LjQ3LTE0LjI1bC4yOC4wNi4zMi4xMi4zNS4xOC4zNi4yNy4zNi4zNS4zNS40Ny4zMi41OS4yOC43My4yMS44OC4xNCAxLjA0LjA1IDEuMjMtLjA2IDEuMjMtLjE2IDEuMDQtLjI0Ljg2LS4zMi43MS0uMzYuNTctLjQuNDUtLjQyLjMzLS40Mi4yNC0uNC4xNi0uMzYuMDktLjMyLjA1LS4yNC4wMi0uMTYtLjAxaC04LjIydi44Mmg1Ljg0bC4wMSAyLjc2LjAyLjM2LS4wNS4zNC0uMTEuMzEtLjE3LjI5LS4yNS4yNS0uMzEuMjQtLjM4LjItLjQ0LjE3LS41MS4xNS0uNTguMTMtLjY0LjA5LS43MS4wNy0uNzcuMDQtLjg0LjAxLTEuMjctLjA0LTEuMDctLjE0LS45LS4yLS43My0uMjUtLjU5LS4zLS40NS0uMzMtLjM0LS4zNC0uMjUtLjM0LS4xNi0uMzMtLjEtLjMtLjA0LS4yNS0uMDItLjIuMDEtLjEzdi01LjM0bC4wNS0uNjQuMTMtLjU0LjIxLS40Ni4yNi0uMzguMy0uMzIuMzMtLjI0LjM1LS4yLjM1LS4xNC4zMy0uMS4zLS4wNi4yNi0uMDQuMjEtLjAyLjEzLS4wMWg1Ljg0bC42OS0uMDUuNTktLjE0LjUtLjIxLjQxLS4yOC4zMy0uMzIuMjctLjM1LjItLjM2LjE1LS4zNi4xLS4zNS4wNy0uMzIuMDQtLjI4LjAyLS4yMVY2LjA3aDIuMDlsLjE0LjAxLjIxLjAzeiIgZmlsbD0iI2Q0ZDRkNCIvPjwvc3ZnPg==&label=Pycord)](https://pycord.dev) [![Tests Status](https://github.com/CSSUoB/TeX-Bot-Py-V2/actions/workflows/check-build-deploy.yaml/badge.svg)](https://github.com/CSSUoB/TeX-Bot-Py-V2/actions/workflows/check-build-deploy.yaml) [![mypy Status](https://img.shields.io/badge/mypy-checked-%232EBB4E&label=mypy)](https://mypy-lang.org) @@ -15,34 +15,47 @@ This is a [Discord bot](https://discord.com/developers/docs/topics/oauth2#bot-vs Featured in the [CSS Discord guild](https://cssbham.com/discord). -## Terminology +> [!NOTE] +> Please familiarise yourself with all the terms defined in [TERMINOLOGY.md](TERMINOLOGY.md) before continuing, to prevent any confusion. -### ["Guild"](https://discord.com/developers/docs/resources/guild) Vs ["Server"](https://wikipedia.org/wiki/Discord#Servers) +## Features -Confusingly, [Discord](https://discord.com) uses the term ["guild"](https://discord.com/developers/docs/resources/guild) to refer to a [Discord "server"](https://wikipedia.org/wiki/Discord#Servers), when communicating with developers. -Therefore, the same terminology (["guild"](https://discord.com/developers/docs/resources/guild)) will be used across all documentation in this project. -(See [the Discord developer docs](https://discord.com/developers/docs/resources/guild) & [Pycord's docs](https://docs.pycord.dev/en/stable/api/models.html#discord.Guild) for more information.) +TeX-Bot provides the following functionality within your community group's [Discord guild](TERMINOLOGY.md#guild-vs-server): -The term "main guild" is used throughout the code in this repository to refer specifically to your community group's main [Discord guild](https://discord.com/developers/docs/resources/guild). +* **Induction** - Give new [guests](TERMINOLOGY.md#community-group-membership) the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object) & welcome them into your [Discord guild](TERMINOLOGY.md#guild-vs-server). +(Using the `/induct` [slash command](TERMINOLOGY.md#slash-commands), the "Induct User" & "Silently Induct User" [user commands](TERMINOLOGY.md#user-commands) or the "Induct Message Author" [message command](TERMINOLOGY.md#message-commands).) +The `/ensure-members-inducted` [slash command](TERMINOLOGY.md#slash-commands) gives the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object) to any [members](TERMINOLOGY.md#community-group-membership) that are missing it. -### "User" Vs "Member" Vs "Guest" +* **Membership** - Allow [Discord members](TERMINOLOGY.md#discord-objects) to give themselves the "@**Member**" [role](https://discord.com/developers/docs/topics/permissions#role-object), after their membership ID has been validated against your group's members list on the SU platform (using the `/make-member` [slash command](TERMINOLOGY.md#slash-commands)). +The `/member-count` [slash command](TERMINOLOGY.md#slash-commands) displays how many [members](TERMINOLOGY.md#community-group-membership) your community group has. -#### [Discord Objects](https://discord.com/developers/docs) +* **Applicants** - Give [Discord members](TERMINOLOGY.md#discord-objects) the "@**Applicant**" [role](https://discord.com/developers/docs/topics/permissions#role-object). +(Using the `/make-applicant` [slash command](TERMINOLOGY.md#slash-commands), the "Make Applicant" [user command](TERMINOLOGY.md#user-commands) or the "Make Message Author Applicant" [message command](TERMINOLOGY.md#message-commands).) -In the context of [Discord](https://discord.com) itself, a ["user"](https://discord.com/developers/docs/resources/user) object represents a [Discord](https://discord.com) account not connected to any specific [guild](https://discord.com/developers/docs/resources/guild). -Therefore, it can be [messaged via DM](https://dictionary.com/browse/dm) or be retrieved via its [snowflake ID](https://discord.com/developers/docs/reference#snowflakes), but little else can be done with it. -(See [the Discord developer docs](https://discord.com/developers/docs/resources/user) & [Pycord's docs](https://docs.pycord.dev/en/stable/api/models.html#users) for more information.) +* **Moderation** - Apply strikes to [Discord members](TERMINOLOGY.md#discord-objects), with the matching moderation action being performed automatically. +(Using the `/strike`, `/get-strikes` & `/decrement-strikes` [slash commands](TERMINOLOGY.md#slash-commands), the "Strike User" [user command](TERMINOLOGY.md#user-commands) or the "Strike Message Author" [message command](TERMINOLOGY.md#message-commands).) +Moderation actions that are applied manually (instead of by using the `/strike` [command](TERMINOLOGY.md#application-commands)) are also tracked. +The "Send Message to Committee" [message command](TERMINOLOGY.md#message-commands) forwards a message to your committee for discussion. -In contrast, a [Discord "member" object](https://discord.com/developers/docs/resources/guild#guild-member-object) is a [user](https://discord.com/developers/docs/resources/user) attached to a specific [guild](https://discord.com/developers/docs/resources/guild). -Therefore, it can have [roles](https://discord.com/developers/docs/topics/permissions#role-object), be [banned](https://discord.com/developers/docs/resources/guild#ban-object) & have many other actions applied to it. -(See [the Discord developer docs](https://discord.com/developers/docs/resources/guild#guild-member-object) & [Pycord's docs](https://docs.pycord.dev/en/stable/api/models.html#discord.Member) for more information.) +* **Committee Actions Tracking** - Create, assign, update & list actions for your committee members (using the `/committee-actions` group of [slash commands](TERMINOLOGY.md#slash-commands) or the "Action Message Author" [message command](TERMINOLOGY.md#message-commands)). -#### Community Group Membership +* **Reminders** - Send [Discord members](TERMINOLOGY.md#discord-objects) [repeated reminders](#repeated-tasks-conditions) to introduce themselves, and to give themselves opt-in [roles](https://discord.com/developers/docs/topics/permissions#role-object). -In the context of your community group's membership structure, a "member" is a person that has purchased a membership to join your community group. -This is in contrast to a "guest", which is a person that has not purchased a membership. -Guests often can only attend events that are open to anyone (i.e. **not** members only), and have limited communication/perks within your [Discord guild](https://discord.com/developers/docs/resources/guild). -Some commands may require you to create [roles](https://discord.com/developers/docs/topics/permissions#role-object) within your [Discord guild](https://discord.com/developers/docs/resources/guild), to differentiate between these different types of users. +* **Annual Handover** - Give the "@**Committee**" [role](https://discord.com/developers/docs/topics/permissions#role-object) to the new committee (any [Discord members](TERMINOLOGY.md#discord-objects) with the "@**Committee-Elect**" [role](https://discord.com/developers/docs/topics/permissions#role-object)), reset the "@**Member**" & academic year [roles](https://discord.com/developers/docs/topics/permissions#role-object) and increment the academic year channels (using the `/committee-handover`, `/annual-roles-reset` & `/increment-year-channels` [slash commands](TERMINOLOGY.md#slash-commands)). + +* **Channel Management** - Archive channels & categories (using the `/archive-channel` & `/archive-category` [slash commands](TERMINOLOGY.md#slash-commands)), and add [users](TERMINOLOGY.md#discord-objects) or [roles](https://discord.com/developers/docs/topics/permissions#role-object) to channels & threads (using the `/add-users-to-channel` & `/add-role-to-channel` [slash commands](TERMINOLOGY.md#slash-commands)). +The committee [roles](https://discord.com/developers/docs/topics/permissions#role-object) can also be automatically added to any new threads created within committee categories. + +* **Statistics** - Display graphs of message statistics for a channel, your whole [Discord guild](TERMINOLOGY.md#guild-vs-server) or yourself, and of the [roles](https://discord.com/developers/docs/topics/permissions#role-object) that [Discord members](TERMINOLOGY.md#discord-objects) had when they left (using the `/stats` group of [slash commands](TERMINOLOGY.md#slash-commands)). + +* **Bot Messages** - Send the opt-in [roles](https://discord.com/developers/docs/topics/permissions#role-object) message into the "#**roles**" channel (using the `/write-roles` [slash command](TERMINOLOGY.md#slash-commands)) and edit messages previously sent by TeX-Bot (using the `/edit-message` [slash command](TERMINOLOGY.md#slash-commands)). + +* **SU Platform Authorisation Checking** - Check whether your `SU_PLATFORM_ACCESS_COOKIE` is valid, and which organisations it has administrative access to (using the `/check-su-platform-authorisation` [slash command](TERMINOLOGY.md#slash-commands)). +This check can also be run automatically as a [repeated task](#repeated-tasks-conditions). + +* **Data Management** - Delete all of a specific type of data stored in the database (using the `/delete-all` group of [slash commands](TERMINOLOGY.md#slash-commands)). + +* **Utilities** - `/ping`, `/source`, `/invite-link`, `/everest` & `/kill` (to shut down TeX-Bot). ## Error Codes @@ -50,43 +63,37 @@ Members of your [Discord guild](https://discord.com/developers/docs/resources/gu If a user encounters any of these errors, please communicate the error to the committee member that has been assigned to upkeep & deployment of your instance of TeX-Bot. The meaning of each error code is given here: -* `E1011` - The value for the [environment variable](https://wikipedia.org/wiki/Environment_variable) `DISCORD_GUILD_ID` is an [ID](https://discord.com/developers/docs/reference#snowflakes) that references a [Discord guild](https://discord.com/developers/docs/resources/guild) that does not exist +* `E1011` - The value for the [environment variable](https://wikipedia.org/wiki/Environment_variable) `DISCORD_GUILD_ID` is an [ID](https://discord.com/developers/docs/reference#snowflakes) that references a [Discord guild](TERMINOLOGY.md#guild-vs-server) that does not exist * `E1021` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Committee**". -(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/write-roles`, `/edit-message`, `/induct`, `/strike`, `/archive`, `/kill`, `/delete-all` & `/ensure-members-inducted` [commands](https://discord.com/developers/docs/interactions/application-commands)) +(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/add-role-to-channel`, `/add-users-to-channel`, `/annual-roles-reset`, `/archive-category`, `/archive-channel`, `/check-su-platform-authorisation`, `/committee-handover`, `/decrement-strikes`, `/edit-message`, `/ensure-members-inducted`, `/get-strikes`, `/increment-year-channels`, `/induct`, `/kill`, `/make-applicant`, `/strike` & `/write-roles` [commands](TERMINOLOGY.md#application-commands). +It is also required for all the `/delete-all` [commands](TERMINOLOGY.md#application-commands), the `/committee-actions create`, `/committee-actions list`, `/committee-actions list-all`, `/committee-actions reassign`, `/committee-actions action-random-user` & `/committee-actions action-all-committee` [commands](TERMINOLOGY.md#application-commands), and the "Induct User", "Silently Induct User", "Induct Message Author", "Make Applicant", "Make Message Author Applicant", "Strike User", "Strike Message Author" & "Action Message Author" [context commands](TERMINOLOGY.md#context-commands). +The `/committee-actions list` [command](TERMINOLOGY.md#application-commands) only requires this [role](https://discord.com/developers/docs/topics/permissions#role-object) when listing the actions of another user.) * `E1022` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Guest**". -(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/induct`, `/stats`, `/archive` & `/ensure-members-inducted` [commands](https://discord.com/developers/docs/interactions/application-commands)) +(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/induct`, `/ensure-members-inducted`, `/increment-year-channels`, `/make-applicant`, `/stats server` & `/stats self` [commands](TERMINOLOGY.md#application-commands), and the "Induct User", "Silently Induct User", "Induct Message Author", "Make Applicant" & "Make Message Author Applicant" [context commands](TERMINOLOGY.md#context-commands)) * `E1023` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Member**". -(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/make-member` & `/ensure-members-inducted` [commands](https://discord.com/developers/docs/interactions/application-commands)) +(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/make-member`, `/ensure-members-inducted` & `/annual-roles-reset` [commands](TERMINOLOGY.md#application-commands)) * `E1024` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Archivist**". -(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/archive` [command](https://discord.com/developers/docs/interactions/application-commands)) +(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/archive-category` & `/increment-year-channels` [commands](TERMINOLOGY.md#application-commands)) -* `E1025` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Applicant**". (This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/make-applicant` [command](https://discord.com/developers/docs/interactions/application-commands) and respective user and message commands) +* `E1025` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Applicant**". (This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/make-applicant` [command](TERMINOLOGY.md#application-commands) and respective user and message commands) -* `E1026` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-objec) with the name "@**Committee-Elect**". -(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/handover` [command](https://discord.com/developers/docs/interactions/application-commands)) +* `E1026` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [role](https://discord.com/developers/docs/topics/permissions#role-object) with the name "@**Committee-Elect**". +(This [role](https://discord.com/developers/docs/topics/permissions#role-object) is required for the `/committee-handover` [command](TERMINOLOGY.md#application-commands)) * `E1031` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) with the name "#**roles**". -(This [text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) is required for the `/writeroles` [command](https://discord.com/developers/docs/interactions/application-commands)) +(This [text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) is required for the `/write-roles` [command](TERMINOLOGY.md#application-commands)) * `E1032` - Your [Discord guild](https://discord.com/developers/docs/resources/guild) does not contain a [text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) with the name "#**general**". -(This [text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) is required for the `/induct` [command](https://discord.com/developers/docs/interactions/application-commands)) - -* `E1041` - The community group member IDs could not be retrieved from the SU platform. -(It is likely that your `SU_PLATFORM_ACCESS_COOKIE` is invalid. -If your community group is a [Guild of Students](https://guildofstudents.com) [society](https://wikipedia.org/wiki/Student_society), the community group member IDs will be a list of [UoB IDs](https://intranet.birmingham.ac.uk/campus-services/id-cards.aspx)) +(This [text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) is required for the `/induct` [command](TERMINOLOGY.md#application-commands) (unless the `silent` option is used), and the "Induct User" & "Induct Message Author" [context commands](TERMINOLOGY.md#context-commands)) * `E1042` - The reference to the `@everyone` [role](https://discord.com/developers/docs/topics/permissions#role-object) could not be correctly retrieved. Try running the command that caused this error again. If the error persists, please file an issue on [this project's bug tracker](https://github.com/CSSUoB/TeX-Bot-Py-V2/issues), including the details of what command was run to create this error -* `E1043` - A button callback interaction did not contain the related [user](https://discord.com/developers/docs/resources/user). -Try pressing the button that caused this error again. -If the error persists, please file an issue on [this project's bug tracker](https://github.com/CSSUoB/TeX-Bot-Py-V2/issues), including the details of what command was run to create this error - * `E1044` - An interaction was denied because the Discord permissions for TeX-Bot were not set correctly ## Log-Entry Error Levels @@ -107,88 +114,20 @@ This level of error will cause TeX-Bot to shut down, as the problem can only be ## [Repeated Tasks](https://docs.pycord.dev/en/stable/ext/tasks) Conditions -The [configuration variables](https://wikipedia.org/wiki/Environment_variable) `SEND_INTRODUCTION_REMINDERS` & `SEND_GET_ROLES_REMINDERS` determine whether their related [tasks](https://docs.pycord.dev/en/stable/ext/tasks) should run. -However, because these are rather annoying/drastic actions to be executed automatically, there are additional conditions that must be met on a per-[member](https://discord.com/developers/docs/resources/guild#guild-member-object) basis for the action to trigger. +The [configuration variables](https://wikipedia.org/wiki/Environment_variable) `SEND_INTRODUCTION_REMINDERS`, `SEND_GET_ROLES_REMINDERS` & `AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING` determine whether their related [tasks](TERMINOLOGY.md#tasks) should run. +However, because the reminder [tasks](TERMINOLOGY.md#tasks) are rather annoying/drastic actions to be executed automatically, there are additional conditions that must be met on a per-[member](https://discord.com/developers/docs/resources/guild#guild-member-object) basis for the action to trigger. The conditions for each [task](https://docs.pycord.dev/en/stable/ext/tasks) are listed below, along with the additional [environment variables](https://wikipedia.org/wiki/Environment_variable) that can be used to configure the conditions to suit your needs. | Task Name | Enable/Disable | Per-Member Conditions | Scheduled Interval | |-------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| `introduction_reminder` | `SEND_INTRODUCTION_REMINDERS`:
* `Once` - Only send the introduction reminder once (even if they later delete the message)
* `Interval` - Send an introduction reminder at a set interval
* `False` - Do not send introduction reminders | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not been inducted (does not have the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) joined your community's guild is greater than `SEND_INTRODUCTION_REMINDERS_DELAY`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not opted out of introduction reminders
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent an introduction reminder. (Only applies when `SEND_INTRODUCTION_REMINDERS` is set to the value `Once`) | The interval of time between this task running is determined by `SEND_INTRODUCTION_REMINDERS_INTERVAL`. (When `SEND_INTRODUCTION_REMINDERS` is set to the value `Once`, all [Discord members](https://discord.com/developers/docs/resources/guild#guild-member-object) will still be checked at this interval, just not sent a message if they have already been sent an introduction reminder). The default interval is to send messages every 6 hours | -| `get_roles_reminder` | `SEND_GET_ROLES_REMINDERS`:
* `True` - A single reminder for the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) will be sent to them only once (even if they later delete the message)
* `False` - Do not send any reminders for [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has been inducted (has the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) does not have any of the opt-in [roles](https://discord.com/developers/docs/topics/permissions#role-object). (E.g. "@**First Year**" or "@**Anime**".) (Having the green "@**Member**" [role](https://discord.com/developers/docs/topics/permissions#role-object) or even the "@**Committee**" [role](https://discord.com/developers/docs/topics/permissions#role-object) makes no difference)
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) was inducted (gained the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object)) is greater than `SEND_GET_ROLES_REMINDERS_DELAY`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent a reminder to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | The interval of time between this task running is determined by `ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL`. It is unlikely that this value will need to be changed from the default of 24 hours | - -## Deploying in Production - -The only supported way to deploy TeX-Bot in production is by using our pre-built [docker container](https://docs.docker.com/resources/what-container). -It is can be pulled from the [GitHub Container Registry](https://docs.github.com/packages/working-with-a-github-packages-registry/working-with-the-container-registry) with this identifier: [`ghcr.io/CSSUoB/tex-bot-py-v2:latest`](https://github.com/CSSUoB/TeX-Bot-Py-V2/pkgs/container/tex-bot-py-v2). -([Here is an introduction](https://docs.docker.com/get-started/08_using_compose) on how to use a [docker-compose deployment](https://docs.docker.com/compose).) -See [**Versioning**](#versioning) for the full list of available version tags for each release. - -Before running the [container](https://docs.docker.com/resources/what-container), some [environment variables](https://wikipedia.org/wiki/Environment_variable) will need to be set. -These can be defined in your [`compose.yaml`](https://docs.docker.com/compose/compose-application-model#the-compose-file) file. -The required [environment variables](https://wikipedia.org/wiki/Environment_variable) are explained within [the "Setting Environment Variables" section](#setting-environment-variables). - -## Local Deployment - -### Installing Dependencies - -1. Ensure that you have [uv](https://docs.astral.sh/uv/getting-started/installation) installed -2. Navigate to this project's repository root folder -3. To install the required dependencies, execute the following command: - -```shell -uv sync -``` - -> [!TIP] -> Syncing the dependencies is not required. uv performs this automatically every time the `uv run` command is used - -### Creating Your [Bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) - -A full guide on how to create your bot's account can be found [here; on Pycord's wiki](https://docs.pycord.dev/en/stable/discord.html). - -You'll need to create a [Discord bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) of your own in the [Discord Developer Portal](https://discord.com/developers/applications). -It's also handy if you have an empty [Discord guild](https://discord.com/developers/docs/resources/guild) for you to test in. - -The correct [invite URL](https://docs.pycord.dev/en/stable/discord.html#inviting-your-bot) will be displayed to you in the console the first time you run the bot (or if you set a high verbosity log level) - -### Setting [Environment Variables](https://wikipedia.org/wiki/Environment_variable) - -You'll also need to set a number of [environment variables](https://wikipedia.org/wiki/Environment_variable) before running TeX-Bot: - -* `DISCORD_BOT_TOKEN`: The [Discord bot secret token](https://itexus.com/glossary/discord-bot-token) for the [instance of TeX-Bot](https://discord.com/developers/docs/topics/oauth2#bot-vs-user-accounts) you created. - * The [Discord bot token](https://itexus.com/glossary/discord-bot-token) is available on [your bot's page in the Discord Developer Portal](https://discord.com/developers/applications). - -* `DISCORD_GUILD_ID`: The [ID](https://discord.com/developers/docs/reference#snowflakes) of your community group's [Discord guild](https://discord.com/developers/docs/resources/guild). - -* `DISCORD_LOG_CHANNEL_WEBHOOK_URL`: The [webhook URL](https://support.discord.com/hc/articles/228383668-Intro-to-Webhooks) of the [Discord text channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel) where error log messages should be sent. - * This setting is optional. - Error logs will **always** be sent to the [console](https://wikipedia.org/wiki/Terminal_emulator), this setting just allows them to also be sent to a [Discord log channel](https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel). - -* `ORGANISATION_ID`: Your SU platform organisation ID. This is used to dynamically create the members list and other needed URLs. - -* `SU_PLATFORM_ACCESS_COOKIE`: The SU platform [access session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie). - * This [session cookie](https://wikipedia.org/wiki/HTTP_cookie#Session_cookie) will [authenticate](https://wikipedia.org/wiki/Authentication) TeX-Bot to view your group's members list on the SU platform, as if it were [logged in to the website](https://wikipedia.org/wiki/Login_session) as a Committee member. - * This can be [extracted from your web-browser](https://wikihow.com/View-Cookies), after logging in to view your members list yourself. - It will most likely be listed as a [cookie](https://wikipedia.org/wiki/HTTP_cookie) named `.AspNet.SharedCookie`. - * If you wish to test TeX-Bot with the SU platform-access disabled, a dummy value of 128 `0` characters can be used. - Note that this will cause many commands and scheduled tasks to fail when they are used at runtime. - -You can put these [variables](https://wikipedia.org/wiki/Environment_variable) in a [`.env` file](https://blog.bitsrc.io/a-gentle-introduction-to-env-files-9ad424cc5ff4) in the root folder, as [python-dotenv](https://saurabh-kumar.com/python-dotenv) is used to collect all [environment variables](https://wikipedia.org/wiki/Environment_variable). -There is an [`.env.example` file](.env.example) in the repo that you can rename and populate. - -There are also many other configuration settings that can be changed to alter the behaviour of TeX-Bot. -These are all listed in [the `.env.example` file](.env.example), along with the behaviours that will be affected. - -Any [variables](https://wikipedia.org/wiki/Environment_variable), in [the `.env.example` file](.env.example), marked with `# !!REQUIRED!!` must be set before running TeX-Bot. -All other [variables](https://wikipedia.org/wiki/Environment_variable) are optional and their default values are shown as the example value for each variable in [the `.env.example` file](.env.example). - -### Running The Bot +| `send_introduction_reminders` | `SEND_INTRODUCTION_REMINDERS`:
* `Once` - Only send the introduction reminder once (even if they later delete the message)
* `Interval` - Send an introduction reminder at a set interval
* `False` - Do not send introduction reminders | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not been inducted (does not have the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) joined your community's guild is greater than `SEND_INTRODUCTION_REMINDERS_DELAY`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not opted out of introduction reminders
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent an introduction reminder. (Only applies when `SEND_INTRODUCTION_REMINDERS` is set to the value `Once`) | The interval of time between this task running is determined by `SEND_INTRODUCTION_REMINDERS_INTERVAL`. (When `SEND_INTRODUCTION_REMINDERS` is set to the value `Once`, all [Discord members](https://discord.com/developers/docs/resources/guild#guild-member-object) will still be checked at this interval, just not sent a message if they have already been sent an introduction reminder). The default interval is to send messages every 6 hours | +| `send_get_roles_reminders` | `SEND_GET_ROLES_REMINDERS`:
* `True` - A single reminder for the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) will be sent to them only once (even if they later delete the message)
* `False` - Do not send any reminders for [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | * The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has been inducted (has the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object))
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) does not have any of the opt-in [roles](https://discord.com/developers/docs/topics/permissions#role-object). (E.g. "@**First Year**" or "@**Anime**".) (Having the green "@**Member**" [role](https://discord.com/developers/docs/topics/permissions#role-object) or even the "@**Committee**" [role](https://discord.com/developers/docs/topics/permissions#role-object) makes no difference)
* The time since the [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) was inducted (gained the "@**Guest**" [role](https://discord.com/developers/docs/topics/permissions#role-object)) is greater than `SEND_GET_ROLES_REMINDERS_DELAY`
* The [Discord member](https://discord.com/developers/docs/resources/guild#guild-member-object) has not yet been sent a reminder to get [roles](https://discord.com/developers/docs/topics/permissions#role-object) | The interval of time between this task running is determined by `ADVANCED_SEND_GET_ROLES_REMINDERS_INTERVAL`. It is unlikely that this value will need to be changed from the default of 24 hours | +| `su_platform_access_cookie_check_task` | `AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING`:
* `True` - Regularly check whether the `SU_PLATFORM_ACCESS_COOKIE` is still valid & log the result
* `False` - Do not automatically check the `SU_PLATFORM_ACCESS_COOKIE` (this is the default) | None (this [task](TERMINOLOGY.md#tasks) does not send any messages to [Discord members](https://discord.com/developers/docs/resources/guild#guild-member-object)) | The interval of time between this task running is determined by `AUTO_SU_PLATFORM_ACCESS_COOKIE_CHECKING_INTERVAL`. The default interval is 24 hours | -Once everything is set up, you should be able to execute the following command to automatically run TeX-Bot & connect it to your [Discord guild](https://discord.com/developers/docs/resources/guild): +## Deployment -```shell -uv run -m main -``` +The full guide on how to deploy TeX-Bot can be found in [DEPLOYMENT.md](DEPLOYMENT.md). +This includes [deploying TeX-Bot in production](DEPLOYMENT.md#deploying-in-production) using our pre-built [docker container](https://docker.com/resources/what-container), as well as [deploying TeX-Bot locally](DEPLOYMENT.md#local-deployment) for development & testing. ## Contributing @@ -206,7 +145,7 @@ This will ensure your code meets the standard required for this project and give This project follows the [semantic versioning scheme](https://semver.org). We currently treat TeX-Bot as alpha software, and as such no numbered release has been made yet. -When selecting a version tag to use for [deploying TeX-Bot as a container image](#deploying-in-production) there are multiple tag schemes available: +When selecting a version tag to use for [deploying TeX-Bot as a container image](DEPLOYMENT.md#deploying-in-production), there are multiple tag schemes available: * `latest` - The most recent numerically tagged version released * `br-` - The most recent commit from a given branch in this repository (E.g. `br-main`) (N.B. this does not include branches of forks of this repository) diff --git a/TERMINOLOGY.md b/TERMINOLOGY.md new file mode 100644 index 000000000..46b42c280 --- /dev/null +++ b/TERMINOLOGY.md @@ -0,0 +1,95 @@ +# TeX-Bot-Py-V2 Terminology + +## ["Guild"](https://discord.com/developers/docs/resources/guild) Vs ["Server"](https://wikipedia.org/wiki/Discord#Servers) + +Confusingly, [Discord](https://discord.com) uses the term ["guild"](https://discord.com/developers/docs/resources/guild) to refer to a [Discord "server"](https://wikipedia.org/wiki/Discord#Servers), when communicating with developers. +Therefore, the same terminology (["guild"](https://discord.com/developers/docs/resources/guild)) will be used across all documentation in this project. +(See [the Discord developer docs](https://discord.com/developers/docs/resources/guild) & [Pycord's docs](https://docs.pycord.dev/en/stable/api/models.html#discord.Guild) for more information.) + +The term "main guild" is used throughout the code in this repository to refer specifically to your community group's main [Discord guild](https://discord.com/developers/docs/resources/guild). + +## "User" Vs "Member" Vs "Guest" + +### [Discord Objects](https://discord.com/developers/docs) + +In the context of [Discord](https://discord.com) itself, a ["user"](https://discord.com/developers/docs/resources/user) object represents a [Discord](https://discord.com) account not connected to any specific [guild](https://discord.com/developers/docs/resources/guild). +Therefore, it can be [messaged via DM](https://dictionary.com/browse/dm) or be retrieved via its [snowflake ID](https://discord.com/developers/docs/reference#snowflakes), but little else can be done with it. +(See [the Discord developer docs](https://discord.com/developers/docs/resources/user) & [Pycord's docs](https://docs.pycord.dev/en/stable/api/models.html#users) for more information.) + +In contrast, a [Discord "member" object](https://discord.com/developers/docs/resources/guild#guild-member-object) is a [user](https://discord.com/developers/docs/resources/user) attached to a specific [guild](https://discord.com/developers/docs/resources/guild). +Therefore, it can have [roles](https://discord.com/developers/docs/topics/permissions#role-object), be [banned](https://discord.com/developers/docs/resources/guild#ban-object) and have many other actions applied to it. +(See [the Discord developer docs](https://discord.com/developers/docs/resources/guild#guild-member-object) & [Pycord's docs](https://docs.pycord.dev/en/stable/api/models.html#discord.Member) for more information.) + +### Community Group Membership + +In the context of your community group's membership structure, a "member" is a person that has purchased a membership to join your community group. +This is in contrast to a "guest", which is a person that has not purchased a membership. +Guests often can only attend events that are open to anyone (i.e. **not** members only), and have limited communication/perks within your [Discord guild](https://discord.com/developers/docs/resources/guild). +Some commands may require you to create [roles](https://discord.com/developers/docs/topics/permissions#role-object) within your [Discord guild](https://discord.com/developers/docs/resources/guild), to differentiate between these different types of users. + +### Other Uses + +In some other contexts, the term "user" may be used to refer to any person/organisation making use of this project. +(E.g. the description within [the "Error Codes" section](README.md#error-codes).) + +## [Interactions](https://discord.com/developers/docs/interactions/overview) + +Interactions in Discord are a way for bots to communicate with users in a structured and interactive manner. +They are the initial entry point to allow users to begin interacting with the bot. +(Note that a Discord bot's functionality could also be triggered via non-interaction methods like scheduled tasks or event handlers.) +The primary types of interactions are: + +1. **Application Commands**: These include [Slash Commands](#slash-commands), [Message Commands](#message-commands), and [User Commands](#user-commands). + They are predefined commands that users can invoke to perform specific actions. +2. **Message Components**: These are interactive elements, like buttons and select menus, that can be attached to messages to provide a richer user experience. +3. **Modal Submissions**: These are forms that users can fill out and submit, allowing bots to collect structured input from users, though TeX-Bot does not currently make use of these. + +For more details, refer to the [Discord Developer Documentation on Interactions](https://discord.com/developers/docs/interactions/overview). + +## [Application Commands](https://discord.com/developers/docs/interactions/application-commands) + +An [Application Command](https://discord.com/developers/docs/interactions/application-commands) can be a [Slash Command](#slash-commands), [Message Command](#message-commands) or [User Command](#user-commands). +Within this project, the term "command" is used to refer to any type of [Application Command](https://discord.com/developers/docs/interactions/application-commands). +For example usages, check the [Guides section](CONTRIBUTING.md#guides) of the [CONTRIBUTING.md document](CONTRIBUTING.md). + +### [Slash Commands](https://discord.com/developers/docs/interactions/application-commands#slash-commands) + +Slash commands are executed by typing a slash (/) followed by the command name in the message input. +They are made up of a name, description and a set of options. +These can be defined using the `@discord.slash_command()` decorator. +Bots are limited to 100 slash commands. + +### Context Commands + +Context commands are triggered via a UI context menu that appears when right-clicking on a [User](https://discord.com/developers/docs/resources/user) or [Message](https://discord.com/developers/docs/resources/message). +They do not take user-defined arguments, and instead receive the context that was clicked. +These can be defined using the `@discord.user_command()` or `@discord.message_command()` decorators. +Bots are limited to 15 [Message Commands](#message-commands) and 15 [User Commands](#user-commands). + +#### [Message Commands](https://discord.com/developers/docs/interactions/application-commands#message-commands) + +Message-context commands are executed via right-clicking on a [Discord message](https://discord.com/developers/docs/resources/message), clicking "Apps", then selecting the command from the menu. +The interaction callback method is provided information about which message was clicked, along with which user clicked it. + +#### [User Commands](https://discord.com/developers/docs/interactions/application-commands#user-commands) + +User-context commands are executed via right-clicking on a [Discord user](https://discord.com/developers/docs/resources/user), clicking "Apps", then selecting the command from the menu. +The interaction callback method is provided information about which user was clicked, along with which user clicked it. + +## [Events](https://guide.pycord.dev/getting-started/more-features#event-handlers) + +Events are notifications sent from [Discord](https://discord.com) to TeX-Bot whenever something happens within your [Discord guild](#guild-vs-server). +(E.g. a [Discord member](#discord-objects) joining your [Discord guild](#guild-vs-server), or a [Discord member's](#discord-objects) [roles](https://discord.com/developers/docs/topics/permissions#role-object) being changed.) +Unlike [interactions](#interactions), events are not directly triggered by a user asking TeX-Bot to do something. + +### Event Listeners + +An event listener is a method that TeX-Bot calls every time a specific [event](#events) occurs. +Event listeners are defined within cogs using the `@TeXBotBaseCog.listener()` decorator, and the method must be named after the [event](#events) it listens for (E.g. `on_member_update`). +(See [Pycord's docs](https://docs.pycord.dev/en/stable/api/events.html) for the full list of [events](#events) that can be listened for.) + +## [Tasks](https://docs.pycord.dev/en/stable/ext/tasks) + +Tasks are methods that TeX-Bot runs automatically at a repeated, scheduled interval, rather than in response to an [interaction](#interactions) or an [event](#events). +These can be defined within cogs using the `@tasks.loop()` decorator. +(See [the "Repeated Tasks Conditions" section](README.md#repeated-tasks-conditions) for the list of tasks within TeX-Bot, along with the conditions required for each one to run.)