Compare commits

..

18 Commits

Author SHA1 Message Date
Skylar Grant
03202db21d Stricter check 2023-02-26 12:30:55 -05:00
Skylar Grant
15a1093aa3 Add privacy switch 2023-02-26 12:26:52 -05:00
Skylar Grant
b880503059 Some more logging 2023-02-26 12:18:44 -05:00
Skylar Grant
915ca4bf7c Add percentage modifiers to timetoheight 2023-02-26 12:09:24 -05:00
Skylar Grant
f4ecbf9ba3 Rate limits 2023-02-26 12:09:04 -05:00
Skylar Grant
291db33692 Stop checking ratelimits 2023-02-21 18:41:47 -05:00
Skylar Grant
1b0269c304 Documentation update 2023-02-20 15:17:37 -05:00
Skylar Grant
b2ff3030f9 Stop deleting commands 2023-02-20 15:15:08 -05:00
Skylar Grant
555d0436f8 Fix /setup compare 2023-02-20 15:14:57 -05:00
Skylar Grant
c2fe7bfa9a Documentation update 2023-02-20 15:14:41 -05:00
Skylar Grant
d3a04921d6 CI Update 2023-02-20 15:14:13 -05:00
Skylar Grant
3127305c03 Removed update event 2023-02-20 14:25:39 -05:00
Skylar Grant
989d26af83 Self-destructing water relay 2023-02-20 14:14:54 -05:00
Skylar Grant
30c43ee0cf Error update 2023-02-20 14:07:50 -05:00
Skylar Grant
6fe4456513 Bugfixes in notifications and update to relay 2023-02-20 14:07:38 -05:00
Skylar Grant
3912ccf40e Versioning 2023-02-19 21:46:01 -05:00
Skylar Grant
38a70d5457 Start collector when the command is run 2023-02-19 21:44:58 -05:00
Skylar Grant
53ccfa31d2 Disappearing fruit pings 2023-02-19 21:44:46 -05:00
30 changed files with 337 additions and 1210 deletions

View File

@ -1,47 +0,0 @@
name: Silvanus Production Dockerization
on:
pull_request:
branches:
- main
env:
DHUB_UNAME: ${{ secrets.DHUB_UNAME }}
DHUB_PWORD: ${{ secrets.DHUB_PWORD }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Pull latest from Git
run: |
pwd
whoami
mkdir -p /var/lib/act_runner/
cd /var/lib/act_runner/
if [ ! -d "silvanus" ]; then
git clone https://git.vfsh.dev/voidf1sh/silvanus
cd silvanus
else
cd silvanus
git pull
fi
git checkout ${{ gitea.ref}}
- name: Build the Docker image
run: |
cd /var/lib/act_runner/silvanus
docker build . --file Dockerfile --tag v0idf1sh/silvanus
- name: Log into Docker Hub
run: docker login -u $DHUB_UNAME -p $DHUB_PWORD
- name: Push image to Docker Hub
run: |
cd /var/lib/act_runner/silvanus
docker push v0idf1sh/silvanus
- name: Restart the container
run: |
cd /srv/docker/silvanus
docker-compose down
docker-compose up -d

View File

23
.github/workflows/docker-image-prod.yml vendored Executable file
View File

@ -0,0 +1,23 @@
name: Silvanus Production Dockerization
on:
workflow_dispatch:
env:
DHUB_UNAME: ${{ secrets.DHUB_UNAME }}
DHUB_PWORD: ${{ secrets.DHUB_PWORD }}
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build the Docker image v0idf1sh/silvanus
run: docker build . --file Dockerfile --tag v0idf1sh/silvanus
- name: Log into Docker Hub
run: docker login -u $DHUB_UNAME -p $DHUB_PWORD
- name: Push image to Docker Hub v0idf1sh/silvanus
run: docker push v0idf1sh/silvanus

3
.gitignore vendored
View File

@ -2,7 +2,8 @@
.vscode
package-lock.json
.VSCodeCounter/
.env*
env.dev
env.prod
.DS_Store
data/guildInfo.json
data/rawstring.txt

View File

@ -5,4 +5,4 @@ WORKDIR /usr/src/app
COPY package.json ./
RUN npm install
COPY . .
CMD ["/bin/sh", "-c", "node main.js 2>&1 > /logs/$(date +%Y-%m-%d_%H-%M-%S).txt"]
CMD ["/bin/sh", "-c", "node main.js 2> /logs/error.log 1> /logs/silvanus.log"]

View File

@ -1,18 +1,36 @@
![Current Uptime Status](https://status.vfsh.dev/api/badge/1/status)
![Uptime Percentage](https://status.vfsh.dev/api/badge/1/uptime)
# Silvanus
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!
Important Note: Silvanus is only as up-to-date as your server's newest Tree and Tallest Trees messages. Make sure to refresh them before refreshing Silvanus' Compare message.
Silvanus is not affiliated with Grow A Tree or Limbo Labs.
## Add Silvanus to your server
[Invite Silvanus to your Discord Server](https://discord.com/api/oauth2/authorize?client_id=521624335119810561&permissions=275146475520&scope=applications.commands%20bot)
[Invite Silvanus to your Discord Server](https://discord.com/api/oauth2/authorize?client_id=521624335119810561&permissions=274877908992&scope=bot%20applications.commands)
## Silvanus Support Server
## voidf1sh Development Support Server
[Join Discord Server](https://discord.gg/g5JRGn7PxU)
## Silvanus Support Wiki
Find the most up-to-date guides and information about Silvanus at the [Silvanus Support Wiki](https://silvanus.vfsh.dev/).
[Silvanus Setup Guide](https://silvanus.vfsh.dev/en/setup)
## Setup
Please find the most up-to-date guides and information at the Silvanus Support Discord Server!
If your `/tree` and `/top trees` messages are in the same channel, simply run `/compare` in that channel and you're good to go!
Otherwise, run `/setup compare` to set the proper channels for the bot to look in for the `/tree` and `/top trees` messages.
Use `/commands` to view a description of all my commands.
## Permissions
Silvanus requires permissions to `Send Messages` and `Send Messages in Threads` if applicable. If you plan to use the Role Menu Silvanus will also need permission to `Manage Roles`.
## Commands
* `/compare` - Compare your tree to others on the leaderboard
* `/relay set` - Setup a Notification Relay for the first time
* `/relay update` - Update an already configured Notification Relay
* `/relay disable` - Disable the Notification Relay
* `/rolemenu` - Send a self-assignable role menu for relay pings
* `/watertime` - Calculates the time between waters for a tree of a given height
* `/timetoheight` - Calculates how long it would take a tree to grow to a given height
* `/setup compare` - Set the channels to use with `/compare`
* `/setup view` - View your server's configuration
* `/setup reset` - Delete your server's configuration
* `/help` - Displays the bot's help page

24
TODO.md
View File

@ -1,3 +1,10 @@
## In Progress
☑ Switch `/setup` to ask for the tree and leaderboard channels
* Switch `/compare` to check for newer trees and leaderboards when run **and** on every refresh
## Future Ideas
* Go through and comment the code
## Variable Structures
guildInfo = {
@ -14,18 +21,7 @@ guildInfo = {
reminderOptIn: 0,
}
## New Table Planning
Table: `silvanus`.timers
## Expected Behaviors
id | INT | NOT NULL | AUTO INCREMENT | PRIMARY KEY
status | VARCHAR(10) | NOT NULL | DEFAULT "WAITING"
dc_timecode | INT | NOT NULL | Discord timecode
guild_id | INT UNSIGNED | NOT NULL | Discord guild ID for referencing `silvanus`.guildInfo
Table: `silvanus`.auto_role_status
id | INT | NOT NULL | AUTO INCREMENT | PRIMARY KEY
user_id | INT UNSIGNED | NOT NULL
guild_id | INT UNSIGNED | NOT NULL
status | VARCHAR(10) | NOT NULL | DEFAULT "REMOVED" | OPTION: {"REMOVED", "ADDED"}
* Run `/compare` before `/setup`: `/compare` will search the current channel for tree and leaderboard messages, then create a comparison embed. If it can't find `/tree` or `/top trees` messages, it'll return an error saying as much.
* Run `/compare` after `/setup`: ``/compare` will search the current channel for tree and leaderboard messages, then create a comparison embed. If it can't find `/tree` or `/top trees` messages, it'll just use old data silently (odds are `/compare` is being run from another channel, that's fine)

View File

@ -5,11 +5,5 @@
"treeHeight": 0,
"validCommands": [],
"rankMessageId": "",
"rankings": [],
"devTeamIds": [
"481933290912350209",
"269249959973355520",
"448606738669633536"
],
"ownerId": "481933290912350209"
}
"rankings": []
}

View File

@ -4,12 +4,9 @@
},
"help": {
"title": "Silvanus Help",
"aboutTitle": "About Silvanus",
"info": "Silvanus is the ultimate companion bot designed for Grow A Tree, the popular Discord clicker game. With Silvanus by your side, you can take your tree-growing adventure to new heights! Enjoy customizable notifications, effortless tree height comparisons, and handy math features to optimize your gameplay.\n\n[Privacy Policy](https://assets.vfsh.dev/privacy.txt)",
"topggTitle": "Want to support Silvanus?",
"topggBody": "Vote and leave a review for Silvanus [on Top.gg](https://top.gg/bot/521624335119810561)",
"setup": "For the most up to date guides and information, check out the Silvanus Support Wiki - https://silvanus.vfsh.dev/\n[Silvanus Setup Guide](https://silvanus.vfsh.dev/en/setup)\n\nNeed help and can't reach me on Discord? Send an email to SilvanusDev@gmail.com and I'll get back to you ASAP.",
"longDescription": "Silvanus, the ultimate companion bot for Grow A Tree, takes your tree-growing journey to the next level. Are you tired of cluttered channels filled with notifications? Silvanus has you covered! With its unique notification relay system, Silvanus listens for Grow A Tree's notifications in a hidden channel and sends customized, auto-deleting notifications to the channels of your choice. Customize your notifications and keep your server clean and organized.\n\nSilvanus simplifies leaderboard tree height comparisons with a simple command. No more manual calculations or guesswork. Silvanus shows you exactly how far you are from the next tree on the leaderboard, allowing you to gauge your progress effortlessly.",
"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!\n\nImportant Note: Silvanus is only as up-to-date as your server's newest Tree and Tallest Trees messages. Make sure to refresh them before refreshing Silvanus' Compare message.",
"setup": "If your </tree:972648557796524032> and </top trees:1051840665362894950> messages are in the same channel, simply run </compare:1065346941166297128> in that channel and you're good to go!\n\nOtherwise, run </setup compare:1065407649363005561> to set the proper channels for the bot to look in for the </tree:972648557796524032> and </top trees:1051840665362894950> messages.\n\nUse </commands:1077058896469966888> to view a description of all my commands.",
"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": "</compare:1077058896469966889> - Compare your tree to others on the leaderboard\n</relay set:1077322799032578152> - Setup a Notification Relay for the first time\n</relay update:1077322799032578152> - Update an already configured Notification Relay\n</relay disable:1077322799032578152> - Disable the Notification Relay\n</rolemenu:1077058896469966892> - Send a self-assignable role menu for relay pings\n</watertime:1077058896469966895> - Calculates the time between waters for a tree of a given height\n</timetoheight:1077058896469966894> - Calculates how long it would take a tree to grow to a given height\n</setup compare:1077058896469966893> - Set the channels to use with </compare:1077058896469966889>\n</setup view:1077058896469966893> - View your server's configuration\n</setup reset:1077058896469966893> - Delete your server's configuration\n</help:1077058896469966890> - Displays the bot's help page"
},
"commands": {
@ -22,11 +19,11 @@
},
"embeds": {
"footer": "Silvanus is not affiliated with Grow A Tree or Limbo Labs",
"color": 5635925,
"color": "0x55FF55",
"errorTitle": "Oops!",
"errorPrefix": "There seems to have been a problem.",
"waterColor": 5592575,
"fruitColor": 13391189,
"waterColor": "0x5555FF",
"fruitColor": "0xCC5555",
"waterTitle": "Water Notification",
"fruitTitle": "Fruit Notification",
"roleMenuTitle": "Role Menu",
@ -53,16 +50,8 @@
"supportServer": "https://discord.gg/g5JRGn7PxU"
},
"error": {
"noGuild": "I was unable to find an entry for your server in the database. Try using the `/setup rolemenu` or `/relay` commands to generate a new entry. If that fails, try `/setup reset`, then kick me and re-add me. If you continue receiving this error, join the Support Server or DM @vfsh",
"invalidSubcommand": "Invalid subcommand detected.",
"noTreeMessage": "</tree:0> - Make sure you've sent or refreshed a Tree recently.",
"noLeaderboardMessage": "</top trees:0> - Make sure you've sent or refreshed the Tallest Trees leaderboard recently.",
"noCompareMessage": "</compare:0> - This is awkward, I've lost my own comparison message!",
"noFetchRole": "I was unable to find that role, please make sure it exists and I have access to it.",
"noGiveRole": "I was unable to give that role to you, please make sure I have permission to `Manage Roles` and that the role is below my role in the server settings role list.",
"noTakeRole": "I was unable to remove that role from you, please make sure I have permission to `Manage Roles` and that the role is below my role in the server settings role list.",
"yesGiveRole": "Successfully added the role to your profile!",
"yesTakeRole": "Successfully removed the role from your profile!"
"noGuild": "Setup has not been completed yet. Try running </setup:1065407649363005561> or </help setup:1065346941166297129>",
"invalidSubcommand": "Invalid subcommand detected."
},
"status": {
"treeAndLeaderboard": "Tree and leaderboard messages were both found, setup is complete. Run </setupinfo:1065413032374706196> to verify. Run </compare:1065346941166297128> to get started!",
@ -75,14 +64,11 @@
"reset": "All guild configuration information has been removed from the database.",
"resetError": "There was a problem deleting your guild information, contact @voidf1sh#0420 for help.",
"noRoleMenu": "A role menu has not been created for this guild yet. Run </setup rolemenu:0> to create a role menu.",
"optout": "Notification relay has been disabled, to re-enable the relay use </relay update:0> with no options."
"optout": "Notification relay has been disabled, to re-enable the relay use </notifications update:0> with no options."
},
"notifications": {
"water": "is ready to be watered again!",
"fruit": "Fruit is appearing!"
},
"ids": {
"growATree": "972637072991068220"
},
"temp": {}
}
}

View File

@ -1,18 +0,0 @@
const fn = require('../modules/functions.js');
module.exports = {
name: "",
description: "",
usage: "",
permission: "devTeam", // "devTeam" or "owner"
async execute(message, commandData) {
if (fn.dotCommands.checkPermissions(this.permission, message.author.id)) {
try {
// Code Here
} catch (err) {
console.error(err);
await message.reply(fn.builders.errorEmbed("There was an error running the command."));
}
}
}
}

View File

@ -1,27 +0,0 @@
const fn = require('../modules/functions.js');
module.exports = {
name: "leave",
description: "Leave a server",
usage: "<serverID> [<serverID>]".leave,
permission: "owner",
async execute(message, commandData) {
if (fn.dotCommands.checkPermissions(this.permission, message.author.id)) {
try {
// Code Here
const serverIds = commandData.args.split(" ");
for (let i = 0; i < serverIds.length; i++) {
const id = serverIds[i];
const guild = await message.client.guilds.fetch(id).catch(e => {
if (!(e.status === 404)) throw e;
});
await guild.leave();
await message.channel.send("Left Guild: " + id);
}
} catch (err) {
console.error(err);
await message.reply(fn.builders.errorEmbed("There was an error running the command: " + err));
}
}
}
}

View File

@ -1,23 +0,0 @@
const fn = require('../modules/functions.js');
module.exports = {
name: "message",
description: "Send a message to a server owner or server",
usage: "<serverID> <content>".message,
permission: "owner",
async execute(message, commandData) {
if (fn.dotCommands.checkPermissions(this.permission, message.author.id)) {
try {
// Code Here
args = commandData.args.split(" ");
const guildOwnerId = args.shift();
const content = args.join(" ");
const dmChannel = await message.client.users.createDM(guildOwnerId);
await dmChannel.send(content);
} catch (err) {
console.error(err);
await message.reply(fn.builders.errorEmbed("There was an error running the command: " + err));
}
}
}
}

View File

@ -1,36 +0,0 @@
const fn = require('../modules/functions.js');
const { PermissionsBitField } = require('discord.js');
module.exports = {
name: "permissions",
description: "",
usage: ".permissions",
permission: "devTeam", // "devTeam" or "owner"
async execute(message, commandData) {
if (fn.dotCommands.checkPermissions(this.permission, message.author.id)) {
try {
const me = message.guild.members.me;
const guildPerms = me.permissions;
const manageRoles = guildPerms.has(PermissionsBitField.Flags.ManageRoles);
const mentionEveryone = guildPerms.has(PermissionsBitField.Flags.MentionEveryone);
const channelPerms = me.permissionsIn(message.channel);
const viewChannel = channelPerms.has(PermissionsBitField.Flags.ViewChannel);
const sendMessages = channelPerms.has(PermissionsBitField.Flags.SendMessages);
const responseParts = [
`This is the status of my permissions in this server and this channel (<#${message.channel.id}>)`,
`**Guild Permissions**`,
`Manage Roles: ${manageRoles}`,
`Mention All Roles: ${mentionEveryone}`,
`**Channel Permissions**`,
`View Channel: ${viewChannel}`,
`Send Messages: ${sendMessages}`
];
const replyEmbed = fn.builders.embed(responseParts.join("\n"));
await message.reply(replyEmbed);
} catch (err) {
console.error(err);
await message.reply(fn.builders.errorEmbed("There was an error running the command."));
}
}
}
}

View File

@ -1,18 +0,0 @@
const fn = require('../modules/functions.js');
module.exports = {
name: "ping",
description: "pong",
usage: "ping pong",
permission: "everyone",
async execute(message, commandData) {
if (fn.dotCommands.checkPermissions(this.permission, message.author.id)) {
try {
await message.reply("Pong!");
} catch (err) {
console.error(err);
await message.reply(fn.builders.errorEmbed("There was an error running the command."));
}
}
}
}

View File

@ -1,22 +0,0 @@
const fn = require('../modules/functions.js');
module.exports = {
name: "servers",
description: "Get a list of servers the bot is in",
usage: ".servers",
permission: "owner",
async execute(message, commandData) {
if (fn.dotCommands.checkPermissions(this.permission, message.author.id)) {
try {
let servers = [];
const count = JSON.stringify(message.client.guilds.cache.size);
servers.push("I'm currently in " + count + " servers.");
const guilds = await message.client.guilds.cache;
await message.reply(servers.join("\n"));
} catch (err) {
console.error(err);
await message.reply(fn.builders.errorEmbed("There was an error running the command."));
}
}
}
}

View File

@ -1,24 +0,0 @@
const fn = require('../modules/functions.js');
module.exports = {
name: "setupview",
description: "",
usage: "",
permission: "devTeam",
async execute(message, commandData) {
// Code here...
if (fn.dotCommands.checkPermissions(this.permission, message.author.id)) {
try {
if (message.client.guildInfos.has(message.guildId)) {
let guildInfo = message.client.guildInfos.get(message.guildId);
await message.reply(fn.builders.embed(guildInfo.generateSetupInfo()));
} else {
await message.reply(fn.builders.errorEmbed("Guild doesn't exist in database!"));
}
} catch (err) {
console.error(err);
await message.reply(fn.builders.errorEmbed("There was an error running the command."));
}
}
}
}

158
main.js
View File

@ -5,8 +5,6 @@ const dotenv = require('dotenv');
dotenv.config();
const token = process.env.TOKEN;
const statusChannelId = process.env.STATUSCHANNELID;
const heartbeatUrl = process.env.HEARTBEAT_URL;
const sendHeartbeat = typeof heartbeatUrl === 'string';
// Discord.JS
const { Client, GatewayIntentBits, Partials, ActivityType } = require('discord.js');
@ -27,146 +25,64 @@ const client = new Client({
const fn = require('./modules/functions.js');
const strings = require('./data/strings.json');
const dbfn = require('./modules/dbfn.js');
const { GuildInfo } = require('./modules/CustomClasses.js');
const isDev = process.env.DEBUG === "true";
let statusChannel;
const isDev = process.env.DEBUG;
client.once('ready', async () => {
fn.collectionBuilders.slashCommands(client);
fn.collectionBuilders.dotCommands(client);
fn.collectionBuilders.setvalidCommands(client);
await fn.collectionBuilders.guildInfos(client);
await fn.collectionBuilders.messageCollectors(client);
const serverCount = client.guilds.cache.size;
// checkRateLimits();
console.log('Ready!');
client.user.setActivity({ name: `${serverCount} trees grow.`, type: ActivityType.Watching });
statusChannel = await client.channels.fetch(statusChannelId);
client.user.setActivity({ name: strings.activity.name, type: ActivityType.Watching });
if (isDev == 'false') {
statusChannel.send(`${new Date().toISOString()} -- \nStartup Sequence Complete <@481933290912350209>`);
}
// Heartbeat Timer
if (sendHeartbeat) {
setInterval(() => {
fn.sendHeartbeat(heartbeatUrl);
}, 30000);
if (isDev) console.log("Heartbeat interval set.");
} else {
if (isDev) console.log("No heartbeat URL set, will not send heartbeats for uptime monitoring.");
client.channels.fetch(statusChannelId).then(channel => {
channel.send(`${new Date().toISOString()} -- \nStartup Sequence Complete <@481933290912350209>`);
});
}
});
// slash-commands
client.on('interactionCreate', async interaction => {
try {
if (interaction.isCommand()) {
if (isDev) {
// console.log(interaction);
}
const { commandName } = interaction;
if (client.slashCommands.has(commandName)) {
client.slashCommands.get(commandName).execute(interaction);
} else {
interaction.reply('Sorry, I don\'t have access to that command.');
console.error('Slash command attempted to run but not found: ' + commandName);
}
if (interaction.isCommand()) {
if (isDev) {
console.log(interaction);
}
if (interaction.isButton()) {
switch (interaction.component.customId) {
case 'refresh':
// console.log(JSON.stringify(interaction));
await fn.refresh(interaction).catch(err => {
interaction.channel.send(fn.builders.errorEmbed("Oops! Something went wrong!"));
});
break;
case 'deleteping':
if (interaction.message.deletable) {
await interaction.message.delete().catch(err => {
// console.error(err);
});
}
break;
case 'waterpingrole':
const waterPingStatus = await fn.buttonHandlers.waterPing(interaction);
await interaction.reply(waterPingStatus).catch(e => console.error(e));
break;
case 'fruitpingrole':
const fruitPingStatus = await fn.buttonHandlers.fruitPing(interaction);
await interaction.reply(fruitPingStatus).catch(e => console.error(e));
break;
default:
break;
}
}
} catch(err) {
if (err === "Guild doesn't exist in database!") {
interaction.channel.send(fn.builders.errorEmbed(strings.error.noGuild));
console.error(err);
const { commandName } = interaction;
if (client.slashCommands.has(commandName)) {
client.slashCommands.get(commandName).execute(interaction);
} else {
interaction.channel.send("Oops! An error occurred... Sorry about that, please contact my owner @vfsh if this keeps happening.");
console.error(err);
interaction.reply('Sorry, I don\'t have access to that command.');
console.error('Slash command attempted to run but not found: ' + commandName);
}
}
});
client.on('messageUpdate', async (oldMessage, message) => {
await fn.messages.updateHandler(message).catch(async e => {
switch (e) {
case strings.error.noCompareMessage:
await message.channel.send(strings.error.noCompareMessage);
if (interaction.isButton()) {
switch (interaction.component.customId) {
case 'refresh':
// console.log(JSON.stringify(interaction));
await fn.refresh(interaction).catch(err => {
interaction.channel.send(fn.builders.errorEmbed(err));
});
break;
case 'deleteping':
if (interaction.message.deletable) {
await interaction.message.delete().catch(err => {
console.error(err);
});
}
break;
case 'waterpingrole':
const waterPingStatus = await fn.buttonHandlers.waterPing(interaction);
await interaction.reply(waterPingStatus).catch(e => console.error(e));
break;
case 'fruitpingrole':
const fruitPingStatus = await fn.buttonHandlers.fruitPing(interaction);
await interaction.reply(fruitPingStatus).catch(e => console.error(e));
break;
default:
break;
}
});
});
client.on('messageCreate', async message => {
await fn.messages.updateHandler(message).catch(e => console.error(e));
// Dot Command Handling
// Some basic checking to prevent running unnecessary code
if (message.author.bot) return;
// Break the message down into its components and analyze it
const commandData = fn.dotCommands.getCommandData(message);
// if (isDev) console.log(commandData);
if (commandData.isValid && commandData.isCommand) {
try {
client.dotCommands.get(commandData.command).execute(message, commandData);
}
catch (error) {
console.error(error);
message.reply('There was an error trying to execute that command.');
}
}
return;
});
client.on('guildCreate', async guild => {
const serverCount = client.guilds.cache.size;
client.user.setActivity({ name: `${serverCount} trees grow.`, type: ActivityType.Watching });
await statusChannel.send(`I've been added to a new guild: ${guild.name} (${guild.id})`);
const guildInfo = new GuildInfo()
.setIds(guild.id, guild.ownerId);
const setBasicQuery = guildInfo.queryBuilder("setBasic");
await dbfn.setGuildInfo(setBasicQuery).catch(e => console.error(e));
});
client.on('guildDelete', async guild => {
const serverCount = client.guilds.cache.size;
client.user.setActivity({ name: `${serverCount} trees grow.`, type: ActivityType.Watching });
await statusChannel.send(`I've been removed from a guild: ${guild.name} (${guild.id})`);
if (client.guildInfos.has(guild.id)) {
let guildInfo = client.guildInfos.get(guild.id);
guildInfo.setReminders(undefined, undefined, undefined, undefined, false);
const setRemindersQuery = guildInfo.queryBuilder("setReminders");
await dbfn.setGuildInfo(setRemindersQuery);
}
});
@ -195,7 +111,7 @@ async function checkRateLimits(hi) {
}
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection (pls dont break up with me):', error);
console.error('Unhandled promise rejection:', error);
});
client.login(token);

View File

@ -11,7 +11,6 @@ module.exports = {
GuildInfo: class {
constructor() {
this.guildId = "";
this.ownerId = ""; // TODO Is ownerId fully implemented?
this.treeName = "";
this.treeHeight = 0;
this.treeMessageId = "";
@ -25,13 +24,10 @@ module.exports = {
this.reminderChannelId = "";
this.watchChannelId = "";
this.notificationsEnabled = false;
this.compareChannelId = "";
this.compareMessageId = "";
}
setIds(guildId, ownerId) {
this.guildId = guildId;
this.ownerId = ownerId === undefined ? this.ownerId : ownerId
setId(id) {
this.guildId = id;
return this;
}
setName(name) {
@ -47,29 +43,17 @@ module.exports = {
this.treeChannelId = channelId;
return this;
}
setTreeInfo(name, height, channelId, messageId) {
this.treeName = name ? name : this.treeName;
this.treeHeight = height;
this.treeChannelId = channelId ? channelId : this.treeChannelId;
this.treeMessageId = messageId ? messageId : this.treeMessageId;
return this;
}
setLeaderboardMessage(messageId, channelId) {
this.leaderboardMessageId = messageId ? messageId : this.leaderboardMessageId;
this.leaderboardChannelId = channelId ? channelId : this.leaderboardChannelId;
return this;
}
setCompareMessage(channelId, messageId) {
this.compareChannelId = channelId;
this.compareMessageId = messageId;
this.leaderboardChannelId = channelId;
return this;
}
setReminders(waterMessage, fruitMessage, reminderChannelId, watchChannelId, enabled) {
this.waterMessage = waterMessage === undefined ? this.waterMessage : waterMessage
this.fruitMessage = fruitMessage === undefined ? this.fruitMessage : fruitMessage;
this.reminderChannelId = reminderChannelId === undefined ? this.reminderChannelId : reminderChannelId
this.watchChannelId = watchChannelId === undefined ? this.watchChannelId : watchChannelId;
this.notificationsEnabled = enabled === undefined ? this.notificationsEnabled : enabled;
if (waterMessage) this.waterMessage = waterMessage;
if (fruitMessage) this.fruitMessage = fruitMessage;
if (reminderChannelId) this.reminderChannelId = reminderChannelId;
if (watchChannelId) this.watchChannelId = watchChannelId;
if (enabled) this.notificationsEnabled = enabled;
return this;
}
setRoles(waterRoleId, fruitRoleId) {
@ -136,28 +120,18 @@ module.exports = {
return queryParts.join('');
break;
case "setTreeMessage":
// queryParts = [
// `UPDATE guild_info SET tree_message_id = ${db.escape(this.treeMessageId)}, `,
// `tree_channel_id = ${db.escape(this.treeChannelId)} `,
// `WHERE guild_id = ${db.escape(this.guildId)}`
// ];
queryParts = [
`INSERT INTO guild_info (guild_id, tree_message_id, tree_channel_id)`,
`VALUES (${db.escape(this.guildId)}, ${db.escape(this.treeMessageId)}, ${db.escape(this.treeChannelId)})`,
`ON DUPLICATE KEY UPDATE tree_message_id = ${db.escape(this.treeMessageId)}, tree_channel_id = ${db.escape(this.treeChannelId)}`
`UPDATE guild_info SET tree_message_id = ${db.escape(this.treeMessageId)}, `,
`tree_channel_id = ${db.escape(this.treeChannelId)} `,
`WHERE guild_id = ${db.escape(this.guildId)}`
];
return queryParts.join('');
break;
case "setLeaderboardMessage":
// queryParts = [
// `UPDATE guild_info SET leaderboard_message_id = ${db.escape(this.leaderboardMessageId)}, `,
// `leaderboard_channel_id = ${db.escape(this.leaderboardChannelId)} `,
// `WHERE guild_id = ${db.escape(this.guildId)}`
// ];
queryParts = [
`INSERT INTO guild_info (guild_id, leaderboard_message_id, leaderboard_channel_id)`,
`VALUES (${db.escape(this.guildId)}, ${db.escape(this.leaderboardMessageId)}, ${db.escape(this.leaderboardChannelId)})`,
`ON DUPLICATE KEY UPDATE leaderboard_message_id = ${db.escape(this.leaderboardMessageId)}, leaderboard_channel_id = ${db.escape(this.leaderboardChannelId)}`
`UPDATE guild_info SET leaderboard_message_id = ${db.escape(this.leaderboardMessageId)}, `,
`leaderboard_channel_id = ${db.escape(this.leaderboardChannelId)} `,
`WHERE guild_id = ${db.escape(this.guildId)}`
];
return queryParts.join('');
break;
@ -179,45 +153,7 @@ module.exports = {
}
return queryParts.join('');
break;
case "setTreeInfo":
queryParts = [
`INSERT INTO guild_info (`,
`guild_id, tree_name, tree_height, tree_channel_id, tree_message_id`,
`) VALUES (`,
`${db.escape(this.guildId)}, ${db.escape(this.treeName)}, ${db.escape(this.treeHeight)}, ${db.escape(this.treeChannelId)}, ${db.escape(this.treeMessageId)}`,
`) ON DUPLICATE KEY UPDATE tree_name = ${db.escape(this.treeName)}, `,
`tree_height = ${db.escape(this.treeHeight)}, `,
`tree_channel_id = ${db.escape(this.treeChannelId)}, `,
`tree_message_id = ${db.escape(this.treeMessageId)}`
];
return queryParts.join('');
case "setCompareMessage":
queryParts = [
`INSERT INTO guild_info (`,
`guild_id, compare_channel_id, compare_message_id`,
`) VALUES (`,
`${db.escape(this.guildId)}, ${db.escape(this.compareChannelId)}, ${db.escape(this.compareMessageId)}`,
`) ON DUPLICATE KEY UPDATE compare_channel_id = ${db.escape(this.compareChannelId)}, compare_message_id = ${db.escape(this.compareMessageId)}`,
];
return queryParts.join('');
// TODO This is hacked in and needs to be implemented throughout the code
case "setIds":
queryParts = [
`UPDATE guild_info SET `,
`owner_id=${db.escape(this.ownerId)} `,
`WHERE guild_id=${db.escape(this.guildId)}`
];
return queryParts.join('');
case "setBasic":
queryParts = [
`INSERT INTO guild_info (`,
`guild_id, owner_id`,
`) VALUES (`,
`${db.escape(this.guildId)}, ${db.escape(this.ownerId)}`,
`) ON DUPLICATE KEY UPDATE owner_id=${db.escape(this.ownerId)}`
];
return queryParts.join('');
default:
default:
break;
}
}
@ -230,7 +166,6 @@ module.exports = {
`[Tree Link](https://discord.com/channels/${this.guildId}/${this.treeChannelId}/${this.treeMessageId})`,
`Leaderboard Channel: <#${this.leaderboardChannelId}>`,
`[Leaderboard Link](https://discord.com/channels/${this.guildId}/${this.leaderboardChannelId}/${this.leaderboardMessageId})`,
`Notification Relay Enabled: ${this.notificationsEnabled}`,
`Notification Watch Channel: <#${this.watchChannelId}>`,
`Notification Relay Channel: <#${this.reminderChannelId}>`,
`Water Message: ${this.waterMessage}`,

View File

@ -56,16 +56,20 @@ module.exports = {
db.end();
return;
}
if (res.length == 0) {
reject("There is no database entry for your guild yet. Try running /setup");
db.end();
return;
}
row = res[0];
const guildInfo = new GuildInfo()
.setIds(row.guild_id, row.owner_id)
.setId(row.guild_id)
.setName(row.tree_name)
.setHeight(row.tree_height)
.setTreeMessage(row.tree_message_id, row.tree_channel_id)
.setLeaderboardMessage(row.leaderboard_message_id, row.leaderboard_channel_id)
.setReminders(row.water_message, row.fruit_message, row.reminder_channel_id, row.watch_channel_id, row.notifications_enabled)
.setRoles(row.water_role_id, row.fruit_role_id)
.setCompareMessage(row.compare_channel_id, row.compare_message_id);
.setRoles(row.water_role_id, row.fruit_role_id);
db.end();
resolve(guildInfo);
});
@ -102,17 +106,15 @@ module.exports = {
for (let i = 0; i < res.length; i++) {
let row = res[i];
guildInfos.push(new GuildInfo()
.setIds(row.guild_id, row.owner_id)
.setId(row.guild_id)
.setName(row.tree_name)
.setHeight(row.tree_height)
.setTreeMessage(row.tree_message_id, row.tree_channel_id)
.setLeaderboardMessage(row.leaderboard_message_id, row.leaderboard_channel_id)
.setReminders(row.water_message, row.fruit_message, row.reminder_channel_id, row.watch_channel_id, row.notifications_enabled)
.setRoles(row.water_role_id, row.fruit_role_id)
.setCompareMessage(row.compare_channel_id, row.compare_message_id)
);
}
// console.log(res.length + " // " + guildInfos.length);
db.end();
resolve(guildInfos);
@ -139,7 +141,6 @@ module.exports = {
return;
}
db.end();
// console.log("Updated the database");
resolve();
});
});
@ -169,7 +170,6 @@ module.exports = {
return;
}
db.end();
console.log("Updated the database");
resolve({ "status": "Successfully set the guild information", "data": null });
});
});
@ -298,5 +298,46 @@ 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;
}
let hist24hTree = {};
if (res.length > 0) {
hist24hTree = {
"treeName": res[0].tree_name,
"treeRank": res[0].tree_rank,
"treeHeight": res[0].tree_height,
"hasPin": res[0].has_pin
}
} else {
hist24hTree = {
}
}
db.end();
resolve({ "status": "Successfully fetched historic 24hr tree.", "data": hist24hTree });
});
});
}
};
};

View File

@ -2,7 +2,7 @@
// dotenv for handling environment variables
const dotenv = require('dotenv');
dotenv.config();
const isDev = process.env.DEBUG === "true";
const isDev = process.env.isDev;
const package = require('../package.json');
// filesystem
@ -17,10 +17,8 @@ const { GuildInfo } = require('./CustomClasses');
const config = require('../data/config.json');
const strings = require('../data/strings.json');
const slashCommandFiles = fs.readdirSync('./slash-commands/').filter(file => file.endsWith('.js'));
const dotCommandFiles = fs.readdirSync('./dot-commands/').filter(file => file.endsWith('.js'));
const dbfn = require('./dbfn.js');
const { finished } = require('stream');
const https = require('https');
const functions = {
// Functions for managing and creating Collections
@ -37,44 +35,6 @@ const functions = {
}
if (isDev) console.log('Slash Commands Collection Built');
},
dotCommands(client) {
// If the dotCommands collection doesn't exist already, create it
if (!client.dotCommands) client.dotCommands = new Discord.Collection();
// Empty the dotcommands collection
client.dotCommands.clear();
// Iterate over each file within ./dot-commands that ends with .js
for (const file of dotCommandFiles) {
// Pull the file into a temporary variable
const dotCommand = require(`../dot-commands/${file}`);
// Create a new entry in the collection with the key of the command name, value of the command itself
client.dotCommands.set(dotCommand.name, dotCommand);
// Old code from NodBot to implement aliases for dot commands. Unused as of 5/16/23
// if (Array.isArray(dotCommand.alias)) {
// dotCommand.alias.forEach(element => {
// client.dotCommands.set(element, dotCommand);
// });
// } else if (dotCommand.alias != undefined) {
// client.dotCommands.set(dotCommand.alias, dotCommand);
// }
}
if (isDev) console.log('Dot Commands Collection Built');
},
setvalidCommands(client) {
// Iterate over every entry in the dotCommands collection
for (const entry of client.dotCommands.map(command => command)) {
// Add the command's name to the valid commands list for validation later
config.validCommands.push(entry.name);
// Old code from NodBot to implement aliases for dot commands. Unused as of 5/16/23
// if (Array.isArray(entry.alias)) {
// entry.alias.forEach(element => {
// config.validCommands.push(element);
// });
// } else if (entry.alias != undefined) {
// config.validCommands.push(entry.alias);
// }
}
if (isDev) console.log(`Valid Commands Added to Config\n${config.validCommands}`);
},
async guildInfos(client) {
const guildInfos = await dbfn.getAllGuildInfos();
if (!client.guildInfos) client.guildInfos = new Discord.Collection();
@ -92,17 +52,7 @@ const functions = {
const { guildInfos, messageCollectors } = client;
// Iterate over each guild info
await guildInfos.forEach(async guildInfo => {
await functions.collectors.create(client, guildInfo).catch(async e => {
if (e === "ERRNOGUILD") {
guildInfo.setReminders(undefined, undefined, undefined, undefined, false);
const query = guildInfo.queryBuilder("setReminders");
await dbfn.setGuildInfo(query);
await functions.collectionBuilders.guildInfos(client);
console.log("Disabled notification relay for a guild I'm no longer in: " + guildInfo.guildId);
} else {
throw e;
}
});
await functions.collectors.create(client, guildInfo);
});
}
},
@ -173,16 +123,6 @@ const functions = {
.setDescription(description)
.setFooter({ text: strings.embeds.roleMenuFooter });
return { embeds: [embed], components: [actionRow] };
},
information(content, fields) {
const embed = new EmbedBuilder()
.setColor(strings.embeds.color)
.setTitle('Information')
.setDescription(content)
.setFooter({ text: `v${package.version} - ${strings.embeds.footer}` });
if (fields) embed.addFields(fields);
const messageContents = { embeds: [embed], ephemeral: true };
return messageContents;
}
},
comparisonEmbed(content, guildInfo) {
@ -225,19 +165,6 @@ const functions = {
const messageContents = { embeds: [embed], ephemeral: privateBool };
return messageContents;
},
aboutEmbed(private) {
const embed = new EmbedBuilder()
.setColor(strings.embeds.color)
.setTitle(strings.help.aboutTitle)
.setDescription(`${strings.help.info}\n\n${strings.help.longDescription}`)
.setFooter({ text: `v${package.version} - ${strings.embeds.footer}` });
embed.addFields([
{ name: strings.help.topggTitle, value: strings.help.topggBody}
]);
const privateBool = private == 'true';
const messageContents = { embeds: [embed], ephemeral: privateBool };
return messageContents;
},
errorEmbed(content) {
const embed = new EmbedBuilder()
.setColor(0xFF0000)
@ -257,55 +184,6 @@ const functions = {
return messageContents;
}
},
dotCommands: {
getCommandData(message) {
const commandData = {};
// Split the message content at the final instance of a period
const finalPeriod = message.content.lastIndexOf('.');
// if(isDev) console.log(message.content);
// If the final period is the last character, or doesn't exist
if (finalPeriod < 0) {
// if (isDev) console.log(finalPeriod);
commandData.isCommand = false;
return commandData;
}
commandData.isCommand = true;
// Get the first part of the message, everything leading up to the final period
commandData.args = message.content.slice(0, finalPeriod);
// Get the last part of the message, everything after the final period
commandData.command = message.content.slice(finalPeriod).replace('.', '').toLowerCase();
commandData.author = `${message.author.username}#${message.author.discriminator}`;
return this.checkCommand(commandData);
},
checkCommand(commandData) {
if (commandData.isCommand) {
const validCommands = require('../data/config.json').validCommands;
commandData.isValid = validCommands.includes(commandData.command);
// Add exceptions for messages that contain only a link
if (commandData.args.startsWith('http')) commandData.isValid = false;
}
else {
commandData.isValid = false;
console.error('Somehow a non-command made it to checkCommands()');
}
return commandData;
},
checkPermissions(type, userId) {
if (type === "devTeam") {
const { devTeamIds } = config;
let matchFound = false;
for (let i = 0; i < devTeamIds.length; i++) {
if (userId === devTeamIds[i]) matchFound = true;
}
return matchFound;
} else if (type === "owner") {
return config.ownerId === userId;
} else if (type === "everyone") {
return true;
}
}
},
rankings: {
parse(interaction, guildInfo) {
return new Promise((resolve, reject) => {
@ -372,7 +250,7 @@ const functions = {
});
}).catch(err => {
reject(strings.status.missingLeaderboardMessage);
// console.error(err);
console.error(err);
return;
});
}).catch(err => {
@ -387,9 +265,9 @@ const functions = {
});
},
async compare(guildInfo) {
async compare(interaction, guildInfo) {
try {
const getLeaderboardResponse = await dbfn.getLeaderboard(guildInfo.guildId);
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
@ -436,6 +314,7 @@ const functions = {
},
tree: {
parse(interaction, guildInfo) {
let input;
return new Promise((resolve, reject) => {
if (guildInfo == undefined) {
reject(`The guild entry hasn't been created yet. [${interaction.guildId || interaction.commandGuildId}]`);
@ -448,7 +327,6 @@ const functions = {
reject("This doesn't appear to be a valid ``/tree`` message.");
return;
}
let input;
input = m.embeds[0].data.description;
let treeName = m.embeds[0].data.title;
let lines = input.split('\n');
@ -459,12 +337,12 @@ const functions = {
});
}).catch(err => {
reject(strings.status.missingTreeMessage);
// console.error(err);
console.error(err);
return;
});
}).catch(err => {
reject(strings.status.missingTreeChannel);
// console.error(err);
console.error(err);
return;
});
} else {
@ -605,184 +483,12 @@ const functions = {
},
isTree(message) {
if (message.embeds.length > 0) {
// Grab the description and title
const { description, title } = message.embeds[0].data;
// Make sure it's a tree message
if (description.includes("Your tree is")) {
// Grab the name
const treeName = title;
// Grab the tree's height
const indices = [description.indexOf("Your tree is ") + 13, description.indexOf("ft")];
const treeHeightStr = description.slice(indices[0], indices[1]);
const treeHeightFloat = parseFloat(treeHeightStr).toFixed(1);
// Return the info gathered
return {
treeName: treeName,
treeHeight: treeHeightFloat
};
} else {
return false;
}
} else {
return false;
return message.embeds[0].data.description.includes("Your tree is");
}
},
// Checks if a message is a leaderboard message, and returns the entries if it is
isLeaderboard(message) {
if (message.embeds.length > 0) {
// Grab the description and title from the embed
const { title, description } = message.embeds[0].data;
// Check that it's a Top Trees message
if (title == "Tallest Trees") {
// Break the description into an array of each line
const lines = description.split("\n");
const leaderboard = {
guildId: message.guildId,
entries: []
};
lines.forEach(line => {
// Skeleton entry:
const entry = {
treeRank: 0,
treeName: "",
treeHeight: 0,
hasPin: 0
}
// Break the line into parts separated by a hyphen -
// DO NOT USE this, it breaks when any tree name contains " - " which
// isn't uncommon apparently
// const parts = line.split(" - ");
// Instead, find the indices of the first and last instances of " - "
const hyphenIndices = [line.indexOf(" - "), line.lastIndexOf(" - ")];
const parts = [
line.slice(0, hyphenIndices[0]),
line.slice(hyphenIndices[0] + 3, hyphenIndices[1]),
line.slice(hyphenIndices[1] + 3, line.length)
];
//
// Grab the rank
// Preset the indices to split the lines to get the data
const rankIndices = [parts[0].indexOf("#") + 1, parts[0].lastIndexOf("``")];
const nameIndices = [parts[1].indexOf("``") + 2, parts[1].lastIndexOf("``")];
const heightIndices = [0, parts[2].lastIndexOf("ft")];
// Set the data from the parts using the indices
entry.treeRank = parts[0].slice(...rankIndices);
entry.treeName = parts[1].slice(...nameIndices);
entry.treeHeight = parts[2].slice(...heightIndices);
// Go back and check for the first 3 as they use emojis instead of numbers, this will overwrite above
if (line.includes("🥇")) entry.treeRank = 1;
if (line.includes("🥈")) entry.treeRank = 2;
if (line.includes("🥉")) entry.treeRank = 3;
// Check for the pin showing ownership
if (line.includes("📍")) entry.hasPin = 1;
// Add the entry to the array
leaderboard.entries.push(entry);
});
return leaderboard;
} else {
return false;
}
} else {
return false;
}
},
async updateHandler(message) {
if (message.partial) {
message = await message.fetch().catch(e => {
throw e;
});
}
// Make sure the message is from Grow A Tree
if (message.author.id != strings.ids.growATree) return;
// Check and store the message types
const isLeaderboard = this.isLeaderboard(message);
const isTree = this.isTree(message);
// Check if the message is a leaderboard
if (isLeaderboard) {
if (isDev) console.log(`LU: ${message.guild.name}`);
let guildInfo;
let doDbUpdate = false;
if (message.client.guildInfos.has(message.guildId)) {
guildInfo = message.client.guildInfos.get(message.guildId);
if ((guildInfo.leaderboardChannelId != message.channel.id) || (guildInfo.leaderboardMessageId != message.id)) {
guildInfo.setLeaderboardMessage(message.id, message.channel.id);
doDbUpdate = true;
}
} else {
guildInfo = new GuildInfo().setIds(message.guildId, message.guild.ownerId)
.setLeaderboardMessage(message.id, message.channel.id);
doDbUpdate = true;
}
if (doDbUpdate) {
const query = guildInfo.queryBuilder("setLeaderboardMessage");
await dbfn.setGuildInfo(query);
await functions.collectionBuilders.guildInfos(message.client);
}
await dbfn.uploadLeaderboard(isLeaderboard);
// Update the comparison message
// Check for valid message IDs
if (guildInfo.treeMessageId === "") throw strings.error.noTreeMessage;
if (guildInfo.leaderboardMessageId === "") throw strings.error.noLeaderboardMessage;
if (guildInfo.compareMessageId === "") throw strings.error.noCompareMessage;
// Fetch the messages
const { guild } = message;
// Tree
const treeChannel = await guild.channels.fetch(guildInfo.treeChannelId);
const treeMessage = await treeChannel.messages.fetch(guildInfo.treeMessageId);
// Leaderboard
const leaderboardChannel = await guild.channels.fetch(guildInfo.leaderboardChannelId);
const leaderboardMessage = await leaderboardChannel.messages.fetch(guildInfo.leaderboardMessageId);
// Comparison
const compareChannel = await guild.channels.fetch(guildInfo.compareChannelId);
const compareMessage = await compareChannel.messages.fetch(guildInfo.compareMessageId);
// Update the tree information
// Make sure we have a tree message and parse it
const isTree = this.isTree(treeMessage);
if (!isTree) throw "Tree message isn't actually a tree message!";
guildInfo.setTreeInfo(isTree.treeName, isTree.treeHeight);
// Grab the leaderboard
// Make sure it's a leaderboard and parse it
// const isLeaderboard = this.messages.isLeaderboard(leaderboardMessage);
// if (!isLeaderboard) throw "Leaderboard message isn't actually a leaderboard message!";
// Upload the leaderboard
// await dbfn.uploadLeaderboard(isLeaderboard);
// Build the string that shows the comparison // TODO Move the string building section to fn.builders?
const comparedRankings = await functions.rankings.compare(guildInfo);
const embed = functions.builders.comparisonEmbed(comparedRankings, guildInfo);
await compareMessage.edit(embed).catch(e => console.error(e));
} else if (isTree) {
// Check if the message is a tree
// if (isDev) console.log(`TU: ${isTree.treeName}: ${isTree.treeHeight}ft`);
let guildInfo;
let doDbUpdate = false;
if (message.client.guildInfos.has(message.guildId)) {
guildInfo = message.client.guildInfos.get(message.guildId);
if ((guildInfo.treeName != isTree.treeName) || (guildInfo.treeHeight != isTree.treeHeight)) {
guildInfo.setTreeInfo(isTree.treeName, isTree.treeHeight, message.channel.id, message.id);
doDbUpdate = true;
}
} else {
guildInfo = new GuildInfo().setIds(message.guildId, message.guild.ownerId)
.setTreeInfo(isTree.treeName, isTree.treeHeight, message.channel.id, message.id);
doDbUpdate = true;
}
if (doDbUpdate) {
const query = guildInfo.queryBuilder("setTreeInfo");
await dbfn.setGuildInfo(query);
await functions.collectionBuilders.guildInfos(message.client);
}
return message.embeds[0].data.title == "Tallest Trees";
}
}
},
@ -790,24 +496,14 @@ const functions = {
async fruitPing(interaction) {
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
const role = await functions.roles.fetchRole(interaction.guild, guildInfo.fruitRoleId);
let status = "No Changes Made";
let errorFlag = false;
const role = await functions.roles.fetchRole(interaction.guild, guildInfo.fruitRoleId).catch(e => {
errorFlag = true;
status = strings.error.noFetchRole;
});
if (interaction.member.roles.cache.some(role => role.id == guildInfo.fruitRoleId)) {
await functions.roles.takeRole(interaction.member, role).catch(e => {
errorFlag = true;
status = strings.error.noTakeRole;
});
if (!errorFlag) status = strings.error.yesTakeRole;
await functions.roles.takeRole(interaction.member, role);
status = "Removed the fruit role.";
} else {
await functions.roles.giveRole(interaction.member, role).catch(e => {
errorFlag = true;
status = strings.error.noGiveRole;
});
if (!errorFlag) status = strings.error.yesGiveRole;
await functions.roles.giveRole(interaction.member, role);
status = "Added the fruit role.";
}
return functions.builders.embed(status);
} else {
@ -818,23 +514,13 @@ const functions = {
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
let status = "No Changes Made";
let errorFlag = false;
const role = await functions.roles.fetchRole(interaction.guild, guildInfo.waterRoleId).catch(e => {
errorFlag = true;
status = strings.error.noFetchRole;
});
const role = await functions.roles.fetchRole(interaction.guild, guildInfo.waterRoleId);
if (interaction.member.roles.cache.some(role => role.id == guildInfo.waterRoleId)) {
await functions.roles.takeRole(interaction.member, role).catch(e => {
errorFlag = true;
status = strings.error.noTakeRole;
});
if (!errorFlag) status = strings.error.yesTakeRole;
await functions.roles.takeRole(interaction.member, role);
status = "Removed the water role.";
} else {
await functions.roles.giveRole(interaction.member, role).catch(e => {
errorFlag = true;
status = strings.error.noGiveRole;
});
if (!errorFlag) status = strings.error.yesGiveRole;
await functions.roles.giveRole(interaction.member, role);
status = "Added the water role.";
}
return functions.builders.embed(status);
} else {
@ -844,13 +530,13 @@ const functions = {
},
roles: {
async fetchRole(guild, roleId) {
return await guild.roles.fetch(roleId);
return await guild.roles.fetch(roleId).catch(err => console.error("Error fetching the role: " + err + "\n" + roleId));
},
async giveRole(member, role) {
await member.roles.add(role);
await member.roles.add(role).catch(err => console.error("Error giving the role: " + err + "\n" + JSON.stringify(role)));
},
async takeRole(member, role) {
await member.roles.remove(role);
await member.roles.remove(role).catch(err => console.error("Error taking the role: " + err + "\n" + JSON.stringify(role)));
}
},
collectors: {
@ -861,11 +547,9 @@ const functions = {
await this.end(client, guildInfo);
}
// Make sure guildInfo is what we expect, the watch channel isnt blank, and notifications are enabled
if ((guildInfo instanceof GuildInfo && guildInfo.watchChannelId != "") && (guildInfo.notificationsEnabled == true)) {
if (guildInfo instanceof GuildInfo && guildInfo.watchChannelId != "" && guildInfo.notificationsEnabled) {
// Fetch the Guild
const guild = await client.guilds.fetch(guildInfo.guildId).catch(e => {
throw "ERRNOGUILD"
});
const guild = await client.guilds.fetch(guildInfo.guildId);
// Fetch the Channel
const channel = await guild.channels.fetch(guildInfo.watchChannelId);
// Create the filter function
@ -877,27 +561,23 @@ const functions = {
const collector = channel.createMessageCollector({ filter });
// Add the collector to the messageCollectors Collection
client.messageCollectors.set(guildInfo.guildId, collector);
// if (isDev) console.log("Set up a collector in " + guildInfo.guildId);
collector.on('collect', message => {
// if (isDev) console.log("Collected a message in " + message.guild.id);
// Check for manual relay use with "water ping" and "fruit ping"
if (message.content.toLowerCase().includes("water ping")) {
functions.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
functions.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild);
return;
} else if (message.content.toLowerCase().includes("fruit ping")) {
functions.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
functions.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild);
return;
}
// If the message doesn't contain an embed, we can ignore it
if (message.embeds == undefined) return;
if (message.embeds.length == 0) return;
// console.log(JSON.stringify(message.embeds[0].data));
if (message.embeds[0].data.description == undefined) return;
// Check the description field of the embed to determine if it matches Grow A Tree's notification texts
if (message.embeds[0].data.description.includes(strings.notifications.water)) {
functions.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
functions.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild);
} else if (message.embeds[0].data.description.includes(strings.notifications.fruit)) {
functions.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
functions.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild);
}
});
}
@ -913,45 +593,23 @@ const functions = {
}
},
async refresh(interaction) {
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
// Check for valid message IDs
if (guildInfo.treeMessageId === "") throw strings.error.noTreeMessage;
if (guildInfo.leaderboardMessageId === "") throw strings.error.noLeaderboardMessage;
// Fetch the messages
const { guild } = interaction;
// Tree
const treeChannel = await guild.channels.fetch(guildInfo.treeChannelId);
const treeMessage = await treeChannel.messages.fetch(guildInfo.treeMessageId);
// Leaderboard
const leaderboardChannel = await guild.channels.fetch(guildInfo.leaderboardChannelId);
const leaderboardMessage = await leaderboardChannel.messages.fetch(guildInfo.leaderboardMessageId);
// Update the comparison message information
guildInfo.setCompareMessage(interaction.channel.id, interaction.message.id);
const query = guildInfo.queryBuilder("setCompareMessage");
await dbfn.setGuildInfo(query);
// Update the tree information
// Make sure we have a tree message and parse it
const isTree = this.messages.isTree(treeMessage);
if (!isTree) throw "Tree message isn't actually a tree message!";
guildInfo.setTreeInfo(isTree.treeName, isTree.treeHeight);
// Grab the leaderboard
// Make sure it's a leaderboard and parse it
const isLeaderboard = this.messages.isLeaderboard(leaderboardMessage);
if (!isLeaderboard) throw "Leaderboard message isn't actually a leaderboard message!";
// Upload the leaderboard
await dbfn.uploadLeaderboard(isLeaderboard);
// const getGuildInfoResponse = await dbfn.getGuildInfo(interaction.guildId);
// let guildInfo = getGuildInfoResponse.data;
let guildInfo = interaction.client.guildInfos.get(interaction.guild.id);
const findMessagesResponse = await this.messages.find(interaction, guildInfo);
if (findMessagesResponse.code == 1) {
guildInfo = findMessagesResponse.data;
// Parse the tree
await this.tree.parse(interaction, guildInfo);
// Parse the leaderboard
await this.rankings.parse(interaction, guildInfo);
// Build the string that shows the comparison // TODO Move the string building section to fn.builders?
const comparedRankings = await this.rankings.compare(guildInfo);
const comparedRankings = await this.rankings.compare(interaction, guildInfo);
const embed = this.builders.comparisonEmbed(comparedRankings, guildInfo);
await interaction.update(embed).catch(e => console.error(e));
} else {
throw "Guild doesn't exist in database!";
await interaction.update(this.builders.errorEmbed(findMessagesResponse.status));
}
},
reset(interaction) {
@ -994,9 +652,6 @@ const functions = {
timeToHeight(beginHeight, destHeight, efficiency, quality) {
return new Promise((resolve, reject) => {
let time = 0;
let oldTime = 0;
let compostAppliedCount = 0;
let totalWaterCount = 0;
if ((efficiency) && (quality)) {
for (let i = beginHeight; i < destHeight; i++) {
const randNum = Math.floor(Math.random() * 100);
@ -1006,15 +661,9 @@ const functions = {
let waterTime = functions.getWaterTime(i);
let reductionTime = waterTime * qualityPercent;
let finalTime = waterTime - reductionTime;
compostAppliedCount++;
totalWaterCount++;
time += parseFloat(finalTime);
oldTime += waterTime;
} else {
totalWaterCount++;
let waterTime = parseFloat(functions.getWaterTime(i));
time += waterTime;
oldTime += waterTime;
time += parseFloat(functions.getWaterTime(i));
}
}
} else {
@ -1024,15 +673,8 @@ const functions = {
time += waterTime;
}
}
const readableWaterTime = this.parseWaterTime(time);
const savedTime = this.parseWaterTime(oldTime - time);
resolve({
time: readableWaterTime,
totalWaterCount: totalWaterCount ? totalWaterCount : undefined,
compostAppliedCount: compostAppliedCount ? compostAppliedCount : undefined,
average: totalWaterCount ? parseFloat((compostAppliedCount / totalWaterCount) * 100).toFixed(1) : undefined,
savedTime: savedTime
});
resolve(this.parseWaterTime(time));
});
},
sleep(ms) {
@ -1046,28 +688,28 @@ const functions = {
},
async sendWaterReminder(guildInfo, message, channelId, guild) {
const reminderChannel = await guild.channels.fetch(channelId);
// const reminderEmbed = functions.builders.waterReminderEmbed(message, guildInfo);
if (isDev) console.log(`WR: ${guild.name}: ${guildInfo.treeName}`);
await reminderChannel.send(message).then(async m => {
const reminderEmbed = functions.builders.waterReminderEmbed(message, guildInfo);
console.log(`Water Relay: ${guild.name}: ${guildInfo.treeName}`);
await reminderChannel.send(reminderEmbed).then(async m => {
if (!m.deletable) return;
await this.sleep(500).then(async () => {
await m.delete().catch(e => console.error(e));
});
}).catch(err => {
console.error(`[${err.code}]: ${err.message} - ${err.url}`);
console.error(err);
});
},
async sendFruitReminder(guildInfo, message, channelId, guild) {
const reminderChannel = await guild.channels.fetch(channelId);
// const reminderEmbed = functions.builders.fruitReminderEmbed(message, guildInfo);
if (isDev) console.log(`FR: ${guild.name}: ${guildInfo.treeName}`);
await reminderChannel.send(message).then(async m => {
const reminderEmbed = functions.builders.fruitReminderEmbed(message, guildInfo);
console.log(`Fruit Relay: ${guild.name}: ${guildInfo.treeName}`);
await reminderChannel.send(reminderEmbed).then(async m => {
if (!m.deletable) return;
await this.sleep(500).then(async () => {
await m.delete().catch(e => console.error(e));
});
}).catch(err => {
console.error(`[${err.code}]: ${err.message} - ${err.url}`);
console.error(err);
});
},
async setupCollectors(client) {
@ -1084,19 +726,19 @@ const functions = {
const collector = channel.createMessageCollector({ filter });
collector.on('collect', message => {
if (message.content.toLowerCase().includes("water ping")) {
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild);
return;
} else if (message.content.toLowerCase().includes("fruit ping")) {
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild);
return;
}
if (message.embeds == undefined) return;
if (message.embeds.length == 0) return;
guildInfo = client.guildInfos.get(guild.id);
if (message.embeds[0].data.description.includes(strings.notifications.water)) {
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild);
} else if (message.embeds[0].data.description.includes(strings.notifications.fruit)) {
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild);
}
});
}
@ -1114,49 +756,23 @@ const functions = {
collectors.push(collector);
collector.on('collect', message => {
if (message.content.toLowerCase().includes("water ping")) {
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild);
return;
} else if (message.content.toLowerCase().includes("fruit ping")) {
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild);
return;
}
if (message.embeds == undefined) return;
if (message.embeds.length == 0) return;
if (message.embeds[0].data.description.includes(strings.notifications.water)) {
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendWaterReminder(guildInfo, guildInfo.waterMessage, guildInfo.reminderChannelId, guild);
} else if (message.embeds[0].data.description.includes(strings.notifications.fruit)) {
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild).catch(e => console.error(`[${e.code}]: ${e.message} - ${e.url}`));
this.sendFruitReminder(guildInfo, guildInfo.fruitMessage, guildInfo.reminderChannelId, guild);
}
});
} else {
throw "Guild doesn't exist in database!";
}
},
generateErrorId() {
const digitCount = 10;
const digits = [];
for (let i = 0; i < digitCount; i++) {
const randBase = Math.random();
const randNumRaw = randBase * 10;
const randNumRound = Math.floor(randNumRaw);
digits.push(randNumRound);
}
const errorId = digits.join("");
return errorId;
},
async sendHeartbeat(url) {
https.get(url, async (response) => {
if (isDev) console.log("Sent Heartbeat Request: " + url);
let data = '';
response.on('data', (chunk) => data += chunk);
response.on('end', () => {
if (isDev) console.log("Received Heartbeat Response: " + data);
parsedData = JSON.parse(data);
if ( !(parsedData.ok) ) console.error("Heartbeat failed");
});
}).on("error", (error) => console.error(error));
}
};

View File

@ -1,21 +0,0 @@
information(content, fields) {
const embed = new EmbedBuilder()
.setColor(strings.embeds.color)
.setTitle('Information')
.setDescription(content)
.setFooter({ text: `v${package.version} - ${strings.embeds.footer}` });
if (fields) embed.addFields(fields);
const messageContents = { embeds: [embed], ephemeral: true };
return messageContents;
}
replyContent = `I estimate that a tree with ${efficiency}% Composter Efficiency and ${quality}% Compost Quality growing from ${beginHeight}ft to ${endHeight}ft will take ${time}`;
replyFields = [
{ name: `Start Height:`, value: `**${beginHeight}ft**`, inline: true },
{ name: `End Height:`, value: `**${endHeight}**`, inline: true },
{ name: `Efficiency:`, value: `**${efficiency}%**`, inline: true },
{ name: `Quality:`, value: `**${quality}%**`, inline: true },
{ name: `Summary`, value: `Compost Applied **${compostAppliedCount}** times, out of **${totalWaterCount}** waterings, for an average of **${average}%**` }
];
const reply = information(replyContent, replyFields);

View File

@ -1,98 +0,0 @@
/* eslint-disable no-case-declarations */
/* eslint-disable indent */
// dotenv for handling environment variables
const dotenv = require('dotenv');
dotenv.config();
const token = process.env.TOKEN;
const dbfn = require('./dbfn.js');
// Discord.JS
const { Client, GatewayIntentBits, Partials } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.MessageContent
],
partials: [
Partials.Channel,
Partials.Message
],
});
// Various imports
const fn = require('../modules/functions.js');
client.once('ready', async () => {
// watchRequestRates();
await fn.collectionBuilders.guildInfos(client);
const guilds = client.guilds.cache;
console.log("I'm in " + guilds.size + " guilds with " + client.guildInfos.size + " guildInfos");
// guilds.each(g => {
// console.log(g.name + "," + g.id + "," + g.ownerId);
// });
await setAllGuildOwners();
process.exit();
});
client.login(token);
async function watchRequestRates() {
const axios = require('axios');
// Make a GET request to the Discord API
await axios.get('https://discord.com/api/v10/users/@me', {
headers: {
'Authorization': `Bot ${token}`
}
}).then(response => {
// Get the rate limit headers
const remaining = response.headers['x-ratelimit-remaining'];
const reset = response.headers['x-ratelimit-reset'];
// Log the rate limit headers
console.log(`Remaining requests: ${remaining}`);
console.log(`Reset time (Unix epoch seconds): ${reset}`);
}).catch(error => {
console.error(error);
});
await fn.sleep(500).then(async () => {
await watchRequestRates();
});
}
async function setAllGuildOwners() {
try {
let guildInfosArray = new Array();
let guildUpdateCount = 0;
let guildMissingCount = 0;
client.guildInfos.forEach((guildInfo) => {
guildInfosArray.push(guildInfo);
});
// console.log(guildInfosArray);
for (let i = 0; i < guildInfosArray.length; i++) {
const guildInfo = guildInfosArray[i];
let eFlag = 0;
const guild = await client.guilds.fetch(guildInfo.guildId).catch(e => {
eFlag = 1;
if (e.status === 404) {
console.log("Missing guild: " + guildInfo.guildId);
guildMissingCount++;
} else {
throw e;
}
});
if (eFlag === 1) continue;
guildInfo.setIds(guildInfo.guildId, guild.ownerId);
const query = guildInfo.queryBuilder("setIds");
console.log(query);
await dbfn.setGuildInfo(query);
guildUpdateCount++;
}
console.log(`Updated ${guildUpdateCount} guilds with ${guildMissingCount} missing guilds.`);
} catch(err) {
console.error(err);
}
}

View File

@ -1,6 +1,6 @@
{
"name": "silvanus",
"version": "1.2.9",
"version": "1.2.2",
"description": "Grow A Tree Companion Bot",
"main": "main.js",
"scripts": {
@ -17,8 +17,8 @@
},
"homepage": "https://github.com/voidf1sh/silvanus#readme",
"dependencies": {
"axios": "^1.4.0",
"discord.js": "^14.11.0",
"axios": "^1.3.3",
"discord.js": "^14.7.1",
"dotenv": "^16.0.3",
"mysql": "^2.18.1",
"string-replace-all": "^2.0.0",

39
privacy
View File

@ -1,39 +0,0 @@
Privacy Policy for Silvanus Discord Bot
This Privacy Policy describes how Silvanus ("the Bot," "we," or "us") collects, uses, and stores your personal information when you interact with the bot. Please read this policy carefully to understand our practices regarding your personal data and how we will treat it.
Data Collection and Usage:
We collect and store the following data when you use the Silvanus Discord Bot:
User IDs: We collect user IDs to provide personalized services and ensure smooth bot functionality.
Guild IDs: We collect guild IDs to enable the bot to operate within specific servers and provide server-specific features.
Channel IDs: We collect channel IDs to facilitate bot functionality within specific channels.
Message IDs: We collect message IDs to support certain features and improve the user experience.
Role IDs: We collect role IDs to provide role-based functionality within Discord servers.
Tree Names, Ranks, and Heights: We collect tree-related data for in-game purposes and to enhance user interactions.
Data Storage and Security:
All collected data is stored securely using industry-standard practices. User IDs, guild IDs, channel IDs, message IDs, role IDs, tree names, tree ranks, and tree heights are stored in an encrypted MariaDB database. Additionally, the database is stored on a LUKS encrypted drive, providing an extra layer of security.
Data Deletion Requests:
If you would like to request the deletion of your data, please follow one of the methods below:
Discord Message: You can message @voidf1sh on Discord to request data deletion.
Email: You can send an email to SilvanusDev@gmail.com to request data deletion.
Support Server: You can join our support server at https://discord.gg/g5JRGn7PxU and submit a request for data deletion.
Please note that we will make reasonable efforts to respond to and process your data deletion requests in a timely manner, subject to any legal obligations or legitimate interests that may prevent us from complying with such requests.
Data Sharing:
We do not sell or share your personal information with third parties, except in the following circumstances:
Compliance with Laws: We may share your personal information if required to do so by applicable laws, regulations, legal processes, or governmental requests.
Protection of Rights: We may share your personal information to protect the rights, property, or safety of Silvanus, its users, or others.
Changes to the Privacy Policy:
We reserve the right to modify or update this Privacy Policy at any time. We will notify users of any material changes through the bot or other means. Your continued use of Silvanus after such modifications or updates signifies your acceptance of the revised Privacy Policy.
Contact Information:
If you have any questions, concerns, or requests regarding this Privacy Policy or our data practices, please contact us at SilvanusDev@gmail.com.
Last updated: [22 May 2023]

View File

@ -1,20 +0,0 @@
const { SlashCommandBuilder, messageLink } = require('discord.js');
const fn = require('../modules/functions.js');
const strings = require('../data/strings.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('about')
.setDescription('Get info about the bot')
.addStringOption(o =>
o.setName('private')
.setDescription('Should the response be sent privately?')
.setRequired(true)
.addChoices(
{ name: "True", value: "true" },
{ name: "False", value: "false" })),
async execute(interaction) {
const aboutEmbed = fn.builders.aboutEmbed(interaction.options.getString('private'));
await interaction.reply(aboutEmbed);
},
};

View File

@ -1,7 +1,6 @@
const { SlashCommandBuilder, Guild } = require('discord.js');
const dbfn = require('../modules/dbfn.js');
const fn = require('../modules/functions.js');
const strings = require('../data/strings.json');
const { GuildInfo } = require('../modules/CustomClasses.js');
module.exports = {
@ -15,33 +14,36 @@ module.exports = {
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
// Handle a missing tree or leaderboard
let errors = [];
if (guildInfo.treeMessageId === "") {
errors.push(strings.error.noTreeMessage);
} else if (guildInfo.leaderboardMessageId === "") {
errors.push(strings.error.noLeaderboardMessage);
}
if (errors.length > 0) {
const embed = fn.builders.errorEmbed(`Unable to complete comparison, unable to find message(s):\n${errors.join("\n")}`);
await interaction.editReply(embed);
return;
}
// Build the string that shows the comparison // TODO Move the string building section to fn.builders?
const comparedRankings = await fn.rankings.compare(guildInfo);
const findMessagesResponse = await fn.messages.find(interaction, guildInfo);
if (findMessagesResponse.code == 1) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
// Parse the leaderboard message
await fn.rankings.parse(interaction, guildInfo);
// Build the string that shows the comparison // TODO Move the string building section to fn.builders?
const comparedRankings = await fn.rankings.compare(interaction, guildInfo);
const embed = fn.builders.comparisonEmbed(comparedRankings, guildInfo);
await interaction.editReply(embed).then(async m => {
guildInfo.setCompareMessage(m.channel.id, m.id);
const query = guildInfo.queryBuilder("setCompareMessage");
await dbfn.setGuildInfo(query);
}).catch(e => console.error(e));
const embed = fn.builders.comparisonEmbed(comparedRankings, guildInfo);
await interaction.editReply(embed).catch(e => console.error(e));
} else {
await interaction.editReply(fn.builders.errorEmbed(findMessagesResponse.status));
}
} else {
let errors = [];
errors.push(strings.error.noTreeMessage);
errors.push(strings.error.noLeaderboardMessage);
const embed = fn.builders.errorEmbed(`Unable to complete comparison, unable to find message(s):\n${errors.join("\n")}`);
await interaction.editReply(embed);
// Create a basic guildInfo with blank data
let guildInfo = new GuildInfo()
.setId(interaction.guildId)
.setTreeMessage("", interaction.channelId)
.setLeaderboardMessage("", interaction.channelId)
// Using the above guildInfo, try to find the Grow A Tree messages
const findMessagesResponse = await fn.messages.find(interaction, guildInfo);
guildInfo = findMessagesResponse.data;
if (findMessagesResponse.code == 1) {
// Build the string that shows the comparison // TODO Move the string building section to fn.builders?
const comparedRankings = await fn.rankings.compare(interaction, guildInfo);
const embed = fn.builders.comparisonEmbed(comparedRankings, guildInfo);
await interaction.editReply(embed).catch(e => console.error(e));
} else {
await interaction.editReply(fn.builders.errorEmbed(findMessagesResponse.status));
}
}
} catch (err) {
interaction.editReply(fn.builders.errorEmbed(err)).catch(err => {

View File

@ -55,11 +55,6 @@ module.exports = {
.setDescription("Message to send for fruit reminders")
.setRequired(false)
)
.addBooleanOption(o =>
o.setName('enabled')
.setDescription("Enable the relay?")
.setRequired(false)
)
)
.addSubcommand(sc =>
sc.setName('disable')
@ -110,7 +105,7 @@ module.exports = {
const reminderChannel = interaction.options.getChannel('pingchannel');
// Create a new GuildInfo object
let guildInfo = new GuildInfo()
.setIds(interaction.guildId, interaction.guild.ownerId)
.setId(interaction.guildId)
// Set the reminder configuration
.setReminders(waterMessage, fruitMessage, reminderChannel.id, watchChannel.id, true);
// Update the guildInfos Collection
@ -119,8 +114,6 @@ module.exports = {
let query = guildInfo.queryBuilder("setReminders");
// Run the query
await dbfn.setGuildInfo(query);
// Refresh the collection
await fn.collectionBuilders.guildInfos(interaction.client);
// Create a messageCollector on the watch channel
fn.collectors.create(interaction.client, guildInfo);
// Compose a reply
@ -142,25 +135,21 @@ module.exports = {
const inWaterMessage = interaction.options.getString('watermessage');
const inFruitMessage = interaction.options.getString('fruitmessage');
const inReminderChannel = interaction.options.getChannel('pingchannel');
const inEnabled = interaction.options.getBoolean('enabled');
// Check if each option is set, if it is, use it. Otherwise use what was already set
const outWatchChannelId = inWatchChannel ? inWatchChannel.id : guildInfo.watchChannelId;
const outWaterMessage = inWaterMessage ? inWaterMessage : guildInfo.waterMessage;
const outFruitMessage = inFruitMessage ? inFruitMessage : guildInfo.fruitMessage;
const outReminderChannelId = inReminderChannel ? inReminderChannel.id : guildInfo.reminderChannelId;
const outEnabled = inEnabled ? inEnabled : guildInfo.notificationsEnabled;
// Update the relay configuration
guildInfo.setReminders(outWaterMessage, outFruitMessage, outReminderChannelId, outWatchChannelId, outEnabled);
guildInfo.setReminders(outWaterMessage, outFruitMessage, outReminderChannelId, outWatchChannelId, true);
// Update the guildInfos Collection
interaction.client.guildInfos.set(interaction.guildId, guildInfo);
// Build a query to update the database
let query = guildInfo.queryBuilder("setReminders");
// Run the query
await dbfn.setGuildInfo(query);
// Refresh the collection
await fn.collectionBuilders.guildInfos(interaction.client);
// Create a messageCollector on the watch channel
fn.collectors.create(interaction.client, guildInfo);
// Compose a reply
@ -184,8 +173,6 @@ module.exports = {
interaction.client.guildInfos.set(interaction.guildId, guildInfo);
// Update the database
await dbfn.setGuildInfo(guildInfo.queryBuilder("setReminders")).catch(e => console.error(e));
// Refresh the collection
await fn.collectionBuilders.guildInfos(interaction.client);
// Close the collector
await fn.collectors.end(interaction.client, guildInfo).catch(e => console.error(e));
// Reply confirming disabling of relay

View File

@ -1,30 +0,0 @@
const { SlashCommandBuilder, PermissionsBitField, PermissionFlagsBits } = require('discord.js');
const fn = require('../modules/functions.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('permissions')
.setDescription('Check my permissions here')
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
async execute(interaction) {
await interaction.deferReply({ ephemeral: true });
const me = interaction.guild.members.me;
const guildPerms = me.permissions;
const manageRoles = guildPerms.has(PermissionsBitField.Flags.ManageRoles);
const mentionEveryone = guildPerms.has(PermissionsBitField.Flags.MentionEveryone);
const channelPerms = me.permissionsIn(interaction.channel);
const viewChannel = channelPerms.has(PermissionsBitField.Flags.ViewChannel);
const sendMessages = channelPerms.has(PermissionsBitField.Flags.SendMessages);
const responseParts = [
`This is the status of my permissions in this server and this channel (<#${interaction.channel.id}>)`,
`**Guild Permissions**`,
`Manage Roles: ${manageRoles}`,
`Mention All Roles: ${mentionEveryone}`,
`**Channel Permissions**`,
`View Channel: ${viewChannel}`,
`Send Messages: ${sendMessages}`
];
const replyEmbed = fn.builders.embed(responseParts.join("\n"));
await interaction.editReply(replyEmbed);
}
};

View File

@ -7,7 +7,21 @@ const { GuildInfo } = require('../modules/CustomClasses.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('setup')
.setDescription('Configure some feature settings.')
.setDescription('Attempt automatic configuration of the bot.')
.addSubcommand(sc =>
sc.setName('compare')
.setDescription('Set up the channels to be used with /compare')
.addChannelOption(o =>
o.setName('treechannel')
.setDescription('What channel is your tree in?')
.setRequired(true)
)
.addChannelOption(o =>
o.setName('leaderboardchannel')
.setDescription('What channel is your leaderboard in?')
.setRequired(true)
)
)
.addSubcommand(sc =>
sc.setName('rolemenu')
.setDescription('Setup the roles to be used with /rolemenu')
@ -39,6 +53,30 @@ module.exports = {
await interaction.deferReply({ ephemeral: true });
const subcommand = interaction.options.getSubcommand();
switch (subcommand) {
case "compare":
const treeChannel = interaction.options.getChannel('treechannel');
const leaderboardChannel = interaction.options.getChannel('leaderboardchannel');
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
guildInfo.setTreeMessage(undefined, treeChannel.id);
guildInfo.setLeaderboardMessage(undefined, leaderboardChannel.id);
// Update the database
await dbfn.setGuildInfo(guildInfo.queryBuilder("setTreeMessage")).catch(e => console.error(e));
await dbfn.setGuildInfo(guildInfo.queryBuilder("setLeaderboardMessage")).catch(e => console.error(e));
const reply = `Tree Channel: <#${treeChannel.id}> | Leaderboard Channel: <#${leaderboardChannel.id}>`;
await interaction.editReply(fn.builders.embed(reply)).catch(e => console.error(e));
} else {
let guildInfo = new GuildInfo()
.setId(interaction.guildId)
.setTreeMessage(undefined, treeChannel.id)
.setLeaderboardMessage(undefined, leaderboardChannel.id);
// Update the database
await dbfn.setGuildInfo(guildInfo.queryBuilder("setTreeMessage")).catch(e => console.error(e));
await dbfn.setGuildInfo(guildInfo.queryBuilder("setLeaderboardMessage")).catch(e => console.error(e));
const reply = `Tree Channel: <#${treeChannel.id}> | Leaderboard Channel: <#${leaderboardChannel.id}>`;
await interaction.editReply(fn.builders.embed(reply)).catch(e => console.error(e));
}
break;
case "rolemenu":
let waterRoleId = interaction.options.getRole('waterrole').id;
let fruitRoleId = interaction.options.getRole('fruitrole') ? interaction.options.getRole('fruitrole').id : undefined;
@ -50,7 +88,7 @@ module.exports = {
await interaction.editReply(fn.builders.embeds.treeRoleMenu(guildInfo)).catch(e => console.error(e));
} else {
let guildInfo = new GuildInfo()
.setIds(interaction.guildId, interaction.guild.ownerId);
.setId(interaction.guildId);
guildInfo.setRoles(waterRoleId, fruitRoleId);
await dbfn.setGuildInfo(guildInfo.queryBuilder("setRoles"));
await fn.collectionBuilders.guildInfos(interaction.client);

View File

@ -6,64 +6,61 @@ module.exports = {
data: new SlashCommandBuilder()
.setName('timetoheight')
.setDescription('Calculate how long it would take to reach a given height')
.addIntegerOption(o =>
.addIntegerOption(o =>
o.setName('endheight')
.setDescription('Ending tree height in feet')
.setRequired(true)
.setDescription('Ending tree height in feet')
.setRequired(true)
)
.addIntegerOption(o =>
.addIntegerOption(o =>
o.setName('beginheight')
.setDescription('Beginning tree height in feet')
.setRequired(false)
.setDescription('Beginning tree height in feet')
.setRequired(false)
)
.addIntegerOption(o =>
.addIntegerOption(o =>
o.setName('efficiency')
.setDescription('Composter efficiency percentage, rounded')
.setRequired(false)
.setDescription('Composter efficiency percentage, rounded')
.setRequired(false)
)
.addIntegerOption(o =>
.addIntegerOption(o =>
o.setName('quality')
.setDescription('Compost quality percentage, rounded')
.setRequired(false)
.setDescription('Compost quality percentage, rounded')
.setRequired(false)
)
.addBooleanOption(o =>
o.setName('private')
.setDescription('Should the reply be visible only to you?')
.setRequired(false)
.setDescription('Should the reply be visible only to you?')
.setRequired(false)
),
async execute(interaction) {
const private = interaction.options.getBoolean('private') != undefined ? interaction.options.getBoolean('private') : true;
await interaction.deferReply({ ephemeral: private });
const inBeginHeight = interaction.options.getInteger('beginheight');
const endHeight = interaction.options.getInteger('endheight');
const efficiency = interaction.options.getInteger('efficiency') != undefined ? interaction.options.getInteger('efficiency') : 10;
const quality = interaction.options.getInteger('quality') != undefined ? interaction.options.getInteger('quality') : 5;
const efficiency = interaction.options.getInteger('efficiency');
const quality = interaction.options.getInteger('quality');
let beginHeight, replyContent;
if ((efficiency && !quality) || (quality && !efficiency)) {
const reply = fn.builders.embed("You must include **both** efficiency *and* quality, I only received one.");
await interaction.editReply(reply).catch(e => console.error(e));
return;
}
if (!inBeginHeight) {
const guildInfo = interaction.client.guildInfos.get(interaction.guild.id);
beginHeight = guildInfo.treeHeight;
} else {
beginHeight = inBeginHeight;
}
const timeToHeightResults = await fn.timeToHeight(beginHeight, endHeight, efficiency, quality);
const { time, totalWaterCount, compostAppliedCount, average, savedTime } = timeToHeightResults;
let replyFields = undefined;
const timeString = await fn.timeToHeight(beginHeight, endHeight, efficiency, quality);
if (efficiency && quality) {
replyContent = `I estimate that a tree with ${efficiency}% Composter Efficiency and ${quality}% Compost Quality growing from ${beginHeight}ft to ${endHeight}ft will take ${time}`;
replyFields = [
{ name: `Height Gained:`, value: `${endHeight - beginHeight}ft`, inline: true},
{ name: `E/Q:`, value: `${efficiency}%/${quality}%`, inline: true},
{ name: `Compost Applied`, value: `${compostAppliedCount} times`, inline: true },
{ name: `Compost Average`, value: `${average}%`, inline: true },
{ name: `Saved Time`, value: savedTime, inline: true }
];
replyContent = `I estimate that a tree with ${efficiency}% Composter Efficiency and ${quality}% Compost Quality growing from ${beginHeight}ft to ${endHeight}ft will take ${timeString}`;
} else {
replyContent = `I estimate that a tree growing from ${beginHeight}ft to ${endHeight}ft will take ${time}`;
replyContent = `I estimate that a tree growing from ${beginHeight}ft to ${endHeight}ft will take ${timeString}`;
}
const reply = fn.builders.embeds.information(replyContent, replyFields)
const reply = fn.builders.embed(replyContent)
await interaction.editReply(reply);
}
};