npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

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

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

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:

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:

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.

  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.

//example dbconfig.json
{
  "database": ["my_database"],
  "username": ["my_username"],
  "password": ["my_password"],
  "host": "localhost",
  "dialect": ["database type"],
  "storage": ["./database.sqlite"]
}
  1. 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.

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

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

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

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.