Discord.js v12 清除命令

Posted

技术标签:

【中文标题】Discord.js v12 清除命令【英文标题】:Discord.js v12 clear command 【发布时间】:2021-04-14 05:52:40 【问题描述】:

我有一个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);
    
  
);

【问题讨论】:

只做数量+1? 【参考方案1】:

您的代码运行良好,它删除了正确数量的消息。您忘记的是,您当前带有评论的消息也是一条消息,并且也将计入删除的数量。所以你可以把这个数字加一。

我可能会对您的代码进行一些更改:

    我不会使用一个空格来分割您的消息,而是使用正则表达式来捕获多个空格。当前的不适用于.clear 5。如果您检查,isNaN(' ')false。 检查金额是否为正数。 删除硬编码的prefixes。 删除不必要的await。 为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 \`$prefixclear 5\` or \`$prefixc 5\`.`,
      )
      .setFooter(
        `Requested by $message.author.tag`,
        message.author.displayAvatarURL(),
      )
      .setTimestamp();

    message.channel.send(newEmbed);
  
);

【讨论】:

非常感谢您,我真的很感激。 :)【参考方案2】:

那是因为它也在删除触发它的消息。简单的解决方法,只需将给定的数字加一即可。

await message.channel.bulkDelete(parseInt(amount) + 1, true).then((_message) => 

【讨论】:

听起来不错,但是在 javascript 中如果 amount 是一个字符串,amount + 1 也将是一个字符串。我的意思是,如果amount = "3"amount +1 将是"31" @ZsoltMeszaros 数量在这里不应该是一个字符串。 虽然如此。如果message.content'.clear 3' 并且您检查typeof message.content.split(' ')[1],它将返回"string" @ZsoltMeszaros 检查我的编辑。我认为这行得通? 是的,这应该可以正常工作,尽管添加基数也是一个好习惯:parseInt(amount, 10) + 1。现在让我投票赞成你的答案;)【参考方案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);
    
  
);

【讨论】:

以上是关于Discord.js v12 清除命令的主要内容,如果未能解决你的问题,请参考以下文章

使用 discord.js v12 解禁命令

discord.js V12,我的命令[重复]

discord.js v12 用户信息命令

机器人不响应命令(discord.js v12)

交互式命令 discord.js v12

Discord.js V12 如何显示具有特定角色的所有成员?