I want to make a countdown timer that uses a command /timer minutes seconds
where the user chooses how long the countdown will be. I want the bot to send the timer as a reply to the command which I've successfully done. However, I also want the message to update along with the timer.
I can console.log
the timer and it works but I can't figure out how to make the bot edit its own message. I have tried to just simply edit the bots' message without the timer but with no success.
Code:
const { SlashCommandBuilder,} = require("@discordjs/builders")
const { MessageEmbed, Channel, Message, MessageReaction, Client } = require('discord.js');
const { Countdown } = require('countdown');
module.exports = {
data: new SlashCommandBuilder()
.setName("timer")
.setDescription("Starta en timer")
.addNumberOption((option) => option.setName('minutes').setDescription('Set amount of minutes').setRequired(true))
.addNumberOption((option) => option.setName('seconds').setDescription('Set amount of seconds').setRequired(true)),
execute: async ({ client, interaction}) => {
let minutes = interaction.options.getNumber("minutes")
let seconds = interaction.options.getNumber("seconds")
let minutesToSeconds = minutes * 60;
let time = minutesToSeconds seconds;
let duration = time;
let getTime = "Timer: " duration
let interval = setInterval((timerMessage) => {
duration--;
if(duration == 0) {
clearInterval(interval);
getTime ="Timer is done"
}
getTime.edit("Timer: " duration)
console.log(duration)
}, 1000)
await interaction.reply(
getTime
);
},
}
CodePudding user response:
What you are looking for is interaction.editReply()
to update the interaction message after an x amount of time using your timer. This is an example of how you can use it:
bot.on("interactionCreate", async interaction => {
let seconds = 10;
let timerMessage = "Timer is started.";
let interval = setInterval(() => {
seconds--;
timerMessage = `Timer: ${seconds} seconds left.`;
if(seconds === 0) {
clearInterval(interval);
interval = null;
interaction.editReply(`Timer has finished!`);
} else {
interaction.editReply(timerMessage)
}
}, 1000);
await interaction.reply({
content: timerMessage
});
});
This also works if ephemeral
is set to true
. Note that this is a raw example, and you should adjust the code by your needs.