lukazbaum / discordjs-command-handler

A comprehensive TypeScript command handler for Discord.js, featuring slash commands, prefix commands, message commands, events, automatic intents, and more.
MIT License
5 stars 1 forks source link
bot bot-template command-handler discord discord-bot discord-bot-template discord-command-handler discord-components discord-handler discord-js discordjs discordjs-v14 slash-command-handler typescript

Discord Bot Handler

πŸš€ Elevate Your Discord Programming Experience with Advanced Features!

Transform your Discord bot development with our advanced handler. It simplifies command management, event handling, and offers robust solutions for seamless bot operations.

node - v20.7+ npm - v10.1+ discord.js - v14.14.1 Maintenance - Active

πŸ€” Why?

🌟 Features

This Discord Bot comes packed with a variety of features designed to enhance your server's functionality and user experience:

πŸš€ Getting Started

Follow these steps to install and set up the Discord Bot Handler.

1. πŸ“‹ Prerequisites

Before you begin, ensure you have the following:

2. πŸ“₯ Cloning the Repository

Clone the repository using Git:

git clone https://github.com/lukazbaum/discordjs-command-handler

Alternatively, download it as a ZIP file and extract it.

Navigate to the directory:

cd discord-bot-handler

3. πŸ”§ Installing Dependencies

Install the necessary Node.js packages:

npm install 
# or
yarn install

4. βš™οΈ Configuration

Rename .env.example to .env in your project root and fill in your details:

The CLIENT_ID can be found in your Bot Application under OAuth2.

CLIENT_TOKEN=your_discord_bot_token
CLIENT_ID=your_discord_client_id
GUILD_ID=your_discord_guild_id

When using Linux as operating system change this line in the package.json file:

"compile": "npm run clean-windows && tsc",

to this

"compile": "npm run clean-linux && tsc",

5. πŸ€– Running the Bot

Use the following commands to compile and start your bot:

πŸ“š Documentation

Explore the documentation for in-depth insights on using and optimizing the Discord Bot Handler in your projects.

πŸ› οΈ Command Arguments

Command arguments are optional settings that can be applied to each command to control its behavior. These settings allow for flexible command management, including permissions and usage restrictions. Here are the base command arguments you can use:

ΒΉ Note on Optional Whitelists: When using optional whitelists, the command will be allowed to execute if any one of the optional whitelist conditions is met.

πŸ› οΈ Example Usage:

export = {
    cooldown: 10,
    ownerOnly: false,
    channelWhitelist: ["123456789012345678", "987654321098765432"]
    // ... other arguments
} as SlashCommandModule;

βš”οΈ Slash Commands

Below is an example of a typical Slash Command module:

interface SlashCommandModule {
  type: CommandTypes.SlashCommand;
  register: RegisterTypes;
  data: SlashCommandBuilder;
  execute: (...args: any[]) => Promise<void>;
  autocomplete?: (interaction: AutocompleteInteraction) => Promise<void>;
}

βš”οΈ Example Slash Command:

Here's a practical example of a Slash Command:

export = {
  type: CommandTypes.SlashCommand,
  register: RegisterTypes.Guild,
  data: new SlashCommandBuilder()
          .setName("ping")
          .setDescription("Replies with pong!")
          .setDefaultMemberPermissions(PermissionFlagsBits.SendMessages),
  async execute(interaction: CommandInteraction): Promise<void> {
    await interaction.reply({ content: "Pong" });
  }
} as SlashCommandModule;

πŸ”§ Prefix/Ping/Message Commands

Prefix, Ping and Message Commands follow the same structure. Below is an example of a typical Prefix Command module:

interface PrefixCommandModule {
  name: string;
  aliases?: string[];
  permissions?: string[];
  type: CommandTypes.PrefixCommand;
  execute: (message: Message) => Promise<void>;
}

πŸ”§ Example Prefix Command:

Here's a practical example of a Prefix Command:

export = {
  name: "pong",
  aliases: ["poong"],
  type: CommandTypes.PrefixCommand,
  async execute(message: Message): Promise<void> {
    await message.reply("Ping!");
  }
} as PrefixCommandModule;

πŸ“‘ Context Menus

Context Menus in Discord bots allow users to interact with your bot through right-click context options in the Discord interface. Just like with other commands, standard command arguments can be applied to Context Menus for added flexibility and control. Here is a typical structure of a Context Menu module:

interface ContextMenuCommandModule {
  type: CommandTypes.ContextMenu;
  register: RegisterTypes;
  data: ContextMenuCommandBuilder;
  execute: (interaction: ContextMenuCommandInteraction) => Promise<void>;
}

πŸ“‘ Example Context Menu:

Here's a practical example of a Context Menu:

export = {
  type: CommandTypes.ContextMenu,
  register: RegisterTypes.Guild,
  data: new ContextMenuCommandBuilder()
          .setName("Get Message ID")
          .setType(ApplicationCommandType.Message),
  async execute(interaction: ContextMenuCommandInteraction): Promise<void> {
    await interaction.reply({ content: `Message ID: ${interaction.targetId}` });
  }
} as ContextMenuCommandModule;

πŸ—ƒοΈ Components

On Discord, Components are interactive elements like buttons, select menus, and modals that enhance user interaction. These can be implemented individually or grouped for complex interactions. Below is a typical structure of a Component module:

interface ComponentModule {
  id?: string;
  group?: string;
  type: ComponentTypes;
  execute: (interaction: any) => Promise<void>;
}

πŸ—ƒοΈ Example using ids:

Creating and sending a button:

This example creates a button with a specific id for distinct handling.

const row: any = new ActionRowBuilder()
        .addComponents(
                new ButtonBuilder()
                        .setCustomId("deleteMessage")
                        .setLabel("Delete message")
                        .setStyle(ButtonStyle.Danger)
        );
await interaction.reply({ content: "Example", components: [row] });

Handling the button interaction:

The following code handles the interaction for the previously created button.

export = {
  id: "deleteMessage",
  type: ComponentTypes.Button,
  async execute(interaction: ButtonInteraction): Promise<void> {
    await interaction.message.delete();
  }
} as ComponentModule;

πŸ—ƒοΈ Example using groups:

Creating and sending grouped buttons:

For buttons that are part of a group, the group name is prepended to the customId for easy identification and handling.

const row: any = new ActionRowBuilder()
        .addComponents(
                new ButtonBuilder()
                        .setCustomId("group=subscription;confirm")
                        .setLabel("Click to confirm")
                        .setStyle(ButtonStyle.Success),
                new ButtonBuilder()
                        .setCustomId("group=subscription;cancel")
                        .setLabel("Click to cancel")
                        .setStyle(ButtonStyle.Secondary)
        );
await interaction.reply({ content: "Example", components: [row] });

Handling grouped button interactions::

This example shows how to handle interactions for buttons that are part of a group.

export = {
  group: "subscription",
  type: ComponentTypes.Button,
  async execute(interaction: ButtonInteraction): Promise<void> {
    if (interaction.customId === "confirm") {
      await interaction.reply({ content: "Pressed confirm" });
    } else if (interaction.customId === "cancel") {
      await interaction.reply({ content: "Pressed cancel" });
    }
  }
} as ComponentModule;

This approach allows for more organized and scalable interaction handling, especially when dealing with multiple components grouped under a single category or function.

The examples provided for handling button interactions are also applicable to select menus and modals, which can be found in the code.

πŸŽ‰ Events

Below is an example of a typical Event module:

interface EventModule {
  name: Events;
  once?: boolean;
  execute: (...args: any[]) => Promise<void>;
}

πŸŽ‰ Example Event:

Here's an example handling the ClientReady event:

export = {
  name: Events.ClientReady,
  once: true,
  async execute(client: DiscordClient): Promise<void> {
    if (!client.user) return;

    client.user.setStatus(UserStatus.ONLINE);
    client.user.setActivity("Development", { type: ActivityType.Watching });
    Logger.log(`Ready! Logged in as ${client.user.tag}`);
  }
} as EventModule;

🌈 Colored Message Builder

The ColoredMessageBuilder class is designed to enhance the visual appeal of your Discord bot's messages. It allows for various text formatting options, including text color, background color, and styling. This feature can be particularly useful for highlighting important information or making responses more engaging.

🌈 Example usage:

const msg: string = new ColoredMessageBuilder()
        .add("Hello, ", Color.Red)
        .add("World!", Color.Blue, BackgroundColor.DarkBlue, Format.Underline)
        .addNewLine()
        .addRainbow("This is cool!", Format.Bold)
        .build();

Alternatively, for simpler text formatting needs, you can use the colored or rainbow functions:

const simpleColoredMsg = colored("Simple Colored Message", Color.GREEN);
const simpleRainbowMsg = rainbow("Simple Rainbow Message");

πŸ”¨ Utility

The formatTimestamp function simplifies timestamp formatting for Discord, ensuring a user-friendly display of time in your bot's messages. All possible format styles are supported and can be found in the source code.

πŸ”¨ Example usage:

const discordTimestamp = formatTimestamp(unixTimestamp, TimestampStyle.ShortDate);

Output: 01/23/2024

πŸ“ License

This project is licensed under the [MIT] License, chosen for its permissive nature, allowing developers to freely use, modify, and distribute the code. See the LICENSE file for details.

πŸ‘₯ Contributing

Contributions & Issues are welcome! Please follow our Contribution Guidelines.

πŸ“œ Code of Conduct

For a detailed understanding of our community's values and standards, please refer to our Code of Conduct. We are committed to building a welcoming, inclusive, and respectful community.

✨ Showcase Your Project

Are you using our handler in your open-source bot? We'd love to feature it! Let's highlight the fantastic work you've achieved with our Discord Bot Handler.

To share your project details, connect with us on Discord. We're excited to showcase your creation to the community.

❀️ Show Your Support

If you find the Discord Bot Handler useful, please consider giving it a star on GitHub. This not only helps us understand which projects the community values, but also increases the visibility of our work. Your support means a lot!

🌟 Star us on GitHub β€” it helps!