13

I'm trying to make a Discord bot delete its "system messages" after, say, 10 seconds, because I've been seeing a lot of "Invalid command" errors and "Done!" notifications, and I'd like to clear them out for actual messages. This is different from deleting messages where the user has a command; I already have that capability.

Federico Grandi
  • 6,785
  • 5
  • 30
  • 50
haley
  • 845
  • 1
  • 7
  • 15

3 Answers3

31

I recommend you send the message, wait for the response and delete the returned message after that time. Here's how it'd work now:

message.reply('Invalid command')
  .then(msg => {
    setTimeout(() => msg.delete(), 10000)
  })
  .catch(/*Your Error handling if the Message isn't returned, sent, etc.*/);

See the Discord.JS Docs for more information about the Message.delete() function and the Node Docs for information about setTimeout().

Old ways to do this were:

Discord.JS v12:

message.reply('Invalid command')
  .then(msg => {
    msg.delete({ timeout: 10000 })
  })
  .catch(/*Your Error handling if the Message isn't returned, sent, etc.*/);

Discord.JS v11:

message.reply('Invalid command')
  .then(msg => {
    msg.delete(10000)
  })
  .catch(/*Your Error handling if the Message isn't returned, sent, etc.*/);
LW001
  • 2,452
  • 6
  • 27
  • 36
  • 14
    if you're using discord.js v12 (master branch currently) you will need to change `msg.delete(10000)` to `msg.delete({ timeout: 10000 })` – Tony Jan 08 '20 at 00:24
  • Now deprecated. Please use `setTimeout(() => msg.delete(), 10000)` – PiggyPlex Feb 07 '21 at 12:41
  • As this is still active, I've updated the answer to the way to do it on the current master branch (v13). – LW001 May 28 '21 at 11:32
20

Current API differs from older versions. Proper way to pass timeout looks like this now.

Discord.js v13

message.reply('Invalid command!')
  .then(msg => {
    setTimeout(() => msg.delete(), 10000)
  })
  .catch(console.error);

Discord.js v12

message.reply('Invalid command!')
  .then(msg => {
    msg.delete({ timeout: 10000 })
  })
  .catch(console.error);
Jsowa
  • 9,104
  • 5
  • 56
  • 60
3

Every Discord.JS Version has a new way to delete with timeout.

Discord.JS V11:

message.channel.send('Test!').then(msg => msg.delete(10000));

Discord.JS V12:

message.channel.send('Test!').then(msg => msg.delete({timeout: 10000}));

Discord.JS V13:

message.channel.send('Test!').then(msg => setTimeout(() => msg.delete(), 10000));

Time is in milliseconds

PLASMA chicken
  • 2,777
  • 2
  • 15
  • 25