【问题标题】:How can I properly define my bot's prefix so it doesn't respond to any one-letter prefix?如何正确定义机器人的前缀,使其不响应任何单字母前缀?
【发布时间】:2019-05-02 14:52:33
【问题描述】:

我正在制作一个机器人并将其托管在故障上。我希望前缀为“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' 是前缀。我该如何应对?

【问题讨论】:

    标签: javascript node.js bots discord discord.js


    【解决方案1】:

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

    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; 行。这可以防止您的机器人响应其他机器人,这可能会创建某种无限的消息循环

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-19
      • 2021-02-12
      • 2021-04-25
      • 2020-05-10
      • 2020-11-25
      • 2017-10-15
      • 1970-01-01
      • 2020-06-01
      相关资源
      最近更新 更多