I'm made a purge command which targets a particular member and deletes the given amount. The problem is it deletes the messages correctly while on completion it throws a unknown error. Help me fix it! Here's the code and its error
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) })
}
},
}
Error
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: [] }
}
This error is thrown for a cached message which bot is unable to delete appearently ( maybe pinned?, maybe cached but non existant?) You could just supress this error via try/catch
try {
msg.delete()
} catch {}
Furthermore at the topmost part of your code there's a
setTimeout(() => message.delete(), 3500);
(waiting 3.5 seconds before deleting the first message), when you loop through your messages it's highly likely that the particular message with the command is in the cache existing too, so either one of those would delete it.
My suggestion:
try/catch
in your msg.delete()
within the loop
ORmessage.delete()