javascript - Discord.js Bot 忽略前缀并且会响应前面的任何内容
问题描述
我已经让这个机器人工作了一段时间,出于某种原因,机器人现在将响应它前面的任何前缀,而不是设置的前缀。
const PREFIX = '$';
bot.on('message', message => {
let argus = message.content.substring(PREFIX.length).split(" ");
switch (argus[0]) {
case 'yeet':
message.channel.send("yeet")
break;
}
});
解决方案
在您的代码中,您没有检查消息是否以您的前缀开头。因此,您的代码会针对每条消息执行,如果该命令位于相同长度的子字符串之后PREFIX
,它将触发该命令。
更正的代码:
// Example prefix.
const PREFIX = '!';
bot.on('message', message => {
// Ignore the message if it's from a bot or doesn't start with the prefix.
if (message.author.bot || !message.content.startsWith(PREFIX)) return;
// Take off the prefix and split the message into arguments by any number of spaces.
const args = message.content.slice(PREFIX.length).split(/ +/g);
// Switching the case of the command allows case iNsEnSiTiViTy.
switch(args[0].toLowerCase()) {
case 'yeet':
message.channel.send('yeet')
// Make sure to handle any rejected promises.
.catch(console.error);
break;
}
});
推荐阅读
- c# - 单元测试中的配置值永远不会被设置
- c# - MySQL、C# 和 C# 之间的字符编码
- android - 更新gradle后将多模块项目发布到工件停止工作
- css - 如何在 reacttjs 中修复 video.js 包的 css
- swift - 数据请求为零,处理来自 REST API 的请求时出现问题
- react-admin - 如何在 ArrayImput 和 SimpleFormIterator 中对输入进行水平排序
- macros - Elixir:defmacro 和 pipline 的基准测试
- java - 如果我使用 getText() 方法,有什么方法可以只获取 json 数据
- html - 获取@Html.DropDownList 或选择值
- git - 将最新提交压缩到最后一次合并提交