Compare commits

...

128 Commits

Author SHA1 Message Date
Skylar Grant ac6eca4827 Merge pull request 'v1.2.9-dev' (#8) from v1.2.9-dev into main
Reviewed-on: #8
2024-04-06 13:16:15 +00:00
Skylar Grant 88cc4eda3c Remove reminder embed, only send text message
Silvanus Production Dockerization / build (pull_request) Has been cancelled Details
2024-04-06 09:01:57 -04:00
Skylar Grant 7291216dcb Versioning 2024-04-06 09:01:43 -04:00
Skylar Grant 36f44f4b41 Merge pull request 'v1.2.8 Heartbeat Monitoring' (#6) from v1.2.8 into main
Reviewed-on: #6
2023-09-02 08:37:11 -07:00
Skylar Grant 825ec725d1 Timer planning
Silvanus Production Dockerization / build (pull_request) Has been cancelled Details
2023-09-02 09:42:10 -04:00
Skylar Grant fb43d09d13 Fix debug mode detection
Silvanus Production Dockerization / build (pull_request) Has been cancelled Details
2023-08-27 20:27:11 -04:00
Skylar Grant 0463695323 Improved logging
Silvanus Production Dockerization / build (pull_request) Successful in 12s Details
2023-08-27 19:34:15 -04:00
Skylar Grant 314b793042 Versioning
Silvanus Production Dockerization / build (pull_request) Successful in 53s Details
2023-08-10 22:18:28 -04:00
Skylar Grant eca3207d4e Remove excess console.log 2023-08-10 22:16:23 -04:00
Skylar Grant e2658c41e5 Add heartbeat url for uptime monitoring 2023-08-10 22:13:08 -04:00
Skylar Grant dd313faa60 Merge pull request 'Change dispatch to pull req' (#3) from testing into main
Reviewed-on: #3
2023-08-04 09:52:53 -07:00
Skylar Grant ba81f01fa0 Even more dubious
Silvanus Production Dockerization / build (pull_request) Successful in 27s Details
2023-07-31 16:43:54 -04:00
Skylar Grant e303651f53 Dubious
Silvanus Production Dockerization / build (pull_request) Failing after 2s Details
2023-07-31 16:43:24 -04:00
Skylar Grant 40fc6838a0 Debug
Silvanus Production Dockerization / build (pull_request) Failing after 2s Details
2023-07-31 16:41:52 -04:00
Skylar Grant 67483697f0 Attempt #243095
Silvanus Production Dockerization / build (pull_request) Failing after 2s Details
2023-07-31 16:40:48 -04:00
Skylar Grant 1e1d0cddaa Moar fixxed?!
Silvanus Production Dockerization / build (pull_request) Failing after 2s Details
2023-07-31 16:35:33 -04:00
Skylar Grant 45418e2bd6 Fixed I hope
Silvanus Production Dockerization / build (pull_request) Failing after 2s Details
2023-07-31 16:23:03 -04:00
Skylar Grant 22005ac68f asd;flkasdj;
Silvanus Production Dockerization / build (pull_request) Has been cancelled Details
2023-07-31 16:21:21 -04:00
Skylar Grant 805c20953c Fixes
Silvanus Production Dockerization / build (pull_request) Failing after 7s Details
2023-07-31 16:12:58 -04:00
Skylar Grant ba0e4625c0 Remove host
Silvanus Production Dockerization / build (pull_request) Failing after 6s Details
2023-07-31 16:07:43 -04:00
Skylar Grant 11465287dd Update uses declaration
Silvanus Production Dockerization / build (pull_request) Failing after 12s Details
2023-07-31 16:05:40 -04:00
Skylar Grant 36c59f83f4 Change dispatch to pull req
Silvanus Production Dockerization / build (pull_request) Failing after 46s Details
2023-07-31 16:03:25 -04:00
Skylar Grant 4dda58f48e Merge pull request 'Slight verbiage change' (#2) from testing into main
Reviewed-on: #2
2023-07-31 12:58:33 -07:00
Skylar Grant e85340245c Slight verbiage change 2023-07-31 15:57:04 -04:00
Skylar Grant 252593a327 Merge pull request 'Versioning' (#1) from v1.2.7-dev into main
Reviewed-on: #1
2023-07-31 12:55:29 -07:00
Skylar Grant 7999350f1e Versioning 2023-07-31 15:45:25 -04:00
Skylar Grant 87a468b620 Update workflow trigger for Gitea Actions 2023-07-31 15:44:17 -04:00
Skylar Grant ae602d08de Fixed bug when updating relay settings 2023-07-31 15:12:23 -04:00
Skylar Grant 94c3244016
Merge pull request #17 from eilandert/main
remove if empty database statement
2023-07-31 10:02:01 -04:00
Skylar Grant 2f9126aa6e tweak errors 2023-07-10 19:52:18 -04:00
Skylar Grant 486a59715d vastly improved error handling 2023-07-10 19:46:30 -04:00
Skylar Grant 25859d364d Improved error handling? 2023-07-06 19:04:13 -04:00
Skylar Grant c0cba3e14e Modified log output for better organization 2023-07-06 18:28:03 -04:00
Thijs Eilander e3fb4da9f6 typo, it's late 2023-06-19 03:58:24 +02:00
Thijs Eilander f2560a081e added my own id into the dev team 2023-06-19 03:52:33 +02:00
Thijs Eilander e8f16d8fea change description /notifications update to /relay update 2023-06-19 00:02:47 +02:00
Thijs Eilander 7c56381141 due to this test, when starting with a new database the bot exits upon start, so there is no possibility to add a new entry in the database at all. 2023-06-18 22:51:35 +02:00
Skylar Grant a1386dd688 Add owner IDs to db, clean up some logging 2023-06-16 20:01:29 -04:00
Skylar Grant 9e5a89eabb Add privacy policy 2023-06-13 21:10:21 -04:00
Skylar Grant d6bab1c2da Include email in help 2023-06-13 20:54:35 -04:00
Skylar Grant d117a69893 Add status updates and removal notifs 2023-06-10 15:09:45 -04:00
Skylar Grant 87c7a8e9ec Improve the About embed 2023-06-10 15:03:00 -04:00
Skylar Grant a27dc1923e Fix message 2023-06-10 14:28:19 -04:00
Skylar Grant c3967e0643 Add top.gg link to about command 2023-06-10 14:22:40 -04:00
Skylar Grant 4144dde4d6 Add guild add notif 2023-06-08 17:51:41 -04:00
Skylar Grant e05bd20f1f Add about command 2023-06-07 20:10:49 -04:00
Skylar Grant 7003e12fa1 Add direct link to setup guide 2023-06-07 20:07:51 -04:00
Skylar Grant 246848e94a Add wiki link to readme 2023-06-07 19:56:18 -04:00
Skylar Grant a13888c6c1 New help message 2023-06-07 19:54:33 -04:00
Skylar Grant 49747d4b54 Fix invite link 2023-06-06 19:39:07 -04:00
Skylar Grant e94b8ce433 Fix permissions dot command 2023-06-06 19:37:36 -04:00
Skylar Grant 9a5a457123 Remove out of date information 2023-06-06 19:37:36 -04:00
Skylar Grant c83e94f01d Implement permission troubleshooting 2023-06-06 19:37:36 -04:00
Skylar Grant 08f76fb996 Add notification relay status to setupinfo 2023-06-06 19:37:36 -04:00
Skylar Grant d1ac674c6b Allow everyone ping dot command 2023-06-06 19:37:36 -04:00
Skylar Grant e29a54b0d9 Add leave command, update util to show guildid 2023-06-06 19:37:36 -04:00
Skylar Grant 5b7c0c4225 Fix message command 2023-06-06 19:37:36 -04:00
Skylar Grant 4f0fa1e51f Update to allow enable/disable via relay update 2023-06-06 19:37:36 -04:00
Skylar Grant 946f05d57b Update to ignore all .env 2023-06-06 19:37:36 -04:00
Skylar Grant 92c06529ff Fix for broken relay 2023-06-06 19:37:36 -04:00
Skylar Grant c4fc1a4ba6 Disable relay on guilds I'm no longer in 2023-06-06 19:37:36 -04:00
Skylar Grant b0d6bdcf8a Minor changes 2023-06-06 19:37:36 -04:00
Skylar Grant 2704cac98f Fix for embeds w/o descriptions crashing the bot 2023-06-06 19:37:36 -04:00
Skylar Grant a28957b956 Enable dev team dot commands 2023-06-06 19:37:36 -04:00
Skylar Grant 105fb2827f Versioning 2023-06-06 19:37:36 -04:00
Skylar Grant 9aa9511fd7 Misc updates 2023-06-03 15:02:31 -04:00
Skylar Grant 79821d7abc Rename file to match command name 2023-06-03 15:02:31 -04:00
Skylar Grant e075a3a5d6 Implement error handling for rolemenu 2023-06-03 15:02:31 -04:00
Skylar Grant 3c01d37bd5 Bug fix so message updates will create guild entry 2023-06-03 15:02:31 -04:00
Skylar Grant f7230ec0fb Trying error handling DO NOT PUSH 2 PROD 2023-06-03 15:02:31 -04:00
Skylar Grant 1927d3029a Begin implementing ability to message server owner 2023-06-03 15:02:31 -04:00
Skylar Grant 41b59f8b92 Add basic message command 2023-06-03 15:02:31 -04:00
Skylar Grant f3573eeaed Stop sending name and owner IDs 2023-06-03 15:02:31 -04:00
Skylar Grant 44a4d572bb Fix file reference 2023-06-03 15:02:31 -04:00
Skylar Grant de6b9ec4e4 Adding dot commands from nodbot 2023-06-03 15:02:31 -04:00
Skylar Grant 56d9cacfbe Change squash type to prevent further execution 2023-06-03 15:02:31 -04:00
Skylar Grant 0c28ec437c err -> error 2023-06-03 15:02:31 -04:00
Skylar Grant 8d64640193 Squash missing guild error 2023-06-03 15:02:31 -04:00
Skylar Grant 1cb5e94145 Better logging output 2023-06-03 15:02:31 -04:00
Skylar Grant 428cbc1597 Removed error dumping for missing messages 2023-06-03 15:02:31 -04:00
Skylar Grant 1c57cb70ae Better role error handling 2023-06-03 15:02:31 -04:00
Skylar Grant 6f3710bc07 Updating dependencies 2023-06-03 15:02:31 -04:00
Skylar Grant 0bdca58d03 Update stderr and stdout to files with timestamps 2023-06-03 15:02:31 -04:00
Skylar Grant 7121ab5390 Versioning 2023-06-03 15:02:31 -04:00
Skylar Grant 2353486150 Fix for hypens in tree name 2023-06-03 15:02:31 -04:00
Skylar Grant 26b79327be Update Discord.js / Breaking Discord API changes 2023-04-01 20:44:50 -04:00
Skylar Grant 9580a500fd extra tools to use with the bot 2023-04-01 20:44:50 -04:00
Skylar Grant 10f8ed9438 Remove setup compare 2023-04-01 20:44:50 -04:00
Skylar Grant 024defbbfc Automatically updating compare messages! 2023-04-01 20:44:50 -04:00
Skylar Grant 27169afcf0 Testing new tree update detection 2023-04-01 20:44:50 -04:00
Skylar Grant 5f37a3e5a3 Improvements to timetoheights calculations display 2023-04-01 20:44:50 -04:00
Skylar Grant a44a83beeb Versioning 2023-04-01 20:44:50 -04:00
Skylar Grant d7bd6b5d41 Stricter check 2023-04-01 20:44:50 -04:00
Skylar Grant 0f8e9a3e10 Add privacy switch 2023-04-01 20:44:50 -04:00
Skylar Grant 9c6204b19b Some more logging 2023-04-01 20:44:50 -04:00
Skylar Grant 02201b2bfa Add percentage modifiers to timetoheight 2023-04-01 20:44:50 -04:00
Skylar Grant 1f115252ca Rate limits 2023-04-01 20:44:50 -04:00
Skylar Grant e632dce612 Stop checking ratelimits 2023-04-01 20:44:50 -04:00
Skylar Grant cdb61cf602 Documentation update 2023-04-01 20:44:50 -04:00
Skylar Grant b2e0b2b17d Stop deleting commands 2023-04-01 20:44:50 -04:00
Skylar Grant e7a76eee65 Fix /setup compare 2023-04-01 20:44:50 -04:00
Skylar Grant a70b27b112 Documentation update 2023-04-01 20:44:50 -04:00
Skylar Grant 1e358e582e CI Update 2023-04-01 20:44:50 -04:00
Skylar Grant d5254dc58a Removed update event 2023-04-01 20:44:50 -04:00
Skylar Grant 8bc80dfaa8 Self-destructing water relay 2023-04-01 20:44:50 -04:00
Skylar Grant 663ef2297b Error update 2023-04-01 20:44:50 -04:00
Skylar Grant 56be24b5cd Bugfixes in notifications and update to relay 2023-04-01 20:44:50 -04:00
Skylar Grant ebc31b5a0c Versioning 2023-04-01 20:44:50 -04:00
Skylar Grant 1367a90904 Start collector when the command is run 2023-04-01 20:44:50 -04:00
Skylar Grant 26b5728636 Disappearing fruit pings 2023-04-01 20:44:50 -04:00
Skylar Grant b724229f06
V1.2.1 dev (#11)
* make the beginning height optional, defaulting to the trees current heigt

* improved workflow

* fix

* new fix

* Install modules

* remove unnecessary call to build the tables

* testing

* f

* f

* oops

* undev

* fix const

* new ci

* versioning

* Classes, Collections, and new Notification Relay

* Fix CI for new env vars

* Update to read contents of embeds

* Update filter to check for embeds

* Update to add includes check

* Begin implementing role menu

* Role menu ready for testing

* Add missing emojis

* Fixes, ready for testing

* Tentative deploy

* Documentation update

* I think this fixes unchanging notifications

* Update README.md

* Make reminders visually distinct

* Set Permissions

* Added import for PermissionFlagsBits

* Add ability to manually send ping from watch chan

* CI update

* Confusion

* Make dev dockerization manual only

* Dev Logging

* Update reset command

* Implement updating of notifications piecemeal

* Unified error handling

* Change to refresh commands not blindly update

* Change to manual run only

* Restructured file to allow async use

* Move role menu setup and allow everyone to send it

* Consolidate setupinfo into setup

* Improved error handling

* Update opt out method

* Cleaning up junk

* Added seconds parser and optout detection

* Add opt out method

* Consolidated to setup command

* Add privacy setting and use new parser
2023-02-19 20:42:14 -05:00
Skylar Grant 0b6161f0e0
More accurate package description 2023-02-09 21:50:07 -05:00
Skylar Grant 5ef905449d
Dev-v1.1.4 (#9)
* Add 24h growth indicator

* Fix float math

* Fix some bugs

* Trim decimals

* Add 24 hour observed growth

* Add beginning height option

* Changed startup message to ping me

* Add a ping reminder and setup command for it

* Setup automatic water reminders

* Improved workflows

* New water readiness system

* Documentation Time

* Fix slash command link

* Fix linebreaks

* Readability improvements

* Forgot to allow checking in prod

* Switch to ephemeral reply

* Restructuring and new help messages

* Not meant to be uploaded

* Documentation update

* Changing the way reminders are deleted

* Tweak timings

* Adjust readiness detection system

* moar tweekz

* fix reminders

* Updates to water reminders
2023-01-31 22:51:10 -05:00
Skylar Grant e64fa099c1
V1.1.1-dev (#7)
* Fix db connection handling

* Add new time to height calculator

* Versioning

* Finishing updates
2023-01-25 04:53:49 -05:00
Skylar Grant 83a05374cf
V1.1.0-dev-3 (#6)
* New Name, New Version

* New default branch name

* Migrate to database for long term storage

* Fix uncaught call to a promise

* Reverse the leaderboard

* QoL and Bug fixes

* Handle server timeout

* Pretty help message
2023-01-25 03:07:41 -05:00
Skylar Grant 1433b723c3 Fix where I broke /setup 2023-01-23 21:50:30 -05:00
Skylar Grant 14d46a8b29 Clearer handling of first /compare 2023-01-23 21:42:22 -05:00
Skylar Grant e484bf9962 Streamline Help Page 2023-01-23 21:36:44 -05:00
Skylar Grant b12301344c Better messages 2023-01-23 21:29:12 -05:00
Skylar Grant 6f2b16460b reverse the order in which we check for messages 2023-01-23 21:18:28 -05:00
Skylar Grant 91884fd8b9 AFSD 2023-01-23 21:02:32 -05:00
Skylar Grant 7822016945 Add fancy activities 2023-01-23 20:50:14 -05:00
Skylar Grant 19fb712941 Update 2023-01-23 20:49:49 -05:00
Skylar Grant 29191e2c05 Improve /setupinfo 2023-01-23 20:08:29 -05:00
Skylar Grant 02a5093a8b versioning 2023-01-23 19:38:00 -05:00
Skylar Grant f1570566e8 Add self tree detection 2023-01-23 19:37:51 -05:00
Skylar Grant e26d6dca7d Quick variable name patch 2023-01-23 18:40:41 -05:00
Skylar Grant 48ed66cf0a
Merge pull request #3 from voidf1sh:v1.0.3-dev
Add active growth indicator
2023-01-23 18:28:06 -05:00
45 changed files with 2827 additions and 331 deletions

BIN
.DS_Store vendored Normal file → Executable file

Binary file not shown.

0
.dockerignore Normal file → Executable file
View File

0
.eslintrc.json Normal file → Executable file
View File

View File

@ -1,10 +1,7 @@
name: Docker Image CI name: Silvanus-Dev Dockerization
on: on:
push: workflow_dispatch:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
env: env:
DHUB_UNAME: ${{ secrets.DHUB_UNAME }} DHUB_UNAME: ${{ secrets.DHUB_UNAME }}
@ -18,9 +15,9 @@ jobs:
steps: steps:
- uses: actions/checkout@v3 - uses: actions/checkout@v3
- name: Build the Docker image - name: Build the Docker image v0idf1sh/silvanus-dev
run: docker build . --file Dockerfile --tag v0idf1sh/silvanus run: docker build . --file Dockerfile --tag v0idf1sh/silvanus-dev
- name: Log into Docker Hub - name: Log into Docker Hub
run: docker login -u $DHUB_UNAME -p $DHUB_PWORD run: docker login -u $DHUB_UNAME -p $DHUB_PWORD
- name: Push image to Docker Hub - name: Push image to Docker Hub v0idf1sh/silvanus-dev
run: docker push v0idf1sh/silvanus run: docker push v0idf1sh/silvanus-dev

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

@ -0,0 +1,35 @@
name: Silvanus Production Dockerization
on:
pull_request:
branches:
- main
env:
DHUB_UNAME: ${{ secrets.DHUB_UNAME }}
DHUB_PWORD: ${{ secrets.DHUB_PWORD }}
jobs:
build:
runs-on: self-hosted
steps:
- name: Pull latest from Git
run: |
pwd
whoami
cd /root/silvanus
git pull
git checkout $GITHUB_HEAD_REF
- name: Build the Docker image
run: |
cd /root/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 /root/silvanus
docker push v0idf1sh/silvanus

7
.gitignore vendored Normal file → Executable file
View File

@ -2,9 +2,11 @@
.vscode .vscode
package-lock.json package-lock.json
.VSCodeCounter/ .VSCodeCounter/
env.dev .env*
env.prod
.DS_Store .DS_Store
data/guildInfo.json
data/rawstring.txt
modules/input.txt
# Custom folders # Custom folders
# gifs/* # gifs/*
@ -116,3 +118,4 @@ dist
# TernJS port file # TernJS port file
.tern-port .tern-port
data/guildInfo.json

2
Dockerfile Normal file → Executable file
View File

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

53
README.md Normal file → Executable file
View File

@ -1,47 +1,16 @@
# Grow A Tree Analyzer # Silvanus
This bot works with Grow A Tree Bot by Limbo Labs. This project is not affiliated with Limbo Labs in any way. 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!
This bot allows easy comparison between a server's tree and other trees displayed on the leaderboard. Silvanus is not affiliated with Grow A Tree or Limbo Labs.
## Usage ## Add Silvanus to your server
Add the bot to your server and make sure it has the proper permissions (`Send Messages` and `Send Messages in Threads` if applicable), then run `/setup` in the channel(s) that contain your server's tree and leaderboard messages. [Invite Silvanus to your Discord Server](https://discord.com/api/oauth2/authorize?client_id=521624335119810561&permissions=275146475520&scope=applications.commands%20bot)
## Commands ## Silvanus Support Server
[Join Discord Server](https://discord.gg/g5JRGn7PxU)
* `/setup` - Attempts automatic detection of your server's tree and leaderboard messages. ## Silvanus Support Wiki
* `/setupinfo` - Displays your server's current configuration. Find the most up-to-date guides and information about Silvanus at the [Silvanus Support Wiki](https://silvanus.vfsh.dev/).
* `/reset` - Resets your server's configuration, run `/setup` again if needed. [Silvanus Setup Guide](https://silvanus.vfsh.dev/en/setup)
Please find the most up-to-date guides and information at the Silvanus Support Discord Server!
## Database Structure
### Table: guildinfo
```
+-----------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+-------------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| guild_id | varchar(50) | NO | | NULL | |
| tree_message_id | varchar(50) | NO | | NULL | |
| tree_channel_id | varchar(50) | NO | | NULL | |
| rank_message_id | varchar(50) | NO | | NULL | |
| rank_channel_id | varchar(50) | NO | | NULL | |
| tree_height | varchar(10) | NO | | NULL | |
+-----------------+-------------+------+-----+---------+----------------+
```
### Table: treeinfo
```
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| treename | varchar(100) | NO | | NULL | |
| treerank | int(10) | NO | | NULL | |
| timestamp | varchar(50) | NO | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
```
## Changes to Implement
* Move around some of the functions.
* Migrate storage to SQLite.

31
TODO.md Executable file
View File

@ -0,0 +1,31 @@
## Variable Structures
guildInfo = {
guildId: "",
treeName: "name",
treeHeight: 0,
treeMessageId: "",
treeChannelId: "",
leaderboardMessageId: "",
leaderboardChannelId: "",
reminderMessage: "",
reminderChannelId: "",
remindedStatus: 0,
reminderOptIn: 0,
}
## New Table Planning
Table: `silvanus`.timers
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"}

10
data/config.json Normal file → Executable file
View File

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

View File

@ -1 +0,0 @@
{"269250657809072139":{"treeMessageId":"1042987280954032158","treeChannelId":"1042987243670872154","rankMessageId":"1065390277767987210","rankChannelId":"1042987923928256553","rankings":[{"rank":"111","name":"Taboo Tree","height":"3030.0"},{"rank":"112","name":"booster tree","height":"3029.0"},{"rank":"113","name":"Pod Birch","height":"3017.0"},{"rank":"114","name":"Wise Mystical Tree","height":"3013.0"},{"rank":"115","name":"Shimmer Doge DAO Tree","height":"2978.9"},{"rank":"116","name":"Simon","height":"2969.1"},{"rank":"117","name":"Cloud Tree","height":"2959.6"},{"rank":"118","name":"The Monke Tree","height":"2947.3"},{"rank":"119","name":"Woody","height":"2925.6"},{"rank":"120","name":"Azure Woodku","height":"2908.0"}],"treeHeight":"179.1"},"803049831839956992":{"treeMessageId":"1052343193980645376","treeChannelId":"1022324601864331335","rankMessageId":"1065121016604524544","rankChannelId":"1022324665374474341","rankings":[{"rank":"1 ","name":"WLR's Ultimate Sudowoodo","height":14203.5},{"rank":"2 ","name":"Our Bonfire Tree","height":13572.9},{"rank":"3 ","name":"The Gremlin Tree","height":12968},{"rank":"4 ","name":"World Tree","height":10600.6},{"rank":"5 ","name":"Emory's Baby","height":10163.9},{"rank":"6 ","name":"Charles the Tree","height":9920},{"rank":"7 ","name":"SMMO-Babel","height":9397},{"rank":"8 ","name":"Spaghetti","height":9341},{"rank":"9 ","name":"the fortnite tree","height":8883},{"rank":"10","name":"TreeVana","height":8002.6}],"treeHeight":261},"1006579138909458513":{"treeMessageId":"1065399196682821713","treeChannelId":"1065398553528250369","rankMessageId":"1065399316979662928","rankChannelId":"1065398553528250369","rankings":[{"rank":"1 ","name":"WLR's Ultimate Sudowoodo","height":"14232.9"},{"rank":"2 ","name":"Our Bonfire Tree","height":"13612.1"},{"rank":"3 ","name":"The Gremlin Tree","height":"12994.8"},{"rank":"4 ","name":"World Tree","height":"10623.0"},{"rank":"5 ","name":"Emory's Baby","height":"10187.8"},{"rank":"6 ","name":"Charles the Tree","height":"9951.0"},{"rank":"7 ","name":"SMMO-Babel","height":"9438.0"},{"rank":"8 ","name":"Spaghetti","height":"9365.0"},{"rank":"9 ","name":"the fortnite tree","height":"8895.0"},{"rank":"10","name":"TreeVana","height":"8019.2"}],"treeHeight":"7941.9"},"760701839427108874":{"treeMessageId":"1065405516400042114","treeChannelId":"1050272057839067178","rankMessageId":"1051889574365904907","rankChannelId":"1050272057839067178","rankings":[{"rank":"251","name":"Bom","height":"1621.0"},{"rank":"252","name":"Tree Of Happiness","height":"1621.0"},{"rank":"253","name":"Treehouse","height":"1604.0"},{"rank":"254","name":"Viktoria II","height":"1595.0"},{"rank":"255","name":"tree of virginity","height":"1588.0"},{"rank":"256","name":"nick's pride","height":"1588.0"},{"rank":"257","name":"Vitraya Ramunong","height":"1583.0"},{"rank":"258","name":"oven tree","height":"1538.7"},{"rank":"259","name":"Tr3e","height":"1527.1"},{"rank":"260","name":"Dicecraft","height":"1523.0"}],"treeHeight":"1527.1"},"868542949737246730":{"treeMessageId":"1065417587502092328","treeChannelId":"1065417555445043300","rankMessageId":"1065417630581801100","rankChannelId":"1065417587502092328","rankings":[{"rank":"1 ","name":"WLR's Ultimate Sudowoodo","height":"14233.4"},{"rank":"2 ","name":"Our Bonfire Tree","height":"13612.7"},{"rank":"3 ","name":"The Gremlin Tree","height":"12995.3"},{"rank":"4 ","name":"World Tree","height":"10623.8"},{"rank":"5 ","name":"Emory's Baby","height":"10188.1"},{"rank":"6 ","name":"Charles the Tree","height":"9951.0"},{"rank":"7 ","name":"SMMO-Babel","height":"9438.4"},{"rank":"8 ","name":"Spaghetti","height":"9365.5"},{"rank":"9 ","name":"the fortnite tree","height":"8895.0"},{"rank":"10","name":"TreeVana","height":"8020.0"}],"treeHeight":"6.0"}}

80
data/strings.json Normal file → Executable file
View File

@ -1,22 +1,88 @@
{ {
"activity": {
"name": "trees grow"
},
"help": { "help": {
"info": "This bot will analyze your tree (from the Grow A Tree Bot by Limbo Labs) and compare its growth to other trees displayed on the leaderboard.\n\nThis bot assumes that there is a single </tree:972648557796524032> message and a single </top trees:1051840665362894950> message that everyone uses. If everyone creates their own </tree:972648557796524032> and </top trees:1051840665362894950>, the reference messages will have to be updated every time, or old data will be displayed.", "title": "Silvanus Help",
"setup": "To begin analyzing your Tree, first you must set up the reference messages.\n\n1. Run </setup:1065407649363005561> in the channel(s) that contain your server's tree and leaderboard messages.\n2. Now simply run </compare:1065346941166297128> where you want your analysis to be visible.", "aboutTitle": "About Silvanus",
"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." "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.",
"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": {
"compare": "</compare:1065346941166297128>",
"setup": "</setup:1065407649363005561>",
"watertime": "</watertime:1066970330029113444>",
"setupinfo": "</setupinfo:1065413032374706196>",
"reset": "</reset:1065412317052944476>",
"help": "</help:1065346941166297129>"
}, },
"embeds": { "embeds": {
"footer": "Silvanus is not affiliated with Grow A Tree or Limbo Labs", "footer": "Silvanus is not affiliated with Grow A Tree or Limbo Labs",
"color": "0x55FF55" "color": 5635925,
"errorTitle": "Oops!",
"errorPrefix": "There seems to have been a problem.",
"waterColor": 5592575,
"fruitColor": 13391189,
"waterTitle": "Water Notification",
"fruitTitle": "Fruit Notification",
"roleMenuTitle": "Role Menu",
"treeRoleMenu": [
"Use the buttons below to give yourself roles.\n\n",
"``💧`` - ",
": Get notifications when the tree is ready to be watered.",
"\n``🍎`` - ",
": Get notifications when fruit is falling from the tree."
],
"roleMenuFooter": "Tip: Tap the button again to remove the role."
}, },
"emoji": { "emoji": {
"joint": "<:joint:862082955902976000>", "joint": "<:joint:862082955902976000>",
"next": "⏭️", "next": "⏭️",
"previous": "⏮️", "previous": "⏮️",
"confirm": "☑️", "confirm": "☑️",
"cancel": "❌" "cancel": "❌",
"water": "💧",
"fruit": "🍎"
}, },
"urls": { "urls": {
"avatar": "https://cdn.discordapp.com/avatars/513184762073055252/12227aa23a06d5178853e59b72c7487b.webp?size=128" "avatar": "https://cdn.discordapp.com/avatars/513184762073055252/12227aa23a06d5178853e59b72c7487b.webp?size=128",
"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!"
},
"status": {
"treeAndLeaderboard": "Tree and leaderboard messages were both found, setup is complete. Run </setupinfo:1065413032374706196> to verify. Run </compare:1065346941166297128> to get started!",
"missingMessage": "I was unable to find both a ``/tree`` and ``/top trees`` message in this channel. Please run </setup:1065407649363005561> to set up separate ``/tree`` and ``/top trees`` channels.",
"noneFound": "Unable to find a tree or leaderboard in the last 20 messages in this channel, make sure you've run ``/tree`` and/or ``/top trees`` recently.",
"missingLeaderboardMessage": "There was a problem finding the Tallest Trees message. Please make sure the ``/tree`` and ``/top trees`` messages are in this channel, or run </setup:1065407649363005561> to set the ``/tree`` and ``/top trees`` channels.",
"missingLeaderboardChannel": "There was a problem finding the Tallest Trees channel, was it deleted? Please make sure the ``/tree`` and ``/top trees`` messages are in this channel, or run </setup:1065407649363005561> to set the ``/tree`` and ``/top trees`` channels.",
"missingTreeMessage": "There was a problem finding the Tree message. Please make sure the ``/tree`` and ``/top trees`` messages are this channel, or run </setup:1065407649363005561> to set the ``/tree`` and ``/top trees`` channels.",
"missingTreeChannel": "There was a problem finding the Tree channel, was it deleted? Please make sure the ``/tree`` and ``/top trees`` messages are in this channel, or run </setup:1065407649363005561> to set the ``/tree`` and ``/top trees`` channels.",
"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."
},
"notifications": {
"water": "is ready to be watered again!",
"fruit": "Fruit is appearing!"
},
"ids": {
"growATree": "972637072991068220"
}, },
"temp": {} "temp": {}
} }

18
dot-commands/_template Normal file
View File

@ -0,0 +1,18 @@
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."));
}
}
}
}

27
dot-commands/leave.js Normal file
View File

@ -0,0 +1,27 @@
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));
}
}
}
}

23
dot-commands/message.js Normal file
View File

@ -0,0 +1,23 @@
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

@ -0,0 +1,36 @@
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."));
}
}
}
}

18
dot-commands/ping.js Normal file
View File

@ -0,0 +1,18 @@
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."));
}
}
}
}

22
dot-commands/servers.js Normal file
View File

@ -0,0 +1,22 @@
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."));
}
}
}
}

24
dot-commands/setupview.js Normal file
View File

@ -0,0 +1,24 @@
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."));
}
}
}
}

183
main.js Normal file → Executable file
View File

@ -4,10 +4,12 @@
const dotenv = require('dotenv'); const dotenv = require('dotenv');
dotenv.config(); dotenv.config();
const token = process.env.TOKEN; const token = process.env.TOKEN;
const statusChannelId = process.env.statusChannelId; const statusChannelId = process.env.STATUSCHANNELID;
const heartbeatUrl = process.env.HEARTBEAT_URL;
const sendHeartbeat = typeof heartbeatUrl === 'string';
// Discord.JS // Discord.JS
const { Client, GatewayIntentBits, Partials } = require('discord.js'); const { Client, GatewayIntentBits, Partials, ActivityType } = require('discord.js');
const client = new Client({ const client = new Client({
intents: [ intents: [
GatewayIntentBits.Guilds, GatewayIntentBits.Guilds,
@ -24,35 +26,176 @@ const client = new Client({
// Various imports // Various imports
const fn = require('./modules/functions.js'); const fn = require('./modules/functions.js');
const strings = require('./data/strings.json'); const strings = require('./data/strings.json');
const isDev = process.env.isDev; const dbfn = require('./modules/dbfn.js');
const { GuildInfo } = require('./modules/CustomClasses.js');
const isDev = process.env.DEBUG === "true";
let statusChannel;
client.once('ready', () => { client.once('ready', async () => {
fn.collections.slashCommands(client); 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!'); console.log('Ready!');
client.channels.fetch(statusChannelId).then(channel => { client.user.setActivity({ name: `${serverCount} trees grow.`, type: ActivityType.Watching });
channel.send(`${new Date().toISOString()} -- \nStartup Sequence Complete`); statusChannel = await client.channels.fetch(statusChannelId);
}); 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.");
}
}); });
// slash-commands // slash-commands
client.on('interactionCreate', async interaction => { client.on('interactionCreate', async interaction => {
if (interaction.isCommand()) { try {
// if (isDev) { if (interaction.isCommand()) {
// console.log(interaction); if (isDev) {
// } // console.log(interaction);
const { commandName } = interaction; }
const { commandName } = interaction;
if (client.slashCommands.has(commandName)) {
client.slashCommands.get(commandName).execute(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.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);
} else { } else {
interaction.reply('Sorry, I don\'t have access to that command.'); interaction.channel.send("Oops! An error occurred... Sorry about that, please contact my owner @vfsh if this keeps happening.");
console.error('Slash command attempted to run but not found: ' + commandName); console.error(err);
} }
} }
});
if (interaction.isButton() && interaction.component.customId == 'refresh') { client.on('messageUpdate', async (oldMessage, message) => {
fn.refresh(interaction); await fn.messages.updateHandler(message).catch(async e => {
switch (e) {
case strings.error.noCompareMessage:
await message.channel.send(strings.error.noCompareMessage);
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);
} }
}); });
async function checkRateLimits(hi) {
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 checkRateLimits();
})
}
process.on('unhandledRejection', error => {
console.error('Unhandled promise rejection (pls dont break up with me):', error);
});
client.login(token); client.login(token);

244
modules/CustomClasses.js Executable file
View File

@ -0,0 +1,244 @@
const mysql = require('mysql');
const db = mysql.createConnection({
host: process.env.DBHOST,
user: process.env.DBUSER,
password: process.env.DBPASS,
database: process.env.DBNAME,
port: process.env.DBPORT
});
module.exports = {
GuildInfo: class {
constructor() {
this.guildId = "";
this.ownerId = ""; // TODO Is ownerId fully implemented?
this.treeName = "";
this.treeHeight = 0;
this.treeMessageId = "";
this.treeChannelId = "";
this.leaderboardMessageId = "";
this.leaderboardChannelId = "";
this.waterMessage = "";
this.waterRoleId = "";
this.fruitMessage = "";
this.fruitRoleId = "";
this.reminderChannelId = "";
this.watchChannelId = "";
this.notificationsEnabled = false;
this.compareChannelId = "";
this.compareMessageId = "";
}
setIds(guildId, ownerId) {
this.guildId = guildId;
this.ownerId = ownerId === undefined ? this.ownerId : ownerId
return this;
}
setName(name) {
this.treeName = name;
return this;
}
setHeight(height) {
this.treeHeight = height;
return this;
}
setTreeMessage(messageId, channelId) {
this.treeMessageId = messageId ? messageId : this.treeMessageId;
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;
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;
return this;
}
setRoles(waterRoleId, fruitRoleId) {
this.waterRoleId = waterRoleId;
if (fruitRoleId) this.fruitRoleId = fruitRoleId;
return this;
}
queryBuilder(query) {
let queryParts = [];
switch (query) {
case "setAll":
queryParts = [
`INSERT INTO guild_info `,
`(guild_id, `,
`tree_name, `,
`tree_height, `,
`tree_message_id, `,
`tree_channel_id, `,
`leaderboard_message_id, `,
`leaderboard_channel_id, `,
`water_message, `,
`fruit_message, `,
`reminder_channel_id, `,
`watch_channel_id) `,
`VALUES (${db.escape(this.guildId)}, `,
`${db.escape(this.treeName)}, `,
`${db.escape(this.treeHeight)}, `,
`${db.escape(this.treeMessageId)}, `,
`${db.escape(this.treeChannelId)}, `,
`${db.escape(this.leaderboardMessageId)}, `,
`${db.escape(this.leaderboardChannelId)}, `,
`${db.escape(this.waterMessage)}, `,
`${db.escape(this.fruitMessage)}, `,
`${db.escape(this.reminderChannelId)}, `,
`${db.escape(this.watchChannelId)}) `,
`ON DUPLICATE KEY UPDATE tree_name = ${db.escape(this.treeName)}, `,
`tree_height = ${db.escape(this.treeHeight)}, `,
`tree_message_id = ${db.escape(this.treeMessageId)}, `,
`tree_channel_id = ${db.escape(this.treeChannelId)}, `,
`leaderboard_message_id = ${db.escape(this.leaderboardMessageId)}, `,
`leaderboard_channel_id = ${db.escape(this.leaderboardChannelId)}, `,
`water_message = ${db.escape(this.waterMessage)}, `,
`fruit_message = ${db.escape(this.fruitMessage)}, `,
`reminder_channel_id = ${db.escape(this.reminderChannelId)}, `,
`watch_channel_id = ${db.escape(this.watchChannelId)})`
];
return queryParts.join('');
break;
case "setReminders":
queryParts = [
`INSERT INTO guild_info (guild_id, water_message, fruit_message, reminder_channel_id, watch_channel_id, notifications_enabled) VALUES (`,
`${db.escape(this.guildId)},`,
`${db.escape(this.waterMessage)},`,
`${db.escape(this.fruitMessage)},`,
`${db.escape(this.reminderChannelId)},`,
`${db.escape(this.watchChannelId)},`,
`${db.escape(this.notificationsEnabled)}`,
`) ON DUPLICATE KEY UPDATE water_message = ${db.escape(this.waterMessage)}, `,
`fruit_message = ${db.escape(this.fruitMessage)}, `,
`reminder_channel_id = ${db.escape(this.reminderChannelId)}, `,
`watch_channel_id = ${db.escape(this.watchChannelId)},`,
`notifications_enabled = ${db.escape(this.notificationsEnabled)}`
];
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)}`
];
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)}`
];
return queryParts.join('');
break;
case "setRoles":
if (this.fruitRoleId != "") {
queryParts = [
`INSERT INTO guild_info (`,
`guild_id, water_role_id, fruit_role_id`,
`) VALUES (`,
`${db.escape(this.guildId)}, ${db.escape(this.waterRoleId)}, ${db.escape(this.fruitRoleId)}`,
`) ON DUPLICATE KEY UPDATE water_role_id = ${db.escape(this.waterRoleId)}, `,
`fruit_role_id = ${db.escape(this.fruitRoleId)}`
];
} else {
queryParts = [
`UPDATE guild_info SET water_role_id = ${db.escape(this.waterRoleId)} `,
`WHERE guild_id = ${db.escape(this.guildId)}`
];
}
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:
break;
}
}
generateSetupInfo() {
let setupInfoParts = [
`Here is your server's configuration:`,
`Tree Name: ${this.treeName}`,
`Tree Height: ${this.treeHeight}`,
`Tree Channel: <#${this.treeChannelId}>`,
`[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}`,
`Fruit Message: ${this.fruitMessage}`,
`Water Role: <@&${this.waterRoleId}>`,
`Fruit Role: <@&${this.fruitRoleId}>`
]
return setupInfoParts.join('\n');
}
}
}

0
modules/_clear-commands.js Normal file → Executable file
View File

0
modules/_deploy-commands.js Normal file → Executable file
View File

28
modules/_deploy-global.js Normal file → Executable file
View File

@ -4,7 +4,7 @@ dotenv.config();
const { REST } = require('@discordjs/rest'); const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9'); const { Routes } = require('discord-api-types/v9');
const clientId = process.env.clientId; const clientId = process.env.BOTID;
const token = process.env.TOKEN; const token = process.env.TOKEN;
const fs = require('fs'); const fs = require('fs');
@ -18,13 +18,28 @@ for (const file of commandFiles) {
} }
} }
console.log(commands); console.log(`Token: ${token} Client ID: ${clientId}`);
const rest = new REST({ version: '9' }).setToken(token); const rest = new REST({ version: '9' }).setToken(token);
(async () => { async function deleteCommands() {
try { try {
console.log('Started refreshing application (/) commands.'); console.log('Started deleting application (/) commands.');
await rest.put(
Routes.applicationCommands(clientId),
{ body: "" },
);
console.log('Successfully deleted application (/) commands.');
} catch (error) {
console.error(error);
}
}
async function uploadCommands() {
try {
console.log('Started reloading application (/) commands.');
await rest.put( await rest.put(
Routes.applicationCommands(clientId), Routes.applicationCommands(clientId),
@ -36,4 +51,9 @@ const rest = new REST({ version: '9' }).setToken(token);
} catch (error) { } catch (error) {
console.error(error); console.error(error);
} }
}
(async () => {
// await deleteCommands();
await uploadCommands();
})(); })();

29
modules/_prepareStrings.js Executable file
View File

@ -0,0 +1,29 @@
const commands = [
{raw: "`/compare`", clickable: "</compare:1077058896469966889>"},
{raw: "`/relay set`", clickable: "</relay set:1077322799032578152>"},
{raw: "`/relay update`", clickable: "</relay update:1077322799032578152>"},
{raw: "`/relay disable`", clickable: "</relay disable:1077322799032578152>"},
{raw: "`/rolemenu`", clickable: "</rolemenu:1077058896469966892>"},
{raw: "`/watertime`", clickable: "</watertime:1077058896469966895>"},
{raw: "`/timetoheight`", clickable: "</timetoheight:1077058896469966894>"},
{raw: "`/setup compare`", clickable: "</setup compare:1077058896469966893>"},
{raw: "`/setup view`", clickable: "</setup view:1077058896469966893>"},
{raw: "`/setup reset`", clickable: "</setup reset:1077058896469966893>"},
{raw: "`/help`", clickable: "</help:1077058896469966890>"},
{raw: "`/tree`", clickable: "</tree:972648557796524032>"},
{raw: "`/top trees`", clickable: "</top trees:1051840665362894950>"},
{raw: "`/commands`", clickable: "</commands:1077058896469966888>"}
];
const fs = require('fs');
const replaceAll = require('string.prototype.replaceall');
const path = "./modules/input.txt";
const string = fs.readFileSync(path).toString();
let newString = replaceAll(string, '\* ', '');
newString = replaceAll(newString, '\n', '\\n');
newString = replaceAll(newString, '\t', ' - ');
commands.forEach(command => {
newString = replaceAll(newString, command.raw, command.clickable);
});
newString = replaceAll(newString, '`', '``');
fs.writeFileSync(path, newString);
return "Done";

302
modules/dbfn.js Executable file
View File

@ -0,0 +1,302 @@
const dotenv = require('dotenv');
dotenv.config();
const debugMode = process.env.DEBUG || true;
const mysql = require('mysql');
const { GuildInfo } = require('./CustomClasses.js');
/* Table Structures
guild_info
+------------------------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+-------------+------+-----+---------+----------------+
| guild_id | varchar(50) | NO | PRI | NULL | auto_increment |
| tree_name | varchar(100)| NO | | | |
| tree_height | varchar(10) | NO | | 0 | |
| tree_message_id | varchar(50) | NO | | | |
| tree_channel_id | varchar(50) | NO | | | |
| leaderboard_message_id | varchar(50) | NO | | | |
| leaderboard_channel_id | varchar(50) | NO | | | |
+------------------------+-------------+------+-----+---------+----------------+
*/
/*
leaderboard
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(10) | NO | PRI | NULL | auto_increment |
| guild_id | varchar(50) | NO | | | |
| tree_name | varchar(100) | NO | | | |
| tree_rank | int(10) | NO | | | |
| tree_height | int(10) | NO | | 1 | |
| has_pin | tinyint(1) | NO | | 0 | |
| timestamp | varchar(50) | NO | | | |
+-------------+--------------+------+-----+---------+----------------+
*/
module.exports = {
getGuildInfo(guildId) {
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}`;
});
// Get a server's tree information from the database
const selectGuildInfoQuery = `SELECT * FROM guild_info WHERE guild_id = ${db.escape(guildId)}`;
// TODO run this query and return a promise then structure the output into a GuildInfo object. resolve with { "status": , "data": guildInfo }
return new Promise((resolve, reject) => {
db.query(selectGuildInfoQuery, (err, res) => {
if (err) {
console.error(err);
reject("Error fetching guild information: " + err.message);
db.end();
return;
}
row = res[0];
const guildInfo = new GuildInfo()
.setIds(row.guild_id, row.owner_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);
db.end();
resolve(guildInfo);
});
});
},
getAllGuildInfos() {
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}`;
});
// Get a server's tree information from the database
const query = 'SELECT * FROM guild_info';
// TODO run this query and return a promise then structure the output into a GuildInfo object. resolve with { "status": , "data": guildInfo }
return new Promise((resolve, reject) => {
db.query(query, (err, res) => {
if (err) {
console.error(err);
reject("Error fetching all guild infos: " + err.message);
db.end();
return;
}
if (res.length == 0) {
reject("There are no servers yet!");
db.end();
return;
}
let guildInfos = [];
for (let i = 0; i < res.length; i++) {
let row = res[i];
guildInfos.push(new GuildInfo()
.setIds(row.guild_id, row.owner_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);
});
});
},
setGuildInfo(query) {
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}`;
});
return new Promise((resolve, reject) => {
db.query(query, (err, res) => {
if (err) {
console.error(err + "\n" + query);
reject("Error setting the guild info: " + err.message);
db.end();
return;
}
db.end();
// console.log("Updated the database");
resolve();
});
});
},
setTreeInfo(guildInfo) {
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": null })
// guildInfo = { "guildId": "123", "treeName": "name", "treeHeight": 123, "treeMessageId": "123", "treeChannelId": "123", "leaderboardMessageId": "123", "leaderboardChannelId": "123"}
// Set a server's tree information in the database)
const insertGuildInfoQuery = `INSERT INTO guild_info (guild_id, tree_name, tree_height, tree_message_id, tree_channel_id) VALUES (${db.escape(guildInfo.guildId)}, ${db.escape(guildInfo.treeName)}, ${db.escape(guildInfo.treeHeight)},${db.escape(guildInfo.treeMessageId)}, ${db.escape(guildInfo.treeChannelId)}) ON DUPLICATE KEY UPDATE tree_name = ${db.escape(guildInfo.treeName)},tree_height = ${db.escape(guildInfo.treeHeight)},tree_message_id = ${db.escape(guildInfo.treeMessageId)},tree_channel_id = ${db.escape(guildInfo.treeChannelId)}`;
// TODO run this query and return a promise, then resolve with { "status": , "data": null }
return new Promise((resolve, reject) => {
db.query(insertGuildInfoQuery, (err, res) => {
if (err) {
console.error(err);
db.end();
reject("Error setting the guild info: " + err.message);
return;
}
db.end();
console.log("Updated the database");
resolve({ "status": "Successfully set the guild information", "data": null });
});
});
},
setLeaderboardInfo(guildInfo) {
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": null })
// guildInfo = { "guildId": "123", "treeName": "name", "treeHeight": 123, "treeMessageId": "123", "treeChannelId": "123", "leaderboardMessageId": "123", "leaderboardChannelId": "123"}
// Set a server's tree information in the database
const insertGuildInfoQuery = `INSERT INTO guild_info (guild_id, leaderboard_message_id, leaderboard_channel_id) VALUES (${db.escape(guildInfo.guildId)}, ${db.escape(guildInfo.leaderboardMessageId)}, ${db.escape(guildInfo.leaderboardChannelId)}) ON DUPLICATE KEY UPDATE leaderboard_message_id = ${db.escape(guildInfo.leaderboardMessageId)},leaderboard_channel_id = ${db.escape(guildInfo.leaderboardChannelId)}`;
// TODO run this query and return a promise, then resolve with { "status": , "data": null }
return new Promise((resolve, reject) => {
db.query(insertGuildInfoQuery, (err, res) => {
if (err) {
console.error(err);
db.end();
reject("Error setting the guild info: " + err.message);
return;
}
db.end();
resolve({ "status": "Successfully set the guild information", "data": null });
});
});
},
deleteGuildInfo(guildId) {
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": null })
// guildInfo = { "guildId": "123", "treeName": "name", "treeHeight": 123, "treeMessageId": "123", "treeChannelId": "123", "leaderboardMessageId": "123", "leaderboardChannelId": "123"}
// Set a server's tree information in the database
const deleteGuildInfoQuery = `DELETE FROM guild_info WHERE guild_id = ${db.escape(guildId)}`;
// TODO run this query and return a promise, then resolve with { "status": , "data": null }
return new Promise((resolve, reject) => {
db.query(deleteGuildInfoQuery, (err, res) => {
if (err) {
console.error(err);
db.end();
reject("Error deleting the guild info: " + err.message);
return;
}
db.end();
resolve({ "status": "Successfully deleted the guild information", "data": null });
});
});
},
getLeaderboard(guildId) {
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 selectLeaderboardQuery = `SELECT id, tree_name, tree_rank, tree_height, has_pin FROM leaderboard WHERE guild_id = ${db.escape(guildId)} ORDER BY id DESC LIMIT 10`;
// TODO run the query and return a promise then process the results. resolve with { "status": , "data": leaderboard }
return new Promise((resolve, reject) => {
db.query(selectLeaderboardQuery, (err, res) => {
if (err) {
console.error(err);
db.end();
reject("Error fetching the most recent leaderboard: " + err.message);
return;
}
let leaderboard = [];
res.forEach(row => {
leaderboard.push({
"treeName": row.tree_name,
"treeRank": row.tree_rank,
"treeHeight": row.tree_height,
"hasPin": row.has_pin
});
});
db.end();
resolve({ "status": "Successfully fetched leaderboard.", "data": leaderboard });
});
});
},
uploadLeaderboard(leaderboard) {
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": res })
// leaderboard = { "guildId": 1234, "entries": [ { "treeHeight": 12, "treeRank": 34, "treeName": "name", "hasPin": false }, {...}, {...} ] }
const insertLeaderboardQuery = "INSERT INTO `leaderboard` (guild_id, tree_name, tree_rank, tree_height, has_pin) VALUES ?";
const leaderboardValues = [];
leaderboard.entries.forEach(ranking => {
leaderboardValues.push([leaderboard.guildId, ranking.treeName, ranking.treeRank, ranking.treeHeight, ranking.hasPin]);
});
return new Promise((resolve, reject) => {
db.query(insertLeaderboardQuery, [leaderboardValues], (err, res) => {
if (err) {
reject("Error uploading the leaderboard: " + err.message);
db.end();
console.error(err);
return;
}
db.end();
resolve({ "status": "Successfully uploaded the leaderboard", "data": res });
});
});
}
};

1164
modules/functions.js Normal file → Executable file

File diff suppressed because it is too large Load Diff

21
modules/testing.js Executable file
View File

@ -0,0 +1,21 @@
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);

98
modules/utils.js Normal file
View File

@ -0,0 +1,98 @@
/* 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);
}
}

20
package.json Normal file → Executable file
View File

@ -1,23 +1,27 @@
{ {
"name": "treeanalyzer", "name": "silvanus",
"version": "1.0.3", "version": "1.2.9",
"description": "Analyze Grow A Tree", "description": "Grow A Tree Companion Bot",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "test": "echo \"Error: no test specified\" && exit 1"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+https://github.com/voidf1sh/treeanalyzer.git" "url": "git+https://github.com/voidf1sh/silvanus.git"
}, },
"author": "Skylar Grant", "author": "Skylar Grant",
"license": "ISC", "license": "ISC",
"bugs": { "bugs": {
"url": "https://github.com/voidf1sh/treeanalyzer/issues" "url": "https://github.com/voidf1sh/silvanus/issues"
}, },
"homepage": "https://github.com/voidf1sh/treeanalyzer#readme", "homepage": "https://github.com/voidf1sh/silvanus#readme",
"dependencies": { "dependencies": {
"discord.js": "^14.7.1", "axios": "^1.4.0",
"dotenv": "^16.0.3" "discord.js": "^14.11.0",
"dotenv": "^16.0.3",
"mysql": "^2.18.1",
"string-replace-all": "^2.0.0",
"string.prototype.replaceall": "^1.0.7"
} }
} }

39
privacy Normal file
View File

@ -0,0 +1,39 @@
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]

0
slash-commands/.DS_Store vendored Normal file → Executable file
View File

20
slash-commands/about.js Executable file
View File

@ -0,0 +1,20 @@
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);
},
};

20
slash-commands/commands.js Executable file
View File

@ -0,0 +1,20 @@
const { SlashCommandBuilder, messageLink } = require('discord.js');
const fn = require('../modules/functions.js');
const strings = require('../data/strings.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('commands')
.setDescription('Get a list of all my commands')
.addStringOption(o =>
o.setName('private')
.setDescription('Should the response be sent privately?')
.setRequired(true)
.addChoices(
{ name: "True", value: "true" },
{ name: "False", value: "false" })),
execute(interaction) {
const helpEmbed = fn.builders.helpEmbed(`**All Commands**\n${strings.help.allCommands}`, interaction.options.getString('private'));
interaction.reply(helpEmbed);
},
};

47
slash-commands/compare.js Normal file → Executable file
View File

@ -1,12 +1,53 @@
const { SlashCommandBuilder } = require('discord.js'); const { SlashCommandBuilder, Guild } = require('discord.js');
const dbfn = require('../modules/dbfn.js');
const fn = require('../modules/functions.js'); const fn = require('../modules/functions.js');
const strings = require('../data/strings.json');
const { GuildInfo } = require('../modules/CustomClasses.js');
module.exports = { module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('compare') .setName('compare')
.setDescription('See how your tree compares to other trees!'), .setDescription('See how your tree compares to other trees!'),
async execute(interaction) { async execute(interaction) {
const embed = fn.builders.comparisonEmbed(fn.rankings.compare(interaction), fn.builders.refreshAction()); try {
interaction.reply(embed); await interaction.deferReply();
// Get the guildInfo from the database
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 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));
} 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);
}
} catch (err) {
interaction.editReply(fn.builders.errorEmbed(err)).catch(err => {
console.error(err);
});
console.error(err);
}
}, },
}; };

45
slash-commands/help.js Normal file → Executable file
View File

@ -6,44 +6,15 @@ module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('help') .setName('help')
.setDescription('Get help using the bot') .setDescription('Get help using the bot')
.addSubcommand(subcommand => .addStringOption(o =>
subcommand o.setName('private')
.setName('info') .setDescription('Should the response be sent privately?')
.setDescription('Learn about the bot') .setRequired(true)
.addStringOption(o => .addChoices(
o.setName('private') { name: "True", value: "true" },
.setDescription('Should the response be sent privately?') { name: "False", value: "false" })),
.setRequired(true)
.addChoices(
{ name: "True", value: "true" },
{ name: "False", value: "false" }
)))
.addSubcommand(subcommand =>
subcommand
.setName('setup')
.setDescription('Learn how to setup 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" }
)))
.addSubcommand(subcommand =>
subcommand
.setName('permissions')
.setDescription('Learn about the bot\'s permissions')
.addStringOption(o =>
o.setName('private')
.setDescription('Should the response be sent privately?')
.setRequired(true)
.addChoices(
{ name: "True", value: "true" },
{ name: "False", value: "false" }
))),
execute(interaction) { execute(interaction) {
const helpEmbed = fn.builders.helpEmbed(strings.help[interaction.options.getSubcommand()], interaction.options.getString('private')); const helpEmbed = fn.builders.helpEmbed(`${strings.help.info}\n\n**Setup**\n${strings.help.setup}\n\n**Support Server**\n${strings.urls.supportServer}`, interaction.options.getString('private'));
interaction.reply(helpEmbed); interaction.reply(helpEmbed);
}, },
}; };

30
slash-commands/permissions.js Executable file
View File

@ -0,0 +1,30 @@
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);
}
};

205
slash-commands/relay.js Executable file
View File

@ -0,0 +1,205 @@
const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const { GuildInfo } = require('../modules/CustomClasses.js');
const dbfn = require('../modules/dbfn.js');
const fn = require('../modules/functions.js');
const strings = require('../data/strings.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('relay')
.setDescription('A notification relay for improved water and fruit notifications')
.addSubcommand(sc =>
sc.setName('set')
.setDescription('Set up the notification relay for the first time')
.addChannelOption(o =>
o.setName('watchchannel')
.setDescription('The channel Grow A Tree sends your notifications in')
.setRequired(true)
)
.addStringOption(o =>
o.setName('watermessage')
.setDescription('Message to send for water reminders')
.setRequired(true)
)
.addChannelOption(o =>
o.setName('pingchannel')
.setDescription('The channel to send the water reminder in')
.setRequired(true)
)
.addStringOption(o =>
o.setName('fruitmessage')
.setDescription("Message to send for fruit reminders")
.setRequired(false)
)
)
.addSubcommand(sc =>
sc.setName('update')
.setDescription('Update an already setup notification relay')
.addChannelOption(o =>
o.setName('watchchannel')
.setDescription('The channel Grow A Tree sends your notifications in')
.setRequired(false)
)
.addStringOption(o =>
o.setName('watermessage')
.setDescription('Message to send for water reminders')
.setRequired(false)
)
.addChannelOption(o =>
o.setName('pingchannel')
.setDescription('The channel to send the water reminder in')
.setRequired(false)
)
.addStringOption(o =>
o.setName('fruitmessage')
.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')
.setDescription('Disable the notification relay')
)
.setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles),
async execute(interaction) {
try {
await interaction.deferReply({ ephemeral: true });
const subcommand = interaction.options.getSubcommand();
// if (process.env.DEBUG) console.log(`${typeof subcommand}: ${subcommand}`);
switch (subcommand) {
// Set all components for the first time
case "set":
// If there is already a guildInfo object for this server
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
// Get options from the interaction
const watchChannel = interaction.options.getChannel('watchchannel');
const waterMessage = interaction.options.getString('watermessage');
// If the fruit message is set, use it, otherwise default to the water message.
const fruitMessage = interaction.options.getString('fruitmessage') ? interaction.options.getString('fruitmessage') : interaction.options.getString('watermessage');
const reminderChannel = interaction.options.getChannel('pingchannel');
// Set the reminder configuration in the GuildInfo object
guildInfo.setReminders(waterMessage, fruitMessage, reminderChannel.id, watchChannel.id, 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);
// Set up a collector on the watch channel
fn.collectors.create(interaction.client, guildInfo);
// Compose a reply
const reply = [
`I'll watch <#${watchChannel.id}> for Grow A Tree Notifications and relay them to <#${reminderChannel.id}>.`,
`Water Message: ${waterMessage}`,
`Fruit Message: ${fruitMessage}`
].join("\n");
// Send the reply
await interaction.editReply(fn.builders.embed(reply)).catch(e => console.error(e));
} else {
// Get options from the interaction
const watchChannel = interaction.options.getChannel('watchchannel');
const waterMessage = interaction.options.getString('watermessage');
// If the fruit message is set, use it. Otherwise default to the water message
const fruitMessage = interaction.options.getString('fruitmessage') ? interaction.options.getString('fruitmessage') : interaction.options.getString('watermessage');
const reminderChannel = interaction.options.getChannel('pingchannel');
// Create a new GuildInfo object
let guildInfo = new GuildInfo()
.setIds(interaction.guildId, interaction.guild.ownerId)
// Set the reminder configuration
.setReminders(waterMessage, fruitMessage, reminderChannel.id, watchChannel.id, 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
const reply = [
`I'll watch <#${watchChannel.id}> for Grow A Tree Notifications and relay them to <#${reminderChannel.id}>.`,
`Water Message: ${waterMessage}`,
`Fruit Message: ${fruitMessage}`
].join("\n");
// Send the reply
await interaction.editReply(reply).catch(e => console.error(e));
}
break;
case "update": // Update the relay configuration piecemeal
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
// Get all possible options from the interaction
const inWatchChannel = interaction.options.getChannel('watchchannel');
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);
// 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
const reply = [
`I'll watch <#${outWatchChannelId}> for Grow A Tree Notifications and relay them to <#${outReminderChannelId}>.`,
`Water Message: ${outWaterMessage}`,
`Fruit Message: ${outFruitMessage}`
].join("\n");
// Send the reply
await interaction.editReply(reply).catch(e => console.error(e));
} else {
await interaction.editReply(fn.builders.errorEmbed("There is no existing notification relay to update!")).catch(e => console.error(e));
}
break;
case 'disable': // Disable the relay
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
// Update the relay config with all undefined except for `enabled` which is false
guildInfo.setReminders(undefined, undefined, undefined, undefined, false);
// Update the guildInfos Collection
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
await interaction.editReply(fn.builders.embed(strings.status.optout)).catch(e => console.error(e));
} else {
await interaction.editReply(fn.builders.errorEmbed("A notification relay has not been set up yet!")).catch(e => console.error(e));
}
break;
default:
await interaction.editReply(fn.builders.errorEmbed("Invalid subcommand detected.")).catch(e => console.error(e));
break;
}
} catch (err) {
console.error("Error occurred while setting up a notification relay: " + err);
}
},
};

View File

@ -1,12 +0,0 @@
const { SlashCommandBuilder } = require('discord.js');
const fn = require('../modules/functions.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('reset')
.setDescription('Reset all message assignments in your server'),
execute(interaction) {
fn.reset(interaction.guildId);
interaction.reply(fn.builders.embed("Assignments Reset"));
},
};

18
slash-commands/rolemenu.js Executable file
View File

@ -0,0 +1,18 @@
const { SlashCommandBuilder } = require('discord.js');
const fn = require('../modules/functions.js');
const strings = require('../data/strings.json');
module.exports = {
data: new SlashCommandBuilder()
.setName('rolemenu')
.setDescription('Send a self-assignable role selection menu'),
async execute(interaction) {
await interaction.deferReply().catch(e => console.error(e));
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
await interaction.editReply(fn.builders.embeds.treeRoleMenu(guildInfo)).catch(e => console.error(e));
} else {
await interaction.editReply(fn.builders.errorEmbed(strings.status.noRoleMenu)).catch(e => console.error(e));
}
},
};

130
slash-commands/setup.js Normal file → Executable file
View File

@ -1,47 +1,99 @@
const { SlashCommandBuilder } = require('discord.js'); const { SlashCommandBuilder, PermissionFlagsBits } = require('discord.js');
const fn = require('../modules/functions.js'); const fn = require('../modules/functions.js');
const guildInfo = require('../data/guildInfo.json'); const strings = require('../data/strings.json');
const dbfn = require('../modules/dbfn.js');
const { GuildInfo } = require('../modules/CustomClasses.js');
module.exports = { module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('setup') .setName('setup')
.setDescription('Attempt automatic configuration of the bot.'), .setDescription('Configure some feature settings.')
execute(interaction) { .addSubcommand(sc =>
if (guildInfo[interaction.guildId] == undefined) { sc.setName('rolemenu')
guildInfo[interaction.guildId] = { .setDescription('Setup the roles to be used with /rolemenu')
"treeMessageId": "", .addRoleOption(o =>
"treeChannelId": "", o.setName('waterrole')
"rankMessageId": "", .setDescription('The role for water reminder pings')
"rankChannelId": "", .setRequired(true)
"rankings": [], )
"treeHeight": 0 .addRoleOption(o =>
}; o.setName('fruitrole')
} .setDescription('The role for fruit alert pings')
interaction.channel.messages.fetch({ limit: 20 }).then(msgs => { .setRequired(false)
let treeFound = false; )
let rankFound = false; )
msgs.forEach(msg => { .addSubcommand(sc =>
if (msg.embeds.length > 0) { sc.setName('view')
if (msg.embeds[0].data.description.includes("Your tree is")) { .setDescription('View your server\'s configuration'))
treeFound = true; .addSubcommand(sc =>
guildInfo[interaction.guildId].treeChannelId = msg.channelId; sc.setName('reset')
guildInfo[interaction.guildId].treeMessageId = msg.id; .setDescription('Remove all server configuration from the database')
fn.tree.parse(msg); .addBooleanOption(o =>
} else if (msg.embeds[0].data.title == "Tallest Trees") { o.setName('confirm')
rankFound = true; .setDescription('WARNING THIS IS IRREVERSIBLE')
guildInfo[interaction.guildId].rankChannelId = msg.channelId; .setRequired(true)
guildInfo[interaction.guildId].rankMessageId = msg.id; )
fn.rankings.parse(msg); )
} .setDefaultMemberPermissions(PermissionFlagsBits.Administrator),
async execute(interaction) {
await interaction.deferReply({ ephemeral: true });
const subcommand = interaction.options.getSubcommand();
switch (subcommand) {
case "rolemenu":
let waterRoleId = interaction.options.getRole('waterrole').id;
let fruitRoleId = interaction.options.getRole('fruitrole') ? interaction.options.getRole('fruitrole').id : undefined;
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
guildInfo.setRoles(waterRoleId, fruitRoleId);
await dbfn.setGuildInfo(guildInfo.queryBuilder("setRoles"));
await fn.collectionBuilders.guildInfos(interaction.client);
await interaction.editReply(fn.builders.embeds.treeRoleMenu(guildInfo)).catch(e => console.error(e));
} else {
let guildInfo = new GuildInfo()
.setIds(interaction.guildId, interaction.guild.ownerId);
guildInfo.setRoles(waterRoleId, fruitRoleId);
await dbfn.setGuildInfo(guildInfo.queryBuilder("setRoles"));
await fn.collectionBuilders.guildInfos(interaction.client);
await interaction.editReply(fn.builders.embeds.treeRoleMenu(guildInfo)).catch(e => console.error(e));
} }
}); break;
if (treeFound && !(rankFound)) { case "view":
interaction.reply(fn.builders.embed("A tree message was found, but a leaderboard message was not. Please run this command again in the channel containing the leaderboard if you haven't done so already. Run ``/setupinfo`` to see if the message is set.")); try {
} else if (!(treeFound) && rankFound) { if (interaction.client.guildInfos.has(interaction.guildId)) {
interaction.reply(fn.builders.embed("A leaderboard message was found, but a tree message was not. Please run this command again in the channel containing the tree if you haven't done so already. Run ``/setupinfo`` to see if the message is set.")); let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
} else if (treeFound && rankFound) { await interaction.editReply(fn.builders.embed(guildInfo.generateSetupInfo()));
interaction.reply(fn.builders.embed("Tree and leaderboard messages were both found, setup is complete. Run ``/setupinfo`` to verify.")); } else {
} await interaction.editReply(fn.builders.errorEmbed("Guild doesn't exist in database!"));
}); }
} catch (err) {
console.error(err);
await interaction.editReply(fn.builders.errorEmbed("There was an error running the command."));
}
break;
case "reset":
if (interaction.client.guildInfos.has(interaction.guildId)) {
let guildInfo = interaction.client.guildInfos.get(interaction.guildId);
if (interaction.options.getBoolean('confirm')) {
fn.reset(interaction).then(res => {
interaction.editReply(fn.builders.embed(strings.status.reset)).catch(err => {
console.error(err);
});
}).catch(err => {
console.error(err);
interaction.editReply(strings.status.resetError).catch(err => {
console.error(err);
});
});
} else {
await interaction.editReply(fn.builders.embed("You must select 'true' to confirm setup reset. No changes have been made.")).catch(e => console.error(e));
}
} else {
await interaction.editReply(fn.builders.errorEmbed("There is no configuration to delete.")).catch(e => console.error(e));
}
break;
default:
await interaction.editReply(fn.builders.errorEmbed(strings.error.invalidSubcommand)).catch(e => console.error(e));
break;
}
}, },
}; };

View File

@ -1,12 +0,0 @@
const { SlashCommandBuilder } = require('discord.js');
const fn = require('../modules/functions.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('setupinfo')
.setDescription('View information about how the bot is set up in your server'),
execute(interaction) {
const embed = fn.builders.embed(fn.getInfo(interaction.guildId));
interaction.reply(embed);
},
};

0
slash-commands/template Normal file → Executable file
View File

69
slash-commands/timetoheight.js Executable file
View File

@ -0,0 +1,69 @@
const { SlashCommandBuilder } = require('discord.js');
const dbfn = require('../modules/dbfn.js');
const fn = require('../modules/functions.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('timetoheight')
.setDescription('Calculate how long it would take to reach a given height')
.addIntegerOption(o =>
o.setName('endheight')
.setDescription('Ending tree height in feet')
.setRequired(true)
)
.addIntegerOption(o =>
o.setName('beginheight')
.setDescription('Beginning tree height in feet')
.setRequired(false)
)
.addIntegerOption(o =>
o.setName('efficiency')
.setDescription('Composter efficiency percentage, rounded')
.setRequired(false)
)
.addIntegerOption(o =>
o.setName('quality')
.setDescription('Compost quality percentage, rounded')
.setRequired(false)
)
.addBooleanOption(o =>
o.setName('private')
.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;
let beginHeight, replyContent;
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;
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 }
];
} else {
replyContent = `I estimate that a tree growing from ${beginHeight}ft to ${endHeight}ft will take ${time}`;
}
const reply = fn.builders.embeds.information(replyContent, replyFields)
await interaction.editReply(reply);
}
};

20
slash-commands/watertime.js Normal file → Executable file
View File

@ -6,13 +6,21 @@ module.exports = {
data: new SlashCommandBuilder() data: new SlashCommandBuilder()
.setName('watertime') .setName('watertime')
.setDescription('Calculate the watering time for a given tree height') .setDescription('Calculate the watering time for a given tree height')
.addStringOption(o => .addIntegerOption(o =>
o.setName('height') o.setName('height')
.setDescription('Tree height in feet, numbers ONLY') .setDescription('Tree height')
.setRequired(true)), .setRequired(true))
.addBooleanOption(o =>
o.setName('private')
.setDescription('Should the response be private? Default: true')
.setRequired(false)),
async execute(interaction) { async execute(interaction) {
await interaction.deferReply(); const treeHeight = interaction.options.getInteger('height');
const treeHeight = interaction.options.getString('height'); const privateOpt = interaction.options.getBoolean('private');
await interaction.editReply(`A tree that is ${treeHeight}ft tall will have a watering time of ${fn.getWaterTime(treeHeight)} minutes.`); const private = privateOpt != undefined ? privateOpt : true;
await interaction.deferReply( {ephemeral: private });
const waterSeconds = fn.getWaterTime(treeHeight);
const waterTime = fn.parseWaterTime(waterSeconds);
await interaction.editReply(`A tree that is ${treeHeight}ft tall will have a watering time of ${waterTime}.`);
}, },
}; };