首页 > 解决方案 > 如何正确定义机器人的前缀,使其不响应任何单字母前缀?

问题描述

我正在制作一个机器人并将其托管在故障上。我希望前缀为“a”,但机器人响应任何单个字母前缀。

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

这就是我的 config.json 包含的内容。


//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);
})

这就是我的 index.js 包含的内容,所有不相关的部分都被删除了。
当我使用我的机器人时会发生什么,我可以去 ping,它会 ping。然后,我可以去 bping,它会 ping,而无需我指定 'b' 是前缀。我该如何对抗这个?

标签: javascriptnode.jsbotsdiscorddiscord.js

解决方案


我这样做的方式是检查消息内容是否以前缀开头。下面我粘贴了一些用于我的机器人的代码。主线是

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

在这里,我检查消息是否包含我的前缀,如果是,是否在消息的开头。如果不是这种情况,我就退出该方法。

 

我的代码:

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
});

最后一点,我强烈建议您if (message.author.bot) return;在代码中也包含该行。这可以防止您的机器人响应其他机器人,这可能会创建某种无限的消息循环


推荐阅读