cyliim
cyliim

Reputation: 301

How can I properly define my bot's prefix so it doesn't respond to any one-letter prefix?

I'm making a bot and hosting it on glitch. I want to have the prefix be 'a', but the bot responds to any single letter prefix.

{
 "prefix": "a",
 "devID": "443992049746968586"
}

This is what my config.json contains.


//cmd handler
client.commands = new Discord.Collection();

fs.readdir("./commands/", (err, files) => {
    if (err) console.log(err);

    let jsfile = files.filter(f => f.split(".").pop() === "js")
    if(jsfile.length <= 0){
        console.log("Couldn't find commands")
        return;
    }
    jsfile.forEach((f, i) =>{
let props = require(`./commands/${f}`);
console.log(`${f} loaded`);
client.commands.set(props.help.name, props);
    });
});


client.on("message", msg =>{
    let messageArray = msg.content.split(" ");
    let cmd = messageArray[0];
    let args = messageArray.slice(1);
    let commandfile = client.commands.get(cmd.slice(config.prefix.length));
    if(commandfile) commandfile.run(client,msg,args);
})

That is what my index.js contains, with all irrelevant parts cut out.
What happens when I use my bot is, I can go aping, and it pings. Then, I can go bping and it will ping, without me specifying that 'b' is a prefix. How can I combat this?

Upvotes: 1

Views: 1079

Answers (1)

T. Dirks
T. Dirks

Reputation: 3676

The way I have done it, is by checking if the message content starts with the prefix. Below I've pasted some code which I use for my bot. The main line is

if (message.content.indexOf(config.prefix) !== 0) return;

Here I check if the message contains my prefix, and if so, if it's at the start of the message. If that isn't the case, I just return out of the method.

 

My code:

client.on("message", async message =>
{
    // Ignore messages from all bots
    if (message.author.bot) return;

    // Ignore messages which don't start with the given prefix
    if (message.content.indexOf(config.prefix) !== 0) return;

    // Split the message into the command and the remaining arguments
    const args = message.content.slice(config.prefix.length).trim().split(' ');
    const cmd = args.shift().toLowerCase();

    // Do stuff with your input here
});

As a final note, I'd highly suggest you include the line if (message.author.bot) return; in your code as well. This prevents your bot from responding to other bots potentially created some sort of infinite message loop

Upvotes: 1

Related Questions