djsbotbuilder
v1.0.4
Published
A library designed to simplify the creation of Discord bots using discord.js. It provides a structured approach to bot development, with features for easy bot initialization, database interaction, and error handling.
Downloads
16
Maintainers
Readme
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 Database
class is used to manage your database configuration, models, and operations. It provides methods to initialize the database, add models, and create models.
Create a new file, for example initdb.js
, to contain the code to create your database.
Importing the Class
First, you need to import the Database
class into your file:
const Database = require('djsbotbuilder');
Creating an Instance
Next, create a database. The constructor accepts an array of model paths:
const db = new Database(['./models/User.js', './models/Post.js']);
When you create a database, you're setting up the necessary components to interact with your database using Sequelize.
Initializing the Database
After creating a database, you can initialize it using the init
method:
db.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. Ifdbconfig.json
exists then it is used, otherwise you will be asked whether you prefer basic or advanced setup.
basic
Provide the storage path (example:./my_database.sqlite
). Adbconfig.json
file will be created for a basic sqlite database.advanced
You will be asked for each of the values. If you leave any blank, they will not be included. adbconfing.json
file will be created for your database.database
: The name of the database that your application will connect to. For SQLite, this option is not used.username
: The username that your application will use to authenticate with the database server. For SQLite, this option is not used.password
: The password that your application will use to authenticate with the database server. For SQLite, this option is not used.host
: The address of the machine where the database server is running. This is typicallylocalhost
for a database server running on the same machine as your application, but it could be a different address if the database server is running elsewhere. For SQLite, this option is not used.dialect
: The type of database you're connecting to. This should be one of the following:mysql
,postgres
,sqlite
,mssql
,mariadb
. This option tells Sequelize which SQL language to generate behind the scenes when it communicates with the database.storage
: The path to the SQLite database file. This option is only used for SQLite databases. If the file does not exist, SQLite will create it. If it does exist, SQLite will use the existing file. For other types of databases, this option is not used.
//example dbconfig.json
{
"database": ["my_database"],
"username": ["my_username"],
"password": ["my_password"],
"host": "localhost",
"dialect": ["database type"],
"storage": ["./database.sqlite"]
}
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 Database
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:
db.addModel('./models/Guilds.js');
What is a Model?
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
The addModel
method takes a model path as a parameter. The model path is the relative path to the JavaScript file that defines the model.
db.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 Database
class is responsible for adding a new model to the ModelManager
instance.
Model Loading: Loads the model from the provided path as a JavaScript object that defines the structure of a table in the database.
Model Registration: Adds the model to the
ModelManager
instance. TheModelManager
maintains a registry of all loaded models, which can be accessed and used for database operations.Database Synchronization: Synchronizes the newly added model with the database. If the table represented by the model does not exist in the database, it will be created.
Remember, the addModel
method should be called after initializing the Database
instance and connecting to the database.
Creating a Model
Database.createModel();
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: Used as the class name for the model and also to name the file.
Model Attributes: The method will continually prompt the user to enter attribute names and types for the model until the user enters "done". Each attribute represents a column in the database table that the model will map to.
The model will be created in the models
directory by default.
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 database using the addModel
method.
CRUD Operations
IN DEVELOPMENT
The Database
class also provides methods for CRUD operations. These methods are used to create, read, update, and delete data in the database.
Database.create();
Database.read();
Database.update();
Database.delete();
Dependencies
- discord.js
- dotenv
- sequelize
- esprima
- estraverse
License
The MIT License (MIT)
Copyright (c) 2023 System Wolf Technology
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software.