javascript - 如何正确定义机器人的前缀,使其不响应任何单字母前缀?
问题描述
我正在制作一个机器人并将其托管在故障上。我希望前缀为“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' 是前缀。我该如何对抗这个?
解决方案
我这样做的方式是检查消息内容是否以前缀开头。下面我粘贴了一些用于我的机器人的代码。主线是
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;
在代码中也包含该行。这可以防止您的机器人响应其他机器人,这可能会创建某种无限的消息循环
推荐阅读
- javascript - 错误:未捕获的 ReferenceError:未定义 Vue
- python - 如何将熊猫数据框中的列填充为分组出现的计数
- python - 熊猫如何根据另一列中的重复值在列中输出不同的值
- php - Wordpress - 将所有具有未来日期的帖子计数到当前帖子
- google-bigquery - ST_MAKELINE 即使不连续也会丢弃重复点
- java - servlet 中的 ImageIO:我应该关闭输出流以及如何设置 Content-Length?
- testing - compile_time_purge_matching 在测试期间不起作用
- excel - VBA在两个单元格之间添加单元格值
- java - 如何将 Apache Drill 选项配置为环境变量?
- c# - 将进程列出到列表框中