New to coding here; I'm making a discord bot. I want to add a timer function to this "clear messages" command in order to wait a couple seconds before it proceeds to actually clear the messages, and let the user know what is about to be deleted.
module.exports = {
name: 'clear',
description: "Clears messages",
async execute (message, args){
if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply(`You can't use this command.`);
if(!args[0]) return message.reply("Enter the amount of messages that you would like to clear.");
if(isNaN(args[0])) return message.reply("Enter a number.");
if(args[0] > 100) return message.reply("100 messages is the highest amount of messages you can clear.");
if(args[0] < 1) return message.reply("1 messages is the least amount of messages you can clear.");
await message.channel.messages.fetch({limit: 2 + args[0]}).then(messages =>{
message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
message.channel.bulkDelete(messages);
});
}
}
When fetching the messages, I want it to also grab the two new messages made by the one typing the command, and the bots response. I tried adding a timer function here:
await message.channel.messages.fetch({limit: 2 + args[0]}).then(messages =>{
message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
setTimeout(5000)
message.channel.bulkDelete(messages);
but it results in the following error:
UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_CALLBACK]: Callback must be a function. Received 5000
at setTimeout (timers.js:135:3)
at C:\Users\ACER\Desktop\lucariobot\commands\clear.js:14:13
Putting the setTimeout (as well as the warning message) above the await message.channel.messages.fetch function doesn't fix my problem either. Not sure how I would implement it if its going to mess with fetching the messages I want deleted.
setTimeout
's first argument is the callback which will be invoked after the duration (the second argument)
For example,
await message.channel.messages.fetch({limit: 2 + args[0]}).then(messages =>{
message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
setTimeout(() => {
message.channel.bulkDelete(messages);
}, 5000)
...
As a general note, mixing await
and classic Promise chaining ( .then
) is interesting. Something like
// helper so you can await a setTimeout
function sleep(seconds) {
return new Promise(r => setTimeout(r, seconds * 1000))
}
const messages = await message.channel.messages.fetch({limit: 2 + args[0]})
message.channel.send('Deleting '+args[0]+' messages in 5 seconds...')
await sleep(5) // see above
message.channel.bulkDelete(messages);
keeps your code flat and, imo more readable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.