首页 > 解决方案 > 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,它甚至不会接收到它。它只是完全忽略它。

这是我到目前为止所尝试的:

由于机器人只是忽略带有 ! 的消息 一开始,机器人只是减少消息,所以帮助会变成 elp。

任何意见是极大的赞赏!

标签: javascriptnode.jsdiscorddiscord.js

解决方案


您需要替换名为:

if (msg.content.startsWith(prefix)) return;

有了这个:

if (!msg.content.startsWith(prefix)) return;

我认为它应该工作。


推荐阅读