Merge pull request #179 from mariusbegby/grafana

Various fixes and improvements - big logging update
This commit is contained in:
Marius Begby authored and GitHub committed 2023-08-26 18:06:39 +02:00
commit f4b209e527
57 files changed
+1672 -722

No files matched your search

+5
View File
@@ -25,3 +25,8 @@ BOTLIST_DISCORD_BOTLIST_EU_API_TOKEN=
# Optional: Only change this if you know what you are doing
NODE_OPTIONS=
UV_THREADPOOL_SIZE=
# Optional: Password/token for pushing logs to Loki
LOKI_HOST=
LOKI_AUTH_USERNAME=
LOKI_AUTH_PASSWORD=
+8 -2
View File
@@ -23,7 +23,8 @@ module.exports.shardingOptions = {
// You can set logging level to file and console separately.
module.exports.loggerOptions = {
minimumLogLevel: 'debug',
minimumLogLevelConsole: 'info'
minimumLogLevelConsole: 'info',
discordPlayerDebug: false
};
// Options for identifying specific system command.
@@ -51,6 +52,10 @@ module.exports.presenceStatusOptions = {
// Configurations for visual embed messages.
// Includes design elements like colors and custom emojis/symbols.
module.exports.embedOptions = {
info: {
fallbackThumbnailUrl:
'https://raw.githubusercontent.com/mariusbegby/cadence-discord-bot/main/assets/logo-rounded-128px.png'
},
colors: {
success: '#23A55A',
warning: '#F0B232',
@@ -99,7 +104,8 @@ module.exports.embedOptions = {
sourceAppleMusic: '🎵',
sourceYouTube: '🎵',
sourceSoundCloud: '🎵',
sourceSpotify: '🎵'
sourceSpotify: '🎵',
liveTrack: '🔴'
}
};
+351 -48
View File
@@ -18,9 +18,11 @@
"discord-voip": "^0.1.2",
"discord.js": "^14.13.0",
"dotenv": "^16.3.1",
"mediaplex": "^0.0.4",
"mediaplex": "^0.0.6",
"node-os-utils": "^1.3.7",
"pino": "^8.15.0"
"pino": "^8.15.0",
"pino-loki": "^2.1.3",
"uuid": "^9.0.0"
},
"devDependencies": {
"eslint": "^8.47.0",
@@ -381,11 +383,44 @@
"npm": ">=7.0.0"
}
},
"node_modules/@sindresorhus/is": {
"version": "4.6.0",
"resolved": "https://registry.npmjs.org/@sindresorhus/is/-/is-4.6.0.tgz",
"integrity": "sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sindresorhus/is?sponsor=1"
}
},
"node_modules/@szmarczak/http-timer": {
"version": "4.0.6",
"resolved": "https://registry.npmjs.org/@szmarczak/http-timer/-/http-timer-4.0.6.tgz",
"integrity": "sha512-4BAffykYOgO+5nzBWYwE3W90sBgLJoUPRWWcL8wlyiM8IB8ipJz3UMJ9KXQd1RKQXpKp8Tutn80HZtWsu2u76w==",
"dependencies": {
"defer-to-connect": "^2.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/@tokenizer/token": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/@tokenizer/token/-/token-0.3.0.tgz",
"integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A=="
},
"node_modules/@types/cacheable-request": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/@types/cacheable-request/-/cacheable-request-6.0.3.tgz",
"integrity": "sha512-IQ3EbTzGxIigb1I3qPZc1rWJnH0BmSKv5QYTalEwweFvyBDLSAe24zP0le/hyi7ecGfZVlIVAg4BZqb8WBwKqw==",
"dependencies": {
"@types/http-cache-semantics": "*",
"@types/keyv": "^3.1.4",
"@types/node": "*",
"@types/responselike": "^1.0.0"
}
},
"node_modules/@types/eslint": {
"version": "8.44.0",
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.44.0.tgz",
@@ -402,12 +437,25 @@
"integrity": "sha512-LG4opVs2ANWZ1TJoKc937iMmNstM/d0ae1vNbnBvBhqCSezgVUOzcLCqbI5elV8Vy6WKwKjaqR+zO9VKirBBCA==",
"dev": true
},
"node_modules/@types/http-cache-semantics": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/@types/http-cache-semantics/-/http-cache-semantics-4.0.1.tgz",
"integrity": "sha512-SZs7ekbP8CN0txVG2xVRH6EgKmEm31BOxA07vkFaETzZz1xh+cbt8BcI0slpymvwhx5dlFnQG2rTlPVQn+iRPQ=="
},
"node_modules/@types/json-schema": {
"version": "7.0.12",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.12.tgz",
"integrity": "sha512-Hr5Jfhc9eYOQNPYO5WLDq/n4jqijdHNlDXjuAQkkt+mWdQR+XJToOHrsD4cPaMXpn6KO7y2+wM8AZEs8VpBLVA==",
"dev": true
},
"node_modules/@types/keyv": {
"version": "3.1.4",
"resolved": "https://registry.npmjs.org/@types/keyv/-/keyv-3.1.4.tgz",
"integrity": "sha512-BQ5aZNSCpj7D6K2ksrRCTmKRLEpnPvWDiLPfoGyhZ++8YtiK9d/3DBKPJgry359X/P1PfruyYwvnvwFjuEiEIg==",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/node": {
"version": "20.3.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.3.tgz",
@@ -419,6 +467,14 @@
"integrity": "sha512-+68kP9yzs4LMp7VNh8gdzMSPZFL44MLGqiHWvttYJe+6qnuVr4Ek9wSBQoveqY/r+LwjCcU29kNVkidwim+kYA==",
"dev": true
},
"node_modules/@types/responselike": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@types/responselike/-/responselike-1.0.0.tgz",
"integrity": "sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@types/ws": {
"version": "8.5.5",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz",
@@ -759,6 +815,31 @@
"node": ">=10.16.0"
}
},
"node_modules/cacheable-lookup": {
"version": "5.0.4",
"resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz",
"integrity": "sha512-2/kNscPhpcxrOigMZzbiWF7dz8ilhb/nIHU3EyZiXWXpeq/au8qJ8VhdftMkty3n7Gj6HIGalQG8oiBNB3AJgA==",
"engines": {
"node": ">=10.6.0"
}
},
"node_modules/cacheable-request": {
"version": "7.0.4",
"resolved": "https://registry.npmjs.org/cacheable-request/-/cacheable-request-7.0.4.tgz",
"integrity": "sha512-v+p6ongsrp0yTGbJXjgxPow2+DL93DASP4kXCDKb8/bwRtt9OEF3whggkkDkGNzgcWy2XaF4a8nZglC7uElscg==",
"dependencies": {
"clone-response": "^1.0.2",
"get-stream": "^5.1.0",
"http-cache-semantics": "^4.0.0",
"keyv": "^4.0.0",
"lowercase-keys": "^2.0.0",
"normalize-url": "^6.0.1",
"responselike": "^2.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/callsites": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",
@@ -830,6 +911,17 @@
"node": ">=10"
}
},
"node_modules/clone-response": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/clone-response/-/clone-response-1.0.3.tgz",
"integrity": "sha512-ROoL94jJH2dUVML2Y/5PEDNaSHgeOdSDicUyS7izcF63G6sTc/FTjLub4b8Il9S8S0beOfYt0TaA5qvFK+w0wA==",
"dependencies": {
"mimic-response": "^1.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
@@ -858,6 +950,14 @@
"color-support": "bin.js"
}
},
"node_modules/commander": {
"version": "10.0.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-10.0.1.tgz",
"integrity": "sha512-y4Mg2tXshplEbSGzx7amzPwKKOCGuoSRP/CjEdwwk0FOGlUbq6lKuoyDZTNZkmxHdJtp54hdfY/JUrdL7Xfdug==",
"engines": {
"node": ">=14"
}
},
"node_modules/common-tags": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.8.2.tgz",
@@ -956,12 +1056,45 @@
}
}
},
"node_modules/decompress-response": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz",
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
"dependencies": {
"mimic-response": "^3.1.0"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/decompress-response/node_modules/mimic-response": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz",
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
"integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==",
"dev": true
},
"node_modules/defer-to-connect": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/defer-to-connect/-/defer-to-connect-2.0.1.tgz",
"integrity": "sha512-4tvttepXG1VaYGrRibk5EwJd1t4udunSOVMdLSAL6mId1ix438oPwPZMALY41FCijukO1L0twNcGsdzS7dHgDg==",
"engines": {
"node": ">=10"
}
},
"node_modules/delegates": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
@@ -1149,6 +1282,14 @@
"optional": true,
"peer": true
},
"node_modules/end-of-stream": {
"version": "1.4.4",
"resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.4.tgz",
"integrity": "sha512-+uw1inIHVPQoaVuHzRyXd21icM+cnt4CzD5rW+NC1wjOUSTOs+Te7FOv7AhN7vS9x/oIyhLP5PR1H+phQAHu5Q==",
"dependencies": {
"once": "^1.4.0"
}
},
"node_modules/entities": {
"version": "4.5.0",
"resolved": "https://registry.npmjs.org/entities/-/entities-4.5.0.tgz",
@@ -1561,6 +1702,20 @@
"undici": "^5.8.2"
}
},
"node_modules/get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
"integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
"dependencies": {
"pump": "^3.0.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/glob": {
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
@@ -1628,6 +1783,30 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/got": {
"version": "11.8.6",
"resolved": "https://registry.npmjs.org/got/-/got-11.8.6.tgz",
"integrity": "sha512-6tfZ91bOr7bOXnK7PRDCGBLa1H4U080YHNaAQ2KsMGlLEzRbk44nsZF2E1IeRc3vtJHPVbKCYgdFbaGO2ljd8g==",
"dependencies": {
"@sindresorhus/is": "^4.0.0",
"@szmarczak/http-timer": "^4.0.5",
"@types/cacheable-request": "^6.0.1",
"@types/responselike": "^1.0.0",
"cacheable-lookup": "^5.0.3",
"cacheable-request": "^7.0.2",
"decompress-response": "^6.0.0",
"http2-wrapper": "^1.0.0-beta.5.2",
"lowercase-keys": "^2.0.0",
"p-cancelable": "^2.0.0",
"responselike": "^2.0.0"
},
"engines": {
"node": ">=10.19.0"
},
"funding": {
"url": "https://github.com/sindresorhus/got?sponsor=1"
}
},
"node_modules/graphemer": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/graphemer/-/graphemer-1.4.0.tgz",
@@ -1702,6 +1881,23 @@
"entities": "^4.4.0"
}
},
"node_modules/http-cache-semantics": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/http-cache-semantics/-/http-cache-semantics-4.1.1.tgz",
"integrity": "sha512-er295DKPVsV82j5kw1Gjt+ADA/XYHsajl82cGNQG2eyoPkvgUhX+nDIyelzhIWbbsXP39EHcI6l5tYs2FYqYXQ=="
},
"node_modules/http2-wrapper": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/http2-wrapper/-/http2-wrapper-1.0.3.tgz",
"integrity": "sha512-V+23sDMr12Wnz7iTcDeJr3O6AIxlnvT/bmaAAAP/Xda35C90p9599p0F1eHR/N1KILWSoWVAiOMFjBBXaXSMxg==",
"dependencies": {
"quick-lru": "^5.1.1",
"resolve-alpn": "^1.0.0"
},
"engines": {
"node": ">=10.19.0"
}
},
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
@@ -1886,6 +2082,11 @@
"js-yaml": "bin/js-yaml.js"
}
},
"node_modules/json-buffer": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
"integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ=="
},
"node_modules/json-schema-traverse": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz",
@@ -1909,6 +2110,14 @@
"node": ">=6"
}
},
"node_modules/keyv": {
"version": "4.5.3",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.3.tgz",
"integrity": "sha512-QCiSav9WaX1PgETJ+SpNnx2PRRapJ/oRSXM4VO5OGYGSjrxbKPVFVhB3l2OCbLCk329N8qyAtsJjSjvVBWzEug==",
"dependencies": {
"json-buffer": "3.0.1"
}
},
"node_modules/levn": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz",
@@ -2053,6 +2262,14 @@
"node": ">=0.8.0"
}
},
"node_modules/lowercase-keys": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/lowercase-keys/-/lowercase-keys-2.0.0.tgz",
"integrity": "sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==",
"engines": {
"node": ">=8"
}
},
"node_modules/lru-cache": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
@@ -2109,29 +2326,29 @@
}
},
"node_modules/mediaplex": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex/-/mediaplex-0.0.4.tgz",
"integrity": "sha512-TLsBBGCCwUaM6E5eWwDQmL1ReojXUFKH+/akmCRJ1Y2coLZj26UR/FDtfPTdyP1sBxXmU59+FhHaHZA7Y5VAnw==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex/-/mediaplex-0.0.6.tgz",
"integrity": "sha512-uw3/sswE6YkI5ksZlkRhndxWTP6avKKhDunSory7IPQC0tw/7TfxAlC9DCHC89MpsSjOwZKLRQm0ssCB4v8V/g==",
"engines": {
"node": ">= 10"
},
"optionalDependencies": {
"mediaplex-android-arm64": "0.0.4",
"mediaplex-darwin-arm64": "0.0.4",
"mediaplex-darwin-universal": "0.0.4",
"mediaplex-darwin-x64": "0.0.4",
"mediaplex-freebsd-x64": "0.0.4",
"mediaplex-linux-arm-gnueabihf": "0.0.4",
"mediaplex-linux-x64-gnu": "0.0.4",
"mediaplex-win32-arm64-msvc": "0.0.4",
"mediaplex-win32-ia32-msvc": "0.0.4",
"mediaplex-win32-x64-msvc": "0.0.4"
"mediaplex-android-arm64": "0.0.6",
"mediaplex-darwin-arm64": "0.0.6",
"mediaplex-darwin-universal": "0.0.6",
"mediaplex-darwin-x64": "0.0.6",
"mediaplex-freebsd-x64": "0.0.6",
"mediaplex-linux-arm-gnueabihf": "0.0.6",
"mediaplex-linux-x64-gnu": "0.0.6",
"mediaplex-win32-arm64-msvc": "0.0.6",
"mediaplex-win32-ia32-msvc": "0.0.6",
"mediaplex-win32-x64-msvc": "0.0.6"
}
},
"node_modules/mediaplex-android-arm64": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-android-arm64/-/mediaplex-android-arm64-0.0.4.tgz",
"integrity": "sha512-DSuw8jD5ZAGPUHeAJoevcOYJ/DU2RQiTatSeA+ESV2Jep6aOoKWDUSia+f3c+J6TO4bwBRzSESlvZm/g005Dxw==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-android-arm64/-/mediaplex-android-arm64-0.0.6.tgz",
"integrity": "sha512-1SOcbUpugAiwFbmp/umh+oQpfFcpo+PGwxzmjIphLlEKzs9Ut7Ypd/8Jx7KoiXj+xJNC/ovx16xfY6gUMS5UBw==",
"cpu": [
"arm64"
],
@@ -2144,9 +2361,9 @@
}
},
"node_modules/mediaplex-darwin-arm64": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-darwin-arm64/-/mediaplex-darwin-arm64-0.0.4.tgz",
"integrity": "sha512-/5IdGd31TUBOIT8n0uoLXH+R9bI7q034SshOm+yQfsNJkISeJu/KQPdPq/1d52VxDTC0InQBsZKe+nHzMzcp3A==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-darwin-arm64/-/mediaplex-darwin-arm64-0.0.6.tgz",
"integrity": "sha512-nGGBuPjaw6NeIQVHKWlH7/b3dxx7GavKOomK4j+hVKr5dhW+IaUk99COnG6Py58HgTMckmzYV23galnMQMZS0w==",
"cpu": [
"arm64"
],
@@ -2159,9 +2376,9 @@
}
},
"node_modules/mediaplex-darwin-universal": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-darwin-universal/-/mediaplex-darwin-universal-0.0.4.tgz",
"integrity": "sha512-moVLEMPWxLS/JB3FHBgyS74fG9IT+ynl4plOWV8HltVnTsOvHFWFbn8yOQ89e/eJfA/8VXIxPWACa8cZQYrjbg==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-darwin-universal/-/mediaplex-darwin-universal-0.0.6.tgz",
"integrity": "sha512-B08mmQNOTCkzUlqJuutmW2KxpEaQLa4sdID2pRPS53/vqXZQMwCWSDYPl+j/Fcz6AfWl/2BKTAUUJYte2sW/lA==",
"optional": true,
"os": [
"darwin"
@@ -2171,9 +2388,9 @@
}
},
"node_modules/mediaplex-darwin-x64": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-darwin-x64/-/mediaplex-darwin-x64-0.0.4.tgz",
"integrity": "sha512-R/tbU4loBawwMP9uWk90MU1YaEASKNrZ8m5lGMQFVuiz74IQIfr1vbrsyASKkrtbmgT5uhoErbD/ny6qlwfErQ==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-darwin-x64/-/mediaplex-darwin-x64-0.0.6.tgz",
"integrity": "sha512-pCqRBv3N/X4Qafp/l3a95HsHTc8TknhUl+GQ2uTStcExhr0kfG9zaRLSncDMFiyIl+1o4WgXVP4XA1kaFwaJRA==",
"cpu": [
"x64"
],
@@ -2186,9 +2403,9 @@
}
},
"node_modules/mediaplex-freebsd-x64": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-freebsd-x64/-/mediaplex-freebsd-x64-0.0.4.tgz",
"integrity": "sha512-n20/SeTQ2WqhvXkOWvA6U97azzWN083g17VPNDki17aitVvH5B6phDk8YSpAW/jYRMDsK0c1qUqzZ3xNlqD/Ow==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-freebsd-x64/-/mediaplex-freebsd-x64-0.0.6.tgz",
"integrity": "sha512-SurGIwJmWzJ6v1TEWTE2Py6wwU8lLrG0vu9t0sZM6qElJiRY7xKVc1YpGI6egNEX+qlyzBGhFkN31/O9A4ziqw==",
"cpu": [
"x64"
],
@@ -2201,9 +2418,9 @@
}
},
"node_modules/mediaplex-linux-arm-gnueabihf": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-linux-arm-gnueabihf/-/mediaplex-linux-arm-gnueabihf-0.0.4.tgz",
"integrity": "sha512-b4hb9MnfEmBlWHAP0wmvXKE4QrDKeHzGCydi15K63dqvcgdMyHQ1lt1Si732Hvu0eeB9aTO2BcEkdyTP4QW6IA==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-linux-arm-gnueabihf/-/mediaplex-linux-arm-gnueabihf-0.0.6.tgz",
"integrity": "sha512-WZhUm5dhV6PVVKkGSuCpOv+HY2/Vvs2RQe/YfMRtTnXJQXxI63GkadiT+YZ4OVZwnJj3eB3Rvpf7ej2SOq/cGw==",
"cpu": [
"arm"
],
@@ -2216,9 +2433,9 @@
}
},
"node_modules/mediaplex-linux-x64-gnu": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-linux-x64-gnu/-/mediaplex-linux-x64-gnu-0.0.4.tgz",
"integrity": "sha512-877oKhcfT6H0qvHYZGbK7XH9DJlJDIyXT80ir2K0rwpM3UK3TYvxilnp1Pzq3CLZLcj80ZanrZ4PsDE0MSNHvw==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-linux-x64-gnu/-/mediaplex-linux-x64-gnu-0.0.6.tgz",
"integrity": "sha512-pfepLLrvBuVyEYHLuad/GbqUaJmrcSd83MxqdNWv3+qi5q87MLBtVL9YCZIaXPLAWJSbrxlOeXTHJH3HVKdVVw==",
"cpu": [
"x64"
],
@@ -2231,9 +2448,9 @@
}
},
"node_modules/mediaplex-win32-arm64-msvc": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-win32-arm64-msvc/-/mediaplex-win32-arm64-msvc-0.0.4.tgz",
"integrity": "sha512-K1lf9jVTEt4h5t3rIa4NaVUnr6yMnCQjIehO5iFBXRpOqT4wQO8dAOCYKVjYaTL9oI57nlXHsOh16f0Bgsb88Q==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-win32-arm64-msvc/-/mediaplex-win32-arm64-msvc-0.0.6.tgz",
"integrity": "sha512-pWa+aXaEs8mjGF65WyuPTi6OyndhKruPTjUMSBSUFh1cV99tZ+cM4hJFJ1xQCIUTyC368F3V/qMytF5AbCT+zA==",
"cpu": [
"arm64"
],
@@ -2246,9 +2463,9 @@
}
},
"node_modules/mediaplex-win32-ia32-msvc": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-win32-ia32-msvc/-/mediaplex-win32-ia32-msvc-0.0.4.tgz",
"integrity": "sha512-rDLZdq77QBDE5Y+JjqNbugXcgK0dL/TTiP8GhCbY6pP0xwetDLVKatyYn9PooM/Gk+LSHfjJ4r25gXqktuUUhA==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-win32-ia32-msvc/-/mediaplex-win32-ia32-msvc-0.0.6.tgz",
"integrity": "sha512-8hO3QE6V9ETrV1uaEtZhcmrAiafIpCL4stoYhjpXtK9US4O8PAH1AnYy+xt3UbkfVE2v+3T4EjdPghNwJFORPg==",
"cpu": [
"ia32"
],
@@ -2261,9 +2478,9 @@
}
},
"node_modules/mediaplex-win32-x64-msvc": {
"version": "0.0.4",
"resolved": "https://registry.npmjs.org/mediaplex-win32-x64-msvc/-/mediaplex-win32-x64-msvc-0.0.4.tgz",
"integrity": "sha512-hogJHHBQHm4DaReTh8HkpAFJ6nNGRewjajxDooUP4qPQ+4g5S8RPN3zLl+BQtZYrmubW+LuaAQ1FB5nAFVt1bw==",
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/mediaplex-win32-x64-msvc/-/mediaplex-win32-x64-msvc-0.0.6.tgz",
"integrity": "sha512-svrm5hlbrjMW+boPhI73ePzA1Z2HCA9RIwmAWshZtGcFoNzOoOAiz0y4lKc9mzHkAVq3nVNDOnAeYe9F3E1CGQ==",
"cpu": [
"x64"
],
@@ -2297,6 +2514,14 @@
"node": ">=8.6"
}
},
"node_modules/mimic-response": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-1.0.1.tgz",
"integrity": "sha512-j5EctnkH7amfV/q5Hgmoal1g2QHFJRraOtmx0JpIqkxhBhI/lJSl1nMpQ45hVarwNETOoWEimndZ4QK0RHxuxQ==",
"engines": {
"node": ">=4"
}
},
"node_modules/miniget": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/miniget/-/miniget-4.2.3.tgz",
@@ -2453,6 +2678,17 @@
"node": ">=6"
}
},
"node_modules/normalize-url": {
"version": "6.1.0",
"resolved": "https://registry.npmjs.org/normalize-url/-/normalize-url-6.1.0.tgz",
"integrity": "sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/npmlog": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
@@ -2496,7 +2732,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"devOptional": true,
"dependencies": {
"wrappy": "1"
}
@@ -2518,6 +2753,14 @@
"node": ">= 0.8.0"
}
},
"node_modules/p-cancelable": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/p-cancelable/-/p-cancelable-2.1.1.tgz",
"integrity": "sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==",
"engines": {
"node": ">=8"
}
},
"node_modules/p-limit": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz",
@@ -2688,6 +2931,23 @@
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
}
},
"node_modules/pino-loki": {
"version": "2.1.3",
"resolved": "https://registry.npmjs.org/pino-loki/-/pino-loki-2.1.3.tgz",
"integrity": "sha512-CRJh2u3/5JYYLEspjBRiXxKmR759Qo/yylz/efVFLr2CWERBlsndZHscDtfCzYDxT0P47fVLnbAvIAro0PEjag==",
"dependencies": {
"commander": "^10.0.1",
"got": "^11.8.6",
"pino-abstract-transport": "^1.0.0",
"pump": "^3.0.0"
},
"bin": {
"pino-loki": "dist/cli.cjs"
},
"funding": {
"url": "https://github.com/sponsors/Julien-R44"
}
},
"node_modules/pino-std-serializers": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-6.2.2.tgz",
@@ -2826,6 +3086,15 @@
"resolved": "https://registry.npmjs.org/process-warning/-/process-warning-2.2.0.tgz",
"integrity": "sha512-/1WZ8+VQjR6avWOgHeEPd7SDQmFQ1B5mC1eRXsCm5TarlNmx/wCsa5GEaxGm05BORRtyG/Ex/3xq3TuRvq57qg=="
},
"node_modules/pump": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz",
"integrity": "sha512-LwZy+p3SFs1Pytd/jYct4wpv49HiYCqd9Rlc5ZVdk0V+8Yzv6jR5Blk3TRmPL1ft69TxP0IMZGJ+WPFU2BFhww==",
"dependencies": {
"end-of-stream": "^1.1.0",
"once": "^1.3.1"
}
},
"node_modules/punycode": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.0.tgz",
@@ -2860,6 +3129,17 @@
"resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz",
"integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg=="
},
"node_modules/quick-lru": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-5.1.1.tgz",
"integrity": "sha512-WuyALRjWPDGtt/wzJiadO5AXY+8hZ80hVpe6MyivgraREW751X3SbhRvG3eLKOYN+8VEvqLcf3wdnt44Z4S4SA==",
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
@@ -2902,6 +3182,11 @@
"integrity": "sha512-AKGr4qvHiryxRb19m3PsLRGuKVAbJLUD7E6eOaHkfKhwc+vSgVOCY5xNvm9EkolBKTOf0GrQAZKLimOCz81Khg==",
"dev": true
},
"node_modules/resolve-alpn": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/resolve-alpn/-/resolve-alpn-1.2.1.tgz",
"integrity": "sha512-0a1F4l73/ZFZOakJnQ3FvkJ2+gSTQWz/r2KE5OdDY0TxPm5h4GkqkWWfM47T7HsbnOtcJVEF4epCVy6u7Q3K+g=="
},
"node_modules/resolve-from": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz",
@@ -2911,6 +3196,17 @@
"node": ">=4"
}
},
"node_modules/responselike": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/responselike/-/responselike-2.0.1.tgz",
"integrity": "sha512-4gl03wn3hj1HP3yzgdI7d3lCkF95F21Pz4BPGvKHinyQzALR5CapwC8yIi0Rh58DEMQ/SguC03wFj2k0M/mHhw==",
"dependencies": {
"lowercase-keys": "^2.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/reusify": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/reusify/-/reusify-1.0.4.tgz",
@@ -3348,6 +3644,14 @@
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
},
"node_modules/uuid": {
"version": "9.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.0.tgz",
"integrity": "sha512-MXcSTerfPa4uqyzStbRoTgt5XIe3x5+42+q1sDuy3R5MDk66URdLMOZe5aPX/SQd+kuYAh0FdP/pO28IkQyTeg==",
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/vue-eslint-parser": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/vue-eslint-parser/-/vue-eslint-parser-8.3.0.tgz",
@@ -3422,8 +3726,7 @@
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"devOptional": true
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="
},
"node_modules/ws": {
"version": "8.13.0",
+48 -45
View File
@@ -1,46 +1,49 @@
{
"name": "cadence-discord-bot",
"version": "4.1.3",
"description": "A free Discord music and audio bot.",
"repository": {
"type": "git",
"url": "https://github.com/mariusbegby/cadence-discord-bot"
},
"bugs": {
"url": "https://github.com/mariusbegby/cadence-discord-bot/issues"
},
"homepage": "https://github.com/mariusbegby/cadence-discord-bot#readme",
"author": {
"name": "Marius Begby",
"url": "https://github.com/mariusbegby"
},
"publisher": "mariusbegby",
"license": "MIT",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./src/index.js",
"start-pretty": "node ./src/index.js | pino-pretty",
"deploy": "node ./src/utils/deploySlashCommands.js",
"deploy-pretty": "node ./src/utils/deploySlashCommands.js | pino-pretty",
"eslint": "eslint ./"
},
"dependencies": {
"@discord-player/extractor": "^4.4.2-dev.1",
"@discord-player/opus": "^0.1.1",
"@discordjs/rest": "^2.0.0",
"@distube/ytdl-core": "^4.11.17",
"config": "^3.3.9",
"discord-player": "^6.6.3-dev.0",
"discord-voip": "^0.1.2",
"discord.js": "^14.13.0",
"dotenv": "^16.3.1",
"mediaplex": "^0.0.4",
"node-os-utils": "^1.3.7",
"pino": "^8.15.0"
},
"devDependencies": {
"eslint": "^8.47.0",
"prettier-eslint": "^15.0.1"
}
{
"name": "cadence-discord-bot",
"version": "4.1.3",
"description": "A free Discord music and audio bot.",
"repository": {
"type": "git",
"url": "https://github.com/mariusbegby/cadence-discord-bot"
},
"bugs": {
"url": "https://github.com/mariusbegby/cadence-discord-bot/issues"
},
"homepage": "https://github.com/mariusbegby/cadence-discord-bot#readme",
"author": {
"name": "Marius Begby",
"url": "https://github.com/mariusbegby"
},
"publisher": "mariusbegby",
"license": "MIT",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node ./src/index.js",
"start-pretty": "node ./src/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"start-pretty-no-ignore": "node ./src/index.js | pino-pretty",
"deploy": "node ./src/utils/deploySlashCommands.js",
"deploy-pretty": "node ./src/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"eslint": "eslint ./"
},
"dependencies": {
"@discord-player/extractor": "^4.4.2-dev.1",
"@discord-player/opus": "^0.1.1",
"@discordjs/rest": "^2.0.0",
"@distube/ytdl-core": "^4.11.17",
"config": "^3.3.9",
"discord-player": "^6.6.3-dev.0",
"discord-voip": "^0.1.2",
"discord.js": "^14.13.0",
"dotenv": "^16.3.1",
"mediaplex": "^0.0.6",
"node-os-utils": "^1.3.7",
"pino": "^8.15.0",
"pino-loki": "^2.1.3",
"uuid": "^9.0.0"
},
"devDependencies": {
"eslint": "^8.47.0",
"prettier-eslint": "^15.0.1"
}
}
+15 -5
View File
@@ -1,18 +1,28 @@
require('dotenv').config();
const logger = require('./services/logger');
const { registerEventListeners } = require('./utils/registerEventListeners.js');
const { registerClientCommands } = require('./utils/registerClientCommands.js');
const { createClient } = require('./utils/factory/createClient.js');
const { createPlayer } = require('./utils/factory/createPlayer.js');
const { v4: uuidv4 } = require('uuid');
const executionId = uuidv4();
const logger = require('./services/logger').child({
source: 'bot.js',
module: 'shardingClient',
name: 'shardingClient',
executionId: executionId,
shardId: 'client'
});
(async () => {
const client = await createClient();
const player = await createPlayer(client);
const client = await createClient({ executionId });
const player = await createPlayer({ client, executionId });
client.on('allShardsReady', async () => {
client.registerClientCommands = registerClientCommands;
registerEventListeners(client, player);
registerClientCommands(client);
registerEventListeners({ client, player, executionId });
registerClientCommands({ client, executionId });
client.emit('ready', client);
});
+11 -1
View File
@@ -9,7 +9,16 @@ module.exports = {
.setDescription('Show a list of commands and their usage.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client }) => {
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'help.js',
module: 'slashCommand',
name: '/help',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const commandList = client.commands
.filter((command) => {
// don't include system commands
@@ -34,6 +43,7 @@ module.exports = {
? `${embedOptions.icons.bot} **Enjoying ${botOptions.name}?**\nAdd me to another server: \n**[Click me!](${botOptions.botInviteUrl})**`
: '';
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+22 -4
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted');
@@ -14,8 +13,17 @@ module.exports = {
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client }) => {
const uptimeString = await getUptimeFormatted();
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'status.js',
module: 'slashCommand',
name: '/status',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const uptimeString = await getUptimeFormatted({ executionId });
const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage = await osu.cpu.usage();
const releaseVersion = version;
@@ -47,6 +55,11 @@ module.exports = {
activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0);
totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0);
totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0);
logger.debug('Successfully fetched player statistics from shards.');
})
.catch((error) => {
logger.error(error, 'Failed to fetch player statistics from shards.');
});
await client.shard
@@ -58,9 +71,11 @@ module.exports = {
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards.');
})
.catch((error) => {
logger.error(error, `[Shard ${client.shard.ids[0]}] Failed to fetch client values from shards.`);
logger.error(error, 'Failed to fetch client values from shards.');
});
const botStatusString =
@@ -78,6 +93,9 @@ module.exports = {
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
logger.debug('Transformed status into into embed description.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+24 -27
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const ffmpegFilterOptions = config.get('ffmpegFilterOptions');
@@ -22,22 +21,31 @@ module.exports = {
.setDescription('Toggle various audio filters during playback.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'filters.js',
module: 'slashCommand',
name: '/filters',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack(interaction, queue)) {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
@@ -77,6 +85,7 @@ module.exports = {
.setEmoji(embedOptions.icons.disable)
);
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -87,9 +96,6 @@ module.exports = {
],
components: [filterActionRow, disableFiltersActionRow]
});
logger.debug(
`[Shard ${interaction.guild.shardId}] Sent embed for command ${interaction.commandName}, awaiting interaction response.`
);
const collectorFilter = (i) => i.user.id === interaction.user.id;
try {
@@ -98,12 +104,10 @@ module.exports = {
time: 300_000
});
logger.debug(
`[Shard ${interaction.guild.shardId}] Received interaction response for command ${interaction.commandName}.`
);
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
queue.filters.ffmpeg.setInputArgs([
'-threads',
ffmpegFilterOptions.threadAmount,
@@ -119,9 +123,11 @@ module.exports = {
// Reset filters before enabling provided filters
if (queue.filters.ffmpeg.filters.length > 0) {
queue.filters.ffmpeg.setFilters(false);
logger.debug('Reset queue filters.');
}
if (confirmation.customId === 'disable-filters' || confirmation.values.length === 0) {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -148,13 +154,9 @@ module.exports = {
// Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values);
logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] Enabled filters ${confirmation.values.join(', ')} for command ${
interaction.commandName
}.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -181,17 +183,12 @@ module.exports = {
});
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug(
`[Shard ${interaction.guild.shardId}] Interaction response timed out for command ${interaction.commandName}.`
);
logger.debug('Interaction response timed out.');
return;
}
logger.debug(
error,
`[Shard ${interaction.guild.shardId}] Unhandled error while awaiting interaction response for command ${interaction.commandName}, throwing error.`
);
throw error;
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
}
}
};
+17 -10
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -13,17 +12,26 @@ module.exports = {
.setDescription('Clear the track queue and remove the bot from voice channel.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'leave.js',
module: 'slashCommand',
name: '/leave',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (!queue) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no queue.`
);
logger.debug('There is already no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -35,17 +43,16 @@ module.exports = {
});
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (!queue.deleted) {
queue.delete();
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and deleted the queue.`
);
logger.debug('Deleted the queue.');
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+30 -23
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
@@ -27,18 +26,27 @@ module.exports = {
{ name: 'Disabled', value: '0' }
)
),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'loop.js',
module: 'slashCommand',
name: '/loop',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
@@ -55,10 +63,9 @@ module.exports = {
const currentModeUserString = loopModesFormatted.get(currentMode);
if (!mode && mode !== 0) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but no mode was provided.`
);
logger.debug('No mode input was provided, responding with current loop mode.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -73,10 +80,9 @@ module.exports = {
}
if (mode === currentMode) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but loop mode was already set to ${modeUserString}.`
);
logger.debug(`Loop mode is already set to ${modeUserString}.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -90,11 +96,14 @@ module.exports = {
queue.setRepeatMode(mode);
if (!queue.repeatMode === mode) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but failed to change loop mode.`
// switch(queue.repeatMode) instead of multiple if statements
if (queue.repeatMode !== mode) {
logger.warn(
'Failed to change loop mode. After setting queue repeat mode, the value was not the same as input.'
);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -102,15 +111,15 @@ module.exports = {
`**${embedOptions.icons.error} Uh-oh... Failed to change loop mode!**\nI tried to change the loop mode to \`${modeUserString}\`, but something went wrong.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect or the issue persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
if (queue.repeatMode === 0) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and disabled loop mode.`
);
logger.debug('Disabled loop mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -127,10 +136,9 @@ module.exports = {
}
if (queue.repeatMode === 3) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and enabled autoplay.`
);
logger.debug('Enabled autoplay mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -146,10 +154,9 @@ module.exports = {
});
}
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and enabled loop mode.`
);
logger.debug('Enabled loop mode.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+75 -28
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -7,6 +6,14 @@ const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useMainPlayer, useQueue, QueryType } = require('discord-player');
const { lyricsExtractor } = require('@discord-player/extractor');
const recentQueries = new Map();
const loggerTempplate = require('../../services/logger').child({
source: 'lyrics.js',
module: 'slashCommand',
name: '/lyrics'
});
module.exports = {
isNew: false,
isBeta: false,
@@ -24,27 +31,44 @@ module.exports = {
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction }) => {
autocomplete: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const query = interaction.options.getString('query', true);
if (query.length < 2) {
return;
const { lastQuery, result, timestamp } = recentQueries.get(interaction.user.id) || {};
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
logger.debug(`Responding with results from lastQuery for query '${query}'`);
return interaction.respond(result);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const genius = lyricsExtractor();
const lyricsResult = await genius.search(query).catch(() => null);
let response = [];
if (!lyricsResult) {
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
const player = useMainPlayer();
const searchResults = await player.search(query);
response = searchResults.tracks.slice(0, 1).map((track) => ({
name:
`${track.title} [Artist: ${track.author}]`.length > 100
? `${track.title}`.slice(0, 100)
: `${track.title} [Author: ${track.author}]`,
: `${track.title} [Artist: ${track.author}]`,
value: track.title.slice(0, 100)
}));
} else {
logger.debug(`Found Genius lyrics for query '${query}'.`);
response = [
{
name: `${lyricsResult.title} [Artist: ${lyricsResult.artist.name}]`.slice(0, 100),
@@ -54,47 +78,65 @@ module.exports = {
}
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
logger.debug(`[Shard ${interaction.guild.shardId}] Autocomplete search responded for query: ${query}`);
recentQueries.set(interaction.user.id, {
lastQuery: query,
result: response,
timestamp: Date.now()
});
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction }) => {
execute: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const query = interaction.options.getString('query');
const queue = useQueue(interaction.guild.id);
let geniusSearchQuery = '';
if (!query) {
if (await notInVoiceChannel(interaction)) {
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack(interaction, queue)) {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
geniusSearchQuery = queue.currentTrack.title.slice(0, 50);
logger.debug(
`No input query provided, using current track. Using query for genius: '${geniusSearchQuery}'`
);
}
let searchResult;
if (query) {
logger.debug(`Query input provided, using query '${query}' for player.search().`);
const player = useMainPlayer();
const searchResults = await player.search(query, {
searchEngine: QueryType.SPOTIFY_SEARCH
});
if (searchResults.tracks.length === 0) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no search results found.`
);
logger.debug('No search results using player.search() found.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -108,7 +150,7 @@ module.exports = {
searchResult = searchResults.tracks[0];
geniusSearchQuery = searchResults.tracks[0].title;
logger.debug(`Using query for genius: ${geniusSearchQuery}`);
logger.debug(`Using query for genius: '${geniusSearchQuery}'`);
}
// get lyrics
@@ -117,9 +159,15 @@ module.exports = {
// try again with shorter query (some titles just have added info in the end)
if (!lyricsResult && geniusSearchQuery.length > 20) {
logger.debug(
`No Genius lyrics found for query '${geniusSearchQuery}', trying again with shorter query (20 chars).`
);
lyricsResult = await genius.search(geniusSearchQuery.slice(0, 20)).catch(() => null);
}
if (!lyricsResult && geniusSearchQuery.length > 10) {
logger.debug(
`No Genius lyrics found for query '${geniusSearchQuery}', trying again with shorter query (10 chars).`
);
lyricsResult = await genius.search(geniusSearchQuery.slice(0, 10)).catch(() => null);
}
@@ -141,14 +189,14 @@ module.exports = {
!searchResultAuthorSplitIncludesArtist
) {
lyricsResult = null;
logger.debug('Found lyrics but artist name did not match from player result.');
logger.debug('Found Genius lyrics but artist name did not match from player.search() result.');
}
}
if (!lyricsResult || !lyricsResult.lyrics) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no lyrics found.`
);
logger.debug('No matching lyrics found.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -160,16 +208,17 @@ module.exports = {
});
}
logger.debug(`Successfully found matching Genius lyrics for query '${geniusSearchQuery}'.`);
// If message length is too long, split into multiple messages
if (lyricsResult.lyrics.length > 3800) {
logger.debug(`[Shard ${interaction.guild.shardId}] Lyrics too long, splitting into multiple messages.`);
logger.debug('Lyrics text too long, splitting into multiple messages.');
const messageCount = Math.ceil(lyricsResult.lyrics.length / 3800);
for (let i = 0; i < messageCount; i++) {
logger.debuf(
`[Shard ${interaction.guild.shardId}] Lyrics, sending message ${i + 1} of ${messageCount}.`
);
logger.debuf(`Lyrics, sending message ${i + 1} of ${messageCount}.`);
const message = lyricsResult.lyrics.slice(i * 3800, (i + 1) * 3800);
if (i === 0) {
logger.debug('Responding with info embed for first message with lyrics.');
await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -184,6 +233,7 @@ module.exports = {
});
continue;
} else {
logger.debug('Sending consecutive message with lyrics.');
await interaction.channel.send({
embeds: [
new EmbedBuilder()
@@ -197,10 +247,7 @@ module.exports = {
return;
}
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and retrieved lyrics.`
);
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+47 -34
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const playerOptions = config.get('playerOptions');
@@ -15,22 +14,31 @@ module.exports = {
.setDescription('Show information about the track currently playing.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'nowplaying.js',
module: 'slashCommand',
name: '/nowplaying',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack(interaction, queue)) {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
@@ -82,7 +90,11 @@ module.exports = {
})} **\`${timestamp.total.label}\`**`;
if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') {
bar = 'No duration available.';
bar = '_No duration available._';
}
if (currentTrack.raw.live) {
bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
const nowPlayingActionRow = new ActionRowBuilder().addComponents(
@@ -102,10 +114,9 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName}, finished intializing data.`
);
logger.debug('Successfully retrieved information about the current track.');
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -117,7 +128,7 @@ module.exports = {
(queue.node.isPaused()
? '**Currently Paused**\n'
: `**${embedOptions.icons.audioPlaying} Now Playing**\n`) +
`**[${currentTrack.title}](${currentTrack.url})**` +
`**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` +
`\nRequested by: <@${currentTrack.requestedBy.id}>` +
`\n ${bar}\n\n` +
`${
@@ -141,7 +152,9 @@ module.exports = {
},
{
name: '**Track source**',
value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${currentTrack.url})**`,
value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${
currentTrack.raw.url ?? currentTrack.url
})**`,
inline: true
}
)
@@ -154,9 +167,7 @@ module.exports = {
components: [nowPlayingActionRow]
});
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName}, finished sending response.`
);
logger.debug(`User used command '${interaction.commandName}', finished sending response.`);
const collectorFilter = (i) => i.user.id === interaction.user.id;
try {
@@ -167,14 +178,14 @@ module.exports = {
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
if (confirmation.customId === 'nowplaying-skip') {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName}, received skip confirmation.`
);
logger.debug('Received skip confirmation.');
if (!queue || (queue.tracks.data.length === 0 && !queue.currentTrack)) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and tried skipping but there was no queue.`
);
logger.debug('Tried skipping track but there was no queue.');
logger.debug('Responding with warning embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
@@ -189,8 +200,10 @@ module.exports = {
if (queue.currentTrack !== currentTrack) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and tried skipping but the track was already removed.`
'Tried skipping track but it is not the current track and therefore already skipped/removed.'
);
logger.debug('Responding with warning embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
@@ -208,13 +221,16 @@ module.exports = {
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped the track.');
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and skipped the track.`
);
logger.debug('Responding with success embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
@@ -223,7 +239,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` +
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**` +
`${
queue.repeatMode === 0
? ''
@@ -242,17 +260,12 @@ module.exports = {
}
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but did not respond to the skip prompt.`
);
logger.debug('Interaction response timed out.');
return;
}
logger.debug(
error,
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was an unhandled error.`
);
throw error;
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
}
}
};
+23 -12
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -14,22 +13,31 @@ module.exports = {
.setDescription('Pause or resume the current track.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'pause.js',
module: 'slashCommand',
name: '/pause',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack(interaction, queue)) {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
@@ -38,14 +46,15 @@ module.exports = {
? ''
: `\`${queue.currentTrack.duration}\``;
if (queue.currentTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
// change paused state to opposite of current state
queue.node.setPaused(!queue.node.isPaused());
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${
interaction.commandName
} and set paused state to ${queue.node.isPaused()}.`
);
logger.debug(`Set paused state to ${queue.node.isPaused()}.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -56,7 +65,9 @@ module.exports = {
.setDescription(
`**${embedOptions.icons.pauseResumed} ${
queue.node.isPaused() ? 'Paused Track' : 'Resumed track'
}**\n**${durationFormat} [${queue.currentTrack.title}](${queue.currentTrack.url})**`
}**\n**${durationFormat} [${queue.currentTrack.title}](${
queue.currentTrack.raw.url ?? queue.currentTrack.url
})**`
)
.setThumbnail(queue.currentTrack.thumbnail)
.setColor(embedOptions.colors.success)
+119 -73
View File
@@ -1,4 +1,4 @@
const logger = require('../../services/logger');
//const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
@@ -9,6 +9,14 @@ const { transformQuery } = require('../../utils/validation/searchQueryValidator'
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useMainPlayer, useQueue } = require('discord-player');
const recentQueries = new Map();
const loggerTempplate = require('../../services/logger').child({
source: 'play.js',
module: 'slashCommand',
name: '/play'
});
module.exports = {
isNew: false,
isBeta: false,
@@ -26,16 +34,30 @@ module.exports = {
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction }) => {
autocomplete: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const player = useMainPlayer();
const query = interaction.options.getString('query', true);
if (query.length < 2) {
return;
const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {};
if (lastQuery && (query.startsWith(lastQuery) || lastQuery.startsWith(query)) && Date.now() - timestamp < 500) {
logger.debug(`Responding with results from lastQuery for query '${query}'`);
return interaction.respond(results);
}
if (query.length < 3) {
logger.debug(`Responding with empty results due to < 3 length for query '${query}'`);
return interaction.respond([]);
}
const searchResults = await player.search(query);
let response = [];
logger.debug(`[Shard ${interaction.guild.shardId}] Autocomplete search responded for query: ${query}`);
let response = [];
response = searchResults.tracks.slice(0, 5).map((track) => {
if (track.url.length > 100) {
@@ -50,30 +72,44 @@ module.exports = {
};
});
recentQueries.set(interaction.user.id, {
lastQuery: query,
results: response,
timestamp: Date.now()
});
if (!response || response.length === 0) {
logger.debug(`Responding with empty results for query '${query}'`);
return interaction.respond([]);
}
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, client }) => {
if (await notInVoiceChannel(interaction, client)) {
execute: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
if (await cannotJoinVoiceOrTalk(interaction)) {
if (await cannotJoinVoiceOrTalk({ interaction, executionId })) {
return;
}
let queue = useQueue(interaction.guild.id);
if (queue && (await notInSameVoiceChannel(interaction, queue))) {
if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) {
return;
}
const player = useMainPlayer();
const query = interaction.options.getString('query');
const transformedQuery = await transformQuery(query);
const transformedQuery = await transformQuery({ query, executionId });
let searchResult;
@@ -82,13 +118,13 @@ module.exports = {
requestedBy: interaction.user
});
} catch (error) {
logger.error('[Shard ${interaction.guild.shardId}] Failed to search for track with player.search()');
logger.error(error);
logger.error(error, `Failed to search for track with player.search() with query: ${transformedQuery}.`);
}
if (!searchResult || searchResult.tracks.length === 0) {
logger.debug(`[Shard ${interaction.guild.shardId}] No results found for query: ${query}`);
logger.debug(`No results found for query: '${query}'`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -100,34 +136,13 @@ module.exports = {
});
}
/* seems to be supported with @distube/ytdl-core, keeping it commented out to test functionality
if (
searchResult.tracks[0].raw.live &&
searchResult.tracks[0].raw.duration === 0 &&
searchResult.tracks[0].source === 'youtube'
) {
logger.debug(
`[Shard ${interaction.guild.shardId}] Unsupported audio source. Query: ${query}. Track is live, 0 duration and from YouTube.`
);
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Unsupported audio source**\nYouTube live streams are currently not supported. This is due to issues with extracting audio from the livestream.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.warning)
]
});
}
*/
queue = useQueue(interaction.guild.id);
let queueSize = queue?.size ?? 0;
if ((searchResult.playlist && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) {
logger.debug(`[Shard ${interaction.guild.shardId}] Playlist found but too many tracks. Query: ${query}.`);
logger.debug(`Playlist found but would exceed max queue size. Query: '${query}'.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -142,6 +157,8 @@ module.exports = {
let track;
try {
logger.debug(`Attempting to add track with player.play(). Query: '${query}'.`);
({ track } = await player.play(interaction.member.voice.channel, searchResult, {
requestedBy: interaction.user,
nodeOptions: {
@@ -164,13 +181,11 @@ module.exports = {
}
}
}));
logger.debug(`[Shard ${interaction.guild.shardId}] player.play() successful. Query: ${query}.`);
} catch (error) {
if (error.message.includes('Sign in to confirm your age')) {
logger.debug(
`[Shard ${interaction.guild.shardId}] Found track but failed to retrieve audio due to age confirmation warning.`
);
logger.debug('Found track but failed to retrieve audio due to age confirmation warning.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -183,9 +198,9 @@ module.exports = {
}
if (error.message.includes('The following content may contain')) {
logger.debug(
`[Shard ${interaction.guild.shardId}] Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.`
);
logger.debug('Found track but failed to retrieve audio due to graphic/mature/sensitive topic warning.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -203,11 +218,9 @@ module.exports = {
error.message.includes('Failed to fetch resources for ytdl streaming'))) ||
error.message.includes('Could not extract stream for this track')
) {
logger.debug(
error,
`[Shard ${interaction.guild.shardId}] Found track but failed to retrieve audio. Query: ${query}.`
);
logger.debug(error, `Found track but failed to retrieve audio. Query: ${query}.`);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -215,13 +228,15 @@ module.exports = {
`**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nAfter finding a result, I was unable to retrieve audio for the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
if (error.message === 'Cancelled') {
logger.debug(error, `[Shard ${interaction.guild.shardId}] Operation cancelled. Query: ${query}.`);
logger.debug(error, `Operation cancelled. Query: ${query}.`);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -229,23 +244,39 @@ module.exports = {
`**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and the operation was cancelled.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
logger.error(
error,
'[Shard ${interaction.guild.shardId}] Failed to play track with player.play(), unhandled error.'
);
if (error.message === 'Cannot read properties of null (reading \'createStream\')') {
// Can happen if /play then /leave before track starts playing
logger.warn(error, 'Found track but failed to play back audio. Voice connection might be unavailable.');
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nSomething unexpected happened and it was not possible to start playing the track. This could happen if the voice connection is lost or queue is destroyed while adding the track.\n\nYou can try to perform the command again.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
logger.error(error, 'Failed to play track with player.play(), unhandled error.');
}
logger.debug(`Successfully added track with player.play(). Query: '${query}'.`);
queue = useQueue(interaction.guild.id);
if (!queue) {
logger.warn(
`[Shard ${interaction.guild.shardId}] After player.play(), queue is undefined. Query: ${query}.`
);
logger.warn(`After player.play(), queue is undefined. Query: '${query}'.`);
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -253,22 +284,34 @@ module.exports = {
`**${embedOptions.icons.error} Uh-oh... Failed to add track!**\nThere was an issue adding this track to the queue.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
if (track.source === 'arbitrary' || !track.thumnail) {
track.thumbnail =
'https://raw.githubusercontent.com/mariusbegby/cadence-discord-bot/main/assets/logo-rounded-128px.png';
if (
track.source.length === 0 ||
track.source === 'arbitrary' ||
track.thumnail === null ||
track.thumbnail === undefined ||
track.thumbnail === ''
) {
logger.debug(
`Track found but source is arbitrary or missing thumbnail. Using fallback thumbnail url. Query: '${query}'.`
);
track.thumbnail = embedOptions.info.fallbackThumbnailUrl;
}
let durationFormat = track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(
`[Shard ${interaction.guild.shardId}] Playlist found and added with player.play(). Query: ${query}.`
);
if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(`Playlist found and added with player.play(). Query: '${query}'`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -279,7 +322,7 @@ module.exports = {
.setDescription(
`**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${
track.title
}](${track.url})**\n\nAnd **${
}](${track.raw.url ?? track.url})**\n\nAnd **${
searchResult.tracks.length - 1
}** more tracks... **\`/queue\`** to view all.`
)
@@ -290,10 +333,9 @@ module.exports = {
}
if (queue.currentTrack === track && queue.tracks.data.length === 0) {
logger.debug(
`[Shard ${interaction.guild.shardId}] Track found and added with player.play(), started playing. Query: ${query}.`
);
logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -303,7 +345,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${track.title}](${track.url})**`
`**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${
track.title
}](${track.raw.url ?? track.url})**`
)
.setThumbnail(track.thumbnail)
.setColor(embedOptions.colors.success)
@@ -311,9 +355,9 @@ module.exports = {
});
}
logger.debug(
`[Shard ${interaction.guild.shardId}] Track found and added with player.play(), added to queue. Query: ${query}.`
);
logger.debug(`Track found and added with player.play(), added to queue. Query: '${query}'.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -322,7 +366,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${track.url})**`
`${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${
track.raw.url ?? track.url
})**`
)
.setThumbnail(track.thumbnail)
.setColor(embedOptions.colors.success)
+39 -21
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const playerOptions = config.get('playerOptions');
@@ -15,14 +14,23 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false)
.addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'queue.js',
module: 'slashCommand',
name: '/queue',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
@@ -31,9 +39,9 @@ module.exports = {
if (!queue) {
if (pageIndex >= 1) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no queue.`
);
logger.debug(`There is no queue and user tried to access page ${pageIndex + 1}.`);
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -47,10 +55,10 @@ module.exports = {
});
}
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no queue.`
);
logger.debug('There is no queue, displaying empty queue.');
queueString = 'The queue is empty, add some tracks with **`/play`**!';
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -71,10 +79,9 @@ module.exports = {
const totalPages = Math.ceil(queueLength / 10) || 1;
if (pageIndex > totalPages - 1) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but page was higher than total pages.`
);
logger.debug('Specified page was higher than total pages.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -89,6 +96,7 @@ module.exports = {
}
if (queue.tracks.data.length === 0) {
logger.debug('Queue exists but with no tracks, displaying empty queue.');
queueString = 'The queue is empty, add some tracks with **`/play`**!';
} else {
queueString = queue.tracks.data
@@ -97,7 +105,13 @@ module.exports = {
let durationFormat =
track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
return `**${pageIndex * 10 + index + 1}.** **${durationFormat} [${track.title}](${track.url})**`;
if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
return `**${pageIndex * 10 + index + 1}.** **${durationFormat} [${track.title}](${
track.raw.url ?? track.url
})**`;
})
.join('\n');
}
@@ -122,10 +136,9 @@ module.exports = {
}`;
if (!currentTrack) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no current track.`
);
logger.debug('Queue exists but there is no current track.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -143,6 +156,7 @@ module.exports = {
]
});
} else {
logger.debug('Queue exists with current track, gathering information.');
const timestamp = queue.node.getTimestamp();
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false,
@@ -157,9 +171,11 @@ module.exports = {
bar = '_No duration available._';
}
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and got queue in reply with current track.`
);
if (currentTrack.raw.live) {
bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -169,7 +185,9 @@ module.exports = {
})
.setDescription(
`**${embedOptions.icons.audioPlaying} Now playing**\n` +
(currentTrack ? `**[${currentTrack.title}](${currentTrack.url})**` : 'None') +
(currentTrack
? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
: 'None') +
`\nRequested by: <@${currentTrack.requestedBy.id}>` +
`\n ${bar}\n\n` +
`${repeatModeString}` +
+22 -12
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -21,28 +20,36 @@ module.exports = {
.setMinValue(1)
.setRequired(true)
),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'remove.js',
module: 'slashCommand',
name: '/remove',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
const removeTrackNumber = interaction.options.getNumber('tracknumber');
if (removeTrackNumber > queue.tracks.data.length) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but track number was higher than total tracks.`
);
logger.debug('Specified track number is higher than total tracks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -56,12 +63,15 @@ module.exports = {
// Remove specified track number from queue
const removedTrack = queue.node.remove(removeTrackNumber - 1);
logger.debug(`Removed track '${removedTrack.url}' from queue.`);
let durationFormat =
removedTrack.raw.duration === 0 || removedTrack.duration === '0:00' ? '' : `\`${removedTrack.duration}\``;
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and removed track.`
);
if (removedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -70,7 +80,7 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.url})**`
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.raw.url ?? removedTrack.url})**`
)
.setThumbnail(removedTrack.thumbnail)
.setColor(embedOptions.colors.success)
+26 -21
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -20,22 +19,31 @@ module.exports = {
.setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.')
.setRequired(true)
),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'seek.js',
module: 'slashCommand',
name: '/seek',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack(interaction, queue)) {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
@@ -54,10 +62,9 @@ module.exports = {
}
if (durationArray.length === 0 || durationArray.length > 3) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered an invalid duration.`
);
logger.debug('Invalid duration format input.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -83,9 +90,9 @@ module.exports = {
});
if (!validElements) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered an invalid duration after parsing duration.`
);
logger.debug('Invalid duration after parsing duration input.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -106,10 +113,9 @@ module.exports = {
const isValidDuration = regex.test(durationString);
if (!isValidDuration) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered an invalid duration after regex checks.`
);
logger.debug('Invalid duration after regex checks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -128,9 +134,9 @@ module.exports = {
const durationInMilliseconds = durationArray[0] * 3600000 + durationArray[1] * 60000 + durationArray[2] * 1000;
if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but entered a duration longer than the track.`
);
logger.debug('Duration specified is longer than the track duration.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -143,10 +149,9 @@ module.exports = {
}
queue.node.seek(durationInMilliseconds);
logger.debug(`Seeked to '${durationString}' in current track.`);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and seeked to duration.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+16 -10
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -14,31 +13,38 @@ module.exports = {
.setDescription('Shuffle tracks in the queue randomly.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'shuffle.js',
module: 'slashCommand',
name: '/shuffle',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueIsEmpty(interaction, queue)) {
if (await queueIsEmpty({ interaction, queue, executionId })) {
return;
}
queue.tracks.shuffle();
logger.debug('Shuffled queue tracks.');
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and shuffled the queue.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+40 -21
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -17,22 +16,31 @@ module.exports = {
.addNumberOption((option) =>
option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1)
),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'skip.js',
module: 'slashCommand',
name: '/skip',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack(interaction, queue)) {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
@@ -40,9 +48,9 @@ module.exports = {
if (skipToTrack) {
if (skipToTrack > queue.tracks.data.length) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but track number was higher than total tracks.`
);
logger.debug('Specified track number was higher than total tracks.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -58,11 +66,15 @@ module.exports = {
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
queue.node.skipTo(skipToTrack - 1);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and skipped to track.`
);
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skipTo(skipToTrack - 1);
logger.debug('Skipped to specified track number.');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -71,7 +83,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**`
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**`
)
.setThumbnail(skippedTrack.thumbnail)
.setColor(embedOptions.colors.success)
@@ -80,9 +94,9 @@ module.exports = {
}
} else {
if (queue.tracks.data.length === 0 && !queue.currentTrack) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no tracks in queue or current track.`
);
logger.debug('No tracks in queue and no current track.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -99,7 +113,12 @@ module.exports = {
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
if (skippedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
queue.node.skip();
logger.debug('Skipped current track.');
const loopModesFormatted = new Map([
[0, 'disabled'],
@@ -110,9 +129,7 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and skipped track.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -121,7 +138,9 @@ module.exports = {
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${skippedTrack.title}](${skippedTrack.url})**` +
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
skippedTrack.title
}](${skippedTrack.raw.url ?? skippedTrack.url})**` +
`${
queue.repeatMode === 0
? ''
+17 -10
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -13,17 +12,26 @@ module.exports = {
.setDescription('Stop playing audio and clear the track queue.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'stop.js',
module: 'slashCommand',
name: '/stop',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (!queue) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but there was no queue.`
);
logger.debug('There is no queue.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -35,7 +43,7 @@ module.exports = {
});
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
@@ -43,11 +51,10 @@ module.exports = {
queue.setRepeatMode(0);
queue.clear();
queue.node.stop();
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and cleared the queue.`
);
logger.debug('Cleared and stopped the queue.');
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+22 -17
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
@@ -21,18 +20,27 @@ module.exports = {
.setMinValue(0)
.setMaxValue(100)
),
execute: async ({ interaction }) => {
if (await notInVoiceChannel(interaction)) {
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'volume.js',
module: 'slashCommand',
name: '/volume',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
if (await queueDoesNotExist(interaction, queue)) {
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel(interaction, queue)) {
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
@@ -41,9 +49,9 @@ module.exports = {
if (!volume && volume !== 0) {
const currentVolume = queue.node.volume;
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but no volume was provided, providing info of current volume.`
);
logger.debug('No volume input was provided, showing current volume.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -56,9 +64,9 @@ module.exports = {
]
});
} else if (volume > 100 || volume < 0) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} but volume was higher than 100% or lower than 0%.`
);
logger.debug('Volume specified was higher than 100% or lower than 0%.');
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -70,11 +78,10 @@ module.exports = {
});
} else {
queue.node.setVolume(volume);
logger.debug(`Set volume to ${volume}%.`);
if (volume === 0) {
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and muted volume.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -90,9 +97,7 @@ module.exports = {
});
}
logger.debug(
`[Shard ${interaction.guild.shardId}] User used command ${interaction.commandName} and changed volume.`
);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+18 -4
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -13,15 +12,24 @@ module.exports = {
.setDescription('Show list of guilds where bot is added.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client }) => {
if (await notValidGuildId(interaction)) {
logger.debug(`[Shard ${client.shard.ids[0]}] Not a valid guild id.`);
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'guilds.js',
module: 'slashCommand',
name: '/guilds',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
let shardGuilds = [];
let totalGuildCount = 0;
logger.debug('Fetching guilds from all shards.');
await client.shard
.broadcastEval((c) => {
return c.guilds.cache.map((guild) => {
@@ -34,6 +42,8 @@ module.exports = {
totalGuildCount = shardGuilds.length;
logger.debug(`Successfully fetched ${totalGuildCount} guilds.`);
let guildListFormatted = shardGuilds
.map((guild) => {
return {
@@ -54,10 +64,14 @@ module.exports = {
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
`\n\n**Total members:** \`${totalMemberCount}\``;
logger.debug('Transformed guild into into embed description.');
if (embedDescription.length >= 4000) {
logger.debug('Embed description is too long, truncating.');
embedDescription = `${embedDescription.slice(0, 3996)}...`;
}
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.info)]
});
+35 -9
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -13,22 +12,48 @@ module.exports = {
.setDescription('Reload the bot commands.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client }) => {
if (await notValidGuildId(interaction)) {
logger.debug(`[Shard ${client.shard.ids[0]}] Not a valid guild id.`);
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'reload.js',
module: 'slashCommand',
name: '/reload',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
try {
logger.info('Reloading commands across all shards.');
logger.info(`Execution ID: ${executionId}`);
await client.shard
.broadcastEval((shardClient) => {
shardClient.registerClientCommands(shardClient);
})
.broadcastEval(
async (shardClient, { executionId }) => {
shardClient.registerClientCommands({ client: shardClient, executionId });
},
{ context: { executionId: executionId } }
)
.then(() => {
logger.info(`[Shard ${client.shard.ids[0]}] Reloaded commands across all shards.`);
logger.info('Successfully reloaded commands across all shards.');
});
} catch (error) {
logger.error(error, `[Shard ${client.shard.ids[0]}] Failed to reload commands.`);
logger.error(error, 'Failed to reload commands across shards.');
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to reload commands across shards.`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
const commands = client.commands.map((command) => {
@@ -38,6 +63,7 @@ module.exports = {
let embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands.join('\n');
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [new EmbedBuilder().setDescription(embedDescription).setColor(embedOptions.colors.success)]
});
+83 -56
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -30,71 +29,96 @@ module.exports = {
)
.addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)),
execute: async ({ interaction, client }) => {
if (await notValidGuildId(interaction)) {
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'shards.js',
module: 'slashCommand',
name: '/shards',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
let shardInfoList = [];
await client.shard
.broadcastEval((shardClient) => {
/* eslint-disable no-undef */
let playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2);
let shardInfo = {
shardId: shardClient.shard.ids[0],
memUsage: nodeProcessMemUsageInMb,
guildCount: shardClient.guilds.cache.size,
guildMemberCount: shardClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
playerStatistics: {
activeVoiceConnections: playerStats.queues.length,
totalTracks: playerStats.queues.reduce((acc, queue) => acc + queue.tracksCount, 0),
totalListeners: playerStats.queues.reduce((acc, queue) => acc + queue.listeners, 0)
logger.debug('Fetching player statistics and client values from each shard.');
try {
await client.shard
.broadcastEval((shardClient) => {
/* eslint-disable no-undef */
let playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2);
let shardInfo = {
shardId: shardClient.shard.ids[0],
memUsage: nodeProcessMemUsageInMb,
guildCount: shardClient.guilds.cache.size,
guildMemberCount: shardClient.guilds.cache.reduce((acc, guild) => acc + guild.memberCount, 0),
playerStatistics: {
activeVoiceConnections: playerStats.queues.length,
totalTracks: playerStats.queues.reduce((acc, queue) => acc + queue.tracksCount, 0),
totalListeners: playerStats.queues.reduce((acc, queue) => acc + queue.listeners, 0)
}
};
return shardInfo;
})
.then((results) => {
shardInfoList = results;
switch (interaction.options.getString('sort')) {
case 'memory':
shardInfoList = shardInfoList.sort((a, b) => b.memUsage - a.memUsage);
break;
case 'connections':
shardInfoList = shardInfoList.sort(
(a, b) =>
b.playerStatistics.activeVoiceConnections -
a.playerStatistics.activeVoiceConnections
);
break;
case 'tracks':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalTracks - a.playerStatistics.totalTracks
);
break;
case 'listeners':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalListeners - a.playerStatistics.totalListeners
);
break;
case 'guilds':
shardInfoList = shardInfoList.sort((a, b) => b.guildCount - a.guildCount);
break;
case 'members':
shardInfoList = shardInfoList.sort((a, b) => b.guildMemberCount - a.guildMemberCount);
break;
default:
shardInfoList = shardInfoList.sort((a, b) => a.shardId - b.shardId);
break;
}
};
return shardInfo;
})
.then((results) => {
shardInfoList = results;
logger.debug('Successfully fetched player statistics and client values from shards.');
});
} catch (error) {
logger.error(error, 'Failed to fetch player statistics and client values from shards.');
switch (interaction.options.getString('sort')) {
case 'memory':
shardInfoList = shardInfoList.sort((a, b) => b.memUsage - a.memUsage);
break;
case 'connections':
shardInfoList = shardInfoList.sort(
(a, b) =>
b.playerStatistics.activeVoiceConnections - a.playerStatistics.activeVoiceConnections
);
break;
case 'tracks':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalTracks - a.playerStatistics.totalTracks
);
break;
case 'listeners':
shardInfoList = shardInfoList.sort(
(a, b) => b.playerStatistics.totalListeners - a.playerStatistics.totalListeners
);
break;
case 'guilds':
shardInfoList = shardInfoList.sort((a, b) => b.guildCount - a.guildCount);
break;
case 'members':
shardInfoList = shardInfoList.sort((a, b) => b.guildMemberCount - a.guildMemberCount);
break;
default:
shardInfoList = shardInfoList.sort((a, b) => a.shardId - b.shardId);
break;
}
logger.debug('Responding with error embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
logger.debug(`[Shard ${client.shard.ids[0]}] Fetched shardInfo from each shard.`);
})
.catch((error) => {
logger.error(error, `[Shard ${client.shard.ids[0]}] Failed to fetch client values from shards.`);
.setDescription(
`**${embedOptions.icons.error} Oops!**\n_Hmm.._ It seems I am unable to fetch player statistics and client values from shards.`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
const shardCount = shardInfoList.length;
const totalPages = Math.ceil(shardCount / 10) || 1;
@@ -143,6 +167,9 @@ module.exports = {
);
}
logger.debug('Successfully gathered and transformed shard information into embed fields.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+21 -5
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
@@ -16,13 +15,22 @@ module.exports = {
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client }) => {
if (await notValidGuildId(interaction)) {
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'systemstatus.js',
module: 'slashCommand',
name: '/systemstatus',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
// from normal /status command
const uptimeString = await getUptimeFormatted();
const uptimeString = await getUptimeFormatted({ executionId });
const usedMemoryInMB = Math.ceil((await osu.mem.info()).usedMemMb).toLocaleString('en-US');
const cpuUsage = await osu.cpu.usage();
const releaseVersion = version;
@@ -45,6 +53,7 @@ module.exports = {
const mediaplexVersion = dependencies['mediaplex'];
const distubeYtdlVersion = dependencies['@distube/ytdl-core'];
logger.debug('Fetching player statistics from all shards.');
await client.shard
.broadcastEval(() => {
/* eslint-disable no-undef */
@@ -67,8 +76,11 @@ module.exports = {
activeVoiceConnections = queueCountList.reduce((acc, queueAmount) => acc + queueAmount, 0);
totalTracks = trackCountList.reduce((acc, trackAmount) => acc + trackAmount, 0);
totalListeners = listenerCountList.reduce((acc, listenerAmount) => acc + listenerAmount, 0);
logger.debug('Successfully fetched player statistics from shards.');
});
logger.debug('Fetching client values from all shards.');
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
@@ -78,9 +90,10 @@ module.exports = {
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards.');
})
.catch((error) => {
logger.error(error, `[Shard ${client.shard.ids[0]}] Failed to fetch client values from shards.`);
logger.error(error, 'Failed to fetch client values from shards.');
});
const botStatusString =
@@ -111,6 +124,9 @@ module.exports = {
const discordStatusString = `**${client.ws.ping} ms** Discord API latency`;
logger.debug('Transformed system status into embed description.');
logger.debug('Responding with info embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
+10 -1
View File
@@ -1,4 +1,4 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
const { Events } = require('discord.js');
module.exports = {
@@ -6,6 +6,15 @@ module.exports = {
isDebug: true,
once: false,
execute: async (message) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'debug.js',
module: 'event',
name: 'clientDebug',
executionId: executionId
});
logger.debug(message);
}
};
+12 -2
View File
@@ -1,4 +1,4 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
const config = require('config');
const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
@@ -9,7 +9,17 @@ module.exports = {
isDebug: false,
once: false,
execute: async (client) => {
logger.warn(`[Shard ${client.shard.ids[0]}] ${client.user.tag} lost connection to Discord APIs. Disconnected.`);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'disconnect.js',
module: 'event',
name: 'clientDisconnect',
executionId: executionId,
shardId: client.shard.ids[0]
});
logger.warn(`${client.user.tag} lost connection to Discord APIs. Disconnected.`);
// send message to system message channel for event
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
+10 -1
View File
@@ -1,4 +1,4 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
const { Events } = require('discord.js');
module.exports = {
@@ -6,6 +6,15 @@ module.exports = {
isDebug: false,
once: false,
execute: async (error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'error.js',
module: 'event',
name: 'clientError',
executionId: executionId
});
logger.error(error);
}
};
+13 -2
View File
@@ -1,11 +1,22 @@
const logger = require('../../services/logger');
const { Events } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: Events.GuildCreate,
isDebug: false,
once: false,
execute: async (guild) => {
logger.info(`[Shard ${guild.shardId}] Added to guild '${guild.name}' with ${guild.memberCount} members.`);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'guildCreate.js',
module: 'event',
name: 'guildCreate',
executionId: executionId,
shardId: guild.shardId,
guildId: guild.id
});
logger.info(`Added to guild '${guild.id}' with ${guild.memberCount} members.`);
}
};
+13 -4
View File
@@ -1,13 +1,22 @@
const logger = require('../../services/logger');
const { Events } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: Events.GuildDelete,
isDebug: false,
once: false,
execute: async (guild) => {
logger.info(
`[Shard ${guild.shardId}] Removed from guild '${guild.name}' with ${guild.memberCount} members.`
);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'guildDelete.js',
module: 'event',
name: 'guildDelete',
executionId: executionId,
shardId: guild.shardId,
guildId: guild.id
});
logger.info(`Removed from guild '${guild.id}' with ${guild.memberCount} members.`);
}
};
+16 -8
View File
@@ -1,4 +1,3 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
@@ -7,27 +6,36 @@ const loadTestOptions = config.get('loadTestOptions');
const { postBotStats } = require('../../utils/other/postBotStats.js');
const { startLoadTest } = require('../../utils/other/startLoadTest');
const { Events, EmbedBuilder } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: Events.ClientReady,
isDebug: false,
once: false,
execute: async (client) => {
logger.debug(`[Shard ${client.shard.ids[0]}] Client 'ready' event emitted after 'allShardsReady'.`);
await client.user.setPresence(presenceStatusOptions);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'ready.js',
module: 'event',
name: 'clientReady',
executionId: executionId,
shardId: client.shard.ids[0]
});
logger.debug('Client \'ready\' event received after \'allShardsReady\' event.');
await client.user.setPresence(presenceStatusOptions);
if (loadTestOptions.enabled) {
await startLoadTest(client);
logger.info('Initiating load test for bot client.');
await startLoadTest({ client, executionId });
}
const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId);
// Check if the channel exists in curent shard and send a message
if (channel) {
logger.info(
`[Shard ${client.shard.ids[0]}] ALL SHARDS READY, sending system message to channel id ${channel.id}.`
);
logger.debug(`Sending system message for 'allShardsReady' to channel id ${channel.id}.`);
channel.send({
embeds: [
new EmbedBuilder()
@@ -39,6 +47,6 @@ module.exports = {
});
}
process.env.NODE_ENV === 'production' ? await postBotStats(client) : null;
process.env.NODE_ENV === 'production' ? await postBotStats({ client, executionId }) : null;
}
};
+12 -2
View File
@@ -1,4 +1,4 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
const config = require('config');
const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
@@ -9,7 +9,17 @@ module.exports = {
isDebug: false,
once: false,
execute: async (client) => {
logger.warn(`[Shard ${client.shard.ids[0]}] ${client.user.tag} is reconnecting to Discord APIs.`);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'reconnecting.js',
module: 'event',
name: 'clientReconnecting',
executionId: executionId,
shardId: client.shard.ids[0]
});
logger.warn('Client is reconnecting to Discord APIs.');
// send message to system message channel for event
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
+10 -1
View File
@@ -1,4 +1,4 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
const { Events } = require('discord.js');
module.exports = {
@@ -6,6 +6,15 @@ module.exports = {
isDebug: false,
once: false,
execute: async (warning) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'warn.js',
module: 'event',
name: 'clientWarn',
executionId: executionId
});
logger.warn(warning);
}
};
+64 -57
View File
@@ -1,19 +1,29 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
const { cannotSendMessageInChannel } = require('../../utils/validation/permissionValidator');
const { Events, EmbedBuilder } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: Events.InteractionCreate,
isDebug: false,
execute: async (interaction, { client }) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'interactionCreate.js',
module: 'event',
name: 'interactionCreate',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (interaction.isMessageComponent()) {
logger.info(
`[Shard ${interaction.guild.shardId}] Guild ${
interaction.guild.id
}> Message component interaction created for id ${interaction.customId}${
logger.debug(
`Message component interaction created for id ${interaction.customId}${
interaction.values ? ' and values ' + interaction.values : ''
}.`
);
@@ -22,97 +32,94 @@ module.exports = {
const command = client.commands.get(interaction.commandName);
if (!command) {
logger.warn(
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Interaction created but command '${interaction.commandName}' was not found.`
);
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
return;
}
if (interaction.isAutocomplete()) {
logger.debug(`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Autocomplete created.`);
logger.debug('Autocomplete interaction created.');
try {
await command.autocomplete({ interaction, client });
await command.autocomplete({ interaction, executionId });
} catch (error) {
if (
error.message === 'Unknown interaction' ||
error.message === 'Interaction has already been acknowledged.'
) {
logger.debug(
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Autocomplete failed to be responded to, unknown interaction or already acknowledged.`
'Autocomplete failed to be responded to, unknown interaction or already acknowledged.'
);
return;
} else {
logger.warn(error, `[Shard ${interaction.guild.shardId}] Autocomplete failed to execute.`);
logger.warn(error, 'Autocomplete failed to execute.');
}
return;
}
} else if (interaction.isChatInputCommand()) {
logger.debug(`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Interaction created.`);
logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`);
try {
await interaction.deferReply();
if (await cannotSendMessageInChannel(interaction)) {
if (await cannotSendMessageInChannel({ interaction, executionId })) {
return;
}
const inputTime = new Date();
await command.execute({ interaction, client });
await command.execute({ interaction, client, executionId });
const outputTime = new Date();
const executionTime = outputTime - inputTime;
logger.info(
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Command '${interaction}' executed in ${executionTime} ms.`
);
logger.info(`Command '${interaction}' executed in ${executionTime} ms.`);
} catch (error) {
logger.warn(
error,
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Command '${interaction}' throwed an unhandled error and might have failed to execute properly.`
`Command '${interaction}' throwed an unhandled error and might have failed to execute properly.`
);
if (!interaction.deferred || !interaction.replied) {
logger.warn(
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Interaction was not deferred or replied to, and an error was thrown.`
);
if (
error.message === 'Unknown interaction' ||
error.message === 'Interaction has already been acknowledged.'
) {
logger.debug('Command failed to be responded to, unknown interaction or already acknowledged.');
return;
}
if (interaction.replied) {
// If the interaction has already been replied to, most likely command executed successfully or error is already handled.
return;
} else if (interaction.deferred) {
logger.info(
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Interaction was deferred, editing reply and sending Uh-oh message.`
);
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
]
});
} else {
logger.info(
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Interaction was not deferred or replied, sending new reply with Uh-oh message.`
);
await interaction.reply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
]
});
if (!interaction.deferred || !interaction.replied) {
logger.warn('Interaction was not deferred or replied to, and an error was thrown.');
return;
}
if (interaction.replied) {
// If the interaction has already been replied to, most likely command executed successfully or error is already handled.
return;
} else if (interaction.deferred) {
logger.info('Interaction was deferred, editing reply and sending Uh-oh message.');
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
} else {
logger.info('Interaction was not deferred or replied, sending new reply with Uh-oh message.');
await interaction.reply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nThere was an unexpected error while trying to execute this command.\n\nYou can try to perform the command again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
}
}
} else {
logger.warn(
interaction,
`[Shard ${interaction.guild.shardId}] Guild ${interaction.guild.id}> Interaction created but was not a chat input or autocomplete interaction.`
);
logger.warn(interaction, 'Interaction created but was not a chat input or autocomplete interaction.');
}
}
};
+10 -1
View File
@@ -1,10 +1,19 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: 'debug',
isDebug: true,
isPlayerEvent: false,
execute: async (message) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'generalDebug.js',
module: 'event',
name: 'playerGeneralDebug',
executionId: executionId
});
logger.debug(message);
}
};
+16 -8
View File
@@ -1,9 +1,9 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
const systemOptions = config.get('systemOptions');
const { EmbedBuilder } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
// Emitted when the player queue encounters error (general error with queue)
module.exports = {
@@ -11,10 +11,18 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue, error) => {
logger.error(
error,
`[Shard ${queue.metadata.client.shard.ids[0]}] player.events.on('error'): Player queue encountered error event`
);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'generalError.js',
module: 'event',
name: 'playerGeneralError',
executionId: executionId,
shardId: queue.metadata.client.shard.ids[0],
guildId: queue.metadata.channel.guild.id
});
logger.error(error, 'player.events.on(\'error\'): Player queue encountered error event');
await queue.metadata.channel.send({
embeds: [
@@ -23,6 +31,7 @@ module.exports = {
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue related to the queue or current track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
@@ -33,15 +42,14 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('error')**\n${error.message}` +
`${embedOptions.icons.error} **player.events.on('error')**\nExecution id: ${executionId}\n${error.message}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
}
process.env.NODE_ENV === 'development' ? logger.trace(queue, 'Queue object') : null;
}
};
+10 -1
View File
@@ -1,10 +1,19 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: 'error',
isDebug: true,
isPlayerEvent: true,
execute: async (message) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'playerDebug.js',
module: 'event',
name: 'playerDebug',
executionId: executionId
});
logger.trace(message);
}
};
+16 -6
View File
@@ -1,9 +1,9 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
const systemOptions = config.get('systemOptions');
const { EmbedBuilder } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
// Emitted when the player encounters an error while streaming audio track
module.exports = {
@@ -11,10 +11,18 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue, error) => {
logger.error(
error,
`[Shard ${queue.metadata.client.shard.ids[0]}] player.events.on('playerError'): Player error while streaming track`
);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'playerError.js',
module: 'event',
name: 'playerError',
executionId: executionId,
shardId: queue.metadata.client.shard.ids[0],
guildId: queue.metadata.channel.guild.id
});
logger.error(error, 'player.events.on(\'playerError\'): Player error while streaming track');
await queue.metadata.channel.send({
embeds: [
@@ -23,6 +31,7 @@ module.exports = {
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while streaming the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
@@ -33,10 +42,11 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('playerError')**\n${error.message}` +
`${embedOptions.icons.error} **player.events.on('playerError')**\nExecution id: ${executionId}\n${error.message}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
+16 -5
View File
@@ -1,9 +1,9 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
const systemOptions = config.get('systemOptions');
const { EmbedBuilder } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
// Emitted when the audio player fails to load the stream for a track
module.exports = {
@@ -11,9 +11,18 @@ module.exports = {
isDebug: false,
isPlayerEvent: true,
execute: async (queue, track) => {
logger.error(
`[Shard ${queue.metadata.client.shard.ids[0]}] player.events.on('playerSkip'): Failed to play '${track.url}'.`
);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'playerSkip.js',
module: 'event',
name: 'playerSkip',
executionId: executionId,
shardId: queue.metadata.client.shard.ids[0],
guildId: queue.metadata.channel.guild.id
});
logger.error(`player.events.on('playerSkip'): Failed to play '${track.url}'.`);
await queue.metadata.channel.send({
embeds: [
@@ -22,6 +31,7 @@ module.exports = {
`**${embedOptions.icons.error} Uh-oh... _Something_ went wrong!**\nIt seems there was an issue while loading stream for the track.\n\nIf you performed a command, you can try again.\n\n_If this problem persists, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
@@ -32,10 +42,11 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.error} **player.events.on('playerSkip')**\n${track.url}` +
`${embedOptions.icons.error} **player.events.on('playerSkip')**\nExecution id: ${executionId}\n${track.url}` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.error)
.setFooter({ text: `Execution ID: ${executionId}` })
]
});
}
+13 -4
View File
@@ -1,13 +1,22 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: 'playerStart',
isDebug: false,
isPlayerEvent: true,
execute: async (queue, track) => {
logger.debug(
`[Shard ${queue.metadata.client.shard.ids[0]}] playerStart event: Started playing '${track.raw.source}'.`
);
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'playerStart.js',
module: 'event',
name: 'playerStart',
executionId: executionId,
shardId: queue.metadata.client.shard.ids[0],
guildId: queue.metadata.channel.guild.id
});
logger.debug(`playerStart event: Started playing '${track.url}'.`);
process.env.NODE_ENV === 'development' ? logger.trace(queue) : null;
}
};
+10 -1
View File
@@ -1,9 +1,18 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: 'uncaughtException',
isDebug: false,
execute: async (error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'uncaughtException.js',
module: 'event',
name: 'uncaughtException',
executionId: executionId
});
logger.fatal(error, 'UNCAUGHT EXCEPTION ERROR:');
return;
}
+10 -1
View File
@@ -1,9 +1,18 @@
const logger = require('../../services/logger');
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: 'unhandledRejection',
isDebug: false,
execute: async (error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
source: 'unhandledRejection.js',
module: 'event',
name: 'unhandledRejection',
executionId: executionId
});
logger.fatal(error, 'UNHANDLED REJECTION ERROR:');
return;
}
+14 -2
View File
@@ -1,7 +1,7 @@
require('dotenv').config();
const shardingOptions = require('config').get('shardingOptions');
const logger = require('./services/logger');
const { ShardingManager, ShardEvents } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
const manager = new ShardingManager('./src/bot.js', {
token: process.env.DISCORD_BOT_TOKEN,
@@ -9,14 +9,26 @@ const manager = new ShardingManager('./src/bot.js', {
});
const readyShards = new Set();
manager.on('shardCreate', (shard) => {
logger.info(`[Shard ${shard.id}] Launched shard with id ${shard.id}.`);
const executionId = uuidv4();
const logger = require('./services/logger').child({
source: 'index.js',
module: 'shardingManager',
name: 'shardingManager',
executionId: executionId,
shardId: 'manager'
});
logger.info(`Launched shard with id ${shard.id}.`);
// When all shards are ready, emit event 'allShardsReady' to all shards
shard.on(ShardEvents.Ready, () => {
readyShards.add(shard.id);
if (readyShards.size === manager.totalShards) {
manager.broadcastEval((client) => client.emit('allShardsReady'));
logger.info('All shards ready, bot is now online.');
}
});
});
+29 -2
View File
@@ -1,5 +1,7 @@
const pino = require('pino');
const config = require('config');
// Retrieve logger options from config
const loggerOptions = config.get('loggerOptions');
const targets = [
@@ -42,12 +44,37 @@ const targets = [
}
];
// Check for Loki credentials and add Loki as a target if present
if (process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) {
targets.push({
target: 'pino-loki',
level: loggerOptions.minimumLogLevel,
options: {
sync: false,
batching: false,
interval: 5,
host: process.env.LOKI_HOST || 'http://localhost:3100',
basicAuth: {
username: process.env.LOKI_AUTH_USERNAME || '',
password: process.env.LOKI_AUTH_PASSWORD || ''
}
}
});
}
const transport = pino.transport({ targets });
// Default properties for the logger, these will be added to every log entry
const defaultProperties = {
environment: process.env.NODE_ENV || 'development'
};
const logLevelConfig = {
level: loggerOptions.minimumLogLevel,
timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
base: undefined
base: defaultProperties
};
module.exports = pino(logLevelConfig, transport);
const logger = pino(logLevelConfig, transport);
module.exports = logger;
+28 -20
View File
@@ -1,11 +1,20 @@
require('dotenv').config();
const logger = require('../services/logger');
const fs = require('node:fs');
const path = require('node:path');
const { REST, Routes } = require('discord.js');
const config = require('config');
const { v4: uuidv4 } = require('uuid');
const systemOptions = config.get('systemOptions');
const executionId = uuidv4();
const logger = require('../services/logger').child({
source: 'deploySlashCommands.js',
module: 'deploy',
name: 'deploySlashCommands',
executionId: executionId
});
const slashCommands = [];
const systemCommands = [];
const commandFolders = fs.readdirSync(path.resolve('./src/commands'));
@@ -26,46 +35,45 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
(async () => {
if (!process.env.DISCORD_APPLICATION_ID || !process.env.DISCORD_BOT_TOKEN) {
logger.error('Missing required environment variables for deployment.');
logger.error('Provide valid DISCORD_APPLICATION_ID and DISCORD_BOT_TOKEN in .env file.');
logger.error(
'Missing required environment variables for deployment.\nPlease provide valid DISCORD_APPLICATION_ID and DISCORD_BOT_TOKEN in .env file.'
);
}
try {
logger.info('DEPLOYING BOT SLASH COMMANDS');
logger.info(
slashCommands.map((command) => command.name),
'Bot commands found:'
);
logger.debug(`Bot user slash commands found: ${slashCommands.map((command) => `/${command.name}`).join(', ')}`);
logger.info('Started refreshing application (/) bot commands.');
logger.info('Started refreshing user slash commands.');
await refreshCommands(Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID), slashCommands);
logger.info('Successfully refreshed application (/) bot commands.');
logger.info('Successfully refreshed user slash commands.');
} catch (error) {
logger.error(error, 'Failed to refresh application (/) bot commands.');
logger.error(error, 'Failed to refresh user slash commands.');
}
try {
logger.info('DEPLOYING SYSTEM SLASH COMMANDS');
logger.info(
systemCommands.map((systemCommand) => systemCommand.name),
'System commands found:'
logger.debug(
`Bot system slash commands found: ${systemCommands
.map((systemCommand) => `/${systemCommand.name}`)
.join(', ')}`
);
logger.info('Started refreshing application (/) system commands.');
logger.info('Started refreshing system slash commands.');
const systemGuildIds = systemOptions.systemGuildIds;
await Promise.all(
systemGuildIds.map((systemGuildId) => {
logger.info(`Refreshing system commands for guild id: ${systemGuildId}.`);
logger.debug(`Refreshing system slash command for guild id '${systemGuildId}'.`);
refreshCommands(
Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, systemGuildId),
systemCommands
);
})
);
logger.info('Successfully refreshed application (/) system commands.');
logger.info('Successfully refreshed system slash commands.');
} catch (error) {
logger.error(error, 'Failed to refresh application (/) system commands.');
logger.error('Make sure the bot is in the system guilds provided.');
logger.error(
error,
'Failed to refresh system slash commands. Make sure the bot is in the system guilds specified in \'systemOptions\'.'
);
}
})();
+11 -4
View File
@@ -1,9 +1,16 @@
const logger = require('../../services/logger');
const Discord = require('discord.js');
exports.createClient = async () => {
exports.createClient = async ({ executionId }) => {
const logger = require('../../services/logger').child({
source: 'createClient.js',
module: 'utilFactory',
name: 'createClient',
executionId: executionId,
shardId: 'client'
});
try {
logger.info('Creating Discord.js client...');
logger.debug('Creating discord.js client...');
const client = new Discord.Client({
intents: [Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildVoiceStates],
@@ -33,7 +40,7 @@ exports.createClient = async () => {
return client;
} catch (error) {
logger.error('Failed to create Discord.js client', error);
logger.error(error, 'Failed to create discord.js client');
throw error;
}
};
+12 -22
View File
@@ -1,9 +1,16 @@
const logger = require('../../services/logger');
const { Player } = require('discord-player');
exports.createPlayer = async (client) => {
exports.createPlayer = async ({ client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'createPlayer.js',
module: 'utilFactory',
name: 'createPlayer',
executionId: executionId,
shardId: client.shard.ids[0]
});
try {
logger.info(`[Shard ${client.shard.ids[0]}] Creating discord-player player...`);
logger.debug('Creating discord-player player...');
const player = new Player(client, {
useLegacyFFmpeg: false,
@@ -22,29 +29,12 @@ exports.createPlayer = async (client) => {
// primarily to be able to use it in broadcastEval and other sharding methods
global.player = player;
/* Seems to not be needed with @distube/ytdl-core, long duration videos work fine, keeping commented for now
onBeforeCreateStream(async (track) => {
if (track.source === 'youtube') {
return (
await stream(track.url, {
type: 'audio',
quality: 'high',
highWaterMark: 1 << 25,
cookie: process.env.YT_COOKIE || ''
})
).stream;
}
return null;
});
*/
await player.extractors.loadDefault();
logger.trace(`[Shard ${client.shard.ids[0]}] discord-player loaded dependencies:\n${player.scanDeps()}`);
logger.trace(`discord-player loaded dependencies:\n${player.scanDeps()}`);
return player;
} catch (error) {
logger.error(`[Shard ${client.shard.ids[0]}] Failed to create discord-player player`, error);
logger.error(error, 'Failed to create discord-player player');
throw error;
}
};
+24 -12
View File
@@ -1,22 +1,25 @@
const logger = require('../../services/logger');
const https = require('node:https');
exports.postBotStats = async (client) => {
exports.postBotStats = async ({ client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'postBotStats.js',
module: 'utilOther',
name: 'postBotStats',
executionId: executionId,
shardId: client.shard.ids[0]
});
try {
if (client.shard.ids[0] !== 0) {
return logger.debug(`[Shard ${client.shard.ids[0]}] Shard is not the first shard, not posting stats.`);
return;
}
logger.debug(
client.shard.ids,
`[Shard ${client.shard.ids[0]}] Posting stats to bot lists from client with shard id 0.`
);
let guildCount = 0;
let memberCount = 0;
let shardCount = client.shard.count;
let shardId = client.shard.ids[0];
logger.debug('Gathering data about guild and member count from shards...');
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
@@ -26,9 +29,11 @@ exports.postBotStats = async (client) => {
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards');
})
.catch((error) => {
logger.error(error, `[Shard ${client.shard.ids[0]}] Failed to fetch client values from shards.`);
logger.error(error, 'Failed to fetch client values from shards.');
});
/* eslint-disable camelcase */
@@ -112,7 +117,10 @@ exports.postBotStats = async (client) => {
}
];
logger.info(`[Shard ${client.shard.ids[0]}] Posting stats to bot lists with guildCount ${guildCount}...`);
logger.info(`Starting to post bot stats with guild count ${guildCount} and member count ${memberCount}...`);
let statusCodes = [];
sites.map((site) => {
if (site.disabled) {
return;
@@ -132,14 +140,18 @@ exports.postBotStats = async (client) => {
let request = https.request(options, (res) => {
res.statusCode === 200
? logger.info(`Request to ${site.hostname}: statusCode: ${res.statusCode}`)
? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`)
: logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`);
statusCodes.push(res.statusCode);
});
request.write(JSON.stringify(site.body));
request.end();
});
logger.info(`Successfully posted bot stats with status codes ${statusCodes.join(', ')}.`);
} catch (error) {
logger.error(error, `[Shard ${client.shard.ids[0]}] Failed to post stats to bot lists.`);
logger.error(error, 'Failed to post bot stats to sites.');
}
};
+11 -3
View File
@@ -1,15 +1,23 @@
const logger = require('../../services/logger');
const config = require('config');
const loadTestOptions = config.get('loadTestOptions');
exports.startLoadTest = async (client) => {
exports.startLoadTest = async ({ client, executionId }) => {
const logger = require('../../services/logger').child({
source: 'startLoadTest.js',
module: 'utilOther',
name: 'startLoadTest',
executionId: executionId,
shardId: client.shard.ids[0]
});
if (!loadTestOptions.enabled) {
logger.debug('Load test is disabled in options, cancelling.');
return;
}
const channelIds = loadTestOptions.channelIdsToJoin;
const track = loadTestOptions.trackUrl;
logger.info(`Starting load test in ${channelIds.length} channels.`);
logger.info(`Starting load test in ${channelIds.length} specified channels.`);
channelIds.forEach((each) => {
client.shard.broadcastEval(
+14 -8
View File
@@ -1,22 +1,28 @@
const logger = require('../services/logger');
const fs = require('node:fs');
const path = require('node:path');
const { Collection } = require('discord.js');
exports.registerClientCommands = (client) => {
logger.debug(`[Shard ${client.shard.ids[0]}] Registering client commands...`);
exports.registerClientCommands = ({ client, executionId }) => {
const logger = require('../services/logger').child({
source: 'registerClientCommands.js',
module: 'register',
name: 'registerClientCommands',
executionId: executionId,
shardId: client.shard.ids[0]
});
logger.debug('Registering client commands...');
client.commands = new Collection();
const commandFolders = fs.readdirSync(path.resolve('./src/commands'));
for (const folder of commandFolders) {
logger.trace(`Registering client commands for folder '${folder}'...`);
const commandFiles = fs
.readdirSync(path.resolve(`./src/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
try {
logger.trace(`[Shard ${client.shard.ids[0]}] Registering command ${folder}/${file}...`);
// delete command from require cache
delete require.cache[require.resolve(`../commands/${folder}/${file}`)];
@@ -25,10 +31,10 @@ exports.registerClientCommands = (client) => {
client.commands.delete(command.data.name);
client.commands.set(command.data.name, command);
} catch (error) {
logger.error(
`[Shard ${client.shard.ids[0]}] Error registering command ${folder}/${file}: ${error.message}`
);
logger.error(`Error registering command ${folder}/${file}: ${error.message}`);
}
}
}
logger.trace('Registering client commands complete.');
};
+19 -14
View File
@@ -1,12 +1,24 @@
const logger = require('../services/logger');
const fs = require('node:fs');
const path = require('node:path');
const config = require('config');
exports.registerEventListeners = (client, player) => {
logger.debug(`[Shard ${client.shard.ids[0]}] Registering event listeners...`);
const loggerOptions = config.get('loggerOptions');
exports.registerEventListeners = ({ client, player, executionId }) => {
const logger = require('../services/logger').child({
source: 'registerEventListeners.js',
module: 'register',
name: 'registerEventListeners',
executionId: executionId,
shardId: client.shard.ids[0]
});
logger.debug('Registering event listeners...');
const eventFolders = fs.readdirSync(path.resolve('./src/events'));
for (const folder of eventFolders) {
logger.trace(`Registering event listener for folder '${folder}'...`);
const eventFiles = fs
.readdirSync(path.resolve(`./src/events/${folder}`))
.filter((file) => file.endsWith('.js'));
@@ -15,7 +27,6 @@ exports.registerEventListeners = (client, player) => {
const event = require(`../events/${folder}/${file}`);
switch (folder) {
case 'client':
logger.debug(`[Shard ${client.shard.ids[0]}] Registering client event listener ${event.name}...`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
@@ -26,23 +37,17 @@ exports.registerEventListeners = (client, player) => {
break;
case 'interactions':
logger.debug(
`[Shard ${client.shard.ids[0]}] Registering interactions event listener ${event.name}...`
);
client.on(event.name, (...args) => event.execute(...args, { client }));
break;
case 'process':
logger.debug(`[Shard ${client.shard.ids[0]}] Registering process event listener ${event.name}...`);
process.on(event.name, (...args) => event.execute(...args));
break;
case 'player':
logger.debug(`[Shard ${client.shard.ids[0]}] Registering player event listener ${event.name}...`);
if (
!event.isDebug ||
process.env.NODE_ENV === 'development' ||
process.env.MINIMUM_LOG_LEVEL === 'debug'
(loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug)
) {
if (event.isPlayerEvent) {
player.events.on(event.name, (...args) => event.execute(...args));
@@ -54,10 +59,10 @@ exports.registerEventListeners = (client, player) => {
break;
default:
logger.error(
`[Shard ${client.shard.ids[0]}] Unknown event folder '${folder}' while trying to register events.`
);
logger.error(`Unknown event folder '${folder}' while trying to register events.`);
}
}
}
logger.trace('Registering event listeners complete.');
};
+7 -2
View File
@@ -1,6 +1,11 @@
const logger = require('../../services/logger');
exports.getUptimeFormatted = async ({ executionId }) => {
const logger = require('../../services/logger').child({
source: 'getUptimeFormatted.js',
module: 'utilSystem',
name: 'getUptimeFormatted',
executionId: executionId
});
exports.getUptimeFormatted = async () => {
try {
let uptimeFormattedString = '';
+26 -7
View File
@@ -1,9 +1,17 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { EmbedBuilder } = require('discord.js');
exports.cannotJoinVoiceOrTalk = async (interaction) => {
exports.cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotJoinVoiceOrTalk',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const channel = interaction.member.voice.channel;
if (!channel.joinable || !channel.speakable) {
@@ -18,7 +26,7 @@ exports.cannotJoinVoiceOrTalk = async (interaction) => {
});
logger.debug(
`User tried to use command ${interaction.commandName} but the bot had no permission to join/speak in the voice channel.`
`User tried to use command '${interaction.commandName}' but the bot had no permission to join/speak in the voice channel.`
);
return true;
}
@@ -26,13 +34,22 @@ exports.cannotJoinVoiceOrTalk = async (interaction) => {
return false;
};
exports.cannotSendMessageInChannel = async (interaction) => {
exports.cannotSendMessageInChannel = async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotSendMessageInChannel',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
const channel = interaction.channel;
// only checks if channel is viewable, as bot will have permission to send interaction replies if channel is viewable
if (!channel.viewable) {
logger.info(
`User tried to use command ${interaction.commandName} but the bot had no permission to send reply in text channel.`
`User tried to use command '${interaction.commandName}' but the bot had no permission to send reply in text channel.`
);
try {
@@ -51,8 +68,10 @@ exports.cannotSendMessageInChannel = async (interaction) => {
ephemeral: true
});
} catch (error) {
if(error.message == 'The reply to this interaction has already been sent or deferred.') {
logger.warn('Error while sending ephemereal message about insufficient permissions to send message in channel.');
if (error.message == 'The reply to this interaction has already been sent or deferred.') {
logger.warn(
'Error while sending ephemereal message about insufficient permissions to send message in channel.'
);
logger.debug(error);
} else {
logger.error(
+33 -10
View File
@@ -1,9 +1,17 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { EmbedBuilder } = require('discord.js');
exports.queueDoesNotExist = async (interaction, queue) => {
exports.queueDoesNotExist = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueDoesNotExist',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (!queue) {
await interaction.editReply({
embeds: [
@@ -15,15 +23,23 @@ exports.queueDoesNotExist = async (interaction, queue) => {
]
});
logger.debug(`User tried to use command ${interaction.commandName} but there was no queue.`);
logger.debug(`User tried to use command '${interaction.commandName}' but there was no queue.`);
return true;
}
return false;
};
exports.queueNoCurrentTrack = async (interaction, queue) => {
exports.queueNoCurrentTrack = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueNoCurrentTrack',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (!queue.currentTrack) {
await interaction.editReply({
embeds: [
@@ -35,15 +51,23 @@ exports.queueNoCurrentTrack = async (interaction, queue) => {
]
});
logger.debug(`User tried to use command ${interaction.commandName} but there was no current track.`);
logger.debug(`User tried to use command '${interaction.commandName}' but there was no current track.`);
return true;
}
return false;
};
exports.queueIsEmpty = async (interaction, queue) => {
exports.queueIsEmpty = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueIsEmpty',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (queue.tracks.data.length === 0) {
await interaction.editReply({
embeds: [
@@ -55,8 +79,7 @@ exports.queueIsEmpty = async (interaction, queue) => {
]
});
logger.debug(`User tried to use command ${interaction.commandName} but there was no tracks in the queue.`);
logger.debug(`User tried to use command '${interaction.commandName}' but there was no tracks in the queue.`);
return true;
}
+13 -7
View File
@@ -1,22 +1,28 @@
const logger = require('../../services/logger');
exports.transformQuery = async ({ query, executionId }) => {
const logger = require('../../services/logger').child({
source: 'searchQueryValidator.js',
module: 'utilValidation',
name: 'transformQuery',
executionId: executionId
});
exports.transformQuery = async (query) => {
if (query.startsWith('https://open.spotify.com/')) {
try {
// regex to check for country-based Spotify url
const regex = new RegExp(
'https://open.spotify.com/((?:[a-z]{2,4}-[a-z]{2,4}/)|(?:[a-z]{2,4}/))?track/([a-zA-Z0-9]+)'
'https://open.spotify.com/((?:[a-z]{2,4}-[a-z]{2,4}/)|(?:[a-z]{2,4}/))(track|playlist)/([a-zA-Z0-9]+)'
);
const isCountryBased = regex.test(query);
// if country-based, transform to normal Spotify url
if (isCountryBased) {
logger.debug(`Transforming country-based Spotify url to normal Spotify url from query ${query}.`);
const trackId = query.match(regex)[2];
query = `https://open.spotify.com/track/${trackId}`;
logger.debug(`Transforming country-based Spotify url to normal Spotify url from query '${query}'.`);
const type = query.match(regex)[2];
const trackId = query.match(regex)[3];
query = `https://open.spotify.com/${type}/${trackId}`;
}
} catch (error) {
logger.error(error);
logger.error(error, 'Error while validating or transforming Spotify url.');
}
}
+14 -1
View File
@@ -3,7 +3,16 @@ const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
const { EmbedBuilder } = require('discord.js');
exports.notValidGuildId = async (interaction) => {
exports.notValidGuildId = async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'systemCommandValidator.js',
module: 'utilValidation',
name: 'notValidGuildId',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (!systemOptions.systemGuildIds.includes(interaction.guildId)) {
await interaction.editReply({
embeds: [
@@ -14,6 +23,10 @@ exports.notValidGuildId = async (interaction) => {
.setColor(embedOptions.colors.warning)
]
});
logger.debug(
`User tried to use command '${interaction.commandName}' but system command cannot be executed in the specified guild.`
);
return true;
}
+22 -5
View File
@@ -1,9 +1,17 @@
const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const { EmbedBuilder } = require('discord.js');
exports.notInVoiceChannel = async (interaction) => {
exports.notInVoiceChannel = async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
source: 'voiceChannelValidator.js',
module: 'validator',
name: 'notInVoiceChannel',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (!interaction.member.voice.channel) {
await interaction.editReply({
embeds: [
@@ -15,14 +23,23 @@ exports.notInVoiceChannel = async (interaction) => {
]
});
logger.debug(`User tried to use command ${interaction.commandName} but was not in a voice channel.`);
logger.debug(`User tried to use command '${interaction.commandName}' but was not in a voice channel.`);
return true;
}
return false;
};
exports.notInSameVoiceChannel = async (interaction, queue) => {
exports.notInSameVoiceChannel = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
source: 'voiceChannelValidator.js',
module: 'utilValidation',
name: 'notInSameVoiceChannel',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
});
if (!queue || !queue.dispatcher) {
// If there is no queue or bot is not in voice channel, then there is no need to check if user is in same voice channel.
return false;
@@ -39,7 +56,7 @@ exports.notInSameVoiceChannel = async (interaction, queue) => {
]
});
logger.debug(`User tried to use command ${interaction.commandName} but was not in the same voice channel.`);
logger.debug(`User tried to use command '${interaction.commandName}' but was not in the same voice channel.`);
return true;
}