Package Exports
- commandbot
Readme
CommandBot
WARNING! This README was created for CommandBot 3
A Discord.js based framework that makes creating Discord bots with support for slash commands easy and fast.
Features
- Support for slash commands
- Intuitive usage
- Good customization
- Permission system
- Built-in help command
- Built-in information messages
- Automatic error catching
- Large documentation in README and using JSDoc
- Written in TypeScript
Table of contents
Installation
System requirements
- Node.js 16.6.0 or newer
- npm or yarn package manager
Creating a project
Registering Discord app
- Visit Discord Developer Portal and create an app
- Navigate to the Bot section and register a bot
- Navigate to OAuth 2 section, select bot and application.commands scopes and check bot permissions
- Copy the link and add your bot to the servers
Creating application
- Create empty directory
- Run
npm init -y
oryarn init -y
- Add the CommandBot package
// npm
npm install commandbot@latest
// yarn
yarn add commandbot@latest
- Create index.js file
- Import the CommandBot package
// CommonJS
const { Bot, Command } = require("commandbot");
// ES Modules (to use ESM add "type": "module" to your package.json file)
import { Bot, Command } from "commandbot";
- Initialize the bot instance
const bot = new Bot({
name: "YOUR_BOT_NAME",
prefix: "BOT_PREFIX",
parameterSeparator: ",",
clientOptions: {
intents: [..."DISCORD_API_INTENTS"],
},
token: "DISCORD_BOT_TOKEN",
applicationId: "APPLICATION_ID",
});
Properties (* - required):
- name* - string - bot name
- prefix - string - bot prefix to use with text commands (if undefined, only slash commands will be available)
- parameterSeparator - string - used to separate parameters from messages (default: ',')
- clientOptions - ClientOptions - Discord.js client options
- token* - string - Discord bot token
- applicationId* - string - Discord application ID
- Create and add commands to the Bot instance (see Commands)
- Start your bot
bot.start(
port, // If passed, the application will create a HTTP server
true // If true or undefined, the app will register all slash commands in the Discord API
);
WARNING! All commands have to be added to the instance before starting the bot. Adding commands while the bot is running is not possible and can cause issues.
Commands
Creating and registering a command
To create a command, initialize a Command object
Example:
const cmdGreet = new Command({
name: "greet",
parameters: [
{
name: "name",
description: "Name that will be greeted",
optional: true,
type: "string",
},
],
aliases: ["hello"],
description: "Welcomes someone",
usage: "[name]",
permissionCheck: "ALL",
permissions: ["SEND_MESSAGES"],
guilds: undefined,
visible: true,
slash: true,
announceSuccess: true,
function: function(p. m) {
if(p('name')) {
return `Hello, ${p('name')}!`
}
else {
return 'Hello!'
}
}
});
// Register
bot.commands.add(cmdGreet)
Properties (* - required):
- name* - string - command name
- parameters - ParameterSchema[] - array of parameters (see Parameters)
- aliases - string | string[] - array of alternative strings that can call this command (not available for slash commands)
- description - string - command description
- usage - string - command usage visible in the help message (if not defined, usage string will be automatically generated based on defined parameters)
- permissionCheck - "ALL" | "ANY" - whether to check if caller has all defined permission or at least one of them
- permissions - PermissionResolvable | (m?: Message | CommandInteraction) => boolean - permissions required to run this command
- guilds - string[] - array of servers IDs in which this command will be available (if slash command)
- visible - boolean - whether this command is visible in the help message
- slash - boolean - whether this command should be registered as a slash command
- announceSuccess - boolean - whether a command reply should be sent automatically if no other response is defined or the reply should be deleted
- function* - (p: function, m?: Message | CommandInteraction) => void | MessageEmbed | string | ReplyMessageOptions - function that will be executed on call
Register your command in bot client using:
bot.commands.add(cmd);
where (* - required):
- cmd - Command
Command function
Arguments
- p - function - call this function with parameter name to fetch parameter value
- m? - Message | CommandInteraction - interaction object
Return value
If function returns (also after resolving a Promise):
- void - If announceSuccess property is true, bot will automatically send a SUCCESS message (see Messages). If command has been called using slash commands and announceSuccess property is set to false, reply will be automatically deleted
- string - this string will be sent in a reply
- MessageEmbed - embedded content will be sent in a reply
- ReplyMessageOptions - these options will get used to send a reply
It is possible to manually send replies directly from the command function using the m argument. If you are using slash commands don't forget to use the editReply method instead of the reply method since a reply is already deferred when a command function is being called (read more here) If you try to create a new reply, you app will throw an error that will result a crash. If you manually reply to a slash command interaction and return void from the command function, a SUCCESS message will not be sent or reply will not get deleted (if you want to disable SUCCESS messages on prefix interactions set announceSuccess property to false).
Errors
If a command function will throw an error, it will automatically get caught and your bot will send an ERROR message (see Messages). The app will not crash.
Parameters
Types
- string - text value
- boolean - True or False
- number - number (double) value
- user - ObjectID object with ID value (shown as selection menu in Discord)
- role - ObjectID object with ID value (shown as selection menu in Discord)
- channel - ObjectID object with ID value (shown as selection menu in Discord)
- mentionable - ObjectID object with ID value (shown as selection menu in Discord)
To get an entity ID from ObjectID use the value property. You can also call toObject method to retrieve full entity object from Discord API
ObjectID.toObject(g, "TYPE");
where (* - required):
- g* - Guild - Guild object to fetch from
- "TYPE"* - "user' | "role" | "channel" - defines the entity type
Defining
Example:
{
name: "user",
description: "User to mention",
optional: false,
type: "user"
}
Properties (* - required):
- name* - string - parameter name
- description - string - parameter description
- optional* - boolean - whether this parameter is optional
- type* - "string" | "boolean" | "number" | "user" | "role" | "channel" | "mentionable" - parameter type
- choices - string[] - parameter value choices (to use this, set type to "string")
Reading input value
To read parameter values use a function that is passed in the first argument of a call function (defined in function parameter in Command object)
p(query, returnType);
where (* - required):
- query* - string - parameter name
- returnType - "value" | "object" - whether to return only parameter value or a full object
function: (p, m) => {
const userObj = p('user')
if(userObj) {
const user = user.toObject(m.guild, "user");
if(user) {
return `Hello, ${user.toString()}`
}
else {
throw new Error('User not found')
}
}
}
Events
Handling events
CommandBot is using EventEmitter that is built into Node.js. You can listen to events using the on method.
bot.on(eventType, callbackFn);
where (* - required):
- eventType* - "READY" | "COMMAND" | "MESSAGE" | "ERROR" - type of event that you want to listen to
- callbackFn* - Function - a function that will get executed when the event is emitted
Event types
- READY - emitted when the app has finished its initialization process
- MESSAGE - emitted when message is created (similar to messageCreate event from Discord.js) (not emitted when command gets triggered) - a Message object is being passed to the first argument
- COMMAND - emitted when command gets triggered - a Message or CommandInteraction object is being passed to the first argument; an object containing fetched Command object and input parameters is being passed to the second
- ERROR - emitted when a command function throws an error - an Error object is being passed to the first argument
Messages
Information messages
There are 4 information messages:
- ERROR - "An error occurred" message (sent when error occurs)
- SUCCESS - "Task completed successfully" message (sent after successfully executing a command function)
- PERMISSION - "Insufficient permissions" message (sent when the caller doesn't have enough permissions)
- NOT_FOUND - "Command not found" message (sent when someone tries to call a command that does not exist)
Their configuration is stored in messages.system property.
Each of these messages can be customized with these properties (* - required):
- enabled* - boolean - enables or disables the message
- title* - string - title of the message
- bottomText - string - text below the title (also known as description)
- accentColor - ColorResolvable - embed color
- displayDetails - boolean - whether to display additional informations
- showTimestamp - boolean - whether to show date and time in the footer
- footer - string - message footer
- deleteTimeout - number - time (ms) after the message gets deleted
There is also a global deleteTimeout property (messages.system.deleteTimeout)
Help message
Its configuration is stored in messages.help property.
You can customize the help message with these properties (* - required):
- enabled* - boolean - enables or disables the message
- title* - string - title of the message
- bottomText* - string - text below the title (also known as description)
- accentColor* - ColorResolvable - embed color
- description* - string - description shown in the message itself
- usage* - string - usage displayed in the message itself
- visible* - boolean - whether to show the help command in the list
WARNING! You can't customize these messages after starting the bot. Changing these properties while the bot is running will have no effect.
Issues
Since this package is created by only 1 person it may contain some bugs or behave weirdly. If you notice any problem, typo etc, please create an issue in the Issues tab on GitHub.
Thank you.
Created with ❤️ by GRZANA