'Discord JS Commands Ran At Once

I'm trying to make a discord Vouch System but when i do -Vouch it runs 2 commands one is -Vouch And the other is -Vouches ```

client.on("message", (message) => {

    if (message.content.startsWith("-Vouches")) {
                  const user = message.mentions.users.first();
          if (user === undefined) {
    return; }


Solution 1:[1]

If you always uses startsWith it will surely execute two commands if one of the command name is contained into another one.

For example, if we have this code :

client.on("message", (message) => {
    if (message.content.startsWith("!test")) console.log("test command");

    if (message.content.startsWith("!test2")) console.log("test2 command");
});

Both command will be executed if we write !test.

So a solution vastly used is to split the message by spaces, then take the first word, and test it, not if it starts with a string, test the entire string, like this.

client.on("message", (message) => {
    const [commandName, ...arguments] = message.content.split(/\s+/);
    // commandName is the first word
    // arguments is an array of the other words of the message

    if (commandName === "!test") console.log("test command");

    if (commandName === "!test2") console.log("test2 command");
});

Here we split the message by spaces, using the regular expression \s+, then took the first word and tested it directly. You can also then use the array arguments for your commands stuff.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ayfri