diff --git a/data/strings.json b/data/strings.json index 1d2c13b..8aa5de8 100644 --- a/data/strings.json +++ b/data/strings.json @@ -4,7 +4,7 @@ }, "help": { "title": "Silvanus Help", - "info": "Silvanus is the ultimate Grow A Tree companion bot! Quickly compare your server's tree to others on the leaderboard with automatic calculation of tree height differences, active growth detection, watering time calculations, and more! Get started with and , then check out .\n\nImportant Note: Silvanus is only as up-to-date as your server's Tree and Tallest Trees messages. Make sure to refresh them before refreshing Silvanus' Compare message.\n\nFor the best experience we recommend the use of a single and message, otherwise make sure to run each time you run .", + "info": "Silvanus is the ultimate Grow A Tree companion bot! Quickly compare your server's tree to others on the leaderboard with automatic calculation of tree height differences, active growth detection, watering time calculations, and more! Get started with and , then check out .\n\nImportant Note: Silvanus is only as up-to-date as your server's Tree and Tallest Trees messages. Make sure to refresh them before refreshing Silvanus' Compare message.\n\nFor the best experience we recommend the use of a single and message, otherwise make sure to run each time you run .\nStatus Indicator: ``[ Active Growth Indicator: 💧 | 24 Hour Observed Growth | Wait Time Between Waters ]``", "setup": "To begin analyzing your Tree, first you must set up the reference messages.\n\n1. Run in the channel(s) that contain your server's tree and leaderboard messages.\n2. Now simply run where you want your analysis to be visible.", "permissions": "At a minimum, Silvanus requires permissions to `Send Messages` and `Send Messages in Threads` if applicable. If Analyzer is given permission to `Manage Messages`, the bot will delete the `.settree` and `.setranks` messages to reduce spam.", "allCommands": " | | | | | " diff --git a/modules/dbfn.js b/modules/dbfn.js index 296fb3f..c4afba6 100644 --- a/modules/dbfn.js +++ b/modules/dbfn.js @@ -300,5 +300,38 @@ module.exports = { resolve({ "status": "Successfully uploaded the leaderboard", "data": res }); }); }); - } + }, + get24hTree(guildId, treeName) { + const db = mysql.createConnection({ + host : process.env.DBHOST, + user : process.env.DBUSER, + password : process.env.DBPASS, + database : process.env.DBNAME, + port : process.env.DBPORT + }); + db.connect((err) => { + if (err) throw `Error connecting to the database: ${err.message}`; + }); + // Returns a Promise, resolve({ "status": "", "data": leaderboard }) + const select24hTreeQuery = `SELECT id, tree_name, tree_rank, tree_height, has_pin FROM leaderboard WHERE guild_id = ${db.escape(guildId)} AND tree_name = ${db.escape(treeName)} AND timestamp > date_sub(now(), interval 1 day) ORDER BY id ASC LIMIT 1`; + // TODO run the query and return a promise then process the results. resolve with { "status": , "data": leaderboard } + return new Promise((resolve, reject) => { + db.query(select24hTreeQuery, (err, res) => { + if (err) { + console.error(err); + db.end(); + reject("Error fetching the historic 24hr tree height: " + err.message); + return; + } + const hist24hTree = { + "treeName": res[0].tree_name, + "treeRank": res[0].tree_rank, + "treeHeight": res[0].tree_height, + "hasPin": res[0].has_pin + } + db.end(); + resolve({ "status": "Successfully fetched historic 24hr tree.", "data": hist24hTree }); + }); + }); + } }; \ No newline at end of file diff --git a/modules/functions.js b/modules/functions.js index 91e4e46..bf86135 100644 --- a/modules/functions.js +++ b/modules/functions.js @@ -17,6 +17,7 @@ const config = require('../data/config.json'); const strings = require('../data/strings.json'); const slashCommandFiles = fs.readdirSync('./slash-commands/').filter(file => file.endsWith('.js')); const dbfn = require('./dbfn.js'); +const { finished } = require('stream'); dbfn.createGuildTables().then(res => { console.log(res.status); @@ -173,49 +174,55 @@ const functions = { }); }, - compare(interaction) { - return new Promise((resolve, reject) => { - dbfn.getGuildInfo(interaction.guildId).then(res => { - const guildInfo = res.data; - guildInfo.guildId = interaction.guildId; - - let treeHeight = parseFloat(guildInfo.treeHeight).toFixed(1); - dbfn.getLeaderboard(interaction.guildId).then(res => { - const leaderboard = res.data; - - let replyString = 'Current Tree Height: ' + treeHeight + 'ft\n\n'; - leaderboard.reverse().forEach(treeRanking => { - let difference = parseFloat(treeRanking.treeHeight).toFixed(1) - treeHeight; - let decimal = (treeRanking.treeHeight % 1).toFixed(1); - let growthIndicator = ""; - if (decimal > 0) { - growthIndicator += "[+]"; - } - const absDifference = parseFloat(Math.abs(difference)).toFixed(1); - if (treeRanking.hasPin) { - replyString += "This is your tree. "; - } else if ((treeRanking.treeHeight == treeHeight) && (treeRanking.treeName == guildInfo.treeName)) { - replyString += "This might be your tree. Same height, same name. "; - } else { - if (difference > 0) { - replyString += `#${treeRanking.treeRank} - ${absDifference}ft${growthIndicator} shorter `; - } else if (difference < 0) { - replyString += `#${treeRanking.treeRank} - ${absDifference}ft${growthIndicator} taller `; - } else if (difference == 0) { - replyString += `#${treeRanking.treeRank} - Same Height${growthIndicator} `; - } - } - replyString += `[${functions.getWaterTime(treeRanking.treeHeight)} mins]\n`; - }); - resolve('Here\'s how your tree compares: \n' + replyString); - }).catch(err => { - console.error(err); - }); - }).catch(err => { - reject(err); - return; - }); - }); + async compare(interaction) { + try { + // fetch the guild's settings from the database + const guildInfoResponse = await dbfn.getGuildInfo(interaction.guildId); + const guildInfo = guildInfoResponse.data; // { "guildId": "123","treeName": "name","treeHeight": 123,"treeMessageId": "123","treeChannelId": "123","leaderboardMessageId": "123","leaderboardChannelId": "123"}; + // Get the most recent leaderboard listing from the database + const getLeaderboardResponse = await dbfn.getLeaderboard(interaction.guildId); + const leaderboard = getLeaderboardResponse.data; // [ { treeName: "Name", treeHeight: 1234.5, treeRank: 67 }, {...}, {...} ] + + // Prepare the beginning of the comparison message + let comparisonReplyString = `Here\'s how your tree compares: \nCurrent Tree Height: ${guildInfo.treeHeight}ft\n\n`; + // Iterate over the leaderboard entries, backwards + for (let i = leaderboard.length - 1; i >= 0; i--) { + const leaderboardEntry = leaderboard[i]; + // Setup the status indicator, default to blank, we'll change it later + let statusIndicator = "``["; + if ((leaderboardEntry.treeHeight % 1).toFixed(1) > 0) statusIndicator += "💧|"; + + // Get the data for this tree from 24 hours ago + const get24hTreeResponse = await dbfn.get24hTree(interaction.guildId, leaderboardEntry.treeName); + const dayAgoTree = get24hTreeResponse.data; + const hist24hDifference = (leaderboardEntry.treeHeight - dayAgoTree.treeHeight).toFixed(1); + statusIndicator += `+${hist24hDifference}ft|` + + // Get the watering time for this tree + const waterTime = functions.getWaterTime(leaderboardEntry.treeHeight); + statusIndicator += `${waterTime} mins]\`\``; + + // Determine if this tree is the guild's tree + if (leaderboardEntry.hasPin) { + comparisonReplyString += `#{leaderboardEntry.treeRank} - This is your tree`; + } else { // If it's another guild's tree + // Calculate the current height difference + const currentHeightDifference = guildInfo.treeHeight - leaderboardEntry.treeHeight; + + if (currentHeightDifference > 0) { // Guild Tree is taller than the leaderboard tree + comparisonReplyString += `#${leaderboardEntry.treeRank} - ${currentHeightDifference}ft taller`; + } else { + comparisonReplyString += `#${leaderboardEntry.treeRank} - ${Math.abs(currentHeightDifference)}ft shorter`; + } + // Build a string using the current leaderboard entry and the historic entry from 24 hours ago + comparisonReplyString += ` ${statusIndicator}\n`; + } + } + return comparisonReplyString; + } catch (err) { + console.error(err); + return 'An error occurred while comparing the trees.'; + } } }, tree: { diff --git a/package.json b/package.json index 9576e95..9252589 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "silvanus", - "version": "1.1.1", + "version": "1.1.2", "description": "Grow A Tree Comparison Tool", "main": "main.js", "scripts": {