javascript - Discord.js - 如何实现前缀以避免错误触发命令响应?
问题描述
我正在开发一个带有命令处理程序的不和谐机器人,我在自己的文件中拥有所有命令,我将这些命令导入到主文件中。我遇到的问题是我正在努力在命令中实现前缀,因此所有命令都可以由文本触发。
我的命令处理程序的工作方式是我在 bot.js 中有以下代码:
client.on('message', msg => {
if (msg.content.startsWith(prefix)) return;
//Splitting the message from the user
const args = msg.content.split(/ +/);
const command = args.shift().toLowerCase();
console.log(`Called comand: ${command}`);
//See if the commands folder has that command in it
if (!client.commands.has(command)) return;
//Try to execute the command. If we can't, we throw an error instead.
try {
client.commands.get(command).execute(msg, args);
} catch (error) {
console.error(error);
msg.channel.send("I hit an issue trying to issue that command.");
console.log("A Comnmand was issued, but I hit an issue trying to run it.");
}
在该文件的顶部,我也有
const prefix = '!'
然后我在命令文件夹中有一个名为 index.js 的文件,如下所示:
module.exports = {
about: require('./about'),
help: require('./help'),
nokill: require('./nokill'),
animeme: require('./animeme'),
showmeme: require('./showmeme'),
roadmap: require('./roadmap'),
changelog: require('./changelog'),
wuvu: require('./wuvu'),
debug: require('./debug'),
dailyquote: require('./dailyquotes'),
dance: require('./dance'),
对于命令,它们看起来像这样:
const GihpyAPIModule = require('./command_modules/fetchGif.js');
module.exports = {
name: 'dance',
decription: 'Sends a dancing GIF',
execute(msg, args) {
msg.channel.send("Here's your dance!");
var searchPromise = GihpyAPIModule.getGif("dance");
searchPromise.then((gif) => {
msg.channel.send(gif);
})
}
查看机器人运行的控制台后,我注意到如果我先发送带有前缀的消息,例如!dance,它甚至不会接收到它。它只是完全忽略它。
这是我到目前为止所尝试的:
在每个命令文件中实现前缀
在 bot.js 中使用了这个:
const args = msg.content.slice(prefix.length).split(/ +/);
由于机器人只是忽略带有 ! 的消息 一开始,机器人只是减少消息,所以帮助会变成 elp。
任何意见是极大的赞赏!
解决方案
您需要替换名为:
if (msg.content.startsWith(prefix)) return;
有了这个:
if (!msg.content.startsWith(prefix)) return;
我认为它应该工作。
推荐阅读
- java - 无法解决对构造函数的动态引用
- c# - C# 使用反射列出 FindAll
- php - 通过 API 向 Greenhouse 提交申请
- linux - 如何使用来自数据来源的数据打印文件名?
- sip - 我有一个带有 SIP/RTP 的 PCAP 文件...我可以将它重放到交换机中以测试兼容性吗?
- javascript - 如果我们不能从父组件更改属性或操作它们,@ViewChild 有什么用?
- azure - SharePoint 框架 (SPFx) 访问使用 AzureAD 保护的自定义 API
- netlogo - 计算代理集中的品种
- android - Flutter:无法发出 HTTP-GET 请求
- asp.net-mvc - MVC 5 应用程序中的“/”应用程序中的服务器错误