PrezOfTheUnitedIdiots
PrezOfTheUnitedIdiots

Reputation: 181

How to loop the same command with different value in discord.js

I'm coding a discord bot with discord.js, and one of the features is that when someone sends a message with the prefix (.exe) with a word right after (e.g. .exebot or .exeserverinv), the bot returns a specific message. The code works just fine, but I know that by just copy pasting the same code over 30 times and just changing the values isn't good optimization.

Is there any simple way that I can make it so that I can just use a loop or something for the command to repeat, but with different values?

Here's the non-optimized code:

command(client, 'command name', message => {
    message.channel.send('bot message')
})
command(client, 'random', message =>{
    message.channel.send('some text')
})
command(client, 'bot', message =>{
    message.channel.send('random text')
})
command(client, 'testing', message =>{
    message.channel.send('text')
})
command(client, 'test', message =>{
    message.channel.send('example text')
})
command(client, 'second to last test', message =>{
    message.channel.send('is almost there')
})
command(client, 'last test', message =>{
    message.channel.send('is the very last one')
})

The command handler that this command is running from is:

const { prefix } = require('./config.json')

module.exports = (client, aliases, callback) => {
    if (typeof aliases === 'string') {
        aliases = [aliases]
    }

    client.on('message', message => {
        const { content } = message;

        aliases.forEach(alias => {
            const command = `${prefix}${alias}`

            if (content.startsWith(`${command} `) || content === command) {
                console.log(`Running the command ${command}`)
                callback(message)
            }
        })
    })
}

Please advise.

Upvotes: 2

Views: 464

Answers (1)

Skulaurun Mrusal
Skulaurun Mrusal

Reputation: 2837

You can use JavaScript's object notation and map the command names to the replies.

const commandToReply = {
    "command name": "bot message",
    "random": "some text",
    "bot": "random text",
    "testing": "text",
    "test": "example text",
    "second to last test": "is almost there",
    "last test": "is the very last one"
};

for (const [name, reply] of Object.entries(commandToReply)) {
    command(client, name, (message) => {
        message.channel.send(reply);
    });
}

To iterate through the object, look at how Object.entries() works.

Upvotes: 1

Related Questions