Merge pull request #182 from mariusbegby/typescript

Typescript
This commit is contained in:
Marius Begby authored and GitHub committed 2023-08-27 18:44:21 +02:00
commit 51efd162fd
77 files changed
+2409 -1295

No files matched your search

+13 -10
View File
@@ -1,12 +1,17 @@
{
"ignorePatterns": ["config/**/*.js"],
"env": {
"node": true,
"es2021": true
},
"extends": "eslint:recommended",
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest"
"ecmaVersion": "latest",
"sourceType": "module",
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint"],
"rules": {
"indent": ["error", 4, { "SwitchCase": 1 }],
"max-len": [
@@ -21,14 +26,9 @@
}
],
"linebreak-style": ["error", "windows"],
"quotes": ["error", "single"],
"quotes": ["error", "single", { "avoidEscape": true }],
"semi": ["error", "always"],
"camelcase": [
"error",
{
"properties": "always"
}
],
"camelcase": "error",
"array-bracket-spacing": ["error", "never"],
"object-curly-spacing": ["error", "always"],
"jsx-quotes": ["error", "prefer-single"],
@@ -47,6 +47,9 @@
}
],
"curly": ["error", "all"],
"no-console": ["error"]
"no-console": ["error"],
"@typescript-eslint/no-unused-vars": ["error", { "argsIgnorePattern": "^_" }],
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/ban-ts-comment": "off"
}
}
+21 -5
View File
@@ -1,5 +1,8 @@
name: Build and Push Docker Image on Release
env:
RELEASE_VERSION:
on:
release:
types: [published]
@@ -12,6 +15,17 @@ jobs:
- name: Checkout code
uses: actions/checkout@v2
- name: Setup Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Cache Docker layers
uses: actions/cache@v2
with:
path: /tmp/.buildx-cache
key: ${{ runner.os }}-buildx-${{ github.sha }}
restore-keys: |
${{ runner.os }}-buildx-
- name: Login to DockerHub
uses: docker/login-action@v1
with:
@@ -22,8 +36,10 @@ jobs:
run: echo "RELEASE_VERSION=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
- name: Build and Push Docker Image
run: |
docker build -t mariusbegby/cadence:${{ env.RELEASE_VERSION }} .
docker tag mariusbegby/cadence:${{ env.RELEASE_VERSION }} mariusbegby/cadence:latest
docker push mariusbegby/cadence:${{ env.RELEASE_VERSION }}
docker push mariusbegby/cadence:latest
uses: docker/build-push-action@v2
with:
context: .
push: true
tags: mariusbegby/cadence:${{ env.RELEASE_VERSION }}, mariusbegby/cadence:latest
cache-from: type=local,src=/tmp/.buildx-cache
cache-to: type=local,dest=/tmp/.buildx-cache
+2 -1
View File
@@ -26,5 +26,6 @@ jobs:
node-version: ${{ matrix.node-version }}
cache: 'npm'
- run: npm install -g npm@latest
- run: npm ci --legacy-peer-deps
- run: npm ci
- run: npm run eslint
- run: npm run build
+1
View File
@@ -6,3 +6,4 @@
/logs/app-*.log
/cookies.json
/cookies.txt
/dist
+11 -3
View File
@@ -13,16 +13,24 @@ RUN apk add --no-cache python3 make build-base ffmpeg
WORKDIR /cadence-discord-bot
# Copy the rest of the source files into the image.
COPY . .
COPY package*.json ./
COPY tsconfig.json ./
COPY src/ ./src/
COPY config/ ./config/
# Install dependencies from package-lock.json and omit dev dependencies
# Leverage a cache mount to /root/.npm to speed up subsequent builds.
RUN --mount=type=cache,target=/root/.npm \
npm ci
# Transpile TypeScript to JavaScript, remove dev dependencies, and install production dependencies
RUN npm run build && \
rm -rf node_modules && \
npm ci --omit=dev
# Cleanup of unneeded packages and apk cache
# Cleanup of unneeded packages, apk cache, and TypeScript source files
RUN apk del python3 make build-base && \
rm -rf /var/cache/apk/* /tmp/*
rm -rf /var/cache/apk/* /tmp/* ./src/
# Startup command to run the bot after deploying slash commands
CMD /bin/sh -c "npm run deploy && npm run start"
+1 -1
View File
@@ -114,7 +114,7 @@ module.exports.playerOptions = {
leaveOnEmpty: true,
leaveOnEmptyCooldown: 1_800_000,
leaveOnEnd: true,
leaveonEndCooldown: 1_800_000,
leaveOnEndCooldown: 1_800_000,
leaveOnStop: true,
leaveOnStopCooldown: 1_800_000,
defaultVolume: 50,
+294 -49
View File
@@ -25,8 +25,14 @@
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/config": "^3.3.0",
"@types/node": "^20.5.6",
"@types/node-os-utils": "^1.3.1",
"@types/uuid": "^9.0.2",
"@typescript-eslint/eslint-plugin": "^6.4.1",
"eslint": "^8.47.0",
"prettier-eslint": "^15.0.1"
"prettier-eslint": "^15.0.1",
"typescript": "^5.2.2"
}
},
"node_modules/@aashutoshrathi/word-wrap": {
@@ -421,6 +427,12 @@
"@types/responselike": "^1.0.0"
}
},
"node_modules/@types/config": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/@types/config/-/config-3.3.0.tgz",
"integrity": "sha512-9kZSbl3/X3TVNowLCu5HFQdQmD+4287Om55avknEYkuo6R2dDrsp/EXEHUFvfYeG7m1eJ0WYGj+cbcUIhARJAQ==",
"dev": true
},
"node_modules/@types/eslint": {
"version": "8.44.0",
"resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-8.44.0.tgz",
@@ -457,9 +469,15 @@
}
},
"node_modules/@types/node": {
"version": "20.3.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.3.3.tgz",
"integrity": "sha512-wheIYdr4NYML61AjC8MKj/2jrR/kDQri/CIpVoZwldwhnIrD/j9jIU5bJ8yBKuB2VhpFV7Ab6G2XkBjv9r9Zzw=="
"version": "20.5.6",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.5.6.tgz",
"integrity": "sha512-Gi5wRGPbbyOTX+4Y2iULQ27oUPrefaB0PxGQJnfyWN3kvEDGM3mIB5M/gQLmitZf7A9FmLeaqxD3L1CXpm3VKQ=="
},
"node_modules/@types/node-os-utils": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@types/node-os-utils/-/node-os-utils-1.3.1.tgz",
"integrity": "sha512-gokG1AaQo78X3f1KXOPAfwbhERX95XL0nhosOhwFck0hZ3BG52Mfch3oj3gAhXuUsou3lwi+ewZWjDo0wshKwQ==",
"dev": true
},
"node_modules/@types/prettier": {
"version": "2.7.3",
@@ -475,6 +493,18 @@
"@types/node": "*"
}
},
"node_modules/@types/semver": {
"version": "7.5.0",
"resolved": "https://registry.npmjs.org/@types/semver/-/semver-7.5.0.tgz",
"integrity": "sha512-G8hZ6XJiHnuhQKR7ZmysCeJWE08o8T0AXtk5darsCaTVsYZhhgUrq53jizaR2FvsoeCwJhlmwTjkXBY5Pn/ZHw==",
"dev": true
},
"node_modules/@types/uuid": {
"version": "9.0.2",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.2.tgz",
"integrity": "sha512-kNnC1GFBLuhImSnV7w4njQkUiJi0ZXUycu1rUaouPqiKlXkh77JKgdRnTAp1x5eBwcIwbtI+3otwzuIDEuDoxQ==",
"dev": true
},
"node_modules/@types/ws": {
"version": "8.5.5",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.5.tgz",
@@ -483,26 +513,63 @@
"@types/node": "*"
}
},
"node_modules/@typescript-eslint/parser": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz",
"integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==",
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-6.4.1.tgz",
"integrity": "sha512-3F5PtBzUW0dYlq77Lcqo13fv+58KDwUib3BddilE8ajPJT+faGgxmI9Sw+I8ZS22BYwoir9ZhNXcLi+S+I2bkw==",
"dev": true,
"dependencies": {
"@typescript-eslint/scope-manager": "5.62.0",
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/typescript-estree": "5.62.0",
"debug": "^4.3.4"
"@eslint-community/regexpp": "^4.5.1",
"@typescript-eslint/scope-manager": "6.4.1",
"@typescript-eslint/type-utils": "6.4.1",
"@typescript-eslint/utils": "6.4.1",
"@typescript-eslint/visitor-keys": "6.4.1",
"debug": "^4.3.4",
"graphemer": "^1.4.0",
"ignore": "^5.2.4",
"natural-compare": "^1.4.0",
"semver": "^7.5.4",
"ts-api-utils": "^1.0.1"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0"
"@typescript-eslint/parser": "^6.0.0 || ^6.0.0-alpha",
"eslint": "^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/@typescript-eslint/parser": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-6.4.1.tgz",
"integrity": "sha512-610G6KHymg9V7EqOaNBMtD1GgpAmGROsmfHJPXNLCU9bfIuLrkdOygltK784F6Crboyd5tBFayPB7Sf0McrQwg==",
"dev": true,
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "6.4.1",
"@typescript-eslint/types": "6.4.1",
"@typescript-eslint/typescript-estree": "6.4.1",
"@typescript-eslint/visitor-keys": "6.4.1",
"debug": "^4.3.4"
},
"engines": {
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"typescript": {
@@ -511,29 +578,56 @@
}
},
"node_modules/@typescript-eslint/scope-manager": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz",
"integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==",
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-6.4.1.tgz",
"integrity": "sha512-p/OavqOQfm4/Hdrr7kvacOSFjwQ2rrDVJRPxt/o0TOWdFnjJptnjnZ+sYDR7fi4OimvIuKp+2LCkc+rt9fIW+A==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/visitor-keys": "5.62.0"
"@typescript-eslint/types": "6.4.1",
"@typescript-eslint/visitor-keys": "6.4.1"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript-eslint/type-utils": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-6.4.1.tgz",
"integrity": "sha512-7ON8M8NXh73SGZ5XvIqWHjgX2f+vvaOarNliGhjrJnv1vdjG0LVIz+ToYfPirOoBi56jxAKLfsLm40+RvxVVXA==",
"dev": true,
"dependencies": {
"@typescript-eslint/typescript-estree": "6.4.1",
"@typescript-eslint/utils": "6.4.1",
"debug": "^4.3.4",
"ts-api-utils": "^1.0.1"
},
"engines": {
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/@typescript-eslint/types": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz",
"integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==",
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-6.4.1.tgz",
"integrity": "sha512-zAAopbNuYu++ijY1GV2ylCsQsi3B8QvfPHVqhGdDcbx/NK5lkqMnCGU53amAjccSpk+LfeONxwzUhDzArSfZJg==",
"dev": true,
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
@@ -541,21 +635,21 @@
}
},
"node_modules/@typescript-eslint/typescript-estree": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz",
"integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==",
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-6.4.1.tgz",
"integrity": "sha512-xF6Y7SatVE/OyV93h1xGgfOkHr2iXuo8ip0gbfzaKeGGuKiAnzS+HtVhSPx8Www243bwlW8IF7X0/B62SzFftg==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/visitor-keys": "5.62.0",
"@typescript-eslint/types": "6.4.1",
"@typescript-eslint/visitor-keys": "6.4.1",
"debug": "^4.3.4",
"globby": "^11.1.0",
"is-glob": "^4.0.3",
"semver": "^7.3.7",
"tsutils": "^3.21.0"
"semver": "^7.5.4",
"ts-api-utils": "^1.0.1"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
@@ -567,17 +661,42 @@
}
}
},
"node_modules/@typescript-eslint/visitor-keys": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz",
"integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==",
"node_modules/@typescript-eslint/utils": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-6.4.1.tgz",
"integrity": "sha512-F/6r2RieNeorU0zhqZNv89s9bDZSovv3bZQpUNOmmQK1L80/cV4KEu95YUJWi75u5PhboFoKUJBnZ4FQcoqhDw==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"eslint-visitor-keys": "^3.3.0"
"@eslint-community/eslint-utils": "^4.4.0",
"@types/json-schema": "^7.0.12",
"@types/semver": "^7.5.0",
"@typescript-eslint/scope-manager": "6.4.1",
"@typescript-eslint/types": "6.4.1",
"@typescript-eslint/typescript-estree": "6.4.1",
"semver": "^7.5.4"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^7.0.0 || ^8.0.0"
}
},
"node_modules/@typescript-eslint/visitor-keys": {
"version": "6.4.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-6.4.1.tgz",
"integrity": "sha512-y/TyRJsbZPkJIZQXrHfdnxVnxyKegnpEvnRGNam7s3TRR2ykGefEWOhaef00/UUN3IZxizS7BTO3svd3lCOJRQ==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "6.4.1",
"eslint-visitor-keys": "^3.4.1"
},
"engines": {
"node": "^16.0.0 || >=18.0.0"
},
"funding": {
"type": "opencollective",
@@ -1476,9 +1595,9 @@
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
},
"node_modules/fast-glob": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.0.tgz",
"integrity": "sha512-ChDuvbOypPuNjO8yIDf36x7BlZX1smcUMTTcyoIjycexOxd6DFsKsg21qVBzEmr3G7fUKIRy2/psii+CIUt7FA==",
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz",
"integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==",
"dev": true,
"dependencies": {
"@nodelib/fs.stat": "^2.0.2",
@@ -3002,6 +3121,120 @@
"node": ">=10.0.0"
}
},
"node_modules/prettier-eslint/node_modules/@typescript-eslint/parser": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-5.62.0.tgz",
"integrity": "sha512-VlJEV0fOQ7BExOsHYAGrgbEiZoi8D+Bl2+f6V2RrXerRSylnp+ZBHmPvaIa8cz0Ajx7WO7Z5RqfgYg7ED1nRhA==",
"dev": true,
"dependencies": {
"@typescript-eslint/scope-manager": "5.62.0",
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/typescript-estree": "5.62.0",
"debug": "^4.3.4"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependencies": {
"eslint": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/prettier-eslint/node_modules/@typescript-eslint/scope-manager": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-5.62.0.tgz",
"integrity": "sha512-VXuvVvZeQCQb5Zgf4HAxc04q5j+WrNAtNh9OwCsCgpKqESMTu3tF/jhZ3xG6T4NZwWl65Bg8KuS2uEvhSfLl0w==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/visitor-keys": "5.62.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/prettier-eslint/node_modules/@typescript-eslint/types": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-5.62.0.tgz",
"integrity": "sha512-87NVngcbVXUahrRTqIK27gD2t5Cu1yuCXxbLcFtCzZGlfyVWWh8mLHkoxzjsB6DDNnvdL+fW8MiwPEJyGJQDgQ==",
"dev": true,
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/prettier-eslint/node_modules/@typescript-eslint/typescript-estree": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-5.62.0.tgz",
"integrity": "sha512-CmcQ6uY7b9y694lKdRB8FEel7JbU/40iSAPomu++SjLMntB+2Leay2LO6i8VnJk58MtE9/nQSFIH6jpyRWyYzA==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"@typescript-eslint/visitor-keys": "5.62.0",
"debug": "^4.3.4",
"globby": "^11.1.0",
"is-glob": "^4.0.3",
"semver": "^7.3.7",
"tsutils": "^3.21.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
},
"peerDependenciesMeta": {
"typescript": {
"optional": true
}
}
},
"node_modules/prettier-eslint/node_modules/@typescript-eslint/visitor-keys": {
"version": "5.62.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-5.62.0.tgz",
"integrity": "sha512-07ny+LHRzQXepkGg6w0mFY41fVUNBrL2Roj/++7V1txKugfjm/Ci/qSND03r2RhlJhJYMcTn9AhhSSqQp0Ysyw==",
"dev": true,
"dependencies": {
"@typescript-eslint/types": "5.62.0",
"eslint-visitor-keys": "^3.3.0"
},
"engines": {
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/prettier-eslint/node_modules/typescript": {
"version": "4.9.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=4.2.0"
}
},
"node_modules/pretty-format": {
"version": "23.6.0",
"resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-23.6.0.tgz",
@@ -3296,9 +3529,9 @@
"integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw=="
},
"node_modules/semver": {
"version": "7.5.3",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.5.3.tgz",
"integrity": "sha512-QBlUtyVk/5EeHbi7X0fw6liDZc7BBmEaSYn01fMU1OUYbf6GPsbTtd8WmnqbI20SeycoHSeiybkE/q1Q+qlThQ==",
"version": "7.5.4",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz",
"integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==",
"devOptional": true,
"dependencies": {
"lru-cache": "^6.0.0"
@@ -3546,6 +3779,18 @@
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw=="
},
"node_modules/ts-api-utils": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.0.2.tgz",
"integrity": "sha512-Cbu4nIqnEdd+THNEsBdkolnOXhg0I8XteoHaEKgvsxpsbWda4IsUut2c187HxywQCvveojow0Dgw/amxtSKVkQ==",
"dev": true,
"engines": {
"node": ">=16.13.0"
},
"peerDependencies": {
"typescript": ">=4.2.0"
}
},
"node_modules/ts-mixer": {
"version": "6.0.3",
"resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.3.tgz",
@@ -3602,16 +3847,16 @@
}
},
"node_modules/typescript": {
"version": "4.9.5",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz",
"integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==",
"version": "5.2.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz",
"integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==",
"dev": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=4.2.0"
"node": ">=14.17"
}
},
"node_modules/undici": {
+15 -8
View File
@@ -19,12 +19,13 @@
"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 ./"
"start": "node ./dist/index.js",
"start-pretty": "node ./dist/index.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"start-pretty-no-ignore": "node ./dist/index.js | pino-pretty",
"deploy": "node ./dist/utils/deploySlashCommands.js",
"deploy-pretty": "node ./dist/utils/deploySlashCommands.js | pino-pretty --ignore environment,source,module,action,name,context,executionId,shardId,guildId",
"eslint": "eslint ./src",
"build": "tsc"
},
"dependencies": {
"@discord-player/extractor": "^4.4.2-dev.1",
@@ -43,7 +44,13 @@
"uuid": "^9.0.0"
},
"devDependencies": {
"@types/config": "^3.3.0",
"@types/node": "^20.5.6",
"@types/node-os-utils": "^1.3.1",
"@types/uuid": "^9.0.2",
"@typescript-eslint/eslint-plugin": "^6.4.1",
"eslint": "^8.47.0",
"prettier-eslint": "^15.0.1"
"prettier-eslint": "^15.0.1",
"typescript": "^5.2.2"
}
}
}
-32
View File
@@ -1,32 +0,0 @@
require('dotenv').config();
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({ executionId });
const player = await createPlayer({ client, executionId });
client.on('allShardsReady', async () => {
client.registerClientCommands = registerClientCommands;
registerEventListeners({ client, player, executionId });
registerClientCommands({ client, executionId });
client.emit('ready', client);
});
client.login(process.env.DISCORD_BOT_TOKEN);
})().catch((error) => {
logger.error(error);
});
+36
View File
@@ -0,0 +1,36 @@
import 'dotenv/config';
import { Client } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from './services/logger';
import { ExtendedClient } from './types/clientTypes';
import { createClient } from './utils/factory/createClient';
import { createPlayer } from './utils/factory/createPlayer';
import { registerClientCommands } from './utils/registerClientCommands';
import { registerEventListeners } from './utils/registerEventListeners';
const executionId = uuidv4();
const logger = loggerModule.child({
source: 'bot.js',
module: 'shardingClient',
name: 'shardingClient',
executionId: executionId,
shardId: 'client'
});
(async () => {
const client: ExtendedClient = await createClient({ executionId });
const player = await createPlayer({ client, executionId });
client.on('allShardsReady', async () => {
client.registerClientCommands = registerClientCommands;
registerEventListeners({ client, player, executionId });
registerClientCommands({ client, executionId });
client.emit('ready', client as Client);
});
client.login(process.env.DISCORD_BOT_TOKEN);
})().catch((error) => {
logger.error(error);
});
@@ -1,24 +1,35 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { BotOptions, EmbedOptions } from '../../types/configTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('help')
.setDescription('Show a list of commands and their usage.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'help.js',
module: 'slashCommand',
name: '/help',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (!client || !client.commands) {
logger.error('Client is undefined or does not have commands property.');
return;
}
const commandList = client.commands
.filter((command) => {
// don't include system commands
@@ -28,9 +39,9 @@ module.exports = {
return true;
})
.map((command) => {
let params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
let beta = command.isBeta ? `${embedOptions.icons.beta} ` : '';
let newCommand = command.isNew ? `${embedOptions.icons.new} ` : '';
const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
const beta = command.isBeta ? `${embedOptions.icons.beta} ` : '';
const newCommand = command.isNew ? `${embedOptions.icons.new} ` : '';
return `- **\`/${command.data.name}\`** ${params}- ${beta}${newCommand}${command.data.description}`;
});
@@ -1,10 +1,15 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const osu = require('node-os-utils');
const { version } = require('../../../package.json');
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils';
// @ts-ignore
import { version } from '../../../package.json';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -13,25 +18,30 @@ module.exports = {
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'status.js',
module: 'slashCommand',
name: '/status',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
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;
let guildCount = 0;
let memberCount = 0;
let activeVoiceConnections = 0;
let totalTracks = 0;
let totalListeners = 0;
let guildCount: number = 0;
let memberCount: number = 0;
let activeVoiceConnections: number = 0;
let totalTracks: number = 0;
let totalListeners: number = 0;
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
await client.shard
.broadcastEval(() => {
@@ -39,9 +49,9 @@ module.exports = {
return player.generateStatistics();
})
.then((results) => {
let queueCountList = [];
let trackCountList = [];
let listenerCountList = [];
const queueCountList: number[] = [];
const trackCountList: number[] = [];
const listenerCountList: number[] = [];
results.map((result) => {
queueCountList.push(result.queues.length);
if (result.queues.length > 0) {
@@ -65,10 +75,11 @@ module.exports = {
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
results.map((guildCache) => {
const guildCaches = results as Guild[][];
guildCaches.map((guildCache: Guild[]) => {
if (guildCache) {
guildCount += guildCache.length;
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
memberCount += guildCache.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0);
}
});
-194
View File
@@ -1,194 +0,0 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const ffmpegFilterOptions = config.get('ffmpegFilterOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator');
const {
SlashCommandBuilder,
EmbedBuilder,
ActionRowBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder,
ButtonBuilder
} = require('discord.js');
const { useQueue } = require('discord-player');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('filters')
.setDescription('Toggle various audio filters during playback.')
.setDMPermission(false)
.setNSFW(false),
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, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
let filterOptions = [];
ffmpegFilterOptions.availableFilters.forEach((filter) => {
let isEnabled = false;
if (queue.filters.ffmpeg.filters.includes(filter.value)) {
isEnabled = true;
}
filterOptions.push(
new StringSelectMenuOptionBuilder()
.setLabel(filter.label)
.setDescription(filter.description)
.setValue(filter.value)
.setEmoji(filter.emoji)
.setDefault(isEnabled)
);
});
const filterSelect = new StringSelectMenuBuilder()
.setCustomId('filters')
.setPlaceholder('Select multiple options.')
.setMinValues(0)
.setMaxValues(filterOptions.length)
.addOptions(filterOptions);
const filterActionRow = new ActionRowBuilder().addComponents(filterSelect);
const disableFiltersActionRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('disable-filters')
.setLabel('Disable all filters')
.setStyle('Secondary')
.setEmoji(embedOptions.icons.disable)
);
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**Toggle filters** ${embedOptions.icons.beta}\nEnable or disable audio filters for playback from the menu.`
)
.setColor(embedOptions.colors.info)
],
components: [filterActionRow, disableFiltersActionRow]
});
const collectorFilter = (i) => i.user.id === interaction.user.id;
try {
const confirmation = await response.awaitMessageComponent({
filter: collectorFilter,
time: 300_000
});
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
queue.filters.ffmpeg.setInputArgs([
'-threads',
ffmpegFilterOptions.threadAmount,
'-reconnect',
'1',
'-reconnect_streamed',
'1',
'-reconnect_delay_max',
'10',
'-vn'
]);
// 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()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.`
)
.setColor(embedOptions.colors.success)
],
components: []
});
}
// if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion
if (
(confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) &&
!confirmation.values.includes('normalizer')
) {
confirmation.values.push('normalizer');
}
// Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values);
logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
})
.setDescription(
`**${
embedOptions.icons.success
} Filters toggled**\nNow using these filters:\n${confirmation.values
.map((enabledFilter) => {
let filter = ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value
);
return `- **${filter.emoji} ${filter.label}**`;
})
.join('\n')}`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
}
}
};
+239
View File
@@ -0,0 +1,239 @@
import config from 'config';
import { NodeResolvable, QueueFilters, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder,
GuildMember,
Interaction,
SlashCommandBuilder,
StringSelectMenuBuilder,
StringSelectMenuOptionBuilder
} from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams, CustomError } from '../../types/commandTypes';
import { EmbedOptions, FFmpegFilterOption, FFmpegFilterOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const ffmpegFilterOptions: FFmpegFilterOptions = config.get('ffmpegFilterOptions');
module.exports = {
isNew: false,
isBeta: false,
data: new SlashCommandBuilder()
.setName('filters')
.setDescription('Toggle various audio filters during playback.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.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: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
}
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
}
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
const filterOptions: StringSelectMenuOptionBuilder[] = [];
ffmpegFilterOptions.availableFilters.forEach((filter: FFmpegFilterOption) => {
let isEnabled = false;
if (queue.filters.ffmpeg.filters.includes(filter.value as keyof QueueFilters)) {
isEnabled = true;
}
filterOptions.push(
new StringSelectMenuOptionBuilder()
.setLabel(filter.label)
.setDescription(filter.description)
.setValue(filter.value)
.setEmoji(filter.emoji)
.setDefault(isEnabled)
);
});
const filterSelect = new StringSelectMenuBuilder()
.setCustomId('filters')
.setPlaceholder('Select multiple options.')
.setMinValues(0)
.setMaxValues(filterOptions.length)
.addOptions(filterOptions)
.toJSON();
const filterActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [filterSelect]
};
const disableButton = new ButtonBuilder()
.setCustomId('disable-filters')
.setLabel('Disable all filters')
.setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.disable)
.toJSON();
const disableFiltersActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow,
components: [disableButton]
};
logger.debug('Sending info embed with action row components.');
const response = await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription('**Toggle filters**\nEnable or disable audio filters for playback from the menu.')
.setColor(embedOptions.colors.info)
],
components: [filterActionRow, disableFiltersActionRow]
});
const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id;
try {
const confirmation = await response.awaitMessageComponent({
filter: collectorFilter,
time: 300_000
});
confirmation.deferUpdate();
logger.debug('Received component interaction response.');
queue.filters.ffmpeg.setInputArgs([
'-threads',
ffmpegFilterOptions.threadAmount,
'-reconnect',
'1',
'-reconnect_streamed',
'1',
'-reconnect_delay_max',
'10',
'-vn'
]);
// Reset filters before enabling provided filters
if (queue.filters.ffmpeg.filters.length > 0) {
queue.filters.ffmpeg.setFilters(false);
logger.debug('Reset queue filters.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if ('values' in confirmation) {
// if bassboost is enabled and not normalizer, also enable normalizer to avoid distrorion
if (
(confirmation.values.includes('bassboost_low') || confirmation.values.includes('bassboost')) &&
!confirmation.values.includes('normalizer')
) {
confirmation.values.push('normalizer');
}
// Enable provided filters
queue.filters.ffmpeg.toggle(confirmation.values as (keyof QueueFilters)[]);
logger.debug(`Enabled filters ${confirmation.values.join(', ')}.`);
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${
embedOptions.icons.success
} Filters toggled**\nNow using these filters:\n${confirmation.values
.map((enabledFilter: string) => {
const filter = ffmpegFilterOptions.availableFilters.find(
(filter) => enabledFilter == filter.value
);
if (!filter) {
return enabledFilter;
}
return `- **${filter.emoji} ${filter.label}**`;
})
.join('\n')}`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} else if (confirmation.customId === 'disable-filters') {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Disabled filters**\nAll audio filters have been disabled.`
)
.setColor(embedOptions.colors.success)
],
components: []
});
} else {
logger.warn('Unhandled component interaction response.');
}
} catch (error) {
if (error instanceof CustomError) {
if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.');
return;
}
if (error.message === 'Collector received no interactions before ending with reason: time') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
} else {
if (
error instanceof Error &&
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
throw error;
}
}
}
};
@@ -1,9 +1,13 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -12,21 +16,21 @@ module.exports = {
.setDescription('Clear the track queue and remove the bot from voice channel.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'leave.js',
module: 'slashCommand',
name: '/leave',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (!queue) {
logger.debug('There is already no queue.');
@@ -52,13 +56,21 @@ module.exports = {
logger.debug('Deleted the queue.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Leaving channel**\nCleared the track queue and left voice channel.\n\nTo play more music, use the **\`/play\`** command!`
@@ -1,11 +1,15 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { BotOptions, EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -26,21 +30,21 @@ module.exports = {
{ name: 'Disabled', value: '0' }
)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'loop.js',
module: 'slashCommand',
name: '/loop',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -57,7 +61,7 @@ module.exports = {
[3, 'autoplay']
]);
const mode = parseInt(interaction.options.getString('mode'));
const mode = parseInt(interaction.options.getString('mode')!);
const modeUserString = loopModesFormatted.get(mode);
const currentMode = queue.repeatMode;
const currentModeUserString = loopModesFormatted.get(currentMode);
@@ -72,7 +76,7 @@ module.exports = {
.setDescription(
`**${
currentMode === 3 ? embedOptions.icons.autoplay : embedOptions.icons.loop
} Current loop mode**\nThe looping mode is currently set to \`${currentModeUserString}\`.`
} Current loop mode**\nThe looping mode is currently set to **\`${currentModeUserString}\`**.`
)
.setColor(embedOptions.colors.info)
]
@@ -87,7 +91,7 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nLoop mode is already \`${modeUserString}\`.`
`**${embedOptions.icons.warning} Oops!**\nLoop mode is already **\`${modeUserString}\`**.`
)
.setColor(embedOptions.colors.warning)
]
@@ -108,7 +112,7 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${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})**._`
`**${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}` })
@@ -116,6 +120,14 @@ module.exports = {
});
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if (queue.repeatMode === 0) {
logger.debug('Disabled loop mode.');
@@ -124,8 +136,8 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Loop mode disabled**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${currentModeUserString} will no longer play on repeat!`
@@ -143,8 +155,8 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.autoplaying} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nWhen the queue is empty, similar tracks will start playing!`
@@ -161,8 +173,8 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.looping} Loop mode changed**\nChanging loop mode from **\`${currentModeUserString}\`** to **\`${modeUserString}\`**.\n\nThe ${modeUserString} will now play on repeat!`
@@ -1,14 +1,19 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useMainPlayer, useQueue, QueryType } = require('discord-player');
const { lyricsExtractor } = require('@discord-player/extractor');
import config from 'config';
import { NodeResolvable, QueryType, useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import { lyricsExtractor } from '@discord-player/extractor';
import loggerModule from '../../services/logger';
import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const recentQueries = new Map();
const loggerTempplate = require('../../services/logger').child({
const loggerTemplate = loggerModule.child({
source: 'lyrics.js',
module: 'slashCommand',
name: '/lyrics'
@@ -31,11 +36,11 @@ module.exports = {
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query', true);
@@ -58,7 +63,7 @@ module.exports = {
if (!lyricsResult) {
logger.debug(`No Genius lyrics found for query '${query}', using player.search() as fallback.`);
const player = useMainPlayer();
const player = useMainPlayer()!;
const searchResults = await player.search(query);
response = searchResults.tracks.slice(0, 1).map((track) => ({
name:
@@ -91,15 +96,15 @@ module.exports = {
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const query = interaction.options.getString('query');
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
let geniusSearchQuery = '';
if (!query) {
@@ -118,7 +123,7 @@ module.exports = {
if (await queueNoCurrentTrack({ interaction, queue, executionId })) {
return;
}
geniusSearchQuery = queue.currentTrack.title.slice(0, 50);
geniusSearchQuery = queue.currentTrack!.title.slice(0, 50);
logger.debug(
`No input query provided, using current track. Using query for genius: '${geniusSearchQuery}'`
@@ -128,7 +133,7 @@ module.exports = {
let searchResult;
if (query) {
logger.debug(`Query input provided, using query '${query}' for player.search().`);
const player = useMainPlayer();
const player = useMainPlayer()!;
const searchResults = await player.search(query, {
searchEngine: QueryType.SPOTIFY_SEARCH
});
@@ -215,7 +220,7 @@ module.exports = {
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(`Lyrics, sending message ${i + 1} of ${messageCount}.`);
logger.debug(`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.');
@@ -234,7 +239,7 @@ module.exports = {
continue;
} else {
logger.debug('Sending consecutive message with lyrics.');
await interaction.channel.send({
await interaction.channel!.send({
embeds: [
new EmbedBuilder()
.setDescription(`\`\`\`fix\n${message}\`\`\``)
@@ -1,11 +1,25 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const playerOptions = config.get('playerOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder, ActionRowBuilder, ButtonBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, Track, useQueue } from 'discord-player';
import {
APIActionRowComponent,
APIMessageActionRowComponent,
ButtonBuilder,
ButtonStyle,
ComponentType,
EmbedBuilder,
GuildMember,
Interaction,
SlashCommandBuilder
} from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams, TrackMetadata, CustomError } from '../../types/commandTypes';
import { EmbedOptions, PlayerOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -14,21 +28,21 @@ module.exports = {
.setDescription('Show information about the track currently playing.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'nowplaying.js',
module: 'slashCommand',
name: '/nowplaying',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -58,28 +72,27 @@ module.exports = {
['arbitrary', embedOptions.icons.sourceArbitrary]
]);
const currentTrack = queue.currentTrack;
const currentTrack: Track = queue.currentTrack!;
let author = currentTrack.author ? currentTrack.author : 'Unavailable';
if (author === 'cdn.discordapp.com') {
author = 'Unavailable';
}
let plays = currentTrack.views !== 0 ? currentTrack.views : 0;
const plays = currentTrack.views !== 0 ? currentTrack.views : 0;
if (
plays === 0 &&
currentTrack.metadata.bridge &&
currentTrack.metadata.bridge.views !== 0 &&
currentTrack.metadata.bridge.views !== undefined
) {
plays = currentTrack.metadata.bridge.views;
let displayPlays: string = plays.toLocaleString('en-US');
const metadata = currentTrack.metadata as TrackMetadata;
if (plays === 0 && metadata.bridge && metadata.bridge.views !== 0 && metadata.bridge.views !== undefined) {
displayPlays = metadata.bridge.views.toLocaleString('en-US');
} else if (plays === 0) {
plays = 'Unavailable';
displayPlays = 'Unavailable';
}
const source = sourceStringsFormatted.get(currentTrack.raw.source) ?? 'Unavailable';
const source = sourceStringsFormatted.get(currentTrack.raw.source!) ?? 'Unavailable';
const queueLength = queue.tracks.data.length;
const timestamp = queue.node.getTimestamp();
const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false,
length: playerOptions.progressBar.length ?? 12,
@@ -89,7 +102,7 @@ module.exports = {
rightChar: playerOptions.progressBar.rightChar ?? '▬'
})} **\`${timestamp.total.label}\`**`;
if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') {
if (Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00') {
bar = '_No duration available._';
}
@@ -97,13 +110,17 @@ module.exports = {
bar = `${embedOptions.icons.liveTrack} **\`LIVE\`** - Playing continuously from live source.`;
}
const nowPlayingActionRow = new ActionRowBuilder().addComponents(
new ButtonBuilder()
.setCustomId('nowplaying-skip')
.setLabel('Skip track')
.setStyle('Secondary')
.setEmoji(embedOptions.icons.nextTrack)
);
const nowPlayingButton = new ButtonBuilder()
.setCustomId('nowplaying-skip')
.setLabel('Skip track')
.setStyle(ButtonStyle.Secondary)
.setEmoji(embedOptions.icons.nextTrack)
.toJSON(); // Convert the builder to a raw object
const nowPlayingActionRow: APIActionRowComponent<APIMessageActionRowComponent> = {
type: ComponentType.ActionRow, // This might vary based on your discord.js version
components: [nowPlayingButton]
};
const loopModesFormatted = new Map([
[0, 'disabled'],
@@ -121,15 +138,15 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`,
iconURL: interaction.guild.iconURL()
name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(
(queue.node.isPaused()
? '**Currently Paused**\n'
: `**${embedOptions.icons.audioPlaying} Now Playing**\n`) +
`**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**` +
`\nRequested by: <@${currentTrack.requestedBy.id}>` +
`\nRequested by: <@${currentTrack.requestedBy?.id}>` +
`\n ${bar}\n\n` +
`${
queue.repeatMode === 0
@@ -147,12 +164,12 @@ module.exports = {
},
{
name: '**Plays**',
value: plays.toLocaleString('en-US'),
value: displayPlays,
inline: true
},
{
name: '**Track source**',
value: `**${sourceIcons.get(currentTrack.raw.source)} [${source}](${
value: `**${sourceIcons.get(currentTrack.raw.source!)} [${source}](${
currentTrack.raw.url ?? currentTrack.url
})**`,
inline: true
@@ -161,15 +178,15 @@ module.exports = {
.setFooter({
text: queueLength ? `${queueLength} other tracks in the queue...` : ' '
})
.setThumbnail(queue.currentTrack.thumbnail)
.setThumbnail(queue.currentTrack!.thumbnail)
.setColor(embedOptions.colors.info)
],
components: [nowPlayingActionRow]
components: [nowPlayingActionRow as APIActionRowComponent<APIMessageActionRowComponent>]
});
logger.debug(`User used command '${interaction.commandName}', finished sending response.`);
logger.debug('Finished sending response.');
const collectorFilter = (i) => i.user.id === interaction.user.id;
const collectorFilter = (i: Interaction) => i.user.id === interaction.user.id;
try {
const confirmation = await response.awaitMessageComponent({
filter: collectorFilter,
@@ -218,7 +235,7 @@ module.exports = {
const skippedTrack = queue.currentTrack;
let durationFormat =
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00'
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
@@ -230,13 +247,21 @@ module.exports = {
const repeatModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.followUp({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
@@ -259,13 +284,29 @@ module.exports = {
});
}
} catch (error) {
if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.');
return;
}
if (error instanceof CustomError) {
if (error.code === 'InteractionCollectorError') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
if (error.message === 'Collector received no interactions before ending with reason: time') {
logger.debug('Interaction response timed out.');
return;
}
logger.error(error, 'Unhandled error while awaiting or handling component interaction.');
return;
} else {
if (
error instanceof Error &&
error.message === 'Collector received no interactions before ending with reason: time'
) {
logger.debug('Interaction response timed out.');
return;
}
throw error;
}
}
}
};
@@ -1,10 +1,14 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -13,21 +17,21 @@ module.exports = {
.setDescription('Pause or resume the current track.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'pause.js',
module: 'slashCommand',
name: '/pause',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -41,12 +45,14 @@ module.exports = {
return;
}
let durationFormat =
queue.currentTrack.raw.duration === 0 || queue.currentTrack.duration === '0:00'
? ''
: `\`${queue.currentTrack.duration}\``;
const currentTrack = queue.currentTrack!;
if (queue.currentTrack.raw.live) {
let durationFormat =
Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00'
? ''
: `\`${currentTrack.duration}\``;
if (currentTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
@@ -54,22 +60,28 @@ module.exports = {
queue.node.setPaused(!queue.node.isPaused());
logger.debug(`Set paused state to ${queue.node.isPaused()}.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.pauseResumed} ${
queue.node.isPaused() ? 'Paused Track' : 'Resumed track'
}**\n**${durationFormat} [${queue.currentTrack.title}](${
queue.currentTrack.raw.url ?? queue.currentTrack.url
})**`
}**\n**${durationFormat} [${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
)
.setThumbnail(queue.currentTrack.thumbnail)
.setThumbnail(currentTrack.thumbnail)
.setColor(embedOptions.colors.success)
]
});
@@ -1,17 +1,20 @@
//const logger = require('../../services/logger');
const config = require('config');
const embedOptions = config.get('embedOptions');
const botOptions = config.get('botOptions');
const playerOptions = config.get('playerOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { cannotJoinVoiceOrTalk } = require('../../utils/validation/permissionValidator');
const { transformQuery } = require('../../utils/validation/searchQueryValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useMainPlayer, useQueue } = require('discord-player');
import config from 'config';
import { useMainPlayer, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandAutocompleteParams, CommandParams } from '../../types/commandTypes';
import { BotOptions, EmbedOptions, PlayerOptions } from '../../types/configTypes';
import { cannotJoinVoiceOrTalk } from '../../utils/validation/permissionValidator';
import { transformQuery } from '../../utils/validation/searchQueryValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
const recentQueries = new Map();
const loggerTempplate = require('../../services/logger').child({
const loggerTemplate = loggerModule.child({
source: 'play.js',
module: 'slashCommand',
name: '/play'
@@ -34,14 +37,14 @@ module.exports = {
.setMaxLength(500)
.setAutocomplete(true)
),
autocomplete: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
autocomplete: async ({ interaction, executionId }: CommandAutocompleteParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const player = useMainPlayer();
const player = useMainPlayer()!;
const query = interaction.options.getString('query', true);
const { lastQuery, results, timestamp } = recentQueries.get(interaction.user.id) || {};
@@ -86,11 +89,11 @@ module.exports = {
logger.debug(`Responding to autocomplete with results for query: '${query}'.`);
return interaction.respond(response);
},
execute: async ({ interaction, executionId }) => {
const logger = loggerTempplate.child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerTemplate.child({
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
@@ -101,13 +104,13 @@ module.exports = {
return;
}
let queue = useQueue(interaction.guild.id);
let queue = useQueue(interaction.guild!.id);
if (queue && (await notInSameVoiceChannel({ interaction, queue, executionId }))) {
return;
}
const player = useMainPlayer();
const query = interaction.options.getString('query');
const player = useMainPlayer()!;
const query = interaction.options.getString('query')!;
const transformedQuery = await transformQuery({ query, executionId });
@@ -129,17 +132,17 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} No track found**\nNo results found for \`${transformedQuery}\`.\n\nIf you specified a URL, please make sure it is valid and public.`
`**${embedOptions.icons.warning} No track found**\nNo results found for **\`${transformedQuery}\`**.\n\nIf you specified a URL, please make sure it is valid and public.`
)
.setColor(embedOptions.colors.warning)
]
});
}
queue = useQueue(interaction.guild.id);
let queueSize = queue?.size ?? 0;
queue = useQueue(interaction.guild!.id);
const queueSize = queue?.size ?? 0;
if ((searchResult.playlist && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) {
if ((searchResult.playlist! && searchResult.tracks.length) > playerOptions.maxQueueSize - queueSize) {
logger.debug(`Playlist found but would exceed max queue size. Query: '${query}'.`);
logger.debug('Responding with warning embed.');
@@ -159,7 +162,7 @@ module.exports = {
try {
logger.debug(`Attempting to add track with player.play(). Query: '${query}'.`);
({ track } = await player.play(interaction.member.voice.channel, searchResult, {
({ track } = await player.play((interaction.member as GuildMember).voice.channel!, searchResult, {
requestedBy: interaction.user,
nodeOptions: {
leaveOnEmpty: playerOptions.leaveOnEmpty ?? true,
@@ -182,98 +185,106 @@ module.exports = {
}
}));
} catch (error) {
if (error.message.includes('Sign in to confirm your age')) {
logger.debug('Found track but failed to retrieve audio due to age confirmation warning.');
if (error instanceof Error) {
if (error.message.includes('Sign in to confirm your age')) {
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()
.setDescription(
`**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.warning)
]
});
logger.debug('Responding with warning embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source is age restricted and requires login to access. Because of this I cannot retrieve the audio for the track.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.warning)
]
});
}
if (error.message.includes('The following content may contain')) {
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()
.setDescription(
`**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source cannot be played as the video source has a warning for graphic or sensistive topics. It requires a manual confirmation to to play the video, and because of this I am unable to extract the audio for this source.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.warning)
]
});
}
if (
error.message.includes("Cannot read properties of null (reading 'createStream')") ||
error.message.includes('Failed to fetch resources for ytdl streaming') ||
error.message.includes('Could not extract stream for this track')
) {
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()
.setDescription(
`**${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, `Operation cancelled. Query: ${query}.`);
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 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}` })
]
});
}
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.');
} else {
throw error;
}
if (error.message.includes('The following content may contain')) {
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()
.setDescription(
`**${embedOptions.icons.warning} Cannot retrieve audio for track**\nThis audio source cannot be played as the video source has a warning for graphic or sensistive topics. It requires a manual confirmation to to play the video, and because of this I am unable to extract the audio for this source.\n\n_If you think this message is incorrect, please submit a bug report in the **[support server](${botOptions.serverInviteUrl})**._`
)
.setColor(embedOptions.colors.warning)
]
});
}
if (
(error.type === 'TypeError' &&
(error.message.includes('Cannot read properties of null (reading \'createStream\')') ||
error.message.includes('Failed to fetch resources for ytdl streaming'))) ||
error.message.includes('Could not extract stream for this track')
) {
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()
.setDescription(
`**${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, `Operation cancelled. Query: ${query}.`);
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 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}` })
]
});
}
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);
queue = useQueue(interaction.guild!.id);
if (!queue) {
if (!queue || !track) {
logger.warn(`After player.play(), queue is undefined. Query: '${query}'.`);
logger.debug('Responding with error embed.');
@@ -292,7 +303,7 @@ module.exports = {
if (
track.source.length === 0 ||
track.source === 'arbitrary' ||
track.thumnail === null ||
track.thumbnail === null ||
track.thumbnail === undefined ||
track.thumbnail === ''
) {
@@ -302,7 +313,8 @@ module.exports = {
track.thumbnail = embedOptions.info.fallbackThumbnailUrl;
}
let durationFormat = track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
let durationFormat =
Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
@@ -311,13 +323,21 @@ module.exports = {
if (searchResult.playlist && searchResult.tracks.length > 1) {
logger.debug(`Playlist found and added with player.play(). Query: '${query}'`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Added playlist to queue**\n**${durationFormat} [${
@@ -335,14 +355,21 @@ module.exports = {
if (queue.currentTrack === track && queue.tracks.data.length === 0) {
logger.debug(`Track found and added with player.play(), started playing. Query: '${query}'.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name:
interaction.member.nickname || interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.audioStartedPlaying} Started playing**\n**${durationFormat} [${
@@ -357,13 +384,21 @@ module.exports = {
logger.debug(`Track found and added with player.play(), added to queue. Query: '${query}'.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`${embedOptions.icons.success} **Added to queue**\n**${durationFormat} [${track.title}](${
@@ -1,10 +1,14 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const playerOptions = config.get('playerOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions, PlayerOptions } from '../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const playerOptions: PlayerOptions = config.get('playerOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -14,21 +18,21 @@ module.exports = {
.setDMPermission(false)
.setNSFW(false)
.addNumberOption((option) => option.setName('page').setDescription('Page number of the queue').setMinValue(1)),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'queue.js',
module: 'slashCommand',
name: '/queue',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await notInSameVoiceChannel({ interaction, queue, executionId })) {
return;
@@ -46,9 +50,9 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nPage \`${
`**${embedOptions.icons.warning} Oops!**\nPage **\`${
pageIndex + 1
}\` is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!`
}\`** is not a valid page number.\n\nThe queue is currently empty, first add some tracks with **\`/play\`**!`
)
.setColor(embedOptions.colors.warning)
]
@@ -63,8 +67,8 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.guild.name,
iconURL: interaction.guild.iconURL()
name: interaction.guild!.name,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`)
.setColor(embedOptions.colors.info)
@@ -86,9 +90,9 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nPage \`${
`**${embedOptions.icons.warning} Oops!**\nPage **\`${
pageIndex + 1
}\` is not a valid page number.\n\nThere are only a total of \`${totalPages}\` pages in the queue.`
}\`** is not a valid page number.\n\nThere are only a total of **\`${totalPages}\`** pages in the queue.`
)
.setColor(embedOptions.colors.warning)
]
@@ -103,7 +107,7 @@ module.exports = {
.slice(pageIndex * 10, pageIndex * 10 + 10)
.map((track, index) => {
let durationFormat =
track.raw.duration === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
Number(track.raw.duration) === 0 || track.duration === '0:00' ? '' : `\`${track.duration}\``;
if (track.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
@@ -116,7 +120,7 @@ module.exports = {
.join('\n');
}
let currentTrack = queue.currentTrack;
const currentTrack = queue.currentTrack;
const loopModesFormatted = new Map([
[0, 'disabled'],
@@ -127,7 +131,7 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
let repeatModeString = `${
const repeatModeString = `${
queue.repeatMode === 0
? ''
: `**${
@@ -143,8 +147,8 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`,
iconURL: interaction.guild.iconURL()
name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(
`${repeatModeString}` + `**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`
@@ -157,7 +161,7 @@ module.exports = {
});
} else {
logger.debug('Queue exists with current track, gathering information.');
const timestamp = queue.node.getTimestamp();
const timestamp = queue.node.getTimestamp()!;
let bar = `**\`${timestamp.current.label}\`** ${queue.node.createProgressBar({
queue: false,
length: playerOptions.progressBar.length ?? 12,
@@ -167,7 +171,7 @@ module.exports = {
rightChar: playerOptions.progressBar.rightChar ?? '▬'
})} **\`${timestamp.total.label}\`**`;
if (currentTrack.raw.duration === 0 || currentTrack.duration === '0:00') {
if (Number(currentTrack.raw.duration) === 0 || currentTrack.duration === '0:00') {
bar = '_No duration available._';
}
@@ -180,15 +184,15 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: `Channel: ${queue.channel.name} (${queue.channel.bitrate / 1000}kbps)`,
iconURL: interaction.guild.iconURL()
name: `Channel: ${queue.channel!.name} (${queue.channel!.bitrate / 1000}kbps)`,
iconURL: interaction.guild!.iconURL() || ''
})
.setDescription(
`**${embedOptions.icons.audioPlaying} Now playing**\n` +
(currentTrack
? `**[${currentTrack.title}](${currentTrack.raw.url ?? currentTrack.url})**`
: 'None') +
`\nRequested by: <@${currentTrack.requestedBy.id}>` +
`\nRequested by: <@${currentTrack.requestedBy?.id}>` +
`\n ${bar}\n\n` +
`${repeatModeString}` +
`**${embedOptions.icons.queue} Tracks in queue**\n${queueString}`
@@ -1,10 +1,14 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -20,21 +24,21 @@ module.exports = {
.setMinValue(1)
.setRequired(true)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'remove.js',
module: 'slashCommand',
name: '/remove',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -44,7 +48,7 @@ module.exports = {
return;
}
const removeTrackNumber = interaction.options.getNumber('tracknumber');
const removeTrackNumber = interaction.options.getNumber('tracknumber')!;
if (removeTrackNumber > queue.tracks.data.length) {
logger.debug('Specified track number is higher than total tracks.');
@@ -54,7 +58,7 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nTrack \`${removeTrackNumber}\` is not a valid track number. There are a total of\`${queue.tracks.data.length}\` tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.`
`**${embedOptions.icons.warning} Oops!**\nTrack **\`${removeTrackNumber}\`** is not a valid track number. There are a total of **\`${queue.tracks.data.length}\`** tracks in the queue.\n\nView tracks added to the queue with **\`/queue\`**.`
)
.setColor(embedOptions.colors.warning)
]
@@ -62,25 +66,37 @@ module.exports = {
}
// Remove specified track number from queue
const removedTrack = queue.node.remove(removeTrackNumber - 1);
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}\``;
Number(removedTrack.raw.duration) === 0 || removedTrack.duration === '0:00'
? ''
: `\`${removedTrack.duration}\``;
if (removedTrack.raw.live) {
durationFormat = `${embedOptions.icons.liveTrack} \`LIVE\``;
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${removedTrack.raw.url ?? removedTrack.url})**`
`**${embedOptions.icons.success} Removed track**\n**${durationFormat} [${removedTrack.title}](${
removedTrack.raw.url ?? removedTrack.url
})**`
)
.setThumbnail(removedTrack.thumbnail)
.setColor(embedOptions.colors.success)
@@ -1,10 +1,14 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -19,21 +23,21 @@ module.exports = {
.setDescription('Duration in format 00:00:00 (HH:mm:ss) to seek to.')
.setRequired(true)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'seek.js',
module: 'slashCommand',
name: '/seek',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -48,7 +52,8 @@ module.exports = {
}
const durationInput = interaction.options.getString('duration');
let durationArray = durationInput.split(':');
let durationArray = durationInput!.split(':');
switch (durationArray.length) {
case 1:
@@ -61,6 +66,12 @@ module.exports = {
break;
}
durationArray = durationArray.map((value) => {
return value.padStart(2, '0');
});
const durationString = durationArray.join(':');
if (durationArray.length === 0 || durationArray.length > 3) {
logger.debug('Invalid duration format input.');
@@ -69,23 +80,17 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` +
'- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- `/seek` **`42`** - Seek to 42 seconds.'
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- **`/seek`** **`42`** - Seek to 42 seconds.'
)
.setColor(embedOptions.colors.warning)
]
});
}
durationArray = durationArray.map((value) => {
return value.padStart(2, '0');
});
const durationString = durationArray.join(':');
let validElements = durationArray.every((value) => {
const validElements = durationArray.every((value) => {
return value.length === 2;
});
@@ -97,10 +102,10 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` +
'- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- `/seek` **`42`** - Seek to 42 seconds.'
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- **`/seek`** **`42`** - Seek to 42 seconds.'
)
.setColor(embedOptions.colors.warning)
]
@@ -120,18 +125,19 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, \`${durationString}\`.\n\nPlease use the format \`HH:mm:ss\`, \`mm:ss\` or \`ss\`, where \`HH\` is hours, \`mm\` is minutes and \`ss\` is seconds.\n\n**Examples:**\n` +
'- `/seek` **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- `/seek` **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- `/seek` **`42`** - Seek to 42 seconds.'
`**${embedOptions.icons.warning} Oops!**\nYou entered an invalid duration format, **\`${durationString}\`**.\n\nPlease use the format **\`HH:mm:ss\`**, **\`mm:ss\`** or **\`ss\`**, where **\`HH\`** is hours, **\`mm\`** is minutes and **\`ss\`** is seconds.\n\n**Examples:**\n` +
'- **`/seek`** **`1:24:12`** - Seek to 1 hour, 24 minutes and 12 seconds.\n' +
'- **`/seek`** **`3:27`** - Seek to 3 minutes and 27 seconds.\n' +
'- **`/seek`** **`42`** - Seek to 42 seconds.'
)
.setColor(embedOptions.colors.warning)
]
});
}
const currentTrackMaxDurationInMs = queue.currentTrack.durationMS;
const durationInMilliseconds = durationArray[0] * 3600000 + durationArray[1] * 60000 + durationArray[2] * 1000;
const currentTrackMaxDurationInMs = queue.currentTrack!.durationMS;
const durationInMilliseconds: number =
Number(durationArray[0]) * 3600000 + Number(durationArray[1]) * 60000 + Number(durationArray[2]) * 1000;
if (durationInMilliseconds > currentTrackMaxDurationInMs - 1000) {
logger.debug('Duration specified is longer than the track duration.');
@@ -141,7 +147,11 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${queue.currentTrack.duration}\`**).`
`**${
embedOptions.icons.warning
} Oops!**\nYou entered **\`${durationString}\`**, which is a duration that is longer than the duration for the current track.\n\nPlease try a duration that is less than the duration of the track (**\`${
queue.currentTrack!.duration
}\`**).`
)
.setColor(embedOptions.colors.warning)
]
@@ -151,18 +161,26 @@ module.exports = {
queue.node.seek(durationInMilliseconds);
logger.debug(`Seeked to '${durationString}' in current track.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Seeking to duration**\nSeeking to **\`${durationString}\`** in current track.`
)
.setThumbnail(queue.currentTrack.thumbnail)
.setThumbnail(queue.currentTrack!.thumbnail)
.setColor(embedOptions.colors.success)
]
});
@@ -1,10 +1,14 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist, queueIsEmpty } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueIsEmpty } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -13,21 +17,21 @@ module.exports = {
.setDescription('Shuffle tracks in the queue randomly.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'shuffle.js',
module: 'slashCommand',
name: '/shuffle',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -44,13 +48,21 @@ module.exports = {
queue.tracks.shuffle();
logger.debug('Shuffled queue tracks.');
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.shuffled} Shuffled queue tracks**\nThe **${queue.tracks.data.length}** tracks in the queue has been shuffled.\n\nView the new queue order with **\`/queue\`**.`
@@ -1,10 +1,14 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist, queueNoCurrentTrack } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist, queueNoCurrentTrack } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -16,21 +20,21 @@ module.exports = {
.addNumberOption((option) =>
option.setName('tracknumber').setDescription('Track number to skip to in the queue.').setMinValue(1)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'skip.js',
module: 'slashCommand',
name: '/skip',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -55,15 +59,17 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nThere are only \`${queue.tracks.data.length}\` tracks in the queue. You cannot skip to track \`${skipToTrack}\`.\n\nView tracks added to the queue with **\`/queue\`**.`
`**${embedOptions.icons.warning} Oops!**\nThere are only **\`${queue.tracks.data.length}\`** tracks in the queue. You cannot skip to track **\`${skipToTrack}\`**.\n\nView tracks added to the queue with **\`/queue\`**.`
)
.setColor(embedOptions.colors.warning)
]
});
} else {
const skippedTrack = queue.currentTrack;
const skippedTrack = queue.currentTrack!;
logger.debug('Responding with warning embed.');
let durationFormat =
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00'
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
@@ -74,13 +80,21 @@ module.exports = {
queue.node.skipTo(skipToTrack - 1);
logger.debug('Skipped to specified track number.');
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
@@ -108,9 +122,10 @@ module.exports = {
});
}
const skippedTrack = queue.currentTrack;
const skippedTrack = queue.currentTrack!;
let durationFormat =
skippedTrack.raw.duration === 0 || skippedTrack.duration === '0:00'
Number(skippedTrack.raw.duration) === 0 || skippedTrack.duration === '0:00'
? ''
: `\`${skippedTrack.duration}\``;
@@ -129,13 +144,21 @@ module.exports = {
const loopModeUserString = loopModesFormatted.get(queue.repeatMode);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.skipped} Skipped track**\n**${durationFormat} [${
@@ -1,9 +1,13 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -12,21 +16,21 @@ module.exports = {
.setDescription('Stop playing audio and clear the track queue.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'stop.js',
module: 'slashCommand',
name: '/stop',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (!queue) {
logger.debug('There is no queue.');
@@ -54,13 +58,21 @@ module.exports = {
logger.debug('Cleared and stopped the queue.');
}
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.success} Stopped playing**\nStopped playing audio and cleared the track queue.\n\nTo play more music, use the **\`/play\`** command!`
@@ -1,10 +1,14 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notInVoiceChannel, notInSameVoiceChannel } = require('../../utils/validation/voiceChannelValidator');
const { queueDoesNotExist } = require('../../utils/validation/queueValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const { useQueue } = require('discord-player');
import config from 'config';
import { NodeResolvable, useQueue } from 'discord-player';
import { EmbedBuilder, GuildMember, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { queueDoesNotExist } from '../../utils/validation/queueValidator';
import { notInSameVoiceChannel, notInVoiceChannel } from '../../utils/validation/voiceChannelValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isNew: false,
isBeta: false,
@@ -20,21 +24,21 @@ module.exports = {
.setMinValue(0)
.setMaxValue(100)
),
execute: async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'volume.js',
module: 'slashCommand',
name: '/volume',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notInVoiceChannel({ interaction, executionId })) {
return;
}
const queue = useQueue(interaction.guild.id);
const queue: NodeResolvable = useQueue(interaction.guild!.id)!;
if (await queueDoesNotExist({ interaction, queue, executionId })) {
return;
@@ -58,7 +62,7 @@ module.exports = {
.setDescription(
`**${
currentVolume === 0 ? embedOptions.icons.volumeIsMuted : embedOptions.icons.volume
} Playback volume**\nThe playback volume is currently set to \`${currentVolume}%\`.`
} Playback volume**\nThe playback volume is currently set to **\`${currentVolume}%\`**.`
)
.setColor(embedOptions.colors.info)
]
@@ -71,7 +75,7 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to \`${volume}\`, please pick a value betwen \`1\`% and \`100\`%.`
`**${embedOptions.icons.warning} Oops!**\nYou cannot set the volume to **\`${volume}%\`**, please pick a value betwen **\`1%\`** and **\`100%\`**.`
)
.setColor(embedOptions.colors.warning)
]
@@ -80,17 +84,25 @@ module.exports = {
queue.node.setVolume(volume);
logger.debug(`Set volume to ${volume}%.`);
let authorName: string;
if (interaction.member instanceof GuildMember) {
authorName = interaction.member.nickname || interaction.user.username;
} else {
authorName = interaction.user.username;
}
if (volume === 0) {
logger.debug('Responding with success embed.');
return await interaction.editReply({
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to \`${volume}%\`.`
`**${embedOptions.icons.volumeMuted} Audio muted**\nPlayback audio has been muted, because volume was set to **\`${volume}%\`**.`
)
.setColor(embedOptions.colors.success)
]
@@ -102,11 +114,11 @@ module.exports = {
embeds: [
new EmbedBuilder()
.setAuthor({
name: interaction.member.nickname || interaction.user.username,
iconURL: interaction.user.avatarURL()
name: authorName,
iconURL: interaction.user.avatarURL() || ''
})
.setDescription(
`**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to \`${volume}%\`.`
`**${embedOptions.icons.volumeChanged} Volume changed**\nPlayback volume has been changed to **\`${volume}%\`**.`
)
.setColor(embedOptions.colors.success)
]
@@ -1,8 +1,12 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
isNew: false,
@@ -12,23 +16,28 @@ module.exports = {
.setDescription('Show list of guilds where bot is added.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'guilds.js',
module: 'slashCommand',
name: '/guilds',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
let shardGuilds = [];
let shardGuilds: Guild[] = [];
let totalGuildCount = 0;
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
logger.debug('Fetching guilds from all shards.');
await client.shard
.broadcastEval((c) => {
@@ -37,14 +46,14 @@ module.exports = {
});
})
.then((guilds) => {
shardGuilds = guilds.flat(1);
shardGuilds = guilds.flat(1) as Guild[];
});
totalGuildCount = shardGuilds.length;
logger.debug(`Successfully fetched ${totalGuildCount} guilds.`);
let guildListFormatted = shardGuilds
const guildListFormatted = shardGuilds
.map((guild) => {
return {
name: guild.name,
@@ -62,7 +71,7 @@ module.exports = {
`**${embedOptions.icons.bot} ${
totalGuildCount < 25 ? `Top ${totalGuildCount} guilds` : 'Top 25 guilds'
} by member count (${totalGuildCount} total)**\n${guildListFormatted}` +
`\n\n**Total members:** \`${totalMemberCount}\``;
`\n\n**Total members:** **\`${totalMemberCount}\`**`;
logger.debug('Transformed guild into into embed description.');
@@ -1,8 +1,13 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
isNew: false,
@@ -12,25 +17,34 @@ module.exports = {
.setDescription('Reload the bot commands.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'reload.js',
module: 'slashCommand',
name: '/reload',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
try {
logger.debug('Reloading commands across all shards.');
await client.shard
.broadcastEval(
async (shardClient, { executionId }) => {
async (shardClient: ExtendedClient, { executionId }) => {
if (!shardClient.registerClientCommands) {
return;
}
shardClient.registerClientCommands({ client: shardClient, executionId });
},
{ context: { executionId: executionId } }
@@ -55,12 +69,12 @@ module.exports = {
});
}
const commands = client.commands.map((command) => {
let params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
const commands = client.commands?.map((command) => {
const params = command.data.options[0] ? `**\`${command.data.options[0].name}\`**` + ' ' : '';
return `- **\`/${command.data.name}\`** ${params}- ${command.data.description}`;
});
let embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands.join('\n');
const embedDescription = `**${embedOptions.icons.bot} Reloaded commands**\n` + commands?.join('\n');
logger.debug('Responding with success embed.');
return await interaction.editReply({
@@ -1,8 +1,13 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
import config from 'config';
import { EmbedBuilder, SlashCommandBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { CommandParams, ShardInfo } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
isNew: false,
@@ -29,30 +34,42 @@ module.exports = {
)
.addNumberOption((option) => option.setName('page').setDescription('Page number to show').setMinValue(1)),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'shards.js',
module: 'slashCommand',
name: '/shards',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
return;
}
let shardInfoList = [];
let shardInfoList: ShardInfo[] = [];
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
logger.debug('Fetching player statistics and client values from each shard.');
try {
await client.shard
.broadcastEval((shardClient) => {
.broadcastEval((shardClient: ExtendedClient) => {
if (!shardClient.shard) {
return;
}
/* eslint-disable no-undef */
let playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = (process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2);
let shardInfo = {
const playerStats = player.generateStatistics();
const nodeProcessMemUsageInMb = parseFloat(
(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)
);
const shardInfo = {
shardId: shardClient.shard.ids[0],
memUsage: nodeProcessMemUsageInMb,
guildCount: shardClient.guilds.cache.size,
@@ -67,7 +84,7 @@ module.exports = {
return shardInfo;
})
.then((results) => {
shardInfoList = results;
shardInfoList = results.filter(Boolean) as ShardInfo[];
switch (interaction.options.getString('sort')) {
case 'memory':
@@ -129,7 +146,7 @@ module.exports = {
const evenShardIndexes = currentPageShards.filter((shard, index) => index % 2 === 0);
const oddShardIndexes = currentPageShards.filter((shard, index) => index % 2 !== 0);
function shardInfoToString(shard) {
function shardInfoToString(shard: ShardInfo) {
let string = '';
string += `**Shard ${shard.shardId}** - Guilds: ${shard.guildCount.toLocaleString(
'en-US'
@@ -1,10 +1,16 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { notValidGuildId } = require('../../utils/validation/systemCommandValidator');
const { getUptimeFormatted } = require('../../utils/system/getUptimeFormatted');
const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');
const osu = require('node-os-utils');
const { version, dependencies } = require('../../../package.json');
import config from 'config';
import { EmbedBuilder, Guild, SlashCommandBuilder } from 'discord.js';
import osu from 'node-os-utils';
// @ts-ignore
import { dependencies, version } from '../../../package.json';
import loggerModule from '../../services/logger';
import { CommandParams } from '../../types/commandTypes';
import { EmbedOptions } from '../../types/configTypes';
import { getUptimeFormatted } from '../../utils/system/getUptimeFormatted';
import { notValidGuildId } from '../../utils/validation/systemCommandValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
module.exports = {
isSystemCommand: true,
@@ -15,14 +21,14 @@ module.exports = {
.setDescription('Show the bot and system status.')
.setDMPermission(false)
.setNSFW(false),
execute: async ({ interaction, client, executionId }) => {
const logger = require('../../services/logger').child({
execute: async ({ interaction, client, executionId }: CommandParams) => {
const logger = loggerModule.child({
source: 'systemstatus.js',
module: 'slashCommand',
name: '/systemstatus',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (await notValidGuildId({ interaction, executionId })) {
@@ -54,15 +60,21 @@ module.exports = {
const distubeYtdlVersion = dependencies['@distube/ytdl-core'];
logger.debug('Fetching player statistics from all shards.');
if (!client || !client.shard) {
logger.error('Client is undefined or does not have shard property.');
return;
}
await client.shard
.broadcastEval(() => {
/* eslint-disable no-undef */
return player.generateStatistics();
})
.then((results) => {
let queueCountList = [];
let trackCountList = [];
let listenerCountList = [];
const queueCountList: number[] = [];
const trackCountList: number[] = [];
const listenerCountList: number[] = [];
results.map((result) => {
queueCountList.push(result.queues.length);
if (result.queues.length > 0) {
@@ -84,10 +96,11 @@ module.exports = {
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
results.map((guildCache) => {
const guildCaches = results as Guild[][];
guildCaches.map((guildCache: Guild[]) => {
if (guildCache) {
guildCount += guildCache.length;
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
memberCount += guildCache.reduce((acc: number, guild: Guild) => acc + guild.memberCount, 0);
}
});
logger.debug('Successfully fetched client values from shards.');
@@ -1,14 +1,15 @@
const { v4: uuidv4 } = require('uuid');
const { Events } = require('discord.js');
import { Events } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: Events.Debug,
isDebug: true,
once: false,
execute: async (message) => {
execute: async (message: string) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'debug.js',
module: 'event',
name: 'clientDebug',
@@ -1,35 +1,40 @@
const { v4: uuidv4 } = require('uuid');
const config = require('config');
const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
const { EmbedBuilder } = require('discord.js');
import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
module.exports = {
name: 'disconnect',
isDebug: false,
once: false,
execute: async (client) => {
execute: async (client: ExtendedClient) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'disconnect.js',
module: 'event',
name: 'clientDisconnect',
executionId: executionId,
shardId: client.shard.ids[0]
shardId: client.shard?.ids[0]
});
logger.warn(`${client.user.tag} lost connection to Discord APIs. Disconnected.`);
logger.warn(`${client.user?.tag} lost connection to Discord APIs. Disconnected.`);
// send message to system message channel for event
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId);
const channel = (await client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
await channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.warning} **${client.user.tag}** is **\`disconnected\`**!` +
`${embedOptions.icons.warning} **${client.user?.tag}** is **\`disconnected\`**!` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.warning)
@@ -1,14 +1,15 @@
const { v4: uuidv4 } = require('uuid');
const { Events } = require('discord.js');
import { Events } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: Events.Error,
isDebug: false,
once: false,
execute: async (error) => {
execute: async (error: Error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'error.js',
module: 'event',
name: 'clientError',
@@ -1,14 +1,15 @@
const { Events } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
import { Events, Guild } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: Events.GuildCreate,
isDebug: false,
once: false,
execute: async (guild) => {
execute: async (guild: Guild) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'guildCreate.js',
module: 'event',
name: 'guildCreate',
@@ -1,14 +1,15 @@
const { Events } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
import { Events, Guild } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: Events.GuildDelete,
isDebug: false,
once: false,
execute: async (guild) => {
execute: async (guild: Guild) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'guildDelete.js',
module: 'event',
name: 'guildDelete',
-56
View File
@@ -1,56 +0,0 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
const presenceStatusOptions = config.get('presenceStatusOptions');
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) => {
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) {
// Only call function from shard with id 0
// The function uses broadcastEval() to call itself on all shards
if (client.shard.ids[0] === 0) {
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.debug(`Sending system message for 'allShardsReady' to channel id ${channel.id}.`);
channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.success} All shards ready**\n**${client.user.tag}** is now **\`online\`**!`
)
.setColor(embedOptions.colors.success)
]
});
}
process.env.NODE_ENV === 'production' ? await postBotStats({ client, executionId }) : null;
}
};
+59
View File
@@ -0,0 +1,59 @@
import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder, Events, PresenceData } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { EmbedOptions, LoadTestOptions, SystemOptions } from '../../types/configTypes';
import { postBotStats } from '../../utils/other/postBotStats';
import { startLoadTest } from '../../utils/other/startLoadTest';
const embedOptions: EmbedOptions = config.get('embedOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
const presenceStatusOptions: PresenceData = config.get('presenceStatusOptions');
const loadTestOptions: LoadTestOptions = config.get('loadTestOptions');
module.exports = {
name: Events.ClientReady,
isDebug: false,
once: false,
execute: async (client: ExtendedClient) => {
const executionId = uuidv4();
const logger = loggerModule.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) {
// Only call function from shard with id 0
// The function uses broadcastEval() to call itself on all shards
if (client.shard?.ids[0] === 0) {
logger.info('Initiating load test for bot client.');
await startLoadTest({ client, executionId });
}
}
const channel = (await client.channels.cache.get(systemOptions.systemMessageChannelId)) as BaseGuildTextChannel;
// Check if the channel exists in curent shard and send a message
if (channel) {
logger.debug(`Sending system message for 'allShardsReady' to channel id ${channel.id}.`);
channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.success} All shards ready**\n**${client.user?.tag}** is now **\`online\`**!`
)
.setColor(embedOptions.colors.success)
]
});
}
process.env.NODE_ENV === 'production' ? await postBotStats({ client, executionId }) : null;
}
};
@@ -1,22 +1,25 @@
const { v4: uuidv4 } = require('uuid');
const config = require('config');
const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
const { EmbedBuilder } = require('discord.js');
import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { ExtendedClient } from '../../types/clientTypes';
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
module.exports = {
name: 'reconnecting',
isDebug: false,
once: false,
execute: async (client) => {
execute: async (client: ExtendedClient) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'reconnecting.js',
module: 'event',
name: 'clientReconnecting',
executionId: executionId,
shardId: client.shard.ids[0]
shardId: client.shard?.ids[0]
});
logger.warn('Client is reconnecting to Discord APIs.');
@@ -24,13 +27,15 @@ module.exports = {
// send message to system message channel for event
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = await client.channels.cache.get(systemOptions.systemMessageChannelId);
const channel = (await client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
await channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
`${embedOptions.icons.warning} **${client.user.tag}** is **\`reconnecting\`**!` +
`${embedOptions.icons.warning} **${client.user?.tag}** is **\`reconnecting\`**!` +
`\n\n<@${systemOptions.systemUserId}>`
)
.setColor(embedOptions.colors.warning)
@@ -1,14 +1,15 @@
const { v4: uuidv4 } = require('uuid');
const { Events } = require('discord.js');
import { Events } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: Events.Warn,
isDebug: false,
once: false,
execute: async (warning) => {
execute: async (warning: string) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'warn.js',
module: 'event',
name: 'clientWarn',
@@ -1,126 +0,0 @@
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.debug(
`Message component interaction created for id ${interaction.customId}${
interaction.values ? ' and values ' + interaction.values : ''
}.`
);
return;
}
const command = client.commands.get(interaction.commandName);
if (!command) {
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
return;
}
if (interaction.isAutocomplete()) {
logger.debug('Autocomplete interaction created.');
try {
await command.autocomplete({ interaction, executionId });
} catch (error) {
if (
error.message === 'Unknown interaction' ||
error.message === 'Interaction has already been acknowledged.'
) {
logger.debug(
'Autocomplete failed to be responded to, unknown interaction or already acknowledged.'
);
return;
} else {
logger.warn(error, 'Autocomplete failed to execute.');
}
return;
}
} else if (interaction.isChatInputCommand()) {
logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`);
try {
await interaction.deferReply();
if (await cannotSendMessageInChannel({ interaction, executionId })) {
return;
}
const inputTime = new Date();
await command.execute({ interaction, client, executionId });
const outputTime = new Date();
const executionTime = outputTime - inputTime;
logger.info(`Command '${interaction}' executed in ${executionTime} ms.`);
} catch (error) {
logger.warn(
error,
`Command '${interaction}' throwed an unhandled error and might have failed to execute properly.`
);
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;
} else {
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, 'Interaction created but was not a chat input or autocomplete interaction.');
}
}
};
@@ -0,0 +1,145 @@
import config from 'config';
import { EmbedBuilder, Events, Interaction, StringSelectMenuInteraction } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { Command, ExtendedClient } from '../../types/clientTypes';
import { BotOptions, EmbedOptions } from '../../types/configTypes';
import { cannotSendMessageInChannel } from '../../utils/validation/permissionValidator';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
module.exports = {
name: Events.InteractionCreate,
isDebug: false,
execute: async (interaction: Interaction, { client }: { client: ExtendedClient }) => {
const executionId = uuidv4();
const logger = loggerModule.child({
source: 'interactionCreate.js',
module: 'event',
name: 'interactionCreate',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (interaction.isMessageComponent()) {
if (interaction instanceof StringSelectMenuInteraction) {
logger.debug(
`Message component interaction created for id ${interaction.customId}${
interaction.values ? ' and values ' + interaction.values : ''
}.`
);
}
return;
}
if (interaction.isChatInputCommand() || interaction.isAutocomplete()) {
const command = client.commands?.get(interaction.commandName) as Command;
if (interaction.isChatInputCommand()) {
if (!command) {
logger.warn(`Interaction created but command '${interaction.commandName}' was not found.`);
return;
}
logger.debug(`Chat input command interaction created for '${interaction.commandName}'.`);
try {
await interaction.deferReply();
if (await cannotSendMessageInChannel({ interaction, executionId })) {
return;
}
const inputTime: number = new Date().getTime();
await command.execute({ interaction, client, executionId });
const outputTime: number = new Date().getTime();
const executionTime: number = outputTime - inputTime;
logger.info(`Command '${interaction}' executed in ${executionTime} ms.`);
} catch (error) {
if (error instanceof Error) {
logger.warn(
error,
`Command '${interaction}' throwed an unhandled error and might have failed to execute properly.`
);
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;
} else {
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 {
throw error;
}
}
} else if (interaction.isAutocomplete()) {
logger.debug('Autocomplete interaction created.');
try {
command?.autocomplete && (await command?.autocomplete({ interaction, executionId }));
} catch (error) {
if (error instanceof Error) {
if (
error.message === 'Unknown interaction' ||
error.message === 'Interaction has already been acknowledged.'
) {
logger.debug(
'Autocomplete failed to be responded to, unknown interaction or already acknowledged.'
);
return;
} else {
logger.warn(error, 'Autocomplete failed to execute.');
}
return;
} else {
throw error;
}
}
}
} else {
logger.warn(interaction, 'Interaction created but was not a chat input or autocomplete interaction.');
}
}
};
@@ -1,13 +1,14 @@
const { v4: uuidv4 } = require('uuid');
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: 'debug',
isDebug: true,
isPlayerEvent: false,
execute: async (message) => {
execute: async (message: string) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'generalDebug.js',
module: 'event',
name: 'playerGeneralDebug',
@@ -1,30 +1,33 @@
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');
import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
// Emitted when the player queue encounters error (general error with queue)
module.exports = {
name: 'error',
isDebug: false,
isPlayerEvent: true,
execute: async (queue, error) => {
execute: async (queue: ExtendedGuildQueuePlayerNode, error: Error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'generalError.js',
module: 'event',
name: 'playerGeneralError',
executionId: executionId,
shardId: queue.metadata.client.shard.ids[0],
guildId: queue.metadata.channel.guild.id
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');
logger.error(error, "player.events.on('error'): Player queue encountered error event");
await queue.metadata.channel.send({
await queue.metadata?.channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
@@ -36,7 +39,9 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId);
const channel = (await queue.metadata?.client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
await channel.send({
embeds: [
@@ -1,13 +1,14 @@
const { v4: uuidv4 } = require('uuid');
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: 'error',
isDebug: true,
isPlayerEvent: true,
execute: async (message) => {
execute: async (message: string) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'playerDebug.js',
module: 'event',
name: 'playerDebug',
@@ -1,30 +1,33 @@
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');
import config from 'config';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
// Emitted when the player encounters an error while streaming audio track
module.exports = {
name: 'error',
isDebug: false,
isPlayerEvent: true,
execute: async (queue, error) => {
execute: async (queue: ExtendedGuildQueuePlayerNode, error: Error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'playerError.js',
module: 'event',
name: 'playerError',
executionId: executionId,
shardId: queue.metadata.client.shard.ids[0],
guildId: queue.metadata.channel.guild.id
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');
logger.error(error, "player.events.on('playerError'): Player error while streaming track");
await queue.metadata.channel.send({
await queue.metadata?.channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
@@ -36,7 +39,9 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId);
const channel = (await queue.metadata?.client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
await channel.send({
embeds: [
@@ -1,30 +1,34 @@
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');
import config from 'config';
import { Track } from 'discord-player';
import { BaseGuildTextChannel, EmbedBuilder } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { BotOptions, EmbedOptions, SystemOptions } from '../../types/configTypes';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const botOptions: BotOptions = config.get('botOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
// Emitted when the audio player fails to load the stream for a track
module.exports = {
name: 'playerSkip',
isDebug: false,
isPlayerEvent: true,
execute: async (queue, track) => {
execute: async (queue: ExtendedGuildQueuePlayerNode, track: Track) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'playerSkip.js',
module: 'event',
name: 'playerSkip',
executionId: executionId,
shardId: queue.metadata.client.shard.ids[0],
guildId: queue.metadata.channel.guild.id
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({
await queue.metadata?.channel.send({
embeds: [
new EmbedBuilder()
.setDescription(
@@ -36,7 +40,9 @@ module.exports = {
});
if (systemOptions.systemMessageChannelId && systemOptions.systemUserId) {
const channel = await queue.metadata.client.channels.cache.get(systemOptions.systemMessageChannelId);
const channel = (await queue.metadata?.client.channels.cache.get(
systemOptions.systemMessageChannelId
)) as BaseGuildTextChannel;
if (channel) {
await channel.send({
embeds: [
-21
View File
@@ -1,21 +0,0 @@
const { v4: uuidv4 } = require('uuid');
module.exports = {
name: 'playerStart',
isDebug: false,
isPlayerEvent: true,
execute: async (queue, track) => {
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}'.`);
}
};
+24
View File
@@ -0,0 +1,24 @@
import { Track } from 'discord-player';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
import { ExtendedGuildQueuePlayerNode } from '../../types/eventTypes';
module.exports = {
name: 'playerStart',
isDebug: false,
isPlayerEvent: true,
execute: async (queue: ExtendedGuildQueuePlayerNode, track: Track) => {
const executionId = uuidv4();
const logger = loggerModule.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}'.`);
}
};
@@ -1,12 +1,13 @@
const { v4: uuidv4 } = require('uuid');
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: 'uncaughtException',
isDebug: false,
execute: async (error) => {
execute: async (error: Error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'uncaughtException.js',
module: 'event',
name: 'uncaughtException',
@@ -1,12 +1,13 @@
const { v4: uuidv4 } = require('uuid');
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../../services/logger';
module.exports = {
name: 'unhandledRejection',
isDebug: false,
execute: async (error) => {
execute: async (error: Error) => {
const executionId = uuidv4();
const logger = require('../../services/logger').child({
const logger = loggerModule.child({
source: 'unhandledRejection.js',
module: 'event',
name: 'unhandledRejection',
+14 -8
View File
@@ -1,19 +1,25 @@
require('dotenv').config();
const shardingOptions = require('config').get('shardingOptions');
const { ShardingManager, ShardEvents } = require('discord.js');
const { v4: uuidv4 } = require('uuid');
import 'dotenv/config';
const manager = new ShardingManager('./src/bot.js', {
import config from 'config';
import { Client, Shard, ShardEvents, ShardingManager } from 'discord.js';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from './services/logger';
import { ShardingOptions } from './types/configTypes';
const shardingOptions: ShardingOptions = config.get('shardingOptions');
const manager = new ShardingManager('./dist/bot.js', {
token: process.env.DISCORD_BOT_TOKEN,
...shardingOptions
});
const readyShards = new Set();
manager.on('shardCreate', (shard) => {
manager.on('shardCreate', (shard: Shard) => {
const executionId = uuidv4();
const logger = require('./services/logger').child({
const logger = loggerModule.child({
source: 'index.js',
module: 'shardingManager',
name: 'shardingManager',
@@ -27,7 +33,7 @@ manager.on('shardCreate', (shard) => {
shard.on(ShardEvents.Ready, () => {
readyShards.add(shard.id);
if (readyShards.size === manager.totalShards) {
manager.broadcastEval((client) => client.emit('allShardsReady'));
manager.broadcastEval((client: Client) => client.emit('allShardsReady'));
logger.info('All shards ready, bot is now online.');
}
});
@@ -1,10 +1,15 @@
const pino = require('pino');
const config = require('config');
import config from 'config';
import pino from 'pino';
import { LoggerOptions } from '../types/configTypes';
import { TargetOptions } from '../types/serviceTypes';
import type { LokiOptions } from 'pino-loki';
// Retrieve logger options from config
const loggerOptions = config.get('loggerOptions');
const loggerOptions: LoggerOptions = config.get('loggerOptions');
const targets = [
const targets: TargetOptions[] = [
{
target: 'pino/file',
level: loggerOptions.minimumLogLevel,
@@ -17,7 +22,7 @@ const targets = [
},
{
target: 'pino/file',
level: pino.levels.values.info,
level: pino.levels.values.info.toString(),
options: {
destination: './logs/app-info.log',
mkdir: true,
@@ -27,7 +32,7 @@ const targets = [
},
{
target: 'pino/file',
level: pino.levels.values.error,
level: pino.levels.values.error.toString(),
options: {
destination: './logs/app-error.log',
mkdir: true,
@@ -46,11 +51,9 @@ 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({
const transport = pino.transport<LokiOptions>({
target: 'pino-loki',
level: loggerOptions.minimumLogLevel,
options: {
sync: false,
batching: false,
interval: 5,
host: process.env.LOKI_HOST || 'http://localhost:3100',
@@ -60,6 +63,8 @@ if (process.env.LOKI_AUTH_PASSWORD && process.env.LOKI_AUTH_USERNAME) {
}
}
});
targets.push(transport);
}
const transport = pino.transport({ targets });
@@ -76,5 +81,4 @@ const logLevelConfig = {
};
const logger = pino(logLevelConfig, transport);
module.exports = logger;
export default logger;
+21
View File
@@ -0,0 +1,21 @@
import { Client, Collection, SharedNameAndDescription } from 'discord.js';
type RegisterClientCommandsFunction = (params: { client: Client; executionId: string }) => void;
export interface Command {
isNew?: boolean;
isBeta?: boolean;
isSystemCommand?: boolean;
data: {
name: string;
description: string;
options: SharedNameAndDescription[]
};
execute: (params: { interaction: object; client: ExtendedClient | undefined; executionId: string }) => void;
autocomplete?: (params: { interaction: object; executionId: string }) => void;
}
export interface ExtendedClient extends Client {
registerClientCommands?: RegisterClientCommandsFunction;
commands?: Collection<string, Command>;
}
+38
View File
@@ -0,0 +1,38 @@
import { AutocompleteInteraction, ChatInputCommandInteraction } from 'discord.js';
import { ExtendedClient } from './clientTypes';
export interface CommandParams {
interaction: ChatInputCommandInteraction;
client: ExtendedClient | undefined;
executionId: string;
}
export interface CommandAutocompleteParams {
interaction: AutocompleteInteraction;
client: ExtendedClient | undefined;
executionId: string;
}
export interface ShardInfo {
shardId: number;
memUsage: number;
guildCount: number;
guildMemberCount: number;
playerStatistics: {
activeVoiceConnections: number;
totalTracks: number;
totalListeners: number;
};
}
export interface TrackMetadata {
bridge: {
views: number;
};
}
export class CustomError extends Error {
type?: string;
code?: string;
}
+128
View File
@@ -0,0 +1,128 @@
import {
ActivityType, ColorResolvable, PresenceUpdateStatus, ShardingManagerOptions
} from 'discord.js';
export interface BotOptions {
name: string;
botInviteUrl: string;
serverInviteUrl: string;
}
export interface ShardingOptions extends ShardingManagerOptions {}
export interface LoggerOptions {
minimumLogLevel: string;
minimumLogLevelConsole: string;
discordPlayerDebug: boolean;
}
export interface SystemOptions {
systemGuildIds: string[];
systemMessageChannelId: string;
systemUserId: string;
}
export interface PresenceStatusOptions {
status: PresenceUpdateStatus;
activities: {
name: string;
type: ActivityType;
}[];
}
export interface EmbedOptions {
info: {
fallbackThumbnailUrl: string;
};
colors: {
success: ColorResolvable;
warning: ColorResolvable;
error: ColorResolvable;
info: ColorResolvable;
note: ColorResolvable;
};
icons: {
logo: string;
beta: string;
new: string;
rule: string;
support: string;
bot: string;
server: string;
discord: string;
audioPlaying: string;
audioStartedPlaying: string;
success: string;
error: string;
warning: string;
disable: string;
enable: string;
disabled: string;
enabled: string;
nextTrack: string;
previousTrack: string;
pauseResumeTrack: string;
shuffleQueue: string;
loop: string;
loopAction: string;
autoplay: string;
autoplayAction: string;
looping: string;
autoplaying: string;
skipped: string;
back: string;
pauseResumed: string;
shuffled: string;
volume: string;
volumeIsMuted: string;
volumeChanged: string;
volumeMuted: string;
queue: string;
sourceArbitrary: string;
sourceAppleMusic: string;
sourceYouTube: string;
sourceSoundCloud: string;
sourceSpotify: string;
liveTrack: string;
};
}
export interface PlayerOptions {
leaveOnEmpty: boolean;
leaveOnEmptyCooldown: number;
leaveOnEnd: boolean;
leaveOnEndCooldown: number;
leaveOnStop: boolean;
leaveOnStopCooldown: number;
defaultVolume: number;
maxQueueSize: number;
maxHistorySize: number;
bufferingTimeout: number;
connectionTimeout: number;
progressBar: {
length: number;
timecodes: boolean;
separator: string;
indicator: string;
leftChar: string;
rightChar: string;
};
}
export interface FFmpegFilterOption {
label: string;
value: string;
description: string;
emoji: string;
}
export interface FFmpegFilterOptions {
threadAmount: string;
availableFilters: FFmpegFilterOption[];
}
export interface LoadTestOptions {
enabled: boolean;
trackUrl: string;
channelIdsToJoin: string[];
}
+17
View File
@@ -0,0 +1,17 @@
import { GuildQueuePlayerNode } from 'discord-player';
import { BaseGuildTextChannel } from 'discord.js';
import { ExtendedClient } from './clientTypes';
export type ClientEventArguments = unknown[];
export type ProcessEventArguments = unknown[];
export type PlayerEventArguments = unknown[];
export interface ExtendedGuildQueuePlayerNode extends GuildQueuePlayerNode<unknown> {
metadata:
| undefined
| {
client: ExtendedClient;
channel: BaseGuildTextChannel;
};
}
+5
View File
@@ -0,0 +1,5 @@
import { Player } from 'discord-player';
declare global {
const player: Player;
}
+6
View File
@@ -0,0 +1,6 @@
import { Client } from 'discord.js';
export interface CreatePlayerParams {
client: Client;
executionId: string;
}
+18
View File
@@ -0,0 +1,18 @@
export type TargetOptions = {
target: string;
level: string;
options: {
destination?: string;
mkdir?: boolean;
sync?: boolean;
minLength?: number;
colorize?: boolean;
batching?: boolean;
interval?: number;
host?: string;
basicAuth?: {
username: string;
password: string;
};
};
};
+87
View File
@@ -0,0 +1,87 @@
import { GuildQueue, Player } from 'discord-player';
import { ChatInputCommandInteraction } from 'discord.js';
import { ExtendedClient } from './clientTypes';
export interface RegisterEventListenersParams {
client: ExtendedClient;
player: Player;
executionId: string;
}
export interface RegisterClientCommandsParams {
client: ExtendedClient;
executionId: string;
}
export interface NotInVoiceChannelParams {
interaction: ChatInputCommandInteraction;
executionId: string;
}
export interface NotInSameVoiceChannelParams {
interaction: ChatInputCommandInteraction;
queue: GuildQueue;
executionId: string;
}
export interface NotValidGuildIdParams {
interaction: ChatInputCommandInteraction;
executionId: string;
}
export interface TransformQueryParams {
query: string;
executionId: string;
}
export interface QueueDoesNotExistParams {
interaction: ChatInputCommandInteraction;
queue: GuildQueue;
executionId: string;
}
export interface QueueNoCurrentTrackParams {
interaction: ChatInputCommandInteraction;
queue: GuildQueue;
executionId: string;
}
export interface QueueIsEmptyParams {
interaction: ChatInputCommandInteraction;
queue: GuildQueue;
executionId: string;
}
export interface CannotJoinVoiceOrTalkParams {
interaction: ChatInputCommandInteraction;
executionId: string;
}
export interface CannotSendMessageInChannelParams {
interaction: ChatInputCommandInteraction;
executionId: string;
}
export interface GetUptimeFormattedParams {
executionId: string;
}
export interface StartLoadTestParams {
client: ExtendedClient;
executionId: string;
}
export interface PostBotStatsParams {
client: ExtendedClient;
executionId: string;
}
export interface PostBotStatsSite {
enabled: boolean;
hostname: string;
path: string;
method: string;
body: object;
token: string;
}
@@ -1,29 +1,35 @@
require('dotenv').config();
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');
import 'dotenv/config';
import config from 'config';
import { REST, RouteLike, Routes, SlashCommandBuilder } from 'discord.js';
import fs from 'node:fs';
import path from 'node:path';
import { v4 as uuidv4 } from 'uuid';
import loggerModule from '../services/logger';
import { SystemOptions } from '../types/configTypes';
const systemOptions: SystemOptions = config.get('systemOptions');
const executionId = uuidv4();
const logger = require('../services/logger').child({
const logger = loggerModule.child({
source: 'deploySlashCommands.js',
module: 'deploy',
name: 'deploySlashCommands',
executionId: executionId
});
const slashCommands = [];
const systemCommands = [];
const commandFolders = fs.readdirSync(path.resolve('./src/commands'));
const slashCommands: SlashCommandBuilder[] = [];
const systemCommands: SlashCommandBuilder[] = [];
const commandFolders = fs.readdirSync(path.resolve('./dist/commands'));
for (const folder of commandFolders) {
const commandFiles = fs
.readdirSync(path.resolve(`./src/commands/${folder}`))
.readdirSync(path.resolve(`./dist/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
/* eslint-disable @typescript-eslint/no-var-requires */
const command = require(`../commands/${folder}/${file}`);
command.isSystemCommand
? systemCommands.push(command.data.toJSON())
@@ -31,6 +37,14 @@ for (const folder of commandFolders) {
}
}
if (!process.env.DISCORD_BOT_TOKEN) {
throw new Error('DISCORD_BOT_TOKEN environment variable is not set.');
}
if (!process.env.DISCORD_APPLICATION_ID) {
throw new Error('DISCORD_APPLICATION_ID environment variable is not set.');
}
const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN);
(async () => {
@@ -44,7 +58,7 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
logger.debug(`Bot user slash commands found: ${slashCommands.map((command) => `/${command.name}`).join(', ')}`);
logger.info('Started refreshing user slash commands.');
await refreshCommands(Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID), slashCommands);
await refreshCommands(Routes.applicationCommands(process.env.DISCORD_APPLICATION_ID!), slashCommands);
logger.info('Successfully refreshed user slash commands.');
} catch (error) {
logger.error(error, 'Failed to refresh user slash commands.');
@@ -60,10 +74,10 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
logger.info('Started refreshing system slash commands.');
const systemGuildIds = systemOptions.systemGuildIds;
await Promise.all(
systemGuildIds.map((systemGuildId) => {
systemGuildIds.map((systemGuildId: string) => {
logger.debug(`Refreshing system slash command for guild id '${systemGuildId}'.`);
refreshCommands(
Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID, systemGuildId),
Routes.applicationGuildCommands(process.env.DISCORD_APPLICATION_ID!, systemGuildId),
systemCommands
);
})
@@ -72,11 +86,11 @@ const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_BOT_TOKEN)
} catch (error) {
logger.error(
error,
'Failed to refresh system slash commands. Make sure the bot is in the system guilds specified in \'systemOptions\'.'
"Failed to refresh system slash commands. Make sure the bot is in the system guilds specified in 'systemOptions'."
);
}
})();
async function refreshCommands(route, commands) {
async function refreshCommands(route: RouteLike, commands: object[]) {
await rest.put(route, { body: commands });
}
@@ -1,7 +1,9 @@
const Discord = require('discord.js');
import Discord, { Client } from 'discord.js';
exports.createClient = async ({ executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
export const createClient = async ({ executionId }: { executionId: string }) => {
const logger = loggerModule.child({
source: 'createClient.js',
module: 'utilFactory',
name: 'createClient',
@@ -12,7 +14,7 @@ exports.createClient = async ({ executionId }) => {
try {
logger.debug('Creating discord.js client...');
const client = new Discord.Client({
const client: Client = new Discord.Client({
intents: [Discord.GatewayIntentBits.Guilds, Discord.GatewayIntentBits.GuildVoiceStates],
makeCache: Discord.Options.cacheWithLimits({
...Discord.Options.DefaultMakeCacheSettings,
@@ -22,7 +24,7 @@ exports.createClient = async ({ executionId }) => {
ReactionManager: 0,
GuildMemberManager: {
maxSize: 50,
keepOverLimit: (member) => member.id === client.user.id
keepOverLimit: (member) => member.id === client.user?.id
}
}),
sweepers: {
@@ -33,7 +35,7 @@ exports.createClient = async ({ executionId }) => {
},
users: {
interval: 3600,
filter: () => (user) => user.id !== client.user.id
filter: () => (user) => user.id !== client.user?.id
}
}
});
@@ -1,12 +1,15 @@
const { Player } = require('discord-player');
import { Player } from 'discord-player';
exports.createPlayer = async ({ client, executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { CreatePlayerParams } from '../../types/playerTypes';
export const createPlayer = async ({ client, executionId }: CreatePlayerParams) => {
const logger = loggerModule.child({
source: 'createPlayer.js',
module: 'utilFactory',
name: 'createPlayer',
executionId: executionId,
shardId: client.shard.ids[0]
shardId: client.shard?.ids[0]
});
try {
@@ -27,6 +30,7 @@ exports.createPlayer = async ({ client, executionId }) => {
// make player accessible from anywhere in the application
// primarily to be able to use it in broadcastEval and other sharding methods
// @ts-ignore
global.player = player;
await player.extractors.loadDefault();
@@ -1,10 +1,12 @@
const path = require('node:path');
const fs = require('node:fs');
import fs from 'node:fs';
import path from 'node:path';
/* eslint-disable @typescript-eslint/no-var-requires */
const cookies = require(path.resolve('./cookies.json'));
try {
const cookieString = cookies
.map(({ name, value }) => {
.map(({ name, value }: { name: string; value: string }) => {
return `${name}=${value}`;
})
.join('; ');
@@ -1,32 +1,37 @@
const https = require('node:https');
import { Collection, Guild } from 'discord.js';
import https from 'node:https';
exports.postBotStats = async ({ client, executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { PostBotStatsParams, PostBotStatsSite } from '../../types/utilTypes';
export const postBotStats = async ({ client, executionId }: PostBotStatsParams) => {
const logger = loggerModule.child({
source: 'postBotStats.js',
module: 'utilOther',
name: 'postBotStats',
executionId: executionId,
shardId: client.shard.ids[0]
shardId: client.shard?.ids[0]
});
try {
if (client.shard.ids[0] !== 0) {
if (client.shard?.ids[0] !== 0) {
return;
}
let guildCount = 0;
let memberCount = 0;
let shardCount = client.shard.count;
let shardId = client.shard.ids[0];
const shardCount = client.shard.count;
const shardId = client.shard.ids[0];
logger.debug('Gathering data about guild and member count from shards...');
await client.shard
.fetchClientValues('guilds.cache')
.then((results) => {
results.map((guildCache) => {
const guildCaches = results as Collection<string, Guild>[];
guildCaches.map((guildCache) => {
if (guildCache) {
guildCount += guildCache.length;
memberCount += guildCache.reduce((acc, guildCache) => acc + guildCache.memberCount, 0);
guildCount += guildCache.size;
memberCount += guildCache.reduce((acc, guild) => acc + guild.memberCount, 0);
}
});
@@ -37,7 +42,7 @@ exports.postBotStats = async ({ client, executionId }) => {
});
/* eslint-disable camelcase */
const sites = [
const sites: PostBotStatsSite[] = [
{
enabled: false,
hostname: 'top.gg',
@@ -48,7 +53,7 @@ exports.postBotStats = async ({ client, executionId }) => {
shard_count: shardCount,
server_count: guildCount
},
token: process.env.BOTLIST_TOP_GG_API_TOKEN
token: process.env.BOTLIST_TOP_GG_API_TOKEN ?? ''
},
{
enabled: false,
@@ -60,7 +65,7 @@ exports.postBotStats = async ({ client, executionId }) => {
users: memberCount,
guilds: guildCount
},
token: process.env.BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN
token: process.env.BOTLIST_DISCORD_BOT_LIST_COM_API_TOKEN ?? ''
},
{
enabled: false,
@@ -70,7 +75,7 @@ exports.postBotStats = async ({ client, executionId }) => {
body: {
server_count: guildCount
},
token: process.env.BOTLIST_DISCORDS_COM_API_TOKEN
token: process.env.BOTLIST_DISCORDS_COM_API_TOKEN ?? ''
},
{
enabled: false,
@@ -82,7 +87,7 @@ exports.postBotStats = async ({ client, executionId }) => {
shardCount: shardCount,
guildCount: guildCount
},
token: process.env.BOTLIST_DISCORD_BOTS_GG_API_TOKEN
token: process.env.BOTLIST_DISCORD_BOTS_GG_API_TOKEN ?? ''
},
{
enabled: false,
@@ -93,7 +98,7 @@ exports.postBotStats = async ({ client, executionId }) => {
shard_count: shardCount,
server_count: guildCount
},
token: process.env.BOTLIST_BOTLIST_ME_API_TOKEN
token: process.env.BOTLIST_BOTLIST_ME_API_TOKEN ?? ''
},
{
enabled: false,
@@ -119,14 +124,14 @@ exports.postBotStats = async ({ client, executionId }) => {
logger.info(`Starting to post bot stats with guild count ${guildCount} and member count ${memberCount}...`);
let statusCodes = [];
const statusCodes: number[] = [];
sites.map((site) => {
if (site.disabled) {
if (!site.enabled) {
return;
}
let options = {
const options = {
protocol: 'https:',
hostname: site.hostname,
port: 443,
@@ -138,12 +143,18 @@ exports.postBotStats = async ({ client, executionId }) => {
}
};
let request = https.request(options, (res) => {
res.statusCode === 200
? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`)
: logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`);
const request = https.request(options, (res) => {
if (typeof res.statusCode === 'number') {
res.statusCode === 200
? logger.debug(`Request to ${site.hostname}: statusCode: ${res.statusCode}`)
: logger.warn(`Request to ${site.hostname}: statusCode: ${res.statusCode}`);
statusCodes.push(res.statusCode);
statusCodes.push(res.statusCode);
} else {
logger.error(
`Request to ${site.hostname}: statusCode is undefined or not a number (${res.statusCode}).`
);
}
});
request.write(JSON.stringify(site.body));
@@ -1,13 +1,19 @@
const config = require('config');
const loadTestOptions = config.get('loadTestOptions');
import config from 'config';
import { Client } from 'discord.js';
exports.startLoadTest = async ({ client, executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { LoadTestOptions } from '../../types/configTypes';
import { StartLoadTestParams } from '../../types/utilTypes';
const loadTestOptions: LoadTestOptions = config.get('loadTestOptions');
export const startLoadTest = async ({ client, executionId }: StartLoadTestParams) => {
const logger = loggerModule.child({
source: 'startLoadTest.js',
module: 'utilOther',
name: 'startLoadTest',
executionId: executionId,
shardId: client.shard.ids[0]
shardId: client.shard?.ids[0]
});
if (!loadTestOptions.enabled) {
@@ -21,11 +27,12 @@ exports.startLoadTest = async ({ client, executionId }) => {
logger.info(`Starting load test in ${channelIds.length} specified channels.`);
channelIds.forEach((each) => {
client.shard.broadcastEval(
async (shardClient, { channelId, track }) => {
client.shard?.broadcastEval(
async (shardClient: Client, { channelId, track }: { channelId: string; track: string }) => {
const channel = shardClient.channels.cache.get(channelId);
if (channel) {
/* eslint-disable no-undef */
// @ts-ignore
await player.play(channel.id, track, {
nodeOptions: {
leaveOnEmpty: false,
@@ -1,24 +1,27 @@
const fs = require('node:fs');
const path = require('node:path');
const { Collection } = require('discord.js');
import { Collection } from 'discord.js';
import fs from 'node:fs';
import path from 'node:path';
exports.registerClientCommands = ({ client, executionId }) => {
const logger = require('../services/logger').child({
import loggerModule from '../services/logger';
import { RegisterClientCommandsParams } from '../types/utilTypes';
export const registerClientCommands = ({ client, executionId }: RegisterClientCommandsParams) => {
const logger = loggerModule.child({
source: 'registerClientCommands.js',
module: 'register',
name: 'registerClientCommands',
executionId: executionId,
shardId: client.shard.ids[0]
shardId: client.shard?.ids[0]
});
logger.debug('Registering client commands...');
client.commands = new Collection();
const commandFolders = fs.readdirSync(path.resolve('./src/commands'));
const commandFolders = fs.readdirSync(path.resolve('./dist/commands'));
for (const folder of commandFolders) {
logger.trace(`Registering client commands for folder '${folder}'...`);
const commandFiles = fs
.readdirSync(path.resolve(`./src/commands/${folder}`))
.readdirSync(path.resolve(`./dist/commands/${folder}`))
.filter((file) => file.endsWith('.js'));
for (const file of commandFiles) {
@@ -27,11 +30,16 @@ exports.registerClientCommands = ({ client, executionId }) => {
delete require.cache[require.resolve(`../commands/${folder}/${file}`)];
// register command
/* eslint-disable @typescript-eslint/no-var-requires */
const command = require(`../commands/${folder}/${file}`);
client.commands.delete(command.data.name);
client.commands.set(command.data.name, command);
} catch (error) {
logger.error(`Error registering command ${folder}/${file}: ${error.message}`);
if (error instanceof Error) {
logger.error(`Error registering command ${folder}/${file}: ${error.message}`);
} else {
throw error;
}
}
}
}
@@ -1,47 +1,55 @@
const fs = require('node:fs');
const path = require('node:path');
const config = require('config');
import config from 'config';
import fs from 'node:fs';
import path from 'node:path';
const loggerOptions = config.get('loggerOptions');
import loggerModule from '../services/logger';
import { LoggerOptions } from '../types/configTypes';
import {
ClientEventArguments, PlayerEventArguments, ProcessEventArguments
} from '../types/eventTypes';
import { RegisterEventListenersParams } from '../types/utilTypes';
exports.registerEventListeners = ({ client, player, executionId }) => {
const logger = require('../services/logger').child({
const loggerOptions: LoggerOptions = config.get('loggerOptions');
export const registerEventListeners = ({ client, player, executionId }: RegisterEventListenersParams) => {
const logger = loggerModule.child({
source: 'registerEventListeners.js',
module: 'register',
name: 'registerEventListeners',
executionId: executionId,
shardId: client.shard.ids[0]
shardId: client.shard?.ids[0]
});
logger.debug('Registering event listeners...');
const eventFolders = fs.readdirSync(path.resolve('./src/events'));
const eventFolders = fs.readdirSync(path.resolve('./dist/events'));
for (const folder of eventFolders) {
logger.trace(`Registering event listener for folder '${folder}'...`);
const eventFiles = fs
.readdirSync(path.resolve(`./src/events/${folder}`))
.readdirSync(path.resolve(`./dist/events/${folder}`))
.filter((file) => file.endsWith('.js'));
for (const file of eventFiles) {
/* eslint-disable @typescript-eslint/no-var-requires */
const event = require(`../events/${folder}/${file}`);
switch (folder) {
case 'client':
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
client.once(event.name, (...args: ClientEventArguments) => event.execute(...args));
} else {
if (!event.isDebug || process.env.MINIMUM_LOG_LEVEL === 'debug') {
client.on(event.name, (...args) => event.execute(...args));
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args));
}
}
break;
case 'interactions':
client.on(event.name, (...args) => event.execute(...args, { client }));
client.on(event.name, (...args: ClientEventArguments) => event.execute(...args, { client }));
break;
case 'process':
process.on(event.name, (...args) => event.execute(...args));
process.on(event.name, (...args: ProcessEventArguments) => event.execute(...args));
break;
case 'player':
@@ -50,10 +58,10 @@ exports.registerEventListeners = ({ client, player, executionId }) => {
(loggerOptions.minimumLogLevel === 'debug' && loggerOptions.discordPlayerDebug)
) {
if (event.isPlayerEvent) {
player.events.on(event.name, (...args) => event.execute(...args));
player.events.on(event.name, (...args: PlayerEventArguments) => event.execute(...args));
break;
} else {
player.on(event.name, (...args) => event.execute(...args));
player.on(event.name, (...args: PlayerEventArguments) => event.execute(...args));
}
}
break;
@@ -1,5 +1,8 @@
exports.getUptimeFormatted = async ({ executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { GetUptimeFormattedParams } from '../../types/utilTypes';
export const getUptimeFormatted = async ({ executionId }: GetUptimeFormattedParams) => {
const logger = loggerModule.child({
source: 'getUptimeFormatted.js',
module: 'utilSystem',
name: 'getUptimeFormatted',
@@ -9,9 +12,9 @@ exports.getUptimeFormatted = async ({ executionId }) => {
try {
let uptimeFormattedString = '';
const uptimeInSeconds = process.uptime();
let uptimeDate = new Date(0);
uptimeDate.setSeconds(uptimeInSeconds.toFixed(0));
const uptimeInSeconds = parseFloat(process.uptime().toFixed(0));
const uptimeDate = new Date(0);
uptimeDate.setSeconds(uptimeInSeconds);
uptimeFormattedString = `${
uptimeDate.getUTCDate() - 1
}d ${uptimeDate.getUTCHours()}h ${uptimeDate.getUTCMinutes()}m ${uptimeDate.getUTCSeconds()}s`;
@@ -1,20 +1,26 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { EmbedBuilder } = require('discord.js');
import config from 'config';
import { EmbedBuilder, GuildMember, TextChannel, VoiceChannel } from 'discord.js';
exports.cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import {
CannotJoinVoiceOrTalkParams, CannotSendMessageInChannelParams
} from '../../types/utilTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const cannotJoinVoiceOrTalk = async ({ interaction, executionId }: CannotJoinVoiceOrTalkParams) => {
const logger = loggerModule.child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotJoinVoiceOrTalk',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
const channel = interaction.member.voice.channel;
const channel = interaction.member instanceof GuildMember ? interaction.member.voice.channel : null;
if (!channel.joinable || !channel.speakable) {
if (channel instanceof VoiceChannel && (!channel.joinable || !channel.speakable)) {
await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -34,20 +40,20 @@ exports.cannotJoinVoiceOrTalk = async ({ interaction, executionId }) => {
return false;
};
exports.cannotSendMessageInChannel = async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
export const cannotSendMessageInChannel = async ({ interaction, executionId }: CannotSendMessageInChannelParams) => {
const logger = loggerModule.child({
source: 'permissionValidator.js',
module: 'utilValidation',
name: 'cannotSendMessageInChannel',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
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) {
if (channel instanceof TextChannel && !channel.viewable) {
logger.info(
`User tried to use command '${interaction.commandName}' but the bot had no permission to send reply in text channel.`
);
@@ -64,20 +70,23 @@ exports.cannotSendMessageInChannel = async ({ interaction, executionId }) => {
`**${embedOptions.icons.warning} Oops!**\nI do not have permission to send message replies in the channel you are in.\n\nPlease make sure I have the **\`View Channel\`** permission in this text channel.`
)
.setColor(embedOptions.colors.warning)
],
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.'
);
logger.debug(error);
if (error instanceof 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.'
);
logger.debug(error);
} else {
logger.error(
error,
'Failed to send ephemeral reply to user in channel that bot cannot view/send message in.'
);
}
} else {
logger.error(
error,
'Failed to send ephemeral reply to user in channel that bot cannot view/send message in.'
);
throw error;
}
}
@@ -1,15 +1,21 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { EmbedBuilder } = require('discord.js');
import config from 'config';
import { EmbedBuilder } from 'discord.js';
exports.queueDoesNotExist = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import {
QueueDoesNotExistParams, QueueIsEmptyParams, QueueNoCurrentTrackParams
} from '../../types/utilTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const queueDoesNotExist = async ({ interaction, queue, executionId }: QueueDoesNotExistParams) => {
const logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueDoesNotExist',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (!queue) {
@@ -30,14 +36,14 @@ exports.queueDoesNotExist = async ({ interaction, queue, executionId }) => {
return false;
};
exports.queueNoCurrentTrack = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
export const queueNoCurrentTrack = async ({ interaction, queue, executionId }: QueueNoCurrentTrackParams) => {
const logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueNoCurrentTrack',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (!queue.currentTrack) {
@@ -58,14 +64,14 @@ exports.queueNoCurrentTrack = async ({ interaction, queue, executionId }) => {
return false;
};
exports.queueIsEmpty = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
export const queueIsEmpty = async ({ interaction, queue, executionId }: QueueIsEmptyParams) => {
const logger = loggerModule.child({
source: 'queueValidator.js',
module: 'utilValidation',
name: 'queueIsEmpty',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (queue.tracks.data.length === 0) {
@@ -1,5 +1,8 @@
exports.transformQuery = async ({ query, executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { TransformQueryParams } from '../../types/utilTypes';
export const transformQuery = async ({ query, executionId }: TransformQueryParams) => {
const logger = loggerModule.child({
source: 'searchQueryValidator.js',
module: 'utilValidation',
name: 'transformQuery',
@@ -9,7 +12,7 @@ exports.transformQuery = async ({ query, executionId }) => {
if (query.startsWith('https://open.spotify.com/')) {
try {
// regex to check for country-based Spotify url
const regex = new RegExp(
const regex: RegExp = new RegExp(
'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);
@@ -17,9 +20,12 @@ exports.transformQuery = async ({ query, executionId }) => {
// 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 type = query.match(regex)[2];
const trackId = query.match(regex)[3];
query = `https://open.spotify.com/${type}/${trackId}`;
const matches = query.match(regex);
if (matches) {
const type = matches[2];
const trackId = matches[3];
query = `https://open.spotify.com/${type}/${trackId}`;
}
}
} catch (error) {
logger.error(error, 'Error while validating or transforming Spotify url.');
@@ -1,34 +0,0 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const systemOptions = config.get('systemOptions');
const { EmbedBuilder } = require('discord.js');
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: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command \`${interaction.commandName}\` cannot be executed in this server.`
)
.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;
}
return false;
};
@@ -0,0 +1,38 @@
import config from 'config';
import { EmbedBuilder } from 'discord.js';
import loggerModule from '../../services/logger';
import { EmbedOptions, SystemOptions } from '../../types/configTypes';
import { NotValidGuildIdParams } from '../../types/utilTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
const systemOptions: SystemOptions = config.get('systemOptions');
export const notValidGuildId = async ({ interaction, executionId }: NotValidGuildIdParams) => {
const logger = loggerModule.child({
source: 'systemCommandValidator.js',
module: 'utilValidation',
name: 'notValidGuildId',
executionId: executionId,
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (interaction.guildId && !systemOptions.systemGuildIds.includes(interaction.guildId)) {
await interaction.editReply({
embeds: [
new EmbedBuilder()
.setDescription(
`**${embedOptions.icons.warning} Oops!**\nNo permission to execute this command.\n\nThe command **\`/${interaction.commandName}\`** cannot be executed in this server.`
)
.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;
}
return false;
};
@@ -1,18 +1,22 @@
const config = require('config');
const embedOptions = config.get('embedOptions');
const { EmbedBuilder } = require('discord.js');
import config from 'config';
import { EmbedBuilder, GuildMember } from 'discord.js';
exports.notInVoiceChannel = async ({ interaction, executionId }) => {
const logger = require('../../services/logger').child({
import loggerModule from '../../services/logger';
import { EmbedOptions } from '../../types/configTypes';
import { NotInSameVoiceChannelParams, NotInVoiceChannelParams } from '../../types/utilTypes';
const embedOptions: EmbedOptions = config.get('embedOptions');
export const notInVoiceChannel = async ({ interaction, executionId }: NotInVoiceChannelParams) => {
const logger = loggerModule.child({
source: 'voiceChannelValidator.js',
module: 'validator',
name: 'notInVoiceChannel',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (!interaction.member.voice.channel) {
if (interaction.member instanceof GuildMember && !interaction.member.voice.channel) {
await interaction.editReply({
embeds: [
new EmbedBuilder()
@@ -30,14 +34,14 @@ exports.notInVoiceChannel = async ({ interaction, executionId }) => {
return false;
};
exports.notInSameVoiceChannel = async ({ interaction, queue, executionId }) => {
const logger = require('../../services/logger').child({
export const notInSameVoiceChannel = async ({ interaction, queue, executionId }: NotInSameVoiceChannelParams) => {
const logger = loggerModule.child({
source: 'voiceChannelValidator.js',
module: 'utilValidation',
name: 'notInSameVoiceChannel',
executionId: executionId,
shardId: interaction.guild.shardId,
guildId: interaction.guild.id
shardId: interaction.guild?.shardId,
guildId: interaction.guild?.id
});
if (!queue || !queue.dispatcher) {
@@ -45,7 +49,10 @@ exports.notInSameVoiceChannel = async ({ interaction, queue, executionId }) => {
return false;
}
if (interaction.member.voice.channel.id !== queue.dispatcher.channel.id) {
if (
interaction.member instanceof GuildMember &&
interaction.member.voice.channel?.id !== queue.dispatcher.channel.id
) {
await interaction.editReply({
embeds: [
new EmbedBuilder()
+14
View File
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "ES2020", // Specify ECMAScript target version
"module": "commonjs", // Specify module code generation
"outDir": "./dist", // Output directory for compiled files
"rootDir": "./src", // Root directory of source files
"strict": true, // Enable strict type-checking options
"esModuleInterop": true, // Enables ES module interop
"skipLibCheck": true, // Skip type checking of declaration files
"forceConsistentCasingInFileNames": true // Disallow inconsistently-cased references to the same file
},
"include": ["src/**/*.ts", "src/types/**/*.ts"], // Source files to be compiled
"exclude": ["node_modules"] // Exclude node_modules from compilation
}