【问题标题】:Discord.js - How can I implement a prefix to avoid false-triggering a command response?Discord.js - 如何实现前缀以避免错误触发命令响应?
【发布时间】:2020-12-12 03:34:16
【问题描述】:

我正在开发一个带有命令处理程序的不和谐机器人,我在自己的文件中拥有所有命令,我将这些命令导入到主文件中。我遇到的问题是我正在努力在命令中实现前缀,因此所有命令都可以由文本触发。

我的命令处理程序的工作方式是我在 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。

非常感谢任何建议!

【问题讨论】:

    标签: javascript node.js discord discord.js


    【解决方案1】:

    你需要替换你的方法名为:

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

    有了这个:

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

    我认为它应该有效。

    【讨论】:

      【解决方案2】:

      如果命令以前缀开头,则您正在执行 EXIT。回报;函数将终止一个函数并使其返回某个值,或者它会停止它并“返回”到主代码。您所做的是让机器人返回到侦听命令的状态,而不是实际执行它。

      一个简单的解决方法是

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

      !开始时的标记非常重要。这意味着如果不是,则返回侦听新消息。

      【讨论】:

      • 在所有的故障排除之后,我忽略了最重要的事情。感谢您的帮助!
      猜你喜欢
      • 2021-09-10
      • 2018-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-04
      • 2012-04-26
      相关资源
      最近更新 更多