【问题标题】:Discord.js still executes command after other input, with or without argsDiscord.js 在其他输入后仍然执行命令,有或没有 args
【发布时间】:2020-12-28 12:13:43
【问题描述】:

开始认为这确实是一个.split() 错误,它适用于我的所有命令,无论有无参数。以为我找到了解决方案,但事实并非如此。这是一个简单的 ping 命令:

这是我的 index.js:

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();

const featureFiles = fs.readdirSync('./commands/features').filter(file => file.endsWith('.js'));
for (const file of featureFiles) {
    const command = require(`./commands/features/${file}`);
    client.commands.set(command.name, command);
}
    
client.on('message', message => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;
//.trim() is removed, see notes below on why
    const args = message.content.slice(prefix.length).split(/ +/g);
    const commandName = args.shift().toLowerCase();

    const command = client.commands.get(commandName)
        || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

    if (!command) return;

    if (command.guildOnly && message.channel.type !== 'text') {
        return message.reply('That command cannot be used inside a DM');
    }

    if (command.args && !args.length) {
        let reply = `You didn't provide any arguments!`;

        if (command.usage) {
            reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
        }

        return message.channel.send(reply);
    }

    try {
        command.execute(message, client, args);
    } catch (error) {
        console.error(error);
        message.channel.send('Error trying to execute command');
    }});
client.login(token);

我删除了 .trim(),因为它正在读取前缀和命令名称之间的空格,这是我不想要的,所以可以在前缀和命令之间使用 100 个空格,它会执行它。这是 !ping 命令:

const {prefix} = require('../../config.json')

module.exports = {
    name: 'ping',
    description: 'Shows latency',
    usage: ' ',
    execute(message) {
        if (message.content.startsWith(prefix + "ping")) {
            var ping = Date.now() - message.createdTimestamp + " ms";
            message.channel.send(`${Date.now() - message.createdTimestamp}` + " ms");
        
        }
    },
};

解决这个问题的任何方法都很好,因为我只是希望它在我指定的任何参数或命令名称之后 return; 之后仍然使用其他输入执行。我难住了。我想这是由我的 index.js 中的 .split() 引起的。

【问题讨论】:

  • 我不太明白你在问什么,你的意思是如果命令没有args,如果他们用args运行命令,你想@987654329 @?
  • 相当接近,有些命令有args,比如if (args[0] === 'test') {do something},如果有人输入!test test arg1 arg2,即使后面有“arg1 arg2”,它仍然会执行“do something”。实际上,我希望它不执行,或者 return; 如果 if 语句中未指定“arg1”等,而且在整个常规命令(如上面显示的 !ping 示例)中也是如此。希望这会有所帮助,谢谢:)
  • 啊,我明白了,我会继续回答这个问题

标签: javascript discord.js


【解决方案1】:

您可能想检查它是否有args,以及它有多少args,并将其与命令的args 中的args 进行比较。这可能需要您的命令 args 存在并且是一个数组,否则它将不起作用,请尝试以下代码:


index.js:

const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();

const featureFiles = fs.readdirSync('./commands/features').filter(file => file.endsWith('.js'));
for (const file of featureFiles) {
    const command = require(`./commands/features/${file}`);
    client.commands.set(command.name, command);
}
    
client.on('message', message => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).split(/ +/g);
  const commandName = args.shift().toLowerCase();

  const command = client.commands.get(commandName)
    || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));

  if (!command) return;

  if (command.guildOnly && message.channel.type !== 'text') {
      return message.reply('That command cannot be used inside a DM');
  }


  if (command.args && !args.length) {
    // If no arguments were provided, then...

    let reply = `You didn't provide any arguments!`;
    if (command.usage) {
      reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
    }
    return message.channel.send(reply);
  } else if (command.args && (command.args.length > args.length || commands.args.length < args.length)) {
    // If the `args` is too many or too little, then...

    let reply = `You inserted either too many or too little arguments!`;
    if (command.usage) {
      reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
    }
    return message.channel.send(reply);
  }

  try {
    command.execute(message, client, args);
  } catch (error) {
    console.error(error);
    message.channel.send('Error trying to execute command');
  }
});

client.login(token);

ping.js:

const {prefix} = require('../../config.json')

module.exports = {
  name: 'ping',
  description: 'Shows latency',
  args: [], // Array, because we need it's length, you can also add to it, for example
            // the args required is `args_1`, then add `["args_1"]`, for 2 args, add it
            // to the array `["args_1", "args_2"]`
  usage: ' ',
  execute(message, client, args) { // If you don't, this might return an error
    if (message.content.startsWith(prefix + "ping")) {
      var ping = Date.now() - message.createdTimestamp + " ms";
      message.channel.send(`${Date.now() - message.createdTimestamp}` + " ms");
    }
  },
};

有关此问题的更多信息,请查看以下参考资料:

【讨论】:

  • 如果所有命令都有参数,但 ping 命令以及许多其他命令没有参数,则此方法有效,因此它将是 args: false。当设置为 false 时,会出现同样的问题——如上面 ping 命令所示,其他参数在未指定时是允许的(并且应该返回;但只允许读取完全匹配的“ping”)。否则,如果它是空的,它会执行else if 并且不会像它应该的那样用“pong”响应。我会复习这些资源,谢谢:)
  • 不客气,您可以不设置 args,将其完全从文件中取出,这不会触发 args 块。由于如果args 存在则运行该命令,如果它不存在或者是undefined,它将返回。而且,如果您愿意,请将此答案标记为正确,因为它对我有很大帮助。祝你有美好的一天^^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多