const { Client, Message } = require('discord.js');
const calculateLevelXp = require('./calculateLevelXp');
const UserProfile = require('./userProfile.js');
const cooldowns = new Set();
function getRandomXp(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
/**
*
* @param {Client} client
* @param {Message} message
*/
module.exports = async (client, message) => {
if (!message.inGuild() || message.author.bot || cooldowns.has(message.author.id)) return;
const xpToGive = getRandomXp(5, 15);
const query = {
userId: message.author.id,
guildId: message.guild.id,
};
try {
const userProfile = await UserProfile.findOne(query);
if (userProfile) {
userProfile.xp += xpToGive;
if (userProfile.xp > calculateLevelXp(userProfile.level)) {
userProfile.xp = 0;
userProfile.level += 1;
message.channel.send(`${message.member} you have leveled up to **level ${userProfile.level}**.`);
}
await userProfile.save().catch((e) => {
console.log(`Error saving updated level ${e}`);
return;
});
cooldowns.add(message.author.id);
setTimeout(() => {
cooldowns.delete(message.author.id);
}, 60000);
}
// if (!level)
else {
// create new level
const newUserProfile = new UserProfile({
userId: message.author.id,
guildId: message.guild.id,
xp: xpToGive,
});
await newUserProfile.save();
cooldowns.add(message.author.id);
setTimeout(() => {
cooldowns.delete(message.author.id);
}, 60000);
}
} catch (error) {
console.log(`Error giving xp: ${error}`);
}
};