javascript - 顯示冷卻時間剩餘
我想要顯示冷卻時間剩餘的時間,但我不確定是否可以使用我目前的格式來完成。這可能嗎?或者有沒有更好的方式來使用冷卻?我刪掉了大部分與此無關的程式碼。
let cooldown = new Set();
if(msgObject.content.startsWith("-eat")) {
let amount = Math.floor(Math.random() * 2500) + 1;
let Channel = msgObject.channel.id
if(Channel != `623195917083738136` && Channel != `623195981919289344` ){//bot test
msgObject.channel.send('Cannot use command here, ' + msgObject.author)
.then(msg => {
(msg as Discord.Message).delete(20000)
.catch(console.error);
})
return;
}
if(cooldown.has(msgObject.author.id)){
msgObject.channel.send(`You have to wait 3 hours to use this command again!`)
.then(msg => {
(msg as Discord.Message).delete(20000)
.catch(console.error);
})
return;
}
if(msgObject.content.startsWith("-eat")){
cooldown.add(msgObject.author.id)
}
setTimeout(() => {
cooldown.delete(msgObject.author.id)
}, cdseconds * 1000);
{let embed = new Discord.RichEmbed()
.setAuthor(`${msgObject.author.tag}`, msgObject.author.displayAvatarURL)
.setDescription(`${msgObject.author}, ${(eat[index1])}${amount} DinoBucks`)
.setColor("RANDOM");
msgObject.channel.send(embed)
.then(msg => {
(msg as Discord.Message).delete(20000)
.catch(console.error);
})
}
}
}
答案#1
以你目前的設置,這是不可能的。不過,你可以使用類似 Discord.js 指南上的方法:
// a collection of user ids to when (the timestamp) they used the command
const timestamps = new Discord.Collection<string, number>();
if (msgObject.content.startsWith("-eat")) {
const now = Date.now();
const cooldownAmount = cdseconds * 1000;
if (timestamps.has(msgObject.author.id)) {
const expirationTime = timestamps.get(msgObject.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return msgObject.reply(`You have to wait ${timeLeft.toFixed(1)} seconds to use this command again!`)
}
}
// for v11:
// const embed = new Discord.RichEmbed()
const embed = new Discord.MessageEmbed()
.setAuthor(`${msgObject.author.tag}`, msgObject.author.displayAvatarURL)
// rest of command...
timestamps.set(msgObject.author.id, now);
setTimeout(() => timestamps.delete(msgObject.author.id), cooldownAmount);
}
已更新至 Discord.js v13。
答案#2
以你的冷卻定義格式這是不可能的。我建議你為此使用 discord.collection,有一個很好的範例實作。
