Custom Bot Functions

Here is a guide to create customizable discord bot functions.

Before you begin

Please make sure that the functions dont have the same names as the regular client functions of discord bots. For example dont name it member since client.member is already built into discord.js.

Building a custom function

For building a custom function we create a file in src/functions. The name of the file doesnt matter but might name it as you name the function. In that case we create a file called handleDefault.js. This function will handle a default answer in switch functions.

The file structure

Here is the structure of the file:

module.exports = (client) => { //syncing the client
    client.defaultReply /*The name of the function comes after client.*/ = async (i, id) /*The required variables in the function*/ => {
        await i.reply({ content: "Sorry <@${id}>, the command does not exist or is under development"})
        })();
    };
    return { getCount: count };
};

What we did now is a function which makes a default answer when a command got executed but doesnt exist.

Calling the function

To call the function in your command, here is the code example:

const {SlashCommandBuilder} = require("discord.js");
module.exports = {
    data: new SlashCommandBuilder()
    .setName("default-reply")
    .setDescription("A example of a command which is under dev."),

    async execute(interaction) {
        client.defaultReply(interaction, interaction.user.id);
    }
}

Using it in a switch function:

const {SlashCommandBuilder} = require("discord.js");

module.exports = {
    data: new SlashCommandBuilder()
    .setName("default-reply")
    .setDescription("A example of a command which is under dev.")
    .addSubcommand(c => c.setName("test").setDescription("test"))
    .addSubcommand(c => c.setName("test2").setDescription("test")),

    async execute(interaction) {
        switch (interaction.options.getSubcommand()) {
            case "test":
                await interaction.reply("This is a test reply");
            break;
            default:
                client.defaultReply(interaction, interaction.user.id)
        }
    }
}

What we did here is, when someone is trying to execute the test2 command, it replies with the answer of `client.defaultReply()` as we made the function for it before.

Last updated