Discord.js v12清空命令

4

我有一个clear命令,可以删除你想要的数量的消息。但是当我输入clear 3时,它只会删除2条消息。

client.on('message', async (message) => {
  if (
    message.content.toLowerCase().startsWith(prefix + 'clear') ||
    message.content.toLowerCase().startsWith(prefix + 'c ')
  ) {
    if (!message.member.hasPermission('MANAGE_MESSAGES'))
      return message.channel.send("You cant use this command since you're missing `manage_messages` perm");
    if (!isNaN(message.content.split(' ')[1])) {
      let amount = 0;
      if (message.content.split(' ')[1] === '1' || message.content.split(' ')[1] === '0') {
        amount = 1;
      } else {
        amount = message.content.split(' ')[1];
        if (amount > 100) {
          amount = 100;
        }
      }
      await message.channel.bulkDelete(amount, true).then((_message) => {
        message.channel.send(`Bot cleared \`${_message.size}\` messages :broom:`).then((sent) => {
          setTimeout(function () {
            sent.delete();
          }, 2500);
        });
      });
    } else {
      message.channel.send('enter the amount of messages that you would like to clear').then((sent) => {
        setTimeout(function () {
          sent.delete();
        }, 2500);
      });
    }
  } else {
    if (message.content.toLowerCase() === prefix + 'help clear') {
      const newEmbed = new Discord.MessageEmbed().setColor('#00B2B2').setTitle('**Clear Help**');
      newEmbed
        .setDescription('This command clears messages for example `.clear 5` or `.c 5`.')
        .setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL())
        .setTimestamp();
      message.channel.send(newEmbed);
    }
  }
});
3个回答

5

你的代码已经能够正常工作,可以删除正确数量的信息。但是你忘了当前带有评论的消息也算作一个消息,所以应该把这个数字增加1。

我可能会对你的代码做一些修改:

  1. 不要只根据单个空格对消息进行分割,而是使用正则表达式来捕获多个空格。当前的代码不能处理 .clear 5 这样的命令。如果检查一下,isNaN(' ') 的值为 false
  2. 检查传入的数量是否为正数。
  3. 去掉硬编码的前缀(prefix)。
  4. 删除不必要的 await
  5. 在程序开始时检查前缀(prefix)。
client.on('message', (message) => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content
    .toLowerCase()
    .slice(prefix.length)
    .trim()
    .split(/\s+/);
  const [command, input] = args;

  if (command === 'clear' || command === 'c') {
    if (!message.member.hasPermission('MANAGE_MESSAGES')) {
      return message.channel
        .send(
          "You cant use this command since you're missing `manage_messages` perm",
        );
    }

    if (isNaN(input)) {
      return message.channel
        .send('enter the amount of messages that you would like to clear')
        .then((sent) => {
          setTimeout(() => {
            sent.delete();
          }, 2500);
        });
    }

    if (Number(input) < 0) {
      return message.channel
        .send('enter a positive number')
        .then((sent) => {
          setTimeout(() => {
            sent.delete();
          }, 2500);
        });
    }

    // add an extra to delete the current message too
    const amount = Number(input) > 100
      ? 101
      : Number(input) + 1;

    message.channel.bulkDelete(amount, true)
    .then((_message) => {
      message.channel
        // do you want to include the current message here?
        // if not it should be ${_message.size - 1}
        .send(`Bot cleared \`${_message.size}\` messages :broom:`)
        .then((sent) => {
          setTimeout(() => {
            sent.delete();
          }, 2500);
        });
    });
  }

  if (command === 'help' && input === 'clear') {
    const newEmbed = new MessageEmbed()
      .setColor('#00B2B2')
      .setTitle('**Clear Help**')
      .setDescription(
        `This command clears messages for example \`${prefix}clear 5\` or \`${prefix}c 5\`.`,
      )
      .setFooter(
        `Requested by ${message.author.tag}`,
        message.author.displayAvatarURL(),
      )
      .setTimestamp();

    message.channel.send(newEmbed);
  }
});

非常感谢您,我真的很感激。 :) - PoXoS

1
那是因为它正在删除触发它的消息。简单的解决方法是,只需取得给定的数字并加一即可。
await message.channel.bulkDelete(parseInt(amount) + 1, true).then((_message) => {

听起来不错,但在JavaScript中,如果amount是一个字符串,amount + 1也将是一个字符串。我的意思是,如果amount = "3",那么amount +1将是"31" - Zsolt Meszaros
@ZsoltMeszaros 这里的金额不应该是一个字符串。 - Noah Calland
这确实是一个问题。如果 message.content'.clear 3',并且你检查 typeof message.content.split(' ')[1],它返回 "string" - Zsolt Meszaros
1
@ZsoltMeszaros 请检查我的编辑。我认为那样会起作用? - Noah Calland
没错,那应该可以正常工作,不过最好加上基数:parseInt(amount, 10) + 1。现在让我点赞你的回答吧 ;) - Zsolt Meszaros

1

触发消息(命令消息)也在被获取。

有多种解决方案:

  1. 在获取/批量删除其他消息之前删除命令消息
  2. 只获取在命令消息之前发送的消息
  3. 将要删除的消息数量增加1

我在以下代码中标记了所有3个解决方案

client.on('message', async (message) => {
  if (
    message.content.toLowerCase().startsWith(prefix + 'clear') ||
    message.content.toLowerCase().startsWith(prefix + 'c ')
  ) {
    if (!message.member.hasPermission('MANAGE_MESSAGES'))
      return message.channel.send("You cant use this command since you're missing `manage_messages` perm");
    if (!isNaN(message.content.split(' ')[1])) {
      let amount = 0;
      if (message.content.split(' ')[1] === '1' || message.content.split(' ')[1] === '0') {
        amount = 1;
      } else {
        amount = message.content.split(' ')[1];
        if (amount > 100) {
          amount = 100;
        }
      }

/* 1. Solution */

      await message.delete().catch(e => { amount++; });

      await message.channel.bulkDelete(amount, true).then((_message) => {
        message.channel.send(`Bot cleared \`${_message.size}\` messages :broom:`).then((sent) => {
          setTimeout(function () {
            sent.delete();
          }, 2500);
        });
      });

/* 2. Solution */
      const messagesToDelete = await message.channel.messages.fetch({ before: message.id, limit: amount });

      await message.channel.bulkDelete(messagesToDelete, true).then((_message) => {
        message.channel.send(`Bot cleared \`${_message.size}\` messages :broom:`).then((sent) => {
          setTimeout(function () {
            sent.delete();
          }, 2500);
        });
      });

/* 3. Solution */

      amount >= 100 ? await message.delete() /* You can only bulk delete 100 messages */ : amount++;

      await message.channel.bulkDelete(amount, true).then((_message) => {
        message.channel.send(`Bot cleared \`${_message.size}\` messages :broom:`).then((sent) => {
          setTimeout(function () {
            sent.delete();
          }, 2500);
        });
      });

/* The following code is your old code */

    } else {
      message.channel.send('enter the amount of messages that you would like to clear').then((sent) => {
        setTimeout(function () {
          sent.delete();
        }, 2500);
      });
    }
  } else {
    if (message.content.toLowerCase() === prefix + 'help clear') {
      const newEmbed = new Discord.MessageEmbed().setColor('#00B2B2').setTitle('**Clear Help**');
      newEmbed
        .setDescription('This command clears messages for example `.clear 5` or `.c 5`.')
        .setFooter(`Requested by ${message.author.tag}`, message.author.displayAvatarURL())
        .setTimestamp();
      message.channel.send(newEmbed);
    }
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接