# djsbotbuilder

> 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.

Latest version **1.0.4** (published 2024-05-26) · MIT license · 0 weekly downloads

## Install

```sh
npm install djsbotbuilder
pnpm add djsbotbuilder
yarn add djsbotbuilder
bun add djsbotbuilder
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.0.4 |
| Published | 2024-05-26 |
| First published | 2023-12-23 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 6 |
| Unpacked size | 29.1 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | System Wolf |
| Maintainers | sowerofsystems |
| Keywords | discord.js, bot, discord bot, bot builder, bot development, discord.js library, discord bot library, discord bot builder, discord bot development, database interaction, error handling, bot initialization, sequelize |

## Links

- npm: https://www.npmjs.com/package/djsbotbuilder
- npm.io page: https://npm.io/package/djsbotbuilder

## Dependencies (6)

- [dotenv](https://npm.io/package/dotenv.md) ^16.3.1
- [esprima](https://npm.io/package/esprima.md) ^4.0.0
- [sqlite3](https://npm.io/package/sqlite3.md) ^5.1.6
- [sequelize](https://npm.io/package/sequelize.md) ^6.35.2
- [discord.js](https://npm.io/package/discord.js.md) ^14.14.1
- [estraverse](https://npm.io/package/estraverse.md) ^5.3.0

## Alternatives

- [@libsql/sqlite3](https://npm.io/package/@libsql/sqlite3.md) — 39.8K weekly downloads
- [@fortemi/core](https://npm.io/package/@fortemi/core.md) — 461 weekly downloads
- [cdb-converter](https://npm.io/package/cdb-converter.md) — 341 weekly downloads
- [@uplo/adapter-prisma](https://npm.io/package/@uplo/adapter-prisma.md) — 75 weekly downloads
- [typeorm-aios](https://npm.io/package/typeorm-aios.md) — 30 weekly downloads

## Recent versions

- 1.0.4 (latest) — 2024-05-26
- 1.0.3 — 2024-05-26
- 1.0.1 — 2024-05-21
- 1.0.0 — 2023-12-23

## README

# djsbotbuilder

A Discord bot builder library using discord.js.

## Features

- Easy bot initialization
- Database interaction
- Error handling

## Installation

```sh
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 a `data` property (a `CommandData` object) and an `execute` function.
- The `/events` directory should contain your event files. Each event should be a js file that exports an object with a `name` property (the event name) and an `execute` function.
- The `index.js` file is the entry point for your bot. It should import the `Init` class from `djsbotbuilder` and call `Init.runBot()`.

#### index.js

Here's a basic `index.js` file:

```js
const { Init } = require('djsbotbuilder');

Init.runBot();
```

#### Init.runBot()

The `Init.runBot()` method initializes and runs your bot. It does the following:

1. Gets the configuration from environment variables or a `config.json` file.
2. Creates a new Discord client with the necessary intents.
3. Loads the commands from the commands directory and deploys them to your bot.
4. Loads the events from the events directory and attaches them to the client.
5. 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:

```js
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 the `TOKEN` from the configuration.

This method does the following:

1. It gets the configuration using the `getConfig` method.
2. It creates a new `Client` instance from discord.js with the necessary intents.
3. It loads the commands using the `getCommands` method and assigns them to the `commands` property of the client.
4. It deploys the commands using the `deployCommands` method.
5. It loads the events using the `loadEvents` method.
6. 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 a `CommandInteraction` object from discord.js.
- `errorMessage`: The error message to display in the embed.

The method does the following:

1. 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.
2. It filters out any fields in the original embed with the name 'Error'.
3. 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:

```js
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:

```js
const Database = require('djsbotbuilder');
```

#### Creating an Instance

Next, create a database. The constructor accepts an array of model paths:

```js
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:

```js
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.

1. **Sequelize Initialization**: The `init` method initializes Sequelize with the configuration loaded by the `DatabaseConfig` instance. This includes database credentials and other settings. If `dbconfig.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`). A `dbconfig.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. a `dbconfing.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 typically `localhost` 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.

```js
//example dbconfig.json
{
  "database": ["my_database"],
  "username": ["my_username"],
  "password": ["my_password"],
  "host": "localhost",
  "dialect": ["database type"],
  "storage": ["./database.sqlite"]
}
```

2. **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.

3. **Model Loading**: The `init` method also triggers the loading of models by the `ModelManager` instance. These models represent tables in your database and are used for CRUD operations.

4. **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:

```js
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.

```javascript
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:

```js
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.

1. **Model Loading**: Loads the model from the provided path as a JavaScript object that defines the structure of a table in the database.

2. **Model Registration**: Adds the model to the `ModelManager` instance. The `ModelManager` maintains a registry of all loaded models, which can be accessed and used for database operations.

3. **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

```js
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.

1. **Model Name**: Used as the class name for the model and also to name the file.

2. **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.

```js
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.*

---
_Source: https://npm.io/package/djsbotbuilder · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
