Skip to content

Instantly share code, notes, and snippets.

@Eng-Bunnys
Created November 1, 2022 19:37
Show Gist options
  • Save Eng-Bunnys/a797f539ba9955e706bef8fd35c9a0e1 to your computer and use it in GitHub Desktop.
Save Eng-Bunnys/a797f539ba9955e706bef8fd35c9a0e1 to your computer and use it in GitHub Desktop.
Chat XP with cooldown to avoid spam
// This code is a general use case, meaning that it's auto enabled for all guilds, to make it per guild you'll have to moidfy it yourself
// This is done in the messageCreate event
// The channel that the level up message will be sent to, by default this should be the current channel unless you have a feature that has a custom level up channel
const levelUpChannel = message.channel;
// Accessing the data base and checking if the message author has an existing account/schema
let userData = await pointSchema.findOne({
userId: message.author.id
});
// Generating a random amount of XP that will be given
const randomPointAdd = Math.floor(Math.random() * 15) + 1;
// If no data exists, we create one
if (!userData) {
let newUserData = new pointSchema({
userId: message.author.id, // Data type: String
points: randomPointAdd, // Data type : Number
lastXPearned: new Date(Date.now()) // Data type: Date
// Resetting the XP earn cooldown to avoid spamming for XP
});
// Saving the data and returning
return newUserData.save();
}
// Checking if the user is not on cooldown (30 sec)
if (Date.parse(userData.lastXPearned) + 30000 < Date.now()) {
// Adding XP if the user is not on cooldown
await userData.updateOne({
points: userData.points + randomPointAdd,
lastXPearned: new Date(Date.now())
});
// Function that checks how much XP is required to level up once
function levelEquation(currentLevel) {
if (Number.isNaN(currentLevel)) return console.log(`Level is not a number`);
let xpRequired = 500 * Math.pow(currentLevel, 2) - 500 * currentLevel + 50;
return xpRequired;
}
const requiredPoints = levelEquation(userData.level);
// If the user more XP than required we add a level
if (userData.points >= requiredPoints) {
await userData.updateOne({
level: userData.level + 1,
points: 1
});
// Telling the user that they leveled up
await message.react("<a:realization:853273206978773022>");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment