清除命令在清除后抛出错误 - Discord.js V13

Purge command throws error after purging - Discord.js V13

我发出了一个针对特定成员并删除给定数量的清除命令。问题是它会正确删除消息,而在完成时会抛出未知错误。帮我修一下!这是代码及其错误

const Discord = require('discord.js');
const { Permissions } = require('discord.js');
const { MessageEmbed } = require("discord.js")

module.exports = {
    description: 'purge command',
    run: async (client, message, args) => {
        setTimeout(() => message.delete(), 3500);

        if (message.member.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {

            let purgeMember = message.mentions.users.first()
            let amount = args[1]
            if (!purgeMember) return message.channel.send("Please Mention a Member to purge").then(msg => { setTimeout(() => msg.delete(), 4000) })
            if (!amount) return message.channel.send("Please provide a valid number to purge").then(msg => { setTimeout(() => msg.delete(), 4000) })
            if (isNaN(amount)) return message.channel.send("Please provide a valid number to purge").then(msg => { setTimeout(() => msg.delete(), 4000) })
            if (amount > 99) return message.channel.send("I can delete upto 100 messages only").then(msg => { setTimeout(() => msg.delete(), 4000) })

            let AllMessages = await message.channel.messages.fetch()
            let FilteredMessages = await AllMessages.filter(x => x.author.id === purgeMember.id)
            let deletedMessages = 0
            FilteredMessages.forEach(msg => {
                if (deletedMessages >= amount) return
                msg.delete()
                deletedMessages++
            })

        } else {
            message.channel.send('️ | You DONT have permission to use this command!').then(msg => { setTimeout(() => msg.delete(), 5000) })
        }

    },
}

错误

   throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Unknown Message
    at RequestHandler.execute (D:\STUFF\BOT\Passion-Bot-V13\node_modules\discord.js\src\rest\RequestHandler.js:298:13)
    V13\node_modules\discord.js\src\structures\Message.js:709:5) {
  method: 'delete',
  path: '/channels/886173223144792074/messages/886174452994437170',
  code: 10008,
  httpStatus: 404,
  requestData: { json: undefined, files: [] }
}

此错误是针对机器人无法删除的缓存消息抛出的(可能已固定?,可能已缓存但不存在?)您可以通过 try/catch

抑制此错误
try {
msg.delete()
} catch(e) {}

此外,在您的代码的最顶部有一个 setTimeout( () => message.delete(), 3500);(在删除第一条消息之前等待 3.5 秒),当您遍历消息时,带有命令的特定消息很可能也在现有的缓存中,因此其中任何一个都会删除它。

我的建议:

  • 在循环中的 msg.delete() 中使用 try/catch
  • 删除初始 message.delete()
  • 的超时

所以您现在遇到的问题是当一条消息不存在时,因为每 DiscordAPIError: Unknown Message 只意味着一条消息可能会被删除。

代码:

setTimeout(() => message.delete(), 3500);

错误的问题是:

            FilteredMessages.forEach(msg => {
                if (deletedMessages >= amount) return
                msg.delete()
                deletedMessages++
            })

如果你在 forEach 函数中间看到 msg.delete() ,消息已经 已经 被删除,因此 setTimeout 很明显会导致问题。

通过删除 setTimeout(() => message.delete(), 3500);,它很可能会解决问题。