DudeThatsErin

index.js test bot

Apr 23rd, 2021
1,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const Discord = require('discord.js');
  2. const client = new Discord.Client();
  3. client.commands = new Discord.Collection();
  4. const fs = require('fs');
  5. const config = require('./config.json');
  6. client.login(config.token);
  7. const connection = require('./database');
  8.  
  9. // Will delete
  10. const Enmap = require("enmap");
  11. client.points = new Enmap("points");
  12.  
  13. const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
  14.  
  15. for (const file of commandFiles) {
  16.     console.log(file.slice(0, -3));
  17.     const command = require(`./commands/${file.slice(0, -3)}`)
  18.     client.commands.set(command.name, command);
  19.  
  20. }
  21.  
  22. client.on('ready', () => {
  23.     console.log(`logged in as ${client.user.tag}!`);
  24.  
  25.     client.user.setPresence({
  26.         status: "dnd",
  27.         activity: {
  28.             name: `${config.prefix}help`,  
  29.             type: "Listening"
  30.         }
  31.       });
  32. });
  33.  
  34. client.on('message', async message => {
  35.     if (!message.content.startsWith(config.prefix) || message.author.bot) return;
  36.     const args = message.content.slice(config.prefix.length).trim().split(/ + /);
  37.     const commandName = args.shift().toLowerCase();
  38.  
  39.     const command = client.commands.get(commandName)
  40.         || client.commands.find(command => command.aliases && command.aliases.includes(commandName));
  41.     if (!command) return;
  42.  
  43.     if (!message.guild) return;
  44.     if (command.guildOnly && message.channel.type !== 'text') {
  45.         return message.reply('I can\'t execute that command inside DMs!');
  46.     }
  47.  
  48.  
  49.     if (command.args && args.length) {
  50.         let reply = `You didn't provide any arguments, ${message.author}!`;
  51.  
  52.         if (command.usage) {
  53.             reply += `\nThe proper usage would be: \`${config.prefix}${command.name} ${command.usage}\``;
  54.         }
  55.  
  56.         return message.channel.send(reply);
  57.     }
  58.  
  59.     try {
  60.         command.execute(message, args);
  61.     } catch (error) {
  62.         console.error(error);
  63.         message.reply('there was an error trying to execute that command!');
  64.     }
  65.  
  66.     /* OTHER CODE */
  67.  
  68.     //step 1 add new user that never messaged before to our db
  69.     let score;
  70.     if (message.guild) {
  71.         const author = message.author.id;
  72.         const guild = message.guild.id;
  73.         await (await connection).query(
  74.             `INSERT IGNORE INTO Points (guildId, user, level, nextLevel, points, remainingPoints) VALUES (?, ?, 1, 2, 0, 100);`,
  75.             [guild, author]
  76.         );
  77.  
  78.         // ^^ WORKS!
  79.  
  80.     // also retrieve points for current users to store in cache.
  81.     const res = await (await connection).query(
  82.         `SELECT * FROM Points WHERE user = ? AND guildId = ?;`,
  83.         [author, guild]
  84.     )
  85.     let score = res[0][0];
  86.     console.log(score);
  87.  
  88.     //step 2 calculate updated points and update the db
  89.     score.points = ++score.points;
  90.     console.log(score.points);
  91.     const curLevel = Math.floor(0.1 * Math.sqrt(score.points));
  92.     console.log(curLevel);
  93.     if(score.level < curLevel) {
  94.         // Level up!
  95.         score.level++;
  96.         message.reply(`You've leveled up to level **${curLevel}**! Ain't that dandy?`);
  97.     }
  98.     await (await connection).query(
  99.         `UPDATE Points SET points = ? AND level = ? WHERE guildId = ? AND user = ?;`,
  100.         [score.points, score.level, message.guild.id, message.author.id]
  101.     );
  102.      
  103.  
  104.     //step 3 retrieve points from db when !points is ran
  105.  
  106.     //step 4 get leaderboard
  107.  
  108.     //step 5 cleanup db for members not in the server anymore.
  109.  
  110.    
  111.         // Let's simplify the `key` part of this.
  112.         const key = `${message.guild.id}-${message.author.id}`;
  113.         client.points.ensure(key, {
  114.           user: message.author.id,
  115.           guild: message.guild.id,
  116.           points: 0, // adds users to the enmap that have never messaged in a particular guild before.
  117.           level: 1
  118.         });
  119.         client.points.inc(key, "points"); //increments the points by 1 point for each message.
  120.            
  121.     const cureLevel = Math.floor(0.1 * Math.sqrt(client.points.get(key, "points"))); // increments the points for each level
  122.    
  123.         // Act upon level up by sending a message and updating the user's level in enmap.
  124.         if (client.points.get(key, "level") < cureLevel) {
  125.             message.reply(`You've leveled up to level **${cureLevel}**! Ain't that dandy?`);
  126.             client.points.set(key, cureLevel, "level");
  127.           }
  128.  
  129.           if(command === "leaderboard") {
  130.             // Get a filtered list (for this guild only), and convert to an array while we're at it.
  131.             const filtered = client.points.filter( p => p.guild === message.guild.id ).array();
  132.          
  133.             // Sort it to get the top results... well... at the top. Y'know.
  134.             const sorted = filtered.sort((a, b) => b.points - a.points);
  135.          
  136.             // Slice it, dice it, get the top 10 of it!
  137.             const top10 = sorted.splice(0, 10);
  138.          
  139.             // Now shake it and show it! (as a nice embed, too!)
  140.             const embed = new Discord.MessageEmbed()
  141.               .setTitle("Leaderboard")
  142.               .setAuthor(client.user.username, message.guild.iconURL())
  143.               .setDescription("Our top 10 points leaders!")
  144.               .setColor(0x00AE86);
  145.             for(const data of top10) {
  146.               try {
  147.                 embed.addField(client.users.cache.get(data.user).tag, `${data.points} points (level ${data.level})`);
  148.               } catch {
  149.                 embed.addField(`<@${data.user}>`, `${data.points} points (level ${data.level})`);
  150.               }
  151.             }
  152.             return message.channel.send({embed});
  153.           }
  154.  
  155.           if(command === "give") {
  156.             // Limited to guild owner - adjust to your own preference!
  157.             if(message.author.id !== message.guild.ownerID)
  158.               return message.reply("You're not the boss of me, you can't do that!");
  159.        
  160.             const user = message.mentions.users.first() || client.users.get(args[0]);
  161.             if(!user) return message.reply("You must mention someone or give their ID!");
  162.        
  163.             const pointsToAdd = parseInt(args[1], 10);
  164.             if(!pointsToAdd)
  165.               return message.reply("You didn't tell me how many points to give...")
  166.        
  167.             // Ensure there is a points entry for this user.
  168.             client.points.ensure(`${message.guild.id}-${user.id}`, {
  169.               user: message.author.id,
  170.               guild: message.guild.id,
  171.               points: 0,
  172.               level: 1
  173.             });
  174.        
  175.             // Get their current points.
  176.             let userPoints = client.points.get(`${message.guild.id}-${user.id}`, "points");
  177.             userPoints += pointsToAdd;
  178.        
  179.        
  180.             // And we save it!
  181.             client.points.set(`${message.guild.id}-${user.id}`, userPoints, "points")
  182.        
  183.             message.channel.send(`${user.tag} has received **${pointsToAdd}** points and now stands at **${userPoints}** points.`);
  184.           }
  185.        
  186.           if(command === "cleanup") {
  187.             // Let's clean up the database of all "old" users,
  188.             // and those who haven't been around for... say a month.
  189.        
  190.             // Get a filtered list (for this guild only).
  191.             const filtered = client.points.filter( p => p.guild === message.guild.id );
  192.        
  193.             // We then filter it again (ok we could just do this one, but for clarity's sake...)
  194.             // So we get only users that haven't been online for a month, or are no longer in the guild.
  195.             const rightNow = new Date();
  196.             const toRemove = filtered.filter(data => {
  197.               return !message.guild.members.cache.has(data.user) || rightNow - 2592000000 > data.lastSeen;
  198.             });
  199.        
  200.             toRemove.forEach(data => {
  201.               client.points.delete(`${message.guild.id}-${data.user}`);
  202.             });
  203.        
  204.             message.channel.send(`I've cleaned up ${toRemove.size} old farts.`);
  205.           }
  206.     }
  207. });
  208.  
  209.  
  210.  
Advertisement
Add Comment
Please, Sign In to add comment