revolt-bot/util/levels.js

55 lines
1.9 KiB
JavaScript

const Enmap = require('enmap');
const { client, logger, config, db } = require('..');
const levels = new Enmap({ name: "levels" });
let cooldowns = {}
client.on('message', async message => {
if (message.author === client.user._id) return;
try {
if (db.blacklist.get(message.author)?.blacklisted) return;
const channel = await client.channels.fetch(message.channel);
if (channel.channel_type !== "Group") return;
let userLevels = levels.get(message.author);
if (!userLevels) userLevels = { xp: 0, level: 0 }
if (userLevels.enabled === false) return;
// Ensure users only get XP once a minute
if (cooldowns[message.author] > Date.now()) return;
cooldowns[message.author] = Date.now() + 1000 * 60;
// Give a random amount of XP between 15 and 25
userLevels.xp += 15 + Math.round(Math.random() * 10);
let newLevel = 0;
for (const i of levelups) userLevels.xp >= i && newLevel++;
if (newLevel > userLevels.level) {
client.channels.sendMessage(message.channel, `>GG <@${message.author}>, you just leveled up! New level: **${newLevel}**`)
.catch(console.error)
.then(msg => setTimeout(() =>
client.channels.deleteMessage(channel._id, msg?._id).catch(console.warn), 15000));
userLevels.level = newLevel;
}
levels.set(message.author, userLevels);
} catch (e) {
console.error(e);
}
});
// How much XP is required to level up
// 30, 63, 99, 139, 183, 231, 284, ...
const levelups = [ 30 ];
while (levelups.length < 250) {
let i = levelups[levelups.length - 1];
levelups.push(Math.round(i * (i > 50000 ? 0.05 : (i < 100 ? 1.3 : 1.1))));
}
for (const i in levelups) levelups[i] += levelups[i - 1] || 0;
// Export level DB for access from other modules
module.exports = { levels, levelups };