djsbotbuilder v1.0.0
djsbotbuilder
A Discord bot builder library using discord.js.
Features
- Easy bot initialization
- Database interaction
- Error handling
Installation
npm install djsbotbuilder
Setup
Project Structure
Your bot project should have the following structure:
/my-bot
|-- /commands
|-- /events
|-- index.js
|-- config.json or .env
- The
/commands
directory should contain your command files. Each command should be a js file that exports an object with adata
property (aCommandData
object) and anexecute
function. - The
/events
directory should contain your event files. Each event should be a js file that exports an object with aname
property (the event name) and anexecute
function. - The
index.js
file is the entry point for your bot. It should import theInit
class fromdjsbotbuilder
and callInit.runBot()
.
index.js
Here's a basic index.js
file:
const { Init } = require('djsbotbuilder');
Init.runBot();
Init.runBot()
The Init.runBot()
method initializes and runs your bot. It does the following:
- Gets the configuration from environment variables or a
config.json
file. - Creates a new Discord client with the necessary intents.
- Loads the commands from the commands directory and deploys them to your bot.
- Loads the events from the events directory and attaches them to the client.
- Logs the bot in with the token from the configuration.
You can pass an options object to Init.runBot()
to override the token and directories from the configuration:
Init.runBot({
token: 'my-token',
commandsDir: './my-commands',
eventsDir: './my-events'
});
Modules
Init
The Init
class uses either environment variables or a config.json
file for configuration. If a TOKEN
environment variable is found, it will use environment variables. Otherwise, it will look for a config.json
file in the project root.
Methods
runBot(options = {})
Use this method to start the bot. It takes an optional options
object as a parameter, which can contain the following properties:
token
: The bot's token. Use only for troubleshooting purposes. If not provided, the method will use theTOKEN
from the configuration.
This method does the following:
- It gets the configuration using the
getConfig
method. - It creates a new
Client
instance from discord.js with the necessary intents. - It loads the commands using the
getCommands
method and assigns them to thecommands
property of the client. - It deploys the commands using the
deployCommands
method. - It loads the events using the
loadEvents
method. - It logs the bot in using the provided token or the token from the configuration.
ErrorHandler
The ErrorHandler
class is used to handle errors in your bot. It provides a static method errorEmbed
that creates an error embed message.
Sure, here's how you might document the ErrorHandler
class in your README.md:
errorEmbed(interaction, errorMessage)
This method takes two parameters:
interaction
: The interaction that caused the error. This should be aCommandInteraction
object from discord.js.errorMessage
: The error message to display in the embed.
The method does the following:
- If the interaction has a message with an embed, it uses that embed as the base for the error embed. Otherwise, it creates a new embed.
- It filters out any fields in the original embed with the name 'Error'.
- It creates a new embed with the same properties as the original embed, sets the color to red, adds the filtered fields, and adds a new field with the name 'Error' and the error message as the value.
Here's how you can use the errorEmbed
method:
const { ErrorHandler } = require('djsbotbuilder');
// In your command execute function...
try {
// Your command code...
} catch (error) {
const errorEmbed = ErrorHandler.errorEmbed(interaction, error.message);
interaction.reply({ embeds: [errorEmbed] });
}
Databases
The Databases
class is used to manage your database configuration, models, and operations. It provides methods to initialize the database, add models, and create models.
Importing the Class
First, you need to import the Databases
class into your file:
const Databases = require('djsbotbuilder');
Creating an Instance
Next, create an instance of the Databases
class. The constructor accepts an array of model paths:
const databases = new Databases(['./models/User.js', './models/Post.js']);
When you create an instance of the Databases
class, you're setting up the necessary components to interact with your database using Sequelize.
Initializing the Database
After creating an instance, you can initialize the database using the init
method:
databases.init();
This method is responsible for initializing the Sequelize instance and establishing a connection to the database. It also loads and synchronizes the models with the database.
Sequelize Initialization: The
init
method initializes Sequelize with the configuration loaded by theDatabaseConfig
instance. This includes database credentials and other settings.Database Connection: After initializing Sequelize, the
init
method establishes a connection to the database. If the connection is successful, Sequelize is ready to be used for database operations.Model Loading: The
init
method also triggers the loading of models by theModelManager
instance. These models represent tables in your database and are used for CRUD operations.Model Synchronization: Finally, the
init
method synchronizes the models with the database. This means that Sequelize will create the necessary tables in your database if they don't exist. This behavior can be customized based on your needs.
Remember, the init
method should be called after creating an instance of the Databases
class and before performing any database operations.
Adding a Model
To add a model to the ModelManager
instance, use the addModel
method. This method takes a model path as a parameter:
databases.addModel('./models/Guilds.js');
What is a Model?
In the context of Sequelize and this project, a model is a representation of a table in the database. Each model corresponds to a table in the database and defines the structure of the columns (or attributes) within that table. Models are used to perform CRUD (Create, Read, Update, Delete) operations on their corresponding tables.
How to Add a Model
To add a model, you use the addModel
method. This method takes a model path as a parameter. The model path is the relative path to the JavaScript file that defines the model. Here's an example of how to use it:
databases.addModel('./models/Guilds.js');
In this example, Guilds.js
is a JavaScript file in the models
directory that exports a Sequelize model representing the Guilds
table in the database.
example of a model file:
const Sequelize = require('sequelize');
const sequelize = require('../database');
const Guild = sequelize.define('guild', {
id: {
type: Sequelize.STRING,
primaryKey: true,
},
welcomeChannelId: {
type: Sequelize.STRING,
allowNull: true,
},
welcomeRoleId: {
type: Sequelize.STRING,
allowNull: true,
},
});
module.exports = Guild;
addModel
The addModel
method in the Databases
class is responsible for adding a new model to the ModelManager
instance. Here's a high-level overview of what happens when you call this method:
Model Loading: The
addModel
method loads the model from the provided path using Node'srequire
function. This model is a JavaScript object that defines the structure of a table in the database.Model Registration: After loading the model, the
addModel
method adds it to theModelManager
instance. TheModelManager
maintains a registry of all loaded models, which can be accessed and used for database operations.Database Synchronization: Finally, the
addModel
method synchronizes the newly added model with the database using Sequelize'ssync
method. This means that if the table represented by the model does not exist in the database, Sequelize will create it.
Remember, the addModel
method should be called after initializing the Databases
instance and connecting to the database.
Creating a Model
To create a model using the ModelCreator
instance, use the createModel
method:
databases.createModel();
Creating a Model with the createModel
Method
The createModel
method simplifies the process of creating a new Sequelize model. This method prompts the user for input in the terminal to gather the necessary information to create the model.
Model Name: This name is used as the class name for the model and also to name the file that will contain the model definition.
Model Attributes: The method then enters a loop where it continually prompts the user to enter attribute names and types for the model. This continues until the user enters "done" as the attribute name. Each attribute represents a column in the database table that the model will map to.
Once all the necessary information has been gathered, the method generates a string of JavaScript code that defines a Sequelize model with the provided name and attributes. This code is then written to a new file in the models
directory.
Remember, the createModel
method should be used when you want to create a new model. After creating the model, you can add it to the ModelManager
instance using the addModel
method.
CRUD Operations
####IN DEVELOPMENT
The Databases
class also provides methods for CRUD operations. These methods are used to create, read, update, and delete data in the database.
databases.create();
databases.read();
databases.update();
databases.delete();
Dependencies
- discord.js
- dotenv
- sequelize
- esprima
- estraverse
License
ISC
5 months ago