Prefix command that users can only run once a day. If a user tries to run before the cooldown period ends, tells them how much time is remaining before the next use.
const lib = require('lib')({token: process.env.STDLIB_SECRET_TOKEN});
const COOLDOWN_TIME_SECONDS = 86400;
if (context.params.event.content.startsWith('!daily')) {
let key = `daily_prefix_command_example:${context.params.event.author.id}`;
let lastUsedAt = await lib.utils.kv['@0.1.16'].get({
key: key
});
if (lastUsedAt) {
let elapsedTimeSeconds = (new Date() - new Date(lastUsedAt)) / 1000;
let timeRemaining = COOLDOWN_TIME_SECONDS - elapsedTimeSeconds;
let timeRemainingHours = Math.floor(timeRemaining / 3600);
let timeRemainingHoursString = timeRemainingHours ? timeRemainingHours + (timeRemainingHours === 1 ? ' hour' : ' hours') : '';
let timeRemainingMinutes = Math.floor(timeRemaining % 3600 / 60);
let timeRemainingMinutesString = timeRemainingMinutes ? timeRemainingMinutes + (timeRemainingMinutes === 1 ? ' minute' : ' minutes') : '';
let timeRemainingSeconds = Math.floor(timeRemaining % 60);
let timeRemainingSecondsString = timeRemainingSeconds ? timeRemainingSeconds + (timeRemainingSeconds === 1 ? ' second' : ' seconds') : '';
let timeRemainingString = [
timeRemainingHoursString,
timeRemainingMinutesString,
timeRemainingSecondsString
].filter(v => !!v).join(', ');
return lib.discord.channels['@0.1.1'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: `Sorry, you must wait ${timeRemainingString} before you can use this command again.`
});
} else {
await lib.utils.kv['@0.1.16'].set({
key: key,
value: new Date().toISOString(),
ttl: COOLDOWN_TIME_SECONDS
});
return lib.discord.channels['@0.1.1'].messages.create({
channel_id: `${context.params.event.channel_id}`,
content: `You used the command! Now you have to wait 24 hours to use this command again.`
});
}
}