Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const Discord = require('discord.js');
- const client = new Discord.Client();
- client.commands = new Discord.Collection();
- const fs = require('fs');
- const config = require('./config.json');
- client.login(config.token);
- const connection = require('./database');
- // Will delete
- const Enmap = require("enmap");
- client.points = new Enmap("points");
- const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
- for (const file of commandFiles) {
- console.log(file.slice(0, -3));
- const command = require(`./commands/${file.slice(0, -3)}`)
- client.commands.set(command.name, command);
- }
- client.on('ready', () => {
- console.log(`logged in as ${client.user.tag}!`);
- client.user.setPresence({
- status: "dnd",
- activity: {
- name: `${config.prefix}help`,
- type: "Listening"
- }
- });
- });
- client.on('message', async message => {
- if (!message.content.startsWith(config.prefix) || message.author.bot) return;
- const args = message.content.slice(config.prefix.length).trim().split(/ + /);
- const commandName = args.shift().toLowerCase();
- const command = client.commands.get(commandName)
- || client.commands.find(command => command.aliases && command.aliases.includes(commandName));
- if (!command) return;
- if (!message.guild) return;
- if (command.guildOnly && message.channel.type !== 'text') {
- return message.reply('I can\'t execute that command inside DMs!');
- }
- if (command.args && args.length) {
- let reply = `You didn't provide any arguments, ${message.author}!`;
- if (command.usage) {
- reply += `\nThe proper usage would be: \`${config.prefix}${command.name} ${command.usage}\``;
- }
- return message.channel.send(reply);
- }
- try {
- command.execute(message, args);
- } catch (error) {
- console.error(error);
- message.reply('there was an error trying to execute that command!');
- }
- /* OTHER CODE */
- //step 1 add new user that never messaged before to our db
- let score;
- if (message.guild) {
- const author = message.author.id;
- const guild = message.guild.id;
- await (await connection).query(
- `INSERT IGNORE INTO Points (guildId, user, level, nextLevel, points, remainingPoints) VALUES (?, ?, 1, 2, 0, 100);`,
- [guild, author]
- );
- // ^^ WORKS!
- // also retrieve points for current users to store in cache.
- const res = await (await connection).query(
- `SELECT * FROM Points WHERE user = ? AND guildId = ?;`,
- [author, guild]
- )
- let score = res[0][0];
- console.log(score);
- //step 2 calculate updated points and update the db
- score.points = ++score.points;
- console.log(score.points);
- const curLevel = Math.floor(0.1 * Math.sqrt(score.points));
- console.log(curLevel);
- if(score.level < curLevel) {
- // Level up!
- score.level++;
- message.reply(`You've leveled up to level **${curLevel}**! Ain't that dandy?`);
- }
- await (await connection).query(
- `UPDATE Points SET points = ? AND level = ? WHERE guildId = ? AND user = ?;`,
- [score.points, score.level, message.guild.id, message.author.id]
- );
- //step 3 retrieve points from db when !points is ran
- //step 4 get leaderboard
- //step 5 cleanup db for members not in the server anymore.
- // Let's simplify the `key` part of this.
- const key = `${message.guild.id}-${message.author.id}`;
- client.points.ensure(key, {
- user: message.author.id,
- guild: message.guild.id,
- points: 0, // adds users to the enmap that have never messaged in a particular guild before.
- level: 1
- });
- client.points.inc(key, "points"); //increments the points by 1 point for each message.
- const cureLevel = Math.floor(0.1 * Math.sqrt(client.points.get(key, "points"))); // increments the points for each level
- // Act upon level up by sending a message and updating the user's level in enmap.
- if (client.points.get(key, "level") < cureLevel) {
- message.reply(`You've leveled up to level **${cureLevel}**! Ain't that dandy?`);
- client.points.set(key, cureLevel, "level");
- }
- if(command === "leaderboard") {
- // Get a filtered list (for this guild only), and convert to an array while we're at it.
- const filtered = client.points.filter( p => p.guild === message.guild.id ).array();
- // Sort it to get the top results... well... at the top. Y'know.
- const sorted = filtered.sort((a, b) => b.points - a.points);
- // Slice it, dice it, get the top 10 of it!
- const top10 = sorted.splice(0, 10);
- // Now shake it and show it! (as a nice embed, too!)
- const embed = new Discord.MessageEmbed()
- .setTitle("Leaderboard")
- .setAuthor(client.user.username, message.guild.iconURL())
- .setDescription("Our top 10 points leaders!")
- .setColor(0x00AE86);
- for(const data of top10) {
- try {
- embed.addField(client.users.cache.get(data.user).tag, `${data.points} points (level ${data.level})`);
- } catch {
- embed.addField(`<@${data.user}>`, `${data.points} points (level ${data.level})`);
- }
- }
- return message.channel.send({embed});
- }
- if(command === "give") {
- // Limited to guild owner - adjust to your own preference!
- if(message.author.id !== message.guild.ownerID)
- return message.reply("You're not the boss of me, you can't do that!");
- const user = message.mentions.users.first() || client.users.get(args[0]);
- if(!user) return message.reply("You must mention someone or give their ID!");
- const pointsToAdd = parseInt(args[1], 10);
- if(!pointsToAdd)
- return message.reply("You didn't tell me how many points to give...")
- // Ensure there is a points entry for this user.
- client.points.ensure(`${message.guild.id}-${user.id}`, {
- user: message.author.id,
- guild: message.guild.id,
- points: 0,
- level: 1
- });
- // Get their current points.
- let userPoints = client.points.get(`${message.guild.id}-${user.id}`, "points");
- userPoints += pointsToAdd;
- // And we save it!
- client.points.set(`${message.guild.id}-${user.id}`, userPoints, "points")
- message.channel.send(`${user.tag} has received **${pointsToAdd}** points and now stands at **${userPoints}** points.`);
- }
- if(command === "cleanup") {
- // Let's clean up the database of all "old" users,
- // and those who haven't been around for... say a month.
- // Get a filtered list (for this guild only).
- const filtered = client.points.filter( p => p.guild === message.guild.id );
- // We then filter it again (ok we could just do this one, but for clarity's sake...)
- // So we get only users that haven't been online for a month, or are no longer in the guild.
- const rightNow = new Date();
- const toRemove = filtered.filter(data => {
- return !message.guild.members.cache.has(data.user) || rightNow - 2592000000 > data.lastSeen;
- });
- toRemove.forEach(data => {
- client.points.delete(`${message.guild.id}-${data.user}`);
- });
- message.channel.send(`I've cleaned up ${toRemove.size} old farts.`);
- }
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment