Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

358
Visualizações
Discord.js v13 How to prevent the bot from crashing on attempted message deletion?

I have this 'clear' command for my discord bot and it should work like this: -user types in !mute

  1. the bot deletes this many messages (up to 100)
  2. the bot sends a message saying that these messages were deleted
  3. the bot deletes that message 5 seconds later It all works except for the last part, you see if after executing part 2 the message is deleted by another source then the bot can't find a message to delete and crashes. The code is as follow:
module.exports = {
    name: 'clear',
    description: "clears messages",
    async execute(message, args)
    {   
        if(!args[0]) return message.reply("Please specify how many messages you want to clear!");
        if(isNaN(args[0])) return message.reply("Please enter a number of messages you want to clear!");
        
        if(args[0] > 100) return message.reply("You can't delete more than 100 messages!");
        if(args[0] < 1) return message.reply("You can't delete less than 1 message!");

        await message.channel.messages.fetch({limit: args[0]}).then(messages =>{
            message.channel.bulkDelete(messages).then(() => {
                message.channel.send("Deleted " + args[0] + " messages") .then(msg => {
                    let id = msg.id;
                    setTimeout(function(){
                        if(message.channel.messages.fetch(id))
                        {
                            try {
                                msg.delete()
                            }
                            catch (error) {
                                console.log(error)
                                return
                            }
                        }
                    }, 5000);
                  })
                });
            })
    }
}

The error I'm getting is:

C:\Users\Miki\Desktop\discord boty\jajco bot\node_modules\discord.js\src\rest\RequestHandler.js:350
      throw new DiscordAPIError(data, res.status, request);
            ^

DiscordAPIError: Unknown Message
    at RequestHandler.execute (C:\Users\Miki\Desktop\discord boty\jajco bot\node_modules\discord.js\src\rest\RequestHandler.js:350:13)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async RequestHandler.push (C:\Users\Miki\Desktop\discord boty\jajco bot\node_modules\discord.js\src\rest\RequestHandler.js:51:14)
    at async MessageManager._fetchId (C:\Users\Miki\Desktop\discord boty\jajco bot\node_modules\discord.js\src\managers\MessageManager.js:219:18) {
  method: 'get',
  path: '/channels/943105549795471443/messages/946096412922368100',
  code: 10008,
  httpStatus: 404,
  requestData: { json: undefined, files: [] }
}

As you can see I've tried using the try...catch() but it didn't fix the problem. Any ideas on what to do? Or maybe there is a mistake in my code like a missing import or some other thing like that?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

First off lets take a look at this code:

try {
    msg.delete();
} catch (error) {
    return console.log(error);
}

This code won't do what you expect. msg.delete(); is a function that returns a Promise. A try/catch structure won't do anything if the promise fails. So instead, to catch the error, you have to use the catch method on the Promise, just as you used .then() earlier, you'll have to use .catch().

So your new code will be like this:

msg.delete().catch(error => console.error(error);
// Or, even better:
msg.delete().catch(console.error);

That is the exact same thing here:

if (message.channel.messages.fetch(id))

That will always be true because the fetch() function will return a Promise ans since it is neither a 0, '' (empty string),NaN, false, undefined or null See here for false values

Instead, what you're trying to do is check if the messages contain your id:

message.channel.messages.fetch(id).then(msg => {
    // Do what you want with the fetched msg
}).catch(error => {
    // Console error why it failed to fetch the id (probably because it doesn't exist or got deleted)
    message.reply('Failed to fetch the id');
});

Lastly this code also has some issues:

message.channel.bulkDelete(messages).then(() => {

messages is a Collection, not a number, bulkDelete() waits for a number so instead do this:

message.channel.bulkDelete(messages.size).then(() => {

I personnally don't see why you have to fetch the message, you can simply do this:

message.channel.messages.fetch({
    limit: args[0]
}).then(messages => {
    message.channel.bulkDelete(messages.size).then(() => {
        message.channel.send(`Deleted ${args[0]} messages`).then(msg => {
            setTimeout(() => msg.delete(), 5000);
        });
    });
});
about 4 years ago · Juan Pablo Isaza Relatório

0

All you need to do is to await msg.delete() inside your try block. A promise must be settled before it can be tested for any error.

try {
  // Add 'await'
  await msg.delete();
} catch (error) {
  return console.log(error);
}

If you want to void the error to have the function fail silently:

msg.delete()
   .catch(() => null);

You can also check Message#deletable before having your client attempt to delete it:

if (msg.deletable) {
   // I'd still recommend adding your preferred error handling
   msg.delete();
}
about 4 years ago · Juan Pablo Isaza Relatório

0

return message.reply({ content: "Done" })
          .then(m => setTimeout(() => message.delete().catch(() => null), 2500))

use it like this it'll solve the issue for d.js v13.6

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda