A big welcome and thank you for considering contributing to CSS' open-source projects! We welcome anybody who wants to contribute, and we actively encourage everyone to do so, especially if you have never contributed before.
- Getting Started
- Using the Issue Tracker
- Repository Structure
- Making Your First Contribution
- License
- Guidance
If you have never used Git before, we would recommend that you read GitHub's Getting Started guide. Additionally, linked below are some helpful resources:
If you are new to contributing to open-source projects on GitHub, the general workflow is as follows:
- Fork this repository and clone it
- Create a branch off main
- Make your changes and commit them
- Push your local branch to your remote fork
- Open a new pull request on GitHub
We recommend also reading the following if you're unsure or not confident:
TeX-Bot is written in Python using Pycord and uses Discord's slash-commands & user-commands. We would recommend being somewhat familiar with the Pycord library, Python language & project terminology before contributing.
We use GitHub issues to track bugs and feature requests. If you find an issue with TeX-Bot, the best place to report it is through the issue tracker. If you are looking for issues to contribute code to, it's a good idea to look at the issues labelled "good-first-issue"!
When submitting an issue, please be as descriptive as possible. If you are submitting a bug report, please include the steps to reproduce the bug, and the environment it is in. If you are submitting a feature request, please include the steps to implement the feature.
main.py: is the main entrypoint to instantiate theBotobject & run itexceptions/: contains common exception subclasses that may be raised when certain errors occurconfig.py: retrieves the environment variables and populates the correct values into thesettingsobject
cogs/: contains all the cogs within this project, see below for more informationutils/: contains common utility classes and functions used by the top-level modules and cogsdb/core/models/: contains all the database ORM models to interact with storing information longer-term (between individual command events)tests/: contains the complete test suite for this project, based on the Pytest framework
Cogs are attachable modules that are loaded onto the Bot instance.
They combine related listeners and commands (each as individual methods) into one class.
There are separate cog files for each activity, and one __init__.py file which instantiates them all:
For more information about the purpose of each cog, please look at the documentation within the files themselves
-
cogs/__init__.py: instantiates all the cog classes within this directory -
cogs/annual_handover_and_reset.py: cogs for annual handover procedures and role resets -
cogs/archive.py: cogs for archiving categories of channels within your group's Discord guild -
cogs/command_error.py: cogs for sending error messages when commands fail to complete/execute -
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 for editing messages that were previously sent by TeX-Bot -
cogs/get_token_authorisation.py: cogs for retrieving the current status of the supplied authentication token -
cogs/induct.py: cogs for inducting people into your group's Discord guild -
cogs/kill.py: cogs related to the shutdown of TeX-Bot -
cogs/make_applicant: cogs related to making users into applicants -
cogs/make_member.py: cogs related to making guests into members -
cogs/ping.py: cog to request a ping response -
cogs/remind_me.py: cogs to ask TeX-Bot to send a reminder message at a later date -
cogs/send_get_roles_reminders.py: cogs relating to sending reminders, to Discord members, about opt-in roles. (See Repeated Tasks Conditions for which conditions are required to be met, to execute this task) -
cogs/send_introduction_reminders.py: cogs relating to sending reminders, to Discord members, about introducing themselves. (See Repeated Tasks Conditions for which conditions are required to be met, to execute this task) -
cogs/source.py: cogs for displaying information about the source-code of this project -
cogs/startup.py: cogs for startup & bot initialisation -
cogs/stats/: cogs for displaying stats about your group's Discord guild, as well as its channels & Discord members -
cogs/strike.py: cogs for applying moderation actions to Discord members -
cogs/write_roles.py: cogs relating to sending the message, that contains all the opt-in roles, into the "#roles" channel
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.
To ensure your changes adhere to the required functionality of this project, a test suite has been provided in the tests directory.
The test suite uses Pytest, and can be run with the following command:
uv run pytestPycharm & VS Code also provide GUI interfaces to run the Pytest test suite.
In general, follow the formatting in the file you are editing. You should also run the static analysis linting/type checking tools to validate your code.
Ruff is a static analysis code linter, which will alert you to possible formatting mistakes in your Python code. It can be run with the following command:
uv run ruff checkThere are many additional flags to provide more advanced linting help (E.g. --fix).
See ruff's documentation for additional configuration options.
Mypy is a static type checker, which will alert you to possible typing errors in your Python code. It can be run with the following command:
uv run mypy .Although there is a PyCharm plugin to provide GUI control and inline warnings for mypy, it has been rather temperamental recently. So it is suggested to avoid using it, and run mypy from the command-line instead.
PyMarkdown is a static analysis Markdown linter, which will alert you to possible formatting mistakes in your MarkDown files. It can be run with the following command:
uv run ccft-pymarkdown scan-all --with-gitThis command includes the removal of custom-formatted tables. See the CCFT-PyMarkdown tool for more information on linting Markdown files that contain custom-formatted tables.
Commit messages should be written in the imperative present tense. For example, "Fix bug #1".
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. (See Robert Painsi's Commit Message Guidelines for how to write good commit messages.)
For example:
Fix TeX becoming sentient
<more detailed description here>
Once you have made your changes, please describe them in your pull request in full. We will then review them and communicate with you on GitHub. We may ask you to change a few things, so please do check GitHub or your emails frequently.
After that, that's it! You've made your first contribution. 🎉
Please note that any contributions you make will be made under the terms of the Apache Licence 2.0.
We aim to get more people involved with our projects, and help build members' confidence in using git and contributing to open-source. If you see an error, we encourage you to be bold and fix it yourself, rather than just raising an issue. If you are stuck, need help, or have a question, the best place to ask is on our Discord.
Happy contributing!
Cogs are modular components of TeX-Bot that group related commands and listeners into a single class. To create a new cog, follow these steps:
-
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_cog.py).
- Navigate to the
-
Define the Cog Class
- Import the necessary modules, including
TeXBotBaseCogfromutils. - Define a class that inherits from
TeXBotBaseCog. - Add a docstring to describe the purpose of the cog.
Example:
from utils import TeXBotBaseCog class ExampleCog(TeXBotBaseCog): """A cog for demonstrating functionality.""" def do_something(arguments): print("do something")
- Import the necessary modules, including
-
Add Commands and Listeners
- Define methods within the class for commands and event listeners.
- Use decorators like
@discord.slash_command()or@TeXBotBaseCog.listener()to register the callback method to their interaction type. - Include any necessary checks using
CommandChecksdecorators.
Example:
import discord from utils import CommandChecks __all__: "Sequence[str]" = ( "ExampleCog", ) class ExampleCog(TeXBotBaseCog): """A cog for demonstrating functionality."""
-
Register the Cog
- Edit
cogs/__init__.pyto add your new cog class to the list of cogs in thesetupfunction. - Also, include the cog class in the
__all__sequence to ensure it is properly exported.
Example:
from .example_cog import ExampleCog __all__: "Sequence[str]" = ( ...existing cogs... "ExampleCog", ) def setup(bot: "TeXBot") -> None: """Add all the cogs to the bot, at bot startup.""" cogs: Iterable[type[TeXBotBaseCog]] = ( ...existing cogs... ExampleCog, ) Cog: type[TeXBotBaseCog] for Cog in cogs: bot.add_cog(Cog(bot))
- Edit
-
Test the Cog
- Run the bot with your changes and ensure the new cog is loaded without errors.
- Test the commands and listeners to verify they work as expected.
-
Document the Cog
- Add comments and docstrings to explain the functionality of the cog.
- Update the
CONTRIBUTING.mdfile or other relevant documentation if necessary.
To add a new environment variable to the project, follow these steps:
-
Define the Variable in development
.env- Open the
.envfile 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.
- Open the
-
Update
config.py- Open the
config.pyfile. - Add a new private setup method in the
Settingsclass to validate and load the variable. For example:@classmethod def _setup_new_variable(cls) -> None: raw_value: str | None = os.getenv("NEW_VARIABLE") if not raw_value or not re.fullmatch(r"<validation_regex>", raw_value): raise ImproperlyConfiguredError("NEW_VARIABLE is invalid or missing.") cls._settings["NEW_VARIABLE"] = raw_value
- Replace
<validation_regex>with a regular expression to validate the variable's format, if applicable.
- Open the
-
Call the Setup Method
- Add the new setup method to the
_setup_env_variablesmethod inconfig.py:@classmethod def _setup_env_variables(cls) -> None: if cls._is_env_variables_setup: logger.warning("Environment variables have already been set up.") return cls._settings = {} cls._setup_new_variable() # Add other setup methods here cls._is_env_variables_setup = True
- Add the new setup method to the
-
Document the Variable
- Update the
README.mdfile under the "Setting Environment Variables" section to include the new variable, its purpose and any valid values.
- Update the
-
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
.envfile, to confirm that error handling functions correctly.
Response buttons are interactive UI components that allow users to respond to bot messages with predefined actions. To create a response button, follow these steps:
-
Define the Button Class
- Create a new class in your cog file that inherits from
discord.ui.View. - Add button callback response methods using the
@discord.ui.buttondecorator. - Each button method should define the button's label, a custom response ID and style.
Example:
from discord.ui import View class ConfirmActionView(View): """A discord.View containing buttons to confirm or cancel an action.""" @discord.ui.button( label="Yes", style=discord.ButtonStyle.green, custom_id="confirm_yes", ) async def confirm_yes(self, button: discord.Button, interaction: discord.Interaction) -> None: # Handle the 'Yes' button click await interaction.response.send_message("Action confirmed.", ephemeral=True) @discord.ui.button( label="No", style=discord.ButtonStyle.red, custom_id="confirm_no", ) async def confirm_no(self, button: discord.Button, interaction: discord.Interaction) -> None: # Handle the 'No' button click await interaction.response.send_message("Action cancelled.", ephemeral=True)
- Create a new class in your cog file that inherits from
-
Send the View with a Message
- Use the
viewparameter of thesendorrespondmethod to attach the button view to a message. This could be sent in response to a command, event handler or scheduled task.
Example:
await ctx.send( content="Do you want to proceed?", view=ConfirmActionView(), )
- Use the
-
Handle Button Interactions
- Define logic within each button method to handle user interactions.
- Use
interaction.responseto send feedback or perform actions based on the button clicked.
-
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.
-
Document the Button
- Add comments and docstrings to explain the purpose and functionality of the button.
- Update relevant documentation if necessary.
When making changes to the database model, 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. 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 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:
-
Define a Model
- Navigate to the
db/core/models/directory. - Create a new Python file with a name that reflects the purpose of the model (e.g.,
example_model.py). - If your model is a new property related to each Discord member (E.g. the number of smiley faces of each Discord member, then define a class that inherits from
BaseDiscordMemberWrapper(found within the.utilsmodule within thedb/core/models/directory). - If your model is unrelated to Discord members, then define a class that inherits from
AsyncBaseModel(also found within the.utilsmodule within thedb/core/models/directory). - Add your Django fields to the class to represent the model's data structure.
- If your model inherits from
BaseDiscordMemberWrapperthen you must declare a field calleddiscord_memberwhich must be either a DjangoForeignKeyfield or aOneToOneField, 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 = "Members' Smiley Faces")
Example:
from django.db import models from .utils import AsyncBaseModel, BaseDiscordMemberWrapper class ExampleModel(AsyncBaseModel): """A model for demonstrating functionality.""" INSTANCES_NAME_PLURAL: str = "Example Model objects" name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) class MemberSmileyFaces(BaseDiscordMemberWrapper): """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.IntegerField( "Number of smiley faces", null=False, blank=True, default=0, )
- Navigate to the
-
Apply Migrations
- Run the following commands to create and apply migrations for your new model:
uv run manage.py makemigrations uv run manage.py migrate
- Run the following commands to create and apply migrations for your new model:
-
Query the Model
- Use Django's ORM to interact with the model. For example:
from db.core.models.example_model import ExampleModel class ExampleCog(TeXBotBaseCog): """A cog for demonstrating model access.""" async def create_example(self, name: str) -> None: """Create a new instance of ExampleModel.""" await ExampleModel.objects.acreate(name=name) async def retrieve_examples(self) -> list[ExampleModel]: """Retrieve all instances of ExampleModel.""" return await ExampleModel.objects.all() async def filter_examples(self, name: str) -> list[ExampleModel]: """Filter instances of ExampleModel by name.""" return await ExampleModel.objects.filter(name=name) async def update_example(self, example: ExampleModel, new_name: str) -> None: """Update the name of an ExampleModel instance.""" example.name = new_name await example.asave() async def delete_example(self, example: ExampleModel) -> None: """Delete an ExampleModel instance.""" await example.adelete()
- Use Django's ORM to interact with the model. For example:
-
Document the Model
- Add comments and docstrings to explain the purpose and functionality of your new model.
To retrieve members from the database using their hashed Discord ID, follow these steps:
-
Hash the Discord ID
- Use a consistent hashing algorithm to hash the Discord ID before storing or querying it in the database.
Example:
import hashlib def hash_discord_id(discord_id: str) -> str: return hashlib.sha256(discord_id.encode()).hexdigest()
-
Query the Database
- A custom filter field is implemented for models that inherit from
BaseDiscordMemberWrapper, this allows you to filter using the unhashed Discord ID, despite only the hashed Discord ID being stored in the database.
Example:
from db.core.models.member_smiley_faces import MemberSmileyFaces class MyExampleCommandCog(TeXBotBaseCog): @tasks.loop(minutes=5) async def check_member_smiley_faces(self) -> None: member_smiley_faces = await MemberSmileyFaces.objects.filter(discord_id=1234567).afirst() if member_smiley_faces: print(f"Member's smiley faces found: {member_smiley_faces.discord_member.name}") else: print("Member's smiley facesnot found.")
It is unlikely that you will need to query the
DiscordMembermodel directly. Instead, the attributes of the member can be accessed by the relationship between each new Django model to theDiscordMembermodel. - A custom filter field is implemented for models that inherit from
-
Test the Query
- Ensure the query works as expected by testing it with valid and invalid Discord IDs.
-
Document the Query
- Add comments and docstrings to explain the purpose and functionality of the query.