36 Commits
Author SHA1 Message Date
deytenit ace8170323 Comply to Docker Logging 2023-12-06 13:40:18 +03:00
Vladimir (unknowableshade) Eremin 1374bcc25d Merge branch 'master' of https://github.com/unknowableshade/quetza-bot 2023-07-12 02:57:29 +03:00
Vladimir (unknowableshade) Eremin 757d6e3501 Prettier & CI/CD Fixes 2023-07-12 02:57:24 +03:00
Vladimir (unknowableshade) Eremin b023f7134d Merge branch 'master' of https://github.com/unknowableshade/quetza-bot 2023-07-12 02:57:07 +03:00
Vladimir (unknowableshade) Eremin 9f191e6e80 Prettier & CI/CD Fixes 2023-07-12 02:56:53 +03:00
Vladimir (unknowableshade) Eremin 7ca5041725 Merge branch 'master' of https://github.com/unknowableshade/quetza-bot 2023-07-12 02:22:15 +03:00
Vladimir (unknowableshade) Eremin a045be3f2f Prettier & CI/CD Fixes 2023-07-12 02:16:29 +03:00
Vladimir (unknowableshade) Eremin c569661481 Prettier & CI/CD Fixes 2023-07-12 01:10:12 +03:00
Vladimir (unknowableshade) Eremin e8cd52d315 More Fixes 2023-05-09 18:05:41 +03:00
Vladimir (unknowableshade) Eremin d4d2930f58 Formatting 2023-05-09 17:01:40 +03:00
Vladimir (unknowableshade) Eremin 0f6ad29a3c Bug Fixes 2023-05-09 16:58:37 +03:00
Vladimir Eremin e4397c3f54 Merge pull request #5 from unknowableshade/laboratory
v4.2.0
2023-05-09 04:21:33 +03:00
Vladimir (unknowableshade) Eremin ae41f11bef Docker & Versions 2023-05-09 04:11:25 +03:00
Vladimir (unknowableshade) Eremin af57e4a25f Minor Changes 2023-05-09 02:49:11 +03:00
Vladimir (unknowableshade) Eremin 483bc4895d Pretty 2023-05-09 02:48:58 +03:00
Vladimir (unknowableshade) Eremin 615921a2d9 Dependencies 2023-05-09 02:48:17 +03:00
Vladimir (unknowableshade) Eremin 93f3bd1047 Server Module Changes 2023-05-08 23:52:21 +03:00
Vladimir (unknowableshade) Eremin c2f666c408 Music Improvements 2023-05-08 23:51:55 +03:00
Vladimir (unknowableshade) Eremin 3f55646bce Core Improvements 2023-05-08 23:51:37 +03:00
Vladimir (unknowableshade) Eremin 0fdc80aeab Configuration changes 2023-05-08 23:51:13 +03:00
Vladimir (unknowableshade) Eremin 0b451c2c4e Music v2.0.0 (early) 2023-05-07 18:35:13 +03:00
Vladimir (unknowableshade) Eremin bb9448c9c1 Core improvements 2023-05-07 18:34:20 +03:00
Vladimir (unknowableshade) Eremin d726ab6571 Logging, Migrations & Updates 2023-05-07 18:33:14 +03:00
Vladimir (unknowableshade) Eremin 85976917b7 Server Module + DB (very early) 2023-05-04 03:54:34 +03:00
Vladimir (unknowableshade) Eremin 1b218fa7c3 Dependencies & CI/CD 2023-04-01 16:07:55 +03:00
Vladimir (unknowableshade) Eremin 5fe2d9f99d Submit to node-semver 2023-03-30 16:33:06 +03:00
Vladimir (unknowableshade) Eremin 411c2ce262 Pnpm Migration 2023-03-30 16:16:11 +03:00
Vladimir (unknowableshade) Eremin 8e9ce884a6 CI/CD Building & Testing 2023-03-29 12:47:06 +03:00
Vladimir Eremin 151437e7a8 Merge pull request #4 from unknowableshade/laboratory
Laboratory collapse
2023-03-28 23:43:07 +03:00
Vladimir Eremin 076d9a71cb Merge branch 'master' into laboratory 2023-03-28 23:39:33 +03:00
Vladimir (unknowableshade) Eremin b562d74a5c Modular Design + Minor Fixes 2023-03-28 23:34:53 +03:00
Vladimir (unknowableshade) Eremin dea1a5564e Version Update + Misc 2023-03-28 23:34:12 +03:00
Vladimir (unknowableshade) Eremin c178fb21f3 Refactoring flexing 2023-03-02 00:10:01 +03:00
Vladimir (unknowableshade) Eremin b2bc8b928a Modular concept 2023-02-28 16:41:00 +03:00
Vladimir Eremin 8cff02e081 Update package.json 2023-02-27 23:02:13 +03:00
Vladimir (unknowableshade) Eremin d068a6fb01 2302.2 Clean Up & Docker Fix 2023-02-26 20:40:43 +03:00
89 changed files with 6563 additions and 4882 deletions

No files matched your search

+16 -2
View File
@@ -1,2 +1,16 @@
node_modules
Procfile
# Ignore everything by default
*
# Dockerfile
!Dockerfile
# Source
!src/
!prisma/
# Dependencies
!package.json
!pnpm-lock.yaml
# Typescript compiller config
!tsconfig.json
+19 -13
View File
@@ -1,15 +1,21 @@
{
"env": { "browser": true, "es2021": true },
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended"],
"parser": "@typescript-eslint/parser",
"parserOptions": { "ecmaVersion": "latest", "sourceType": "module" },
"plugins": ["@typescript-eslint"],
"rules": {
"indent": ["error", 4],
"linebreak-style": ["error", "windows"],
"quotes": ["error", "double"],
"semi": ["error", "always"],
"brace-style": ["error", "stroustrup"],
"arrow-body-style": ["error", "as-needed"]
}
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"warnOnUnsupportedTypeScriptVersion": false,
"sourceType": "module"
},
"env": {
"browser": false,
"node": true,
"es6": true
},
"extends": ["eslint:recommended", "plugin:@typescript-eslint/recommended", "prettier"],
"plugins": ["@typescript-eslint", "import", "simple-import-sort"],
"ignorePatterns": ["**/node_modules/**", "/dist/**", "/tests/**"],
"rules": {
"curly": ["error", "all"],
"simple-import-sort/imports": "error",
"simple-import-sort/exports": "error"
}
}
-63
View File
@@ -1,63 +0,0 @@
###############################################################################
# Set default behavior to automatically normalize line endings.
###############################################################################
* text=auto
###############################################################################
# Set default behavior for command prompt diff.
#
# This is need for earlier builds of msysgit that does not have it on by
# default for csharp files.
# Note: This is only used by command line
###############################################################################
#*.cs diff=csharp
###############################################################################
# Set the merge driver for project and solution files
#
# Merging from the command prompt will add diff markers to the files if there
# are conflicts (Merging from VS is not affected by the settings below, in VS
# the diff markers are never inserted). Diff markers may cause the following
# file extensions to fail to load in VS. An alternative would be to treat
# these files as binary and thus will always conflict and require user
# intervention with every merge. To do so, just uncomment the entries below
###############################################################################
#*.sln merge=binary
#*.csproj merge=binary
#*.vbproj merge=binary
#*.vcxproj merge=binary
#*.vcproj merge=binary
#*.dbproj merge=binary
#*.fsproj merge=binary
#*.lsproj merge=binary
#*.wixproj merge=binary
#*.modelproj merge=binary
#*.sqlproj merge=binary
#*.wwaproj merge=binary
###############################################################################
# behavior for image files
#
# image files are treated as binary by default.
###############################################################################
#*.jpg binary
#*.png binary
#*.gif binary
###############################################################################
# diff behavior for common document formats
#
# Convert binary document formats to text before diffing them. This feature
# is only available from the command line. Turn it on by uncommenting the
# entries below.
###############################################################################
#*.doc diff=astextplain
#*.DOC diff=astextplain
#*.docx diff=astextplain
#*.DOCX diff=astextplain
#*.dot diff=astextplain
#*.DOT diff=astextplain
#*.pdf diff=astextplain
#*.PDF diff=astextplain
#*.rtf diff=astextplain
#*.RTF diff=astextplain
@@ -1,7 +1,4 @@
# This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs
name: CI/CD
name: actions
on:
push:
@@ -9,41 +6,61 @@ on:
- "*"
jobs:
build:
mocha:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [18.x]
# See supported Node.js release schedule at https://nodejs.org/en/about/releases/
pnpm-version: [8]
steps:
- uses: actions/checkout@v3
- name: Check out the repo
uses: actions/checkout@v3
- uses: pnpm/action-setup@v2
with:
version: ${{ matrix.pnpm-version }}
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v3
with:
node-version: ${{ matrix.node-version }}
cache: "npm"
- run: npm ci
- run: npm run build --if-present
- name: Install dependencies
run: pnpm install
- name: ESLint & Prettier
run: pnpm run lint
- name: Build
run: pnpm run build
- name: Test
run: pnpm run --if-present test
docker:
runs-on: ubuntu-latest
needs: mocha
steps:
- name: Check out the repo
uses: actions/checkout@v3
- name: Log in to Docker Hub
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
uses: docker/login-action@65b78e6e13532edd9afa3aa52ac7964289d1a9c1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
uses: docker/metadata-action@9ec57ed1fcdbf14dcef7dfbe97b2010124a938b7
with:
images: unknowableshade/quetza-bot
- name: Build and push Docker image
uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
uses: docker/build-push-action@f2a1d5e99d037542a71f64918e516c093c6f3fc4
with:
context: .
push: true
+58 -368
View File
@@ -1,374 +1,64 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.rsuser
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Mono auto generated files
mono_crash.*
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Ww][Ii][Nn]32/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
[Ll]og/
[Ll]ogs/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUnit
*.VisualState.xml
TestResult.xml
nunit-*.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
# ASP.NET Scaffolding
ScaffoldingReadMe.txt
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_h.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*_wpftmp.csproj
# Logs
logs
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Chutzpah Test files
_Chutzpah*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Coverlet is a free, cross platform Code Coverage Tool
coverage*.json
coverage*.xml
coverage*.info
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# NuGet Symbol Packages
*.snupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
*.appxbundle
*.appxupload
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!?*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
*- [Bb]ackup.rdl
*- [Bb]ackup ([0-9]).rdl
*- [Bb]ackup ([0-9][0-9]).rdl
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# CodeRush personal settings
.cr/personal
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Local History for Visual Studio
.localhistory/
# BeatPulse healthcheck temp database
healthchecksdb
# Backup folder for Package Reference Convert tool in Visual Studio 2017
MigrationBackup/
# Ionide (cross platform F# VS Code tools) working folder
.ionide/
# Fody - auto-generated XML schema
FodyWeavers.xsd
# assetscript restrictions
dist/
*.js
*.js.map
# binaries is not bundled
# Binaries
bin/
# Keep enviromental variables out of version control
*.env
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript cache
*.tsbuildinfo
dist/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# VSCode
.vscode-test
.vscode
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
+5
View File
@@ -0,0 +1,5 @@
# Node.js Tools
node_modules
# Typescript compiller artifacts
dist/
+23
View File
@@ -0,0 +1,23 @@
{
"semi": true,
"trailingComma": "none",
"singleQuote": false,
"printWidth": 100,
"arrowParens": "always",
"bracketSpacing": true,
"endOfLine": "lf",
"overrides": [
{
"files": ["**/*.json, **/*.yml"],
"options": {
"tabWidth": 2
}
},
{
"files": ["**/*.ts"],
"options": {
"tabWidth": 4
}
}
]
}
+37 -7
View File
@@ -1,3 +1,22 @@
FROM node:18-alpine as builder
RUN apk add --no-cache python3
RUN apk add --no-cache make
RUN apk add --no-cache gcc
RUN apk add --no-cache build-base
RUN npm install -g pnpm
WORKDIR /usr/src/app
COPY package.json pnpm-lock.yaml ./
RUN pnpm install
COPY . .
RUN pnpm run build
FROM node:18-alpine
RUN apk update
@@ -5,17 +24,28 @@ RUN apk add --no-cache bash
RUN apk add --no-cache curl
RUN apk add --no-cache ffmpeg
RUN apk add --no-cache python3
RUN apk add --no-cache make
RUN apk add --no-cache gcc
RUN apk add --no-cache build-base
RUN npm install -g pnpm
ENV NODE_ENV production
USER node
WORKDIR /usr/src/app
RUN mkdir bin
RUN curl -L https://yt-dl.org/downloads/latest/youtube-dl -o /usr/src/app/bin/youtube-dl
RUN chmod a+rx /usr/src/app/bin/youtube-dl
RUN curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/src/app/bin/yt-dlp
RUN chmod a+rx /usr/src/app/bin/yt-dlp
COPY package*.json ./
RUN npm ci
COPY prisma/ .
COPY package.json pnpm-lock.yaml ./
COPY . .
run npm run build
RUN pnpm install --prod
CMD [ "npm", "start" ]
RUN pnpx prisma generate
COPY --from=builder /usr/src/app/dist ./dist
CMD [ "pnpm", "start" ]
-1
View File
@@ -1 +0,0 @@
worker: npm start
+1 -1
View File
@@ -1,4 +1,4 @@
# Quetza - 2302.1 <soundrewrite>
# Quetza 4
_Neat typescript discord bot._
-2402
View File
File diff suppressed because it is too large. Load diff
+42 -27
View File
@@ -1,46 +1,61 @@
{
"name": "quetza-bot",
"engines": {
"node": "18.x.x",
"npm": "*"
},
"version": "4.2.2",
"description": "Discord multipurpose bot",
"type": "module",
"version": "2302.1.0",
"description": "Discord multifunctional bot",
"main": "./dist/index.js",
"scripts": {
"start": "node ./dist/index.js",
"build": "pnpm exec tsc --build",
"clean": "rm -rf ./dist && pnpm run build",
"lint": "pnpm exec eslint . && pnpm exec prettier --check .",
"format": "pnpm exec eslint --fix . && pnpm exec prettier --write .",
"preinstall": "pnpm dlx only-allow pnpm"
},
"license": "MIT",
"keywords": [
"discord",
"bot",
"music"
],
"repository": {
"type": "git",
"url": "git+https://github.com/unknowableshade/quetza-bot.git"
},
"author": {
"name": "unknowableshade",
"email": "60275123+unknowableshade@users.noreply.github.com",
"url": "https://unknowableshade.ru"
},
"repository": {
"type": "git",
"url": "git+https://github.com/unknowableshade/quetza-bot.git"
},
"bugs": {
"url": "https://github.com/unknowableshade/quetza-bot/issues"
},
"readme": "https://github.com/unknowableshade/quetza-bot#readme",
"license": "MIT",
"main": "dist/index.js",
"scripts": {
"poststart": "npm run build",
"start": "node dist/index.js",
"build": "tsc --build",
"clean": "tsc --build --clean"
"engines": {
"node": "18.x.x",
"npm": "*"
},
"dependencies": {
"@discordjs/opus": "^0.8.0",
"@discordjs/voice": "^0.11.0",
"discord-ytdl-core": "^5.0.4",
"discord.js": "^14.3.0",
"@discordjs/opus": "^0.9.0",
"@discordjs/voice": "^0.16.0",
"@prisma/client": "5.0.0",
"discord.js": "^14.11.0",
"prism-media": "^1.3.5",
"tweetnacl": "^1.0.3",
"ytdl-core": "^4.11.1"
"winston": "^3.10.0",
"ytdl-core": "^4.11.4"
},
"devDependencies": {
"@types/node": "^18.7.13",
"@typescript-eslint/eslint-plugin": "^5.35.1",
"@typescript-eslint/parser": "^5.35.1",
"eslint": "^8.22.0",
"typescript": "^4.8.2"
"@types/node": "^20.4.1",
"@typescript-eslint/eslint-plugin": "^6.0.0",
"@typescript-eslint/parser": "^6.0.0",
"eslint": "^8.44.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-simple-import-sort": "^10.0.0",
"mocha": "^10.2.0",
"prettier": "^3.0.0",
"prisma": "^5.0.0",
"typescript": "^5.1.6"
}
}
+3557
View File
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,22 @@
-- CreateTable
CREATE TABLE "Guild" (
"id" TEXT NOT NULL,
CONSTRAINT "Guild_pkey" PRIMARY KEY ("id")
);
-- CreateTable
CREATE TABLE "Event" (
"objectId" SERIAL NOT NULL,
"title" TEXT NOT NULL,
"Roles" TEXT[],
"guildId" TEXT NOT NULL,
CONSTRAINT "Event_pkey" PRIMARY KEY ("objectId")
);
-- CreateIndex
CREATE UNIQUE INDEX "Event_guildId_title_key" ON "Event"("guildId", "title");
-- AddForeignKey
ALTER TABLE "Event" ADD CONSTRAINT "Event_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "Guild"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
@@ -0,0 +1,77 @@
/*
Warnings:
- The primary key for the `Event` table will be changed. If it partially fails, the table could be left without primary key constraint.
- You are about to drop the column `Roles` on the `Event` table. All the data in the column will be lost.
- You are about to drop the column `objectId` on the `Event` table. All the data in the column will be lost.
- A unique constraint covering the columns `[title,action,guildId]` on the table `Event` will be added. If there are existing duplicate values, this will fail.
- Added the required column `action` to the `Event` table without a default value. This is not possible if the table is not empty.
- Added the required column `metadata` to the `Event` table without a default value. This is not possible if the table is not empty.
*/
-- CreateEnum
CREATE TYPE "PenaltyType" AS ENUM ('BAN', 'TIMEOUT', 'WARN');
-- DropIndex
DROP INDEX "Event_guildId_title_key";
-- AlterTable
ALTER TABLE "Event" DROP CONSTRAINT "Event_pkey",
DROP COLUMN "Roles",
DROP COLUMN "objectId",
ADD COLUMN "action" TEXT NOT NULL,
ADD COLUMN "metadata" JSONB NOT NULL;
-- CreateTable
CREATE TABLE "Queue" (
"title" TEXT NOT NULL,
"description" TEXT,
"updatedAt" TIMESTAMP(3) NOT NULL,
"Tracks" JSONB NOT NULL,
"userId" TEXT NOT NULL,
"authorId" TEXT NOT NULL,
"guildId" TEXT NOT NULL
);
-- CreateTable
CREATE TABLE "Member" (
"userId" TEXT NOT NULL,
"level" INTEGER NOT NULL DEFAULT 0,
"guildId" TEXT NOT NULL
);
-- CreateTable
CREATE TABLE "Penalty" (
"userId" TEXT NOT NULL,
"type" "PenaltyType" NOT NULL,
"reason" TEXT,
"expires" TIMESTAMP(3),
"guildId" TEXT NOT NULL
);
-- CreateIndex
CREATE UNIQUE INDEX "Queue_title_guildId_key" ON "Queue"("title", "guildId");
-- CreateIndex
CREATE UNIQUE INDEX "Member_userId_guildId_key" ON "Member"("userId", "guildId");
-- CreateIndex
CREATE UNIQUE INDEX "Penalty_type_userId_guildId_key" ON "Penalty"("type", "userId", "guildId");
-- CreateIndex
CREATE UNIQUE INDEX "Event_title_action_guildId_key" ON "Event"("title", "action", "guildId");
-- AddForeignKey
ALTER TABLE "Queue" ADD CONSTRAINT "Queue_userId_guildId_fkey" FOREIGN KEY ("userId", "guildId") REFERENCES "Member"("userId", "guildId") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Queue" ADD CONSTRAINT "Queue_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "Guild"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Member" ADD CONSTRAINT "Member_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "Guild"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Penalty" ADD CONSTRAINT "Penalty_userId_guildId_fkey" FOREIGN KEY ("userId", "guildId") REFERENCES "Member"("userId", "guildId") ON DELETE RESTRICT ON UPDATE CASCADE;
-- AddForeignKey
ALTER TABLE "Penalty" ADD CONSTRAINT "Penalty_guildId_fkey" FOREIGN KEY ("guildId") REFERENCES "Guild"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
+3
View File
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
+68
View File
@@ -0,0 +1,68 @@
// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Guild {
id String @id
events Event[]
members Member[]
penalties Penalty[]
queues Queue[]
}
model Queue {
title String
description String?
updatedAt DateTime @updatedAt
Tracks Json
Member Member @relation(fields: [userId, guildId], references: [userId, guildId])
userId String
authorId String
Guild Guild @relation(fields: [guildId], references: [id])
guildId String
@@unique([title, guildId], name: "queueIdentifier")
}
model Member {
userId String
level Int @default(0)
queues Queue[]
Guild Guild @relation(fields: [guildId], references: [id])
guildId String
penalties Penalty[]
@@unique([userId, guildId], name: "memberIdentifier")
}
enum PenaltyType {
BAN
TIMEOUT
WARN
}
model Penalty {
Member Member @relation(fields: [userId, guildId], references: [userId, guildId])
userId String
type PenaltyType
reason String?
expires DateTime?
Guild Guild @relation(fields: [guildId], references: [id])
guildId String
@@unique([type, userId, guildId], name: "penaltyIdentifier")
}
model Event {
title String
action String
metadata Json
Guild Guild @relation(fields: [guildId], references: [id])
guildId String
@@unique([title, action, guildId], name: "eventIdentifier")
}
-24
View File
@@ -1,24 +0,0 @@
import Client from "../lib/Client.js";
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
const amount = player.Queue.Tracks.length;
player.clear();
await ctx.reply({ embeds: [I18n.en.cleared(amount)] });
}
const data = new SlashCommandBuilder()
.setName("clear")
.setDescription("Clear the player's queue.");
export { data };
-40
View File
@@ -1,40 +0,0 @@
import Client from "../lib/Client.js";
import { CommandInteraction, GuildMember, SlashCommandBuilder, TextChannel } from "discord.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel || !ctx.member) return;
await ctx.deferReply();
const player =
client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel) ||
client.modules.music.set(ctx.guild, ctx.channel as TextChannel);
if (!player.Connection) {
const channel = (ctx.member as GuildMember).voice.channel;
if (channel) {
player.connect(channel);
await ctx.editReply({ embeds: [I18n.en.okConnected(channel.name)] });
}
else {
client.modules.music.del(ctx.guild.id);
await ctx.editReply({ embeds: [I18n.en.notConnected()] });
return undefined;
}
}
else {
await ctx.editReply({ embeds: [I18n.en.wasConnected()] });
}
return player;
}
const data = new SlashCommandBuilder()
.setName("connect")
.setDescription("Connect me to a voice channel.");
export { data };
-121
View File
@@ -1,121 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const filter = ctx.options.get("filter")?.value as string;
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
player.setFilter(filter || undefined);
await ctx.reply({ embeds: [I18n.en.filtered(filter || undefined)] });
}
const data = new SlashCommandBuilder()
.setName("filter")
.setDescription("Apply unique filters to the tracks.")
.addStringOption(option => option
.setName("filter")
.setDescription("Filter to apply.")
.setChoices(
{
name: "bassboost_low",
value: "bassboost_low",
},
{
name: "bassboost",
value: "bassboost",
},
{
name: "bassboost_high",
value: "bassboost_high",
},
{
name: "8D",
value: "8D",
},
{
name: "vaporwave",
value: "vaporwave",
},
{
name: "nightcore",
value: "nightcore",
},
{
name: "phaser",
value: "phaser",
},
{
name: "tremolo",
value: "tremolo",
},
{
name: "vibrato",
value: "vibrato",
},
{
name: "reverse",
value: "reverse",
},
{
name: "treble",
value: "treble",
},
{
name: "normalizer",
value: "normalizer",
},
{
name: "surrounding",
value: "surrounding",
},
{
name: "pulsator",
value: "pulsator",
},
{
name: "subboost",
value: "subboost",
},
{
name: "mono",
value: "mono",
},
{
name: "compressor",
value: "compressor",
},
{
name: "expander",
value: "expander",
},
{
name: "softlimiter",
value: "softlimiter",
},
{
name: "chorus",
value: "chorus",
},
{
name: "fadein",
value: "fadein",
},
{
name: "dim",
value: "dim",
},
{
name: "earrape",
value: "earrape",
})
.setRequired(true)
);
export { data };
-20
View File
@@ -1,20 +0,0 @@
import Client from "../lib/Client.js";
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel || !ctx.member) return;
await ctx.deferReply();
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
await ctx.editReply({ embeds: [I18n.en.playerInfo(player)] });
}
const data = new SlashCommandBuilder()
.setName("info")
.setDescription("Information about the playback.");
export { data };
-36
View File
@@ -1,36 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const pos = ctx.options.get("position")?.value as number;
const query = ctx.options.get("query")?.value as string;
if (!ctx.guild || !query || !pos || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
await ctx.deferReply();
const track = await player.add(query, ctx.user, pos - 1);
await ctx.editReply({ embeds: [I18n.en.appended(track)] });
}
const data = new SlashCommandBuilder()
.setName("insert")
.setDescription("Insert a new track to specific position in the queue.")
.addStringOption(option => option
.setName("query")
.setDescription("Title or URL of the song.")
.setRequired(true)
)
.addIntegerOption(option => option
.setName("position")
.setDescription("Position to insert.",)
.setRequired(true)
);
export { data };
-28
View File
@@ -1,28 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const query = ctx.options.get("query")?.value as string;
if (!ctx.guild || !query || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
const state = !isNaN(+query) && isFinite(+query) && !/e/i.test(query) ? player.jump(parseInt(query) - 1) : player.jump(query);
await ctx.reply({ embeds: [I18n.en.jumped(state)] });
}
const data = new SlashCommandBuilder()
.setName("jump")
.setDescription("Jump to specific track in the queue.")
.addStringOption(option => option
.setName("query")
.setDescription("Position or title to jump to.")
.setRequired(true)
);
export { data };
-32
View File
@@ -1,32 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import { loopOption } from "../lib/Types.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const query = ctx.options.get("option")?.value as string;
if (!ctx.guild || !query || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
player.Queue.Loop = query as loopOption;
await ctx.reply({ embeds: [I18n.en.looped(query as loopOption)] });
}
const data = new SlashCommandBuilder()
.setName("loop")
.setDescription("Select player's loop mode.")
.addStringOption(option => option
.setName("option")
.setDescription("Select loop option.")
.setChoices( { name: "loop queue", value: "LOOP" },
{ name: "loop single track", value: "SONG" },
{ name: "Till end", value: "NONE" },
{ name: "Random order", value: "AUTO" })
.setRequired(true));
export { data };
-21
View File
@@ -1,21 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
player.skip();
await ctx.reply({ embeds: [I18n.en.skipped()] });
}
const data = new SlashCommandBuilder()
.setName("next")
.setDescription("Skip current song.");
export { data };
-21
View File
@@ -1,21 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
const state = player.pause();
await ctx.reply({ embeds: [I18n.en.paused(state)] });
}
const data = new SlashCommandBuilder()
.setName("pause")
.setDescription("Toggle pause on player.");
export { data };
-22
View File
@@ -1,22 +0,0 @@
import { CommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const start = Date.now();
if (!client.application) {
await ctx.reply({ embeds: [I18n.en.ping(undefined)] });
return;
}
await client.application.fetch();
await ctx.reply({ embeds: [I18n.en.ping(Date.now() - start)] });
}
const data = new SlashCommandBuilder()
.setName("ping")
.setDescription("Try to ping me.");
export { data };
-32
View File
@@ -1,32 +0,0 @@
import { CommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../lib/Client.js";
import { run as connect } from "./connect.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const query = ctx.options.get("query")?.value as string;
const player = await connect(client, ctx);
if (!player) return;
if (query) {
const track = await player.add(query, ctx.user);
await ctx.editReply({ embeds: [I18n.en.appended(track)] });
}
if (!player.Resource) {
player.play();
}
}
const data = new SlashCommandBuilder()
.setName("play")
.setDescription("Launch player and add songs to the queue.")
.addStringOption(option => option
.setName("query")
.setDescription("Title or URL of the song.")
);
export { data };
-86
View File
@@ -1,86 +0,0 @@
import {
ActionRowBuilder,
ButtonBuilder,
ButtonInteraction,
ButtonStyle,
CommandInteraction,
Message,
MessageActionRowComponentBuilder,
SlashCommandBuilder,
TextChannel
} from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
await ctx.deferReply();
if (player.Queue.empty()) {
await ctx.editReply({ embeds: [I18n.en.queueEmpty()] });
return;
}
let page = 0;
const row = new ActionRowBuilder<MessageActionRowComponentBuilder>().addComponents(
new ButtonBuilder()
.setCustomId("QueueTop")
.setLabel("🔼")
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId("QueueUp")
.setLabel("🔺")
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId("QueueDown")
.setLabel("🔻")
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId("QueueEnd")
.setLabel("🔽")
.setStyle(ButtonStyle.Primary)
);
const message = (await ctx.editReply({
embeds: [I18n.en.queueDesigner(player.Queue, 0, player.Resource)],
components: [row],
})) as Message;
const collector = message.createMessageComponentCollector({ time: 30000 });
collector.on("collect", async (btn: ButtonInteraction) => {
switch (btn.customId) {
case "QueueTop": {
page = 0;
break;
}
case "QueueUp": {
page = Math.max(page - 1, 0);
break;
}
case "QueueDown": {
page = Math.min(page + 1, Math.floor(player.Queue.Tracks.length / 11));
break;
}
case "QueueEnd":
page = Math.floor(player.Queue.Tracks.length / 11);
}
await btn.update({
embeds: [I18n.en.queueDesigner(player.Queue, page, player.Resource)],
});
});
}
const data = new SlashCommandBuilder()
.setName("queue")
.setDescription("Print out the queue.");
export { data };
-28
View File
@@ -1,28 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const query = ctx.options.get("query")?.value as string;
if (!ctx.guild || !query || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
const track = !isNaN(+query) && isFinite(+query) && !/e/i.test(query) ? player.remove(parseInt(query) - 1) : player.remove(query);
await ctx.reply({ embeds: [I18n.en.removed(track)] });
}
const data = new SlashCommandBuilder()
.setName("remove")
.setDescription("Remove specific track in the queue.")
.addStringOption(option => option
.setName("query")
.setDescription("Position or title to remove.")
.setRequired(true)
);
export { data };
-21
View File
@@ -1,21 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
player.shuffle();
await ctx.reply({ embeds: [I18n.en.reshuffle()] });
}
const data = new SlashCommandBuilder()
.setName("reshuffle")
.setDescription("Shuffle the queue.");
export { data };
-41
View File
@@ -1,41 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const hours = ctx.options.get("hrs")?.value as number || 0;
const minutes = ctx.options.get("mins")?.value as number || 0;
const seconds = ctx.options.get("secs")?.value as number || 0;
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
const time = hours * 3600 + minutes * 60 + seconds;
player.seek(time * 1000);
await ctx.reply({
embeds: [I18n.en.fastForwarded(time)],
});
}
const data = new SlashCommandBuilder()
.setName("seek")
.setDescription("Fast-forward by the time.")
.addIntegerOption(option => option
.setName("hrs")
.setDescription("Hours to seek.")
)
.addIntegerOption(option => option
.setName("mins")
.setDescription("Minutes to seek.")
)
.addIntegerOption(option => option
.setName("secs")
.setDescription("Seconds to seek.")
);
export { data };
-21
View File
@@ -1,21 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
player.destroy();
await ctx.reply({ embeds: [I18n.en.destroyed()] });
}
const data = new SlashCommandBuilder()
.setName("stop")
.setDescription("Destroy the player.");
export { data };
-28
View File
@@ -1,28 +0,0 @@
import { CommandInteraction, SlashCommandBuilder, TextChannel } from "discord.js";
import Client from "../lib/Client.js";
import I18n from "../lib/I18n.js";
export async function run(client: Client, ctx: CommandInteraction) {
const volume = ctx.options.get("volume")?.value as number || 100;
if (!ctx.guild || !ctx.channel) return;
const player = client.modules.music.get(ctx.guild.id, ctx.channel as TextChannel);
if (!player) return;
player.Volume = volume;
await ctx.reply({ embeds: [I18n.en.volumeSet(player.Volume)] });
}
const data = new SlashCommandBuilder()
.setName("volume")
.setDescription("Change player's volume amount.")
.addIntegerOption(option => option
.setName("volume")
.setDescription("Volume in percents.")
.setRequired(true)
);
export { data };
+18 -5
View File
@@ -1,13 +1,26 @@
import { ActivityOptions, ActivityType, ColorResolvable } from "discord.js";
import path from "path";
import { fileURLToPath } from "url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.dirname(fileURLToPath(import.meta.url));
const discordToken = process.env.DISCORD_TOKEN;
const modulesDir = path.join(ROOT, "/modules/");
const binariesDir = path.join(ROOT, "/../bin/");
const activityStatus: ActivityOptions = { type: ActivityType.Watching, name: "over you" };
const colors = {
default: "#ff6e9b" as ColorResolvable,
error: "#b94e59" as ColorResolvable,
warning: "#e5925f" as ColorResolvable,
info: "#367df6" as ColorResolvable,
success: "#83d18e" as ColorResolvable
};
const config = {
token: process.env.DISCORD_TOKEN,
commands: path.join(__dirname, "/commands/"),
events: path.join(__dirname, "/events/"),
binaries: path.join(__dirname, "/../bin/")
discordToken,
modulesDir,
binariesDir,
activityStatus,
colors
};
export default config;
-14
View File
@@ -1,14 +0,0 @@
import { Interaction } from "discord.js";
import Client from "../lib/Client.js";
export async function run(client: Client, args: Interaction[]): Promise<void> {
const [interaction] = args;
if (interaction.isCommand()) {
const command = client.Commands.get(interaction.commandName);
if (command) command.run(client, interaction);
}
}
export const name = "interactionCreate";
-22
View File
@@ -1,22 +0,0 @@
import Client from "../lib/Client.js";
import { generateDependencyReport } from "@discordjs/voice";
import { ActivityType } from "discord.js";
export async function run(client: Client): Promise<void> {
if (!client.user || !client.application) {
console.log("No user or application is provided!");
process.exit(1);
}
console.log(`${client.user.username} logged in as ${client.user.tag}!`);
console.log(generateDependencyReport());
client.user.setActivity("over you", { type: ActivityType.Watching });
const restCommands = Array.from(client.Commands.values()).map(
value => value.data
);
client.application.commands.set(restCommands);
}
export const name = "ready";
-24
View File
@@ -1,24 +0,0 @@
import { VoiceState } from "discord.js";
import I18n from "../lib/I18n.js";
import Client from "../lib/Client.js";
import { asleep } from "../lib/Misc.js";
export async function run(client: Client, args: VoiceState[]): Promise<void> {
const [oldState] = args;
const player = client.modules.music.get(oldState.guild.id);
if (!player || !oldState.channel || !client.user)
return;
if (oldState.channel.members.filter(value => value.user !== client.user).size === 0) {
await asleep(30000);
if (oldState.channel.members.filter(value => value.user !== client.user).size === 0) {
await player.Channel.send({ embeds: [I18n.en.fullyAlone()] });
player.destroy();
}
}
}
export const name = "voiceStateUpdate";
+11 -3
View File
@@ -1,6 +1,14 @@
import Client from "./lib/Client.js";
import { GatewayIntentBits } from "discord.js";
import config from "./config.js";
import Client from "./lib/client.js";
const client = new Client();
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildMembers
]
});
client.login(config.token);
client.login(config.discordToken);
-57
View File
@@ -1,57 +0,0 @@
import {
Client as DiscordClient,
GatewayIntentBits
} from "discord.js";
import { existsSync, readdirSync } from "fs";
import path from "path";
import Music from "./Music.js";
import { command, event } from "./Types.js";
import config from "../config.js";
import { pathToFileURL } from "url";
export default class Client extends DiscordClient {
private commands = new Map<string, command>();
get Commands(): Map<string, command> {
return this.commands;
}
public readonly modules = {
music: new Music()
};
public constructor() {
super({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildVoiceStates
],
});
if (existsSync(config.commands)) {
const files = readdirSync(config.commands).filter((file) =>
file.endsWith(".js")
);
for (const file of files) {
import(pathToFileURL(path.join(config.commands, file)).toString()).then((cmd: command) =>
this.commands.set(cmd.data.name, cmd)
);
}
}
if (existsSync(config.events)) {
const files = readdirSync(config.events).filter((file) =>
file.endsWith(".js")
);
for (const file of files) {
import(pathToFileURL(path.join(config.events, file)).toString()).then((evnt: event) => {
this.on(evnt.name, (...args: unknown[]) =>
evnt.run(this, args)
);
});
}
}
}
}
-54
View File
@@ -1,54 +0,0 @@
import { ytdlArgs, ytdlResponse } from "./Types.js";
import { execFile } from "child_process";
import { promisify } from "util";
import config from "../config.js";
import path from "path";
const execFileAsync = promisify(execFile);
function argumentsResolver(args: ytdlArgs): string[] {
const options = Object.entries(args);
return options.map(([key, value]) => {
if (typeof value === "boolean" && value) {
return `--${key.split(/(?=[A-Z])/).join("-")}`.toLowerCase();
}
else {
return `--${key
.split(/(?=[A-Z])/)
.join("-")}=${value}`.toLowerCase();
}
});
}
async function ytdlExec(
query: string,
args: ytdlArgs
): Promise<ytdlResponse | undefined> {
try {
const executable = await execFileAsync(
path.join(config.binaries, "/youtube-dl"),
[query].concat(argumentsResolver(args))
);
return JSON.parse(executable.stdout);
}
catch (error) {
console.log(error);
return undefined;
}
}
export async function fetchStream(
query: string,
args: ytdlArgs
): Promise<ytdlResponse | undefined> {
let response = await ytdlExec(query, args);
if (response && !response.extractor.includes("youtube")) {
response = await ytdlExec(
`${response.title} - ${response.creator}`,
args
);
}
return response;
}
-77
View File
@@ -1,77 +0,0 @@
export default class Filter {
private filters: Record<string, [boolean, string]> = {
bassboost_low: [false, "bass=g=15:f=110:w=0.3"],
bassboost: [false, "bass=g=20:f=110:w=0.3"],
bassboost_high: [false, "bass=g=30:f=110:w=0.3"],
"8D": [false, "apulsator=hz=0.09"],
vaporwave: [false, "aresample=48000,asetrate=48000*0.75"],
nightcore: [false, "aresample=48000,asetrate=48000*1.25"],
phaser: [false, "aphaser=in_gain=0.4"],
tremolo: [false, "tremolo"],
vibrato: [false, "vibrato=f=6.5"],
reverse: [false, "areverse"],
treble: [false, "treble=g=5"],
normalizer: [false, "dynaudnorm=g=101"],
normalizer2: [false, "acompressor"],
surrounding: [false, "surround"],
pulsator: [false, "apulsator=hz=1"],
subboost: [false, "asubboost"],
karaoke: [false, "stereotools=mlev=0.03"],
flanger: [false, "flanger"],
gate: [false, "agate"],
haas: [false, "haas"],
mcompand: [false, "mcompand"],
mono: [false, "pan=mono|c0=.5*c0+.5*c1"],
mstlr: [false, "stereotools=mode=ms>lr"],
mstrr: [false, "stereotools=mode=ms>rr"],
compressor: [
false,
"compand=points=-80/-105|-62/-80|-15.4/-15.4|0/-12|20/-7.6",
],
expander: [
false,
"compand=attacks=0:points=-80/-169|-54/-80|-49.5/-64.6|-41.1/-41.1|-25.8/-15|-10.8/-4.5|0/0|20/8.3",
],
softlimiter: [
false,
"compand=attacks=0:points=-80/-80|-12.4/-12.4|-6/-8|0/-6.8|20/-2.8",
],
chorus: [false, "chorus=0.7:0.9:55:0.4:0.25:2"],
chorus2d: [false, "chorus=0.6:0.9:50|60:0.4|0.32:0.25|0.4:2|1.3"],
chorus3d: [
false,
"chorus=0.5:0.9:50|60|40:0.4|0.32|0.3:0.25|0.4|0.3:2|2.3|1.3",
],
fadein: [false, "afade=t=in:ss=0:d=10"],
dim: [
false,
"afftfilt=\"'real=re * (1-clip((b/nb)*b,0,1))':imag='im * (1-clip((b/nb)*b,0,1))'\"",
],
earrape: [false, "channelsplit,sidechaingate=level_in=64"],
};
public get Filters(): [string, string][] {
return Object.entries(this.filters)
.filter(value => value[1][0]).map(value => [value[0], value[1][1]]);
}
public toggle(filter?: string): void {
if (!filter) {
Object.values(this.filters).forEach((value) => {
value[0] = false;
});
return;
}
if (Object.prototype.hasOwnProperty.call(this.filters, filter))
this.filters[filter][0] = !this.filters[filter][0];
}
public toString(): string {
return this.Filters.map(value => value[1]).join(",");
}
public empty(): boolean {
return this.Filters.length === 0;
}
}
-294
View File
@@ -1,294 +0,0 @@
import Player from "./Player.js";
import { loopOption, track } from "./Types.js";
import { loopMoji, secToISO, statusBarGenerator, volumeMoji } from "./Misc.js";
import Queue from "./Queue.js";
import { AudioResource } from "@discordjs/voice";
import { EmbedBuilder } from "discord.js";
export default class I18n {
public static en = {
nowPlaying: (track: track) => new EmbedBuilder()
.setColor("LuminousVividPink")
.setAuthor({
iconURL: track.requester.avatarURL() || undefined,
name: track.requester.tag,
})
.setTitle(track.title)
.setURL(track.url)
.setDescription("**playing now.**")
.setThumbnail(track.thumbnail),
cleared: (amount: number) => new EmbedBuilder()
.setColor("Green")
.setTitle(
`**♻️ ${amount} tracks have been cleared from the queue.**`
)
.setTimestamp(new Date()),
okConnected: (channel: string) => new EmbedBuilder()
.setColor("Green")
.setTitle(`**✅ Successfuly connected to:** _${channel}_.`),
notConnected: () => new EmbedBuilder()
.setColor("Red")
.setTitle(
"**🚫 Make yourself connected to a voice channel beforehand.**"
),
wasConnected: () => new EmbedBuilder()
.setColor("Yellow")
.setTitle("**⚠️ Already connected to a voice channel.**"),
filtered: (filter?: string) => new EmbedBuilder()
.setColor("Green")
.setTitle(filter ? `**✅ ${filter} was applied to the player.**` : "**✅ All filters were declined.**"),
appended: (track?: track) => !track
? new EmbedBuilder()
.setColor("Red")
.setTitle("**🚫 Could not add track to the queue.**")
: new EmbedBuilder()
.setColor("Green")
.setTitle(track.title)
.setURL(track.url)
.setThumbnail(track.thumbnail)
.setAuthor({
iconURL: track.requester.avatarURL() || undefined,
name: track.requester.tag,
})
.setDescription("**has been added to the queue.**")
.setTimestamp(new Date()),
jumped: (state: boolean) => state
? new EmbedBuilder()
.setColor("Green")
.setTitle("_**Perfoming jump.**_")
: new EmbedBuilder()
.setColor("Red")
.setTitle("**❗ Bad _jump_ request.**"),
looped: (query: loopOption) => {
switch (query) {
case "AUTO": {
return new EmbedBuilder()
.setColor("LuminousVividPink")
.setTitle(
"**🔀 Shuffle mode** _(does not affect the queue order)_."
);
}
case "LOOP": {
return new EmbedBuilder()
.setColor("Blue")
.setTitle("**🔁 Looping over the queue.**");
}
case "NONE": {
return new EmbedBuilder()
.setColor("Red")
.setTitle("**⤵️ Player will stop on the queue end.**");
}
case "SONG": {
return new EmbedBuilder()
.setColor("Yellow")
.setTitle("**🔂 Looping a single track.**");
}
}
},
skipped: () => new EmbedBuilder()
.setColor("Green")
.setTitle("**⏭️ Skipping.**"),
paused: (state: boolean) => state
? new EmbedBuilder()
.setColor("Green")
.setTitle("_**▶️ Resumed.**_")
: new EmbedBuilder()
.setColor("Yellow")
.setTitle("_**⏸️ Paused.**_"),
removed: (track?: track) => track
? new EmbedBuilder()
.setColor("Green")
.setTitle(track.title)
.setDescription("**was removed from the queue.**")
.setTimestamp(new Date())
.setURL(track.url)
.setThumbnail(track.thumbnail)
: new EmbedBuilder()
.setColor("Red")
.setTitle("**❗ Bad _remove_ request.**"),
fastForwarded: (amount: number) => new EmbedBuilder()
.setColor("Blue")
.setTitle(
`**⏩ Fast-forwarding to ${secToISO(
amount
)}**`
),
destroyed: () => new EmbedBuilder()
.setColor("Red")
.setTitle("**💀 Destroying the player.**"),
volumeSet: (amount: number) => new EmbedBuilder()
.setColor("Green")
.setTitle(`**${volumeMoji(amount)} Volume has been set to ${amount}%**`),
queueEmpty: () => new EmbedBuilder()
.setColor("Yellow")
.setTitle("**❎ Queue is empty.**"),
playerInfo: (player?: Player) => {
if (!player)
return new EmbedBuilder()
.setColor("Red")
.setTitle("**🚫 Player does not exist.**");
if (player.Resource) {
return new EmbedBuilder()
.setColor("LuminousVividPink")
.setTitle(
`${player.Queue.Position + 1}. ${player.Resource.metadata.title}`
)
.setDescription(
statusBarGenerator(
player.Resource.playbackDuration / 1000,
player.Resource.metadata.duration
)
)
.setThumbnail(player.Resource.metadata.thumbnail)
.setURL(player.Resource.metadata.url)
.addFields([
{
name: "Applied Filters",
value:
player.Filter.Filters.map(
(value) => value[0]
).join("\n") + "\ndefault",
inline: true,
},
{
name: "Queue Length",
value: `🔢 ${player.Queue.Tracks.length}`,
inline: true,
},
{
name: "Queue Duration",
value: `💿 ${secToISO(player.Queue.Duration)}`,
inline: true,
},
{
name: "Queue Looping",
value: `${loopMoji(player.Queue.Loop)} ${player.Queue.Loop}`,
inline: true,
},
{
name: "Volume amount",
value: `${volumeMoji(player.Volume)} ${player.Volume}/150`,
inline: true,
},
{
name: "Player lifetime",
value: `🕓 ${secToISO((Date.now() - player.Created.getTime()) / 1000)}`,
inline: true,
},
]);
}
else {
return new EmbedBuilder()
.setColor("Blue")
.setTitle("💿 Insert the disk...")
.setDescription(statusBarGenerator(0, 0))
.setURL(
"https://www.youtube.com/watch?v=dQw4w9WgXcQ&ab_channel=RickAstley"
)
.addFields([
{
name: "Applied Filters",
value:
player.Filter.Filters.map(
(value) => value[0]
).join("\n") + "\ndefault",
inline: true,
},
{
name: "Queue Length",
value: `🔢 ${player.Queue.Tracks.length}`,
inline: true,
},
{
name: "Queue Duration",
value: `💿 ${secToISO(player.Queue.Duration)}`,
inline: true,
},
{
name: "Queue Looping",
value: `${loopMoji(player.Queue.Loop)} ${player.Queue.Loop}`,
inline: true,
},
{
name: "Volume amount",
value: `${volumeMoji(player.Volume)} ${player.Volume}/150`,
inline: true,
},
{
name: "Player lifetime",
value: `🕓 ${secToISO((Date.now() - player.Created.getTime()) / 1000)}`,
inline: true,
},
]);
}
},
queueDesigner: (
queue: Queue,
page: number,
resource: AudioResource<track> | undefined
) => {
page = Math.max(
0,
Math.min(Math.floor(queue.Tracks.length / 11), page)
);
return new EmbedBuilder()
.setColor("LuminousVividPink")
.setTitle(
resource
? `${queue.Position + 1}. ${resource.metadata.title}`
: "💿 Insert the disk..."
)
.setURL(
resource
? resource.metadata.url
: "https://www.youtube.com/watch?v=5mGuCdlCcNM&ab_channel=Ra%C3%BAlBlanco"
)
.setThumbnail(
resource
? resource.metadata.thumbnail
: "https/img.youtube.com/vi/5mGuCdlCcNM/default.jpg"
)
.setDescription(
resource
? statusBarGenerator(
resource.playbackDuration / 1000,
resource.metadata.duration
)
: statusBarGenerator(0, 0)
)
.setFields(
queue.Tracks.slice(page * 10, page * 10 + 10).map(
(value, index) => ({
name: `${
page * 10 + index + 1
}. ${value.title.padEnd(35)}`,
value: `**[${secToISO(value.duration)}]**`,
})
)
);
},
fullyAlone: () => new EmbedBuilder()
.setColor("LuminousVividPink")
.setTitle("🥬 I have decided to leave to conserve my energy.")
.setDescription(
"_**Since there was nobody in the voice channel.**_"
),
reshuffle: () => new EmbedBuilder()
.setColor("Green")
.setTitle("**✅ Successfuly reshuffled queue.**"),
ping: (ping?: number) => {
const title = ping ? `I have pinged ${ping} ms late.` : "There is no application.";
const comment = !ping ? "How am I speaking then?" : ping > 250 ? "I'm kinda slowpoke ngl." :
ping > 200 ? "I can do better than this." :
"Dream's speed!";
return new EmbedBuilder()
.setColor("Random")
.setTitle(`**${title}**`)
.setDescription(`_**${comment}**_`);
}
};
}
-65
View File
@@ -1,65 +0,0 @@
import { loopOption } from "./Types.js";
export function statusBarGenerator(duration: number, length: number): string {
duration = Math.max(0, duration);
length = Math.max(0, length);
if (duration > length) duration = length;
const filled = Array<string>(
Math.floor((15 * duration) / (length === 0 ? 1 : length))
).fill(":small_blue_diamond:");
const empty = Array<string>(
15 - Math.floor((15 * duration) / (length === 0 ? 1 : length))
).fill(":white_small_square:");
return `**[${filled.join("")}${empty.join("")}] ${secToISO(
duration
)}/${secToISO(length)}**`;
}
export function secToISO(amount: number): string {
const h = Math.floor(amount / 3600);
const m = Math.floor((amount % 3600) / 60);
const s = Math.floor((amount % 3600) % 60);
const hDisplay = h > 0 ? `${h}:` : "";
const mDisplay = `${Math.floor(m / 10)}${Math.floor(m % 10)}:`;
const sDisplay = `${Math.floor(s / 10)}${Math.floor(s % 10)}`;
return hDisplay + mDisplay + sDisplay;
}
export async function asleep(amount: number): Promise<unknown> {
return new Promise((r) => setTimeout(r, amount));
}
export function volumeMoji(amount: number): string {
return amount > 100 ? "🔊" : amount > 50 ? "🔉" : amount > 0 ? "🔈" : "🔇";
}
export function loopMoji(loop: loopOption): string {
return loop === "AUTO"
? "🔀"
: loop === "LOOP"
? "🔁"
: loop === "NONE"
? "⤵️"
: "🔂";
}
export function largestCommonSequence(s1: string, s2: string) {
s1 = s1.toLowerCase().slice(0, 100);
s2 = s2.toLowerCase().slice(0, 100);
const buffer = Array.from(
Array(s1.length + 1),
() => new Array<number>(s2.length + 1).fill(0)
);
for (let i = 1; i <= s1.length; i++) {
for (let j = 1; j <= s2.length; j++) {
if (s1[i - 1] === s2[j - 1])
buffer[i][j] = buffer[i - 1][j - 1] + 1;
else buffer[i][j] = Math.max(buffer[i - 1][j], buffer[i][j - 1]);
}
}
return buffer[s1.length][s2.length];
}
-25
View File
@@ -1,25 +0,0 @@
import { Guild, TextChannel } from "discord.js";
import Player from "./Player.js";
export default class Music {
private players = new Map<string, Player>();
public get(guildId: string, channel?: TextChannel): Player | undefined {
const player = this.players.get(guildId);
if (player) {
if (channel) player.Channel = channel;
return player;
}
}
public set(guild: Guild, channel: TextChannel): Player {
const player = new Player(guild, this, channel);
this.players.set(guild.id, player);
return player;
}
public del(guildId: string): void {
this.players.delete(guildId);
}
}
-335
View File
@@ -1,335 +0,0 @@
import {
VoiceConnection,
AudioPlayer,
createAudioResource,
AudioPlayerStatus,
joinVoiceChannel,
createAudioPlayer,
AudioResource,
DiscordGatewayAdapterCreator,
VoiceConnectionStatus,
entersState,
} from "@discordjs/voice";
import {
Guild,
Message,
TextChannel,
User,
VoiceBasedChannel,
} from "discord.js";
import Music from "./Music.js";
import Filter from "./Filter.js";
import Queue from "./Queue.js";
import { fetchStream } from "./Fetch.js";
import I18n from "./I18n.js";
import ytdl from "discord-ytdl-core";
import { track } from "./Types.js";
import { largestCommonSequence } from "./Misc.js";
export default class Player {
private music: Music;
private guild: Guild;
private channel: TextChannel;
public get Channel(): TextChannel {
return this.channel;
}
public set Channel(x: TextChannel) {
this.channel = x;
}
private connection: VoiceConnection | undefined;
public get Connection(): VoiceConnection | undefined {
return this.connection;
}
private player: AudioPlayer;
public get Player(): AudioPlayer {
return this.player;
}
private filter = new Filter();
public get Filter(): Filter {
return this.filter;
}
private queue = new Queue();
public get Queue(): Queue {
return this.queue;
}
private resource: AudioResource<track> | undefined;
public get Resource(): AudioResource<track> | undefined {
return this.resource;
}
private message: Message | undefined;
private created: Date = new Date();
public get Created(): Date {
return this.created;
}
private volume = 100;
public get Volume(): number {
return this.volume;
}
public set Volume(x: number) {
this.volume = Math.max(0, Math.min(150, x));
if (this.resource && this.resource.volume) this.resource.volume.setVolumeLogarithmic(this.volume / 100);
}
public constructor(
guild: Guild,
music: Music,
textChannel: TextChannel
) {
this.music = music;
this.guild = guild;
this.channel = textChannel;
this.player = createAudioPlayer();
this.player.on(AudioPlayerStatus.Idle, async () =>
this.resourceEndResolvable()
);
}
private resourceGenerator(track: track, seek?: number) {
const stream = ytdl(track.url, {
opusEncoded: false,
fmt: "mp3",
filter: "audioonly",
highWaterMark: 1 << 25,
seek: seek ? seek / 1000 : undefined,
encoderArgs: !this.filter.empty()
? ["-af", this.filter.toString()]
: undefined,
});
this.resource = createAudioResource(stream, {
inlineVolume: true,
metadata: track,
});
if (seek) this.resource.playbackDuration = seek;
if (this.resource.volume) this.resource.volume.setVolumeLogarithmic(this.volume / 100);
return this.resource;
}
private resourceEndResolvable(): void {
if (this.resource) this.resource.encoder?.destroy();
if (this.queue.next()) {
this.play();
}
else {
this.resource = undefined;
this.player.stop();
}
}
private async messageResolvable(track: track) {
if (this.message) await this.message.delete();
this.message = await this.channel.send({
embeds: [I18n.en.nowPlaying(track)],
});
}
private async search(
query: string,
requester: User
): Promise<track[] | undefined> {
const response = await fetchStream(query, {
dumpSingleJson: true,
noWarnings: true,
noCheckCertificate: true,
flatPlaylist: true,
skipDownload: true,
defaultSearch: "ytsearch",
});
if (!response) return undefined;
const tracks: track[] = [];
if (response.entries) {
for (const entry of response.entries) {
tracks.push({
url: `https://youtube.com/watch?v=${entry.id}`,
title: entry.title,
thumbnail: `https://img.youtube.com/vi/${entry.id}/default.jpg`,
duration: entry.duration,
requester: requester,
});
}
}
else {
tracks.push({
url: `https://youtube.com/watch?v=${response.id}`,
title: response.title,
thumbnail: `https://img.youtube.com/vi/${response.id}/default.jpg`,
duration: response.duration,
requester: requester,
});
}
return tracks;
}
public play(seek?: number): void {
const track = this.queue.current();
if (!this.connection || !track) return;
this.player.play(this.resourceGenerator(track, seek));
this.connection.subscribe(this.player);
this.messageResolvable(track);
}
public connect(channel: VoiceBasedChannel): void {
if (this.connection) this.connection.destroy();
this.connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guildId,
adapterCreator: channel.guild
.voiceAdapterCreator as DiscordGatewayAdapterCreator,
});
this.connection.on(
VoiceConnectionStatus.Disconnected,
async () => {
try {
await Promise.race([
entersState(
this.connection as VoiceConnection,
VoiceConnectionStatus.Signalling,
10_000
),
entersState(
this.connection as VoiceConnection,
VoiceConnectionStatus.Connecting,
10_000
),
]);
}
catch (error) {
this.destroy();
}
}
);
}
public async add(
query: string,
requester: User,
index?: number
): Promise<track | undefined> {
const tracks = await this.search(query, requester);
if (!tracks) return;
this.queue.push(tracks, index);
return tracks[0];
}
public jump(query: number | string): boolean {
let position = typeof query === "number" ? query : -1;
let diff = 0;
if (typeof query === "string") {
this.queue.Tracks.forEach((track, index) => {
const tempDiff = largestCommonSequence(track.title, query);
if (diff < tempDiff) {
diff = tempDiff;
position = index;
}
});
}
if (position !== -1 && this.queue.jump(position)) {
this.play();
return true;
}
return false;
}
public remove(query?: number | string): track | undefined {
const oldPosition = this.queue.Position;
let newPosition = typeof query === "number" ? query : this.queue.Position;
let diff = 0;
if (typeof query === "string") {
this.queue.Tracks.forEach((track, index) => {
const tempDiff = largestCommonSequence(track.title, query);
if (diff < tempDiff) {
diff = tempDiff;
newPosition = index;
}
});
}
const track = this.queue.pop(newPosition);
if (track) {
if (oldPosition === newPosition) this.play();
return track;
}
return undefined;
}
public seek(time: number): void {
this.play(time);
}
public clear(): void {
this.queue.clear();
this.resource = undefined;
if (this.player) this.player.stop();
}
public destroy(): void {
if (this.connection) this.connection.destroy();
this.player.stop();
this.music.del(this.guild.id);
}
public pause(): boolean {
if (this.player.state.status === AudioPlayerStatus.Paused) {
this.player.unpause();
return false;
}
else {
this.player.pause();
return true;
}
}
public shuffle(): void {
this.queue.shuffle();
if (this.resource) {
this.player.stop();
this.play();
}
}
public skip(): void {
this.player.stop();
}
public setFilter(filter?: string): void {
this.filter.toggle(filter);
if (this.resource) this.play(this.resource.playbackDuration);
}
}
-115
View File
@@ -1,115 +0,0 @@
import { loopOption, track } from "./Types.js";
export default class Queue {
private tracks: track[] = [];
public get Tracks(): track[] {
return this.tracks;
}
private position = 0;
public get Position(): number {
return this.position;
}
private loop: loopOption = "NONE";
public get Loop(): loopOption {
return this.loop;
}
public set Loop(x: loopOption) {
this.loop = x;
}
private duration = 0;
public get Duration(): number {
return this.duration;
}
public next(): track | undefined {
if (this.loop === "SONG") return this.current();
if (this.loop === "AUTO") {
this.position = Math.floor(Math.random() * this.tracks.length);
return this.current();
}
if (this.position + 1 < this.tracks.length) {
this.position++;
return this.current();
}
else if (this.loop === "LOOP") {
this.position = 0;
return this.current();
}
else if (this.loop === "NONE") {
this.position = 0;
return undefined;
}
}
public shuffle(): void {
let currentIndex = this.tracks.length;
while (currentIndex != 0) {
const randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[this.tracks[currentIndex], this.tracks[randomIndex]] = [
this.tracks[randomIndex],
this.tracks[currentIndex],
];
}
this.position = 0;
}
public push(tracks: track[], index?: number): track {
if (!index || index >= this.tracks.length) {
this.tracks = this.tracks.concat(tracks);
}
else {
this.tracks.splice(Math.max(0, index), 0, ...tracks);
if (this.position >= index) this.position += tracks.length;
}
for (const track of tracks) {
this.duration += track.duration;
}
return this.tracks[index || this.tracks.length - 1];
}
public pop(query: number): track | undefined {
if (query >= 0 && query < this.tracks.length) {
const track = this.tracks[query];
this.tracks.splice(query, 1);
this.position = Math.max(0, this.position - 1);
this.duration -= track.duration;
return track;
}
return undefined;
}
public jump(query: number): track | undefined {
if (query >= 0 && query < this.tracks.length) {
const track = this.tracks[query];
this.position = query;
return track;
}
return undefined;
}
public current(): track {
return this.tracks[this.position];
}
public empty(): boolean {
return this.tracks.length === 0;
}
public clear(): void {
this.tracks = [];
this.position = 0;
}
}
-272
View File
@@ -1,272 +0,0 @@
import { ApplicationCommandData, User, CommandInteraction } from "discord.js";
import Client from "./Client.js";
export type track = {
url: string;
title: string;
thumbnail: string;
duration: number;
requester: User;
};
export type command = {
data: ApplicationCommandData;
run: (arg0: Client, arg1: CommandInteraction) => Promise<void>;
};
export type event = {
name: string;
run: (arg0: Client, arg1: unknown[]) => Promise<void>;
};
export type loopOption = "LOOP" | "SONG" | "NONE" | "AUTO";
export type ytdlArgs = {
help?: boolean;
version?: boolean;
update?: boolean;
ignoreErrors?: boolean;
abortOnError?: boolean;
dumpUserAgent?: boolean;
listExtractors?: boolean;
extractorDescriptions?: boolean;
forceGenericExtractor?: boolean;
defaultSearch?: string;
igonreConfig?: boolean;
configLocation?: string;
flatPlaylist?: boolean;
markWatched?: boolean;
noColor?: boolean;
proxy?: string;
socketTimeout?: number;
sourceAddress?: string;
forceIpv4?: boolean;
forceIpv6?: boolean;
geoVerificationProxy?: string;
geoBypass?: boolean;
geoBypassCountry?: string;
geoBypassIpBlock?: string;
playlistStart?: number;
playlistEnd?: number | "last";
playlistItems?: string;
matchTitle?: string;
rejectTitle?: string;
maxDownloads?: number;
minFilesize?: string;
maxFilesize?: string;
date?: string;
datebefore?: string;
dateafter?: string;
minViews?: number;
maxViews?: number;
matchFilter?: string;
noPlaylist?: boolean;
yesPlaylist?: boolean;
ageLimit?: number;
downloadArchive?: string;
includeAds?: boolean;
limitRate?: string;
retries?: number | "infinite";
skipUnavailableFragments?: boolean;
abortOnUnavailableFragment?: boolean;
keepFragments?: boolean;
bufferSize?: string;
noResizeBuffer?: boolean;
httpChunkSize?: string;
playlistReverse?: boolean;
playlistRandom?: boolean;
xattrSetFilesize?: boolean;
hlsPreferNative?: boolean;
hlsPreferFfmpeg?: boolean;
hlsUseMpegts?: boolean;
externalDownloader?: string;
externalDownloaderArgs?: string;
batchFile?: string;
id?: boolean;
output?: string;
outputNaPlaceholder?: string;
autonumberStart?: number;
restrictFilenames?: boolean;
noOverwrites?: boolean;
continue?: boolean;
noPart?: boolean;
noMtime?: boolean;
writeDescription?: boolean;
writeInfoJson?: boolean;
writeAnnotations?: boolean;
loadInfoJson?: string;
cookies?: string;
cacheDir?: string;
noCacheDir?: boolean;
rmCacheDir?: boolean;
writeThumbnail?: boolean;
writeAllThumbnails?: boolean;
listThumbnails?: boolean;
quiet?: boolean;
noWarnings?: boolean;
simulate?: boolean;
skipDownload?: boolean;
getUrl?: boolean;
getTitle?: boolean;
getId?: boolean;
getThumbnail?: boolean;
getDuration?: boolean;
getFilename?: boolean;
getFormat?: boolean;
dumpJson?: boolean;
dumpSingleJson?: boolean;
printJson?: boolean;
newline?: boolean;
noProgress?: boolean;
consoleTitle?: boolean;
verbose?: boolean;
dumpPages?: boolean;
writePages?: boolean;
printTraffic?: boolean;
callHome?: boolean;
encoding?: string;
noCheckCertificate?: boolean;
preferInsecure?: boolean;
userAgent?: string;
referer?: string;
addHeader?: string;
bidiWorkaround?: boolean;
sleepInterval?: number;
maxSleepInterval?: number;
format?: string;
allFormats?: boolean;
preferFreeFormats?: boolean;
listFormats?: boolean;
youtubeSkipDashManifest?: boolean;
mergeOutputFormat?: string;
writeSub?: boolean;
writeAutoSub?: boolean;
allSubs?: boolean;
listSubs?: boolean;
subFormat?: string;
subLang?: string;
username?: string;
password?: string;
twofactor?: string;
netrc?: boolean;
videoPassword?: string;
apMso?: string;
apUsername?: string;
apPassword?: string;
apListMso?: boolean;
extractAudio?: boolean;
audioFormat?: string;
audioQuality?: number;
recodeVideo?: string;
postprocessorArgs?: string;
keepVideo?: boolean;
noPostOverwrites?: boolean;
embedSubs?: boolean;
embedThumbnail?: boolean;
addMetadata?: boolean;
metadataFromFile?: string;
xattrs?: boolean;
fixup?: string;
preferAvconv?: boolean;
preferFfmpeg?: boolean;
ffmpegLocation?: string;
exec?: string;
convertSubs?: string;
};
type ytdlFormat = {
asr: number;
filesize: number;
format_id: string;
format_note: string;
fps: number;
height: number;
quality: number;
tbr: number;
url: string;
width: number;
ext: string;
vcodec: string;
acodec: string;
abr: number;
downloader_options: unknown;
container: string;
format: string;
protocol: string;
http_headers: unknown;
};
type ytdlThumbnail = {
height: number;
url: string;
width: number;
resolution: string;
id: string;
};
type ytdlEntry = {
uploader: string;
duration: number;
id: string;
title: string;
url: string;
};
export type ytdlResponse = {
id: string;
title: string;
formats: ytdlFormat[];
thumbnails: ytdlThumbnail[];
description: string;
upload_date: string;
uploader: string;
uploader_id: string;
uploader_url: string;
channel_id: string;
channel_url: string;
duration: number;
view_count: number;
average_rating: number;
age_limit: number;
webpage_url: string;
categories: string[];
tags: string[];
is_live: boolean;
like_count: number;
dislike_count: number;
channel: string;
track: string;
artist: string;
creator: string;
alt_title: string;
extractor: string;
webpage_url_basename: string;
extractor_key: string;
playlist: string;
playlist_index: number;
thumbnail: string;
display_id: string;
requested_subtitles: unknown;
asr: number;
filesize: number;
format_id: string;
format_note: string;
fps: number;
height: number;
quality: number;
tbr: number;
url: string;
width: number;
ext: string;
vcodec: string;
acodec: string;
abr: number;
downloader_options: { http_chunk_size: number };
container: string;
format: string;
protocol: string;
http_headers: unknown;
fulltitle: string;
_filename: string;
entries: ytdlEntry[];
};
+91
View File
@@ -0,0 +1,91 @@
import { PrismaClient } from "@prisma/client";
import { Client as DiscordClient, ClientOptions, Collection } from "discord.js";
import { existsSync, lstatSync, readdirSync } from "fs";
import path from "path";
import { pathToFileURL } from "url";
import config from "../config.js";
import { Command, Event, Module, ModuleMetadata } from "./types.js";
const MODULE_ENTRY = "module.js";
const MODULE_COMMANDS = "commands";
const MODULE_EVENTS = "events";
export default class Client extends DiscordClient {
public readonly commands = new Collection<string, Command>();
public readonly modules = new Collection<string, ModuleMetadata>();
public readonly db = new PrismaClient();
public constructor(options: ClientOptions) {
super(options);
for (const module of readdirSync(config.modulesDir)) {
const modulePath = path.join(config.modulesDir, module);
if (!lstatSync(modulePath).isDirectory()) {
continue;
}
import(pathToFileURL(path.join(modulePath, MODULE_ENTRY)).toString()).then(
(data: Module) => this.loadModule(data)
);
}
}
private loadModule(data: Module): void {
const commands: string[] = [];
const events: string[] = [];
function importModule(dir: string, importThen: (data: Command & Event) => void) {
if (existsSync(dir)) {
for (const source of readdirSync(dir)) {
const file = path.join(dir, source);
if (!lstatSync(file).isFile() || !file.endsWith(".js")) {
continue;
}
import(pathToFileURL(file).toString()).then(importThen);
}
}
}
importModule(path.join(data.rootDir, MODULE_COMMANDS), (command: Command) => {
this.commands.set(command.data.name, command);
commands.push(command.data.name);
});
importModule(path.join(data.rootDir, MODULE_EVENTS), (event: Event) => {
this.on(
event.name,
async (...eventee: unknown[]) => await event.execute(this, eventee)
);
events.push(event.name);
});
this.modules.set(data.name, {
...data,
commands,
events
});
}
public generateApplicationStatus(): string[] {
const modulesStatus = this.modules.map((module) => {
const tag = `✓ ${module.name}@${module.tag} module is loaded.`;
const commands = module.commands.map((name) => " - " + name).join("\n");
const events = module.events.map((name) => " - " + name).join("\n");
return [`${tag}\n`, "commands:", `${commands}`, "events:", `${events}`].join("\n");
});
const clientStatus =
this.user && this.application
? `✓ ${this.application.id} successfully logged in as ${this.user.tag}.`
: "✖ Application is not availiable.";
return modulesStatus.concat(clientStatus);
}
}
+13
View File
@@ -0,0 +1,13 @@
import winston from "winston";
const logger = winston.createLogger({
level: "info",
format: winston.format.combine(winston.format.timestamp(), winston.format.json()),
transports: [
new winston.transports.Console({ format: winston.format.simple() }),
new winston.transports.File({ filename: "logs/error.log", level: "error" }),
new winston.transports.File({ filename: "logs/combined.log" })
]
});
export default logger;
+27
View File
@@ -0,0 +1,27 @@
import { ApplicationCommandData, CommandInteraction } from "discord.js";
import Client from "./client.js";
export interface Module {
name: string;
description?: string;
author: string;
tag: string;
controller?: unknown;
rootDir: string;
}
export interface ModuleMetadata extends Module {
commands: string[];
events: string[];
}
export interface Command {
data: ApplicationCommandData;
execute: (client: Client, interaction: CommandInteraction) => Promise<void>;
}
export interface Event {
name: string;
execute: (client: Client, eventee: unknown[]) => Promise<void>;
}
+21
View File
@@ -0,0 +1,21 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.isChatInputCommand()) {
logger.warn("Interaction rejected.", { interaction });
return;
}
await interaction.reply(replies.modules(client.modules));
}
const data = new SlashCommandBuilder()
.setName("modules")
.setDescription("List of availiable modules.");
export { data, execute };
+23
View File
@@ -0,0 +1,23 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.isChatInputCommand()) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const reply = await interaction.reply({ ...replies.ping(client.ws.ping), fetchReply: true });
await interaction.editReply(
replies.ping(client.ws.ping, reply.createdTimestamp - interaction.createdTimestamp)
);
}
const data = new SlashCommandBuilder().setName("ping").setDescription("Try to ping me.");
export { data, execute };
@@ -0,0 +1,32 @@
import { Events, Interaction } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
async function execute(client: Client, eventee: [Interaction]): Promise<void> {
const [interaction] = eventee;
if (interaction.isChatInputCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) {
logger.error(`No command matching ${interaction.commandName} was found.`, {
interaction
});
return;
}
try {
logger.info(`Interaction ${interaction.commandName} was created.`, interaction);
await command.execute(client, interaction);
} catch (error) {
logger.error("Interaction error occured. ", { error, interaction });
}
}
}
const name = Events.InteractionCreate;
export { execute, name };
+37
View File
@@ -0,0 +1,37 @@
import { generateDependencyReport } from "@discordjs/voice";
import { Events } from "discord.js";
import config from "../../../config.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
async function execute(client: Client): Promise<void> {
if (!client.user || !client.application) {
throw new Error("No application or user for it is provided.");
}
const commandData = Array.from(client.commands.values()).map((value) => value.data);
if (process.env.NODE_ENV === "development" && process.env.TEST_GUILD) {
logger.info("Development mode: Commands will be pushed to the test guild!");
logger.info(generateDependencyReport());
const guild = await client.guilds.fetch(process.env.TEST_GUILD);
guild.commands.set(commandData);
}
if (process.env.NODE_ENV === "production") {
logger.info("Production mode: Commands will be pushed to the application!");
await client.application.commands.set(commandData);
}
client.generateApplicationStatus().forEach((report) => logger.info(report));
client.user.setActivity(config.activityStatus);
}
const name = Events.ClientReady;
export { execute, name };
+36
View File
@@ -0,0 +1,36 @@
import { BaseMessageOptions, Collection, EmbedBuilder, italic } from "discord.js";
import config from "../../../config.js";
import { ModuleMetadata } from "../../../lib/types.js";
const replies = {
modules: (modules: Collection<string, ModuleMetadata>): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.default)
.setTitle("Applied modules")
.addFields(
modules.map((value) => {
return {
name: value.name + "@" + value.tag,
value: italic(value.description ?? "")
};
})
);
return { embeds: [embed] };
},
ping: (websocket: number, roundtrip?: number): BaseMessageOptions => {
const title = roundtrip ? `I've pinged ${roundtrip} ms. late` : "Pinging...";
const comment = `Websocket ping is ${websocket} ms.`;
const embed = new EmbedBuilder()
.setColor(config.colors.default)
.setTitle(title)
.setDescription(italic(comment));
return { embeds: [embed] };
}
};
export default replies;
+11
View File
@@ -0,0 +1,11 @@
import path from "path";
import { fileURLToPath } from "url";
const name = "core";
const description = "Quetza core functionality";
const author = "unknowableshade";
const tag = "4.2.2";
const rootDir = path.dirname(fileURLToPath(import.meta.url));
export { author, description, name, rootDir, tag };
+35
View File
@@ -0,0 +1,35 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
const amount = player.queue.tracks.length;
player.clear();
await interaction.reply(replies.cleared(amount));
}
const data = new SlashCommandBuilder()
.setName("clear")
.setDescription("Clear the player's queue.")
.setDMPermission(false);
export { data, execute };
+43
View File
@@ -0,0 +1,43 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
await interaction.deferReply();
const player =
controller.get(interaction.guild, interaction.channel) ??
controller.set(interaction.guild, interaction.channel);
const channel = interaction.member.voice.channel;
if (!channel) {
controller.delete(interaction.guildId);
await interaction.editReply(replies.notConnected());
return;
}
player.connect(channel);
await interaction.editReply(replies.okConnected(channel.name));
return;
}
const data = new SlashCommandBuilder()
.setName("connect")
.setDescription("Connect me explicitly to the voice channel.")
.setDMPermission(false);
export { data, execute };
+46
View File
@@ -0,0 +1,46 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import Filter from "../lib/filter.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const filter = interaction.options.getString("filter") ?? undefined;
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
const status = player.setFilter(filter);
await interaction.reply(replies.filtered(filter, status));
}
const data = new SlashCommandBuilder()
.setName("filter")
.setDescription("Apply unique filters to the playback.")
.addStringOption((option) =>
option
.setName("filter")
.setDescription("Filter to apply.")
.setChoices(
...Object.keys(Filter.filters).map((key) => {
return { name: key, value: key };
})
)
)
.setDMPermission(false);
export { data, execute };
+31
View File
@@ -0,0 +1,31 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
await interaction.reply(replies.info(player));
}
const data = new SlashCommandBuilder()
.setName("info")
.setDescription("Verbose information about player and stats.")
.setDMPermission(false);
export { data, execute };
+44
View File
@@ -0,0 +1,44 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const query = interaction.options.getString("query", true);
const pos = interaction.options.getInteger("position", true);
await interaction.deferReply();
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.editReply(replies.notExists());
return;
}
const track = await player.add(query, interaction.user, pos - 1);
await interaction.editReply(replies.appended(track));
}
const data = new SlashCommandBuilder()
.setName("insert")
.setDescription("Insert a new track to specific position in the queue.")
.addStringOption((option) =>
option.setName("query").setDescription("Title or URL of the song.").setRequired(true)
)
.addIntegerOption((option) =>
option.setName("position").setDescription("Position to insert.").setRequired(true)
)
.setDMPermission(false);
export { data, execute };
+43
View File
@@ -0,0 +1,43 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const query = interaction.options.getString("query", true);
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
const previous = player.resource?.metadata;
const position =
!isNaN(+query) && isFinite(+query) && !/e/i.test(query)
? player.jump(parseInt(query) - 1)
: player.jump(query);
await interaction.reply(replies.jumped(previous, position));
}
const data = new SlashCommandBuilder()
.setName("jump")
.setDescription("Jump to specific track in the queue.")
.addStringOption((option) =>
option.setName("query").setDescription("Position or title to jump to.").setRequired(true)
)
.setDMPermission(false);
export { data, execute };
+48
View File
@@ -0,0 +1,48 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { LoopOption } from "../lib/types.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const option = interaction.options.getString("option", true) as LoopOption;
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
player.queue.loop = option;
await interaction.reply(replies.looped(option));
}
const data = new SlashCommandBuilder()
.setName("loop")
.setDescription("Select player's loop mode.")
.addStringOption((option) =>
option
.setName("option")
.setDescription("Loop option.")
.setChoices(
{ name: "Loop queue", value: "LOOP" },
{ name: "Loop single track", value: "SONG" },
{ name: "Drop on final", value: "NONE" },
{ name: "Random", value: "AUTO" }
)
.setRequired(true)
)
.setDMPermission(false);
export { data, execute };
+33
View File
@@ -0,0 +1,33 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
player.skip();
await interaction.reply(replies.skipped());
}
const data = new SlashCommandBuilder()
.setName("next")
.setDescription("Skip current song.")
.setDMPermission(false);
export { data, execute };
+33
View File
@@ -0,0 +1,33 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
const state = player.pause();
await interaction.reply(replies.paused(state));
}
const data = new SlashCommandBuilder()
.setName("pause")
.setDescription("Toggle pause on playback.")
.setDMPermission(false);
export { data, execute };
+58
View File
@@ -0,0 +1,58 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const query = interaction.options.getString("query");
if (query) {
await interaction.reply(replies.searching());
} else {
await interaction.deferReply();
}
const player =
controller.get(interaction.guild, interaction.channel) ??
controller.set(interaction.guild, interaction.channel);
const channel = interaction.member.voice.channel;
if (!channel) {
controller.delete(interaction.guildId);
await interaction.editReply(replies.notConnected());
return;
}
player.connect(channel);
if (query) {
const track = await player.add(query, interaction.user);
await interaction.editReply(replies.appended(track));
}
if (!player.resource) {
await player.play();
}
}
const data = new SlashCommandBuilder()
.setName("play")
.setDescription("Launch player and add songs to the queue.")
.addStringOption((option) =>
option.setName("query").setDescription("Title or URL of the song.")
)
.setDMPermission(false);
export { data, execute };
+86
View File
@@ -0,0 +1,86 @@
import {
ActionRowBuilder,
ButtonBuilder,
ButtonInteraction,
ButtonStyle,
ChatInputCommandInteraction,
MessageActionRowComponentBuilder,
SlashCommandBuilder
} from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
await interaction.deferReply();
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.editReply(replies.notExists());
return;
}
if (player.queue.empty()) {
await interaction.editReply(replies.queue(player.queue));
return;
}
let position = 1;
const row = new ActionRowBuilder<MessageActionRowComponentBuilder>().addComponents(
new ButtonBuilder().setCustomId("Top").setLabel("🔼").setStyle(ButtonStyle.Primary),
new ButtonBuilder().setCustomId("Up").setLabel("🔺").setStyle(ButtonStyle.Secondary),
new ButtonBuilder().setCustomId("Down").setLabel("🔻").setStyle(ButtonStyle.Secondary),
new ButtonBuilder().setCustomId("End").setLabel("🔽").setStyle(ButtonStyle.Primary)
);
const message = await interaction.editReply({
...replies.queue(player.queue, 0, player.resource),
components: [row]
});
const collector = message.createMessageComponentCollector({ time: 30000 });
collector.on("collect", async (btn: ButtonInteraction) => {
switch (btn.customId) {
case "Top": {
position = 1;
break;
}
case "Up": {
position = Math.max(position - 10, 1);
break;
}
case "Down": {
position = Math.min(
position + 10,
Math.floor(player.queue.tracks.length / 10) * 10
);
break;
}
case "End": {
position = Math.floor(player.queue.tracks.length / 10) * 10;
}
}
await btn.update(replies.queue(player.queue, position - 1, player.resource));
});
}
const data = new SlashCommandBuilder()
.setName("queue")
.setDescription("Print interactive queue pointing to current track.")
.setDMPermission(false);
export { data, execute };
+41
View File
@@ -0,0 +1,41 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const query = interaction.options.getString("query", true);
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
const track =
!isNaN(+query) && isFinite(+query) && !/e/i.test(query)
? player.remove(parseInt(query) - 1)
: player.remove(query);
await interaction.reply(replies.removed(track));
}
const data = new SlashCommandBuilder()
.setName("remove")
.setDescription("Remove specific track in the queue.")
.addStringOption((option) =>
option.setName("query").setDescription("Position or title to remove.").setRequired(true)
)
.setDMPermission(false);
export { data, execute };
+33
View File
@@ -0,0 +1,33 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
player.shuffle();
await interaction.reply(replies.reshuffle());
}
const data = new SlashCommandBuilder()
.setName("reshuffle")
.setDescription("Reshuffle the queue. (Will change queue order)")
.setDMPermission(false);
export { data, execute };
+50
View File
@@ -0,0 +1,50 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const hours = interaction.options.getInteger("hrs") ?? 0;
const minutes = interaction.options.getInteger("mins") ?? 0;
const seconds = interaction.options.getInteger("secs") ?? 0;
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
if (!player.resource) {
await interaction.reply(replies.notPlaying());
return;
}
const prevTime = player.resource.playbackDuration / 1000;
const nextTime = hours * 3600 + minutes * 60 + seconds;
player.seek(nextTime * 1000);
await interaction.reply(replies.seeked(prevTime, nextTime));
}
const data = new SlashCommandBuilder()
.setName("seek")
.setDescription("Fast-forward/Fast-reverse by the given time.")
.addIntegerOption((option) => option.setName("hrs").setDescription("Hours to seek."))
.addIntegerOption((option) => option.setName("mins").setDescription("Minutes to seek."))
.addIntegerOption((option) => option.setName("secs").setDescription("Seconds to seek."))
.setDMPermission(false);
export { data, execute };
+33
View File
@@ -0,0 +1,33 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
player.destroy();
await interaction.reply(replies.destroyed());
}
const data = new SlashCommandBuilder()
.setName("stop")
.setDescription("Destroy the player.")
.setDMPermission(false);
export { data, execute };
+38
View File
@@ -0,0 +1,38 @@
import { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction) {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild() || !interaction.channel) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const volume = interaction.options.getInteger("volume") ?? 100;
const player = controller.get(interaction.guild, interaction.channel);
if (!player) {
await interaction.reply(replies.notExists());
return;
}
player.volume = volume;
await interaction.reply(replies.volumeSet(player.volume));
}
const data = new SlashCommandBuilder()
.setName("volume")
.setDescription("Change player's volume amount.")
.addIntegerOption((option) =>
option.setName("volume").setDescription("Volume in percents.").setRequired(true)
)
.setDMPermission(false);
export { data, execute };
@@ -0,0 +1,36 @@
import { VoiceState } from "discord.js";
import Client from "../../../lib/client.js";
import { asleep } from "../lib/misc.js";
import replies from "../lib/replies.js";
import { controller } from "../module.js";
const WAIT_TIME = 30_000;
async function execute(client: Client, eventee: [VoiceState]): Promise<void> {
const [oldState] = eventee;
const player = controller.get(oldState.guild);
if (!player || !oldState.channel || !client.user) {
return;
}
if (
oldState.channel.members.size === 1 &&
oldState.channel.members.first()?.user === client.user
) {
await asleep(WAIT_TIME);
if (
oldState.channel.members.size === 1 &&
oldState.channel.members.first()?.user === client.user
) {
await player.channel.send(replies.alone());
player.destroy();
}
}
}
const name = "voiceStateUpdate";
export { execute, name };
+245
View File
@@ -0,0 +1,245 @@
import { execFile } from "child_process";
import path from "path";
import prismMedia from "prism-media";
import { Duplex, Readable } from "stream";
import { promisify } from "util";
import ytdl from "ytdl-core";
import config from "../../../config.js";
import logger from "../../../lib/logger.js";
import { StreamOptions, YtdlDump, YtdlResult, YtdlStreamOptions } from "./types.js";
const { opus: Opus, FFmpeg } = prismMedia;
const execFileAsync = promisify(execFile);
const SEARCH_DEPTH = 5;
const YTDL_EVENTS = [
"info",
"progress",
"abort",
"request",
"response",
"error",
"redirect",
"retry",
"reconnect"
];
function isURL(url: string): boolean {
return /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_+.~#?&//=]*)$/.test(
url
);
}
async function fetchInfoRecursive(query: string, depth = 0): Promise<YtdlResult[]> {
if (depth === SEARCH_DEPTH) {
logger.warn("yt-dlp failed to find anything.", { query });
return [];
}
const executable = await execFileAsync(path.join(config.binariesDir, "/yt-dlp"), [
query,
"-O %(.{id,original_url,title,uploader,duration,extractor_key,thumbnail})j",
"-s",
"--flat-playlist"
]);
const dump: YtdlDump[] = JSON.parse("[" + executable.stdout.replace(/\n(?=.+)/g, ",") + "]");
const result: YtdlResult[] = [];
for (const entry of dump) {
if (entry.title && entry.thumbnail && entry.duration && entry.extractor_key === "Youtube") {
result.push({
url: entry.original_url,
title: entry.title,
thumbnail: entry.thumbnail,
duration: entry.duration
});
logger.info("yt-dlp has found corresponding youtube video.", {
result: result[result.length - 1]
});
continue;
}
let unwind: YtdlResult[];
if (entry.extractor_key !== "Youtube" && entry.title) {
unwind = await fetchInfoRecursive(
`ytsearch1:${entry.uploader ? entry.uploader + " - " : ""} ${entry.title}`,
depth + 1
);
} else {
unwind = await fetchInfoRecursive(entry.original_url, depth + 1);
}
if (unwind.length !== 0) {
result.push(unwind[0]);
}
}
return result;
}
export async function fetchInfo(query: string): Promise<YtdlResult[]> {
logger.info("yt-dlp was invoked.", { query });
try {
if (!isURL(query)) {
return await fetchInfoRecursive("ytsearch1:" + query);
}
return await fetchInfoRecursive(query);
} catch (error) {
logger.error("yt-dlp execution invoked error.", { error });
return [];
}
}
export function ytdlStream(url: string, options?: YtdlStreamOptions) {
logger.info("Created ytdl stream.", { url, options });
let ffmpegArgs: string[] = [
"-analyzeduration",
"0",
"-loglevel",
"0",
"-f",
`${options?.fmt ? options.fmt : "s16le"}`,
"-ar",
"48000",
"-ac",
"2"
];
if (options?.seek) {
ffmpegArgs.unshift("-ss", options.seek.toString());
}
if (options?.encoderArgs) {
ffmpegArgs = ffmpegArgs.concat(options.encoderArgs);
}
const transcoder = new FFmpeg({
args: ffmpegArgs
});
const inputStream = ytdl(url, options);
const transcoderStream = inputStream.pipe(transcoder);
if (options && !options.opusEncoded) {
YTDL_EVENTS.forEach((event) =>
inputStream.on(event, (...args) => transcoderStream.emit(event, ...args))
);
inputStream.on("error", () => transcoder.destroy());
transcoderStream.on("close", () => transcoder.destroy());
return transcoderStream;
}
const opus = new Opus.Encoder({
rate: 48000,
channels: 2,
frameSize: 960
});
const outputStream = transcoderStream.pipe(opus);
transcoderStream.on("error", (e) => outputStream.emit("error", e));
YTDL_EVENTS.forEach((event) =>
inputStream.on(event, (...args) => outputStream.emit(event, ...args))
);
outputStream.on("close", () => {
transcoder.destroy();
opus.destroy();
});
return outputStream;
}
export function arbitraryStream(stream: string | Readable | Duplex, options?: StreamOptions) {
logger.info("Created arbitrary stream.", { stream, options });
let ffmpegArgs: string[];
if (typeof stream === "string") {
ffmpegArgs = [
"-reconnect",
"1",
"-reconnect_streamed",
"1",
"-reconnect_delay_max",
"5",
"-i",
stream,
"-analyzeduration",
"0",
"-loglevel",
"0",
"-f",
`${options?.fmt ? options.fmt : "s16le"}`,
"-ar",
"48000",
"-ac",
"2"
];
} else {
ffmpegArgs = [
"-analyzeduration",
"0",
"-loglevel",
"0",
"-f",
`${options?.fmt ? options.fmt : "s16le"}`,
"-ar",
"48000",
"-ac",
"2"
];
}
if (options?.seek) {
ffmpegArgs.unshift("-ss", options.seek.toString());
}
if (options?.encoderArgs) {
ffmpegArgs = ffmpegArgs.concat(options.encoderArgs);
}
let transcoder = new FFmpeg({
args: ffmpegArgs
});
if (typeof stream !== "string") {
transcoder = stream.pipe(transcoder);
stream.on("error", () => transcoder.destroy());
}
if (options && !options.opusEncoded) {
transcoder.on("close", () => transcoder.destroy());
return transcoder;
}
const opus = new Opus.Encoder({
rate: 48000,
channels: 2,
frameSize: 960
});
const outputStream = transcoder.pipe(opus);
outputStream.on("close", () => {
transcoder.destroy();
opus.destroy();
});
return outputStream;
}
+66
View File
@@ -0,0 +1,66 @@
export default class Filter {
public static readonly filters = {
"Bassboost 1.5": "bass=g=15:f=110:w=0.3",
"bassboost 2.0": "bass=g=20:f=110:w=0.3",
"bassboost 3.0": "bass=g=30:f=110:w=0.3",
"8D": "apulsator=hz=0.09",
Daycore: "aresample=48000,asetrate=48000*0.75",
Nightcore: "aresample=48000,asetrate=48000*1.25",
Phaser: "aphaser=in_gain=0.4",
Tremolo: "tremolo",
Vibrato: "vibrato=f=6.5",
Reverse: "areverse",
Treble: "treble=g=5",
"Normalizer 1": "dynaudnorm=g=101",
"Normalizer 2": "acompressor",
"Surround Sound": "surround",
Pulsator: "apulsator=hz=1",
Subboost: "asubboost",
Karaoke: "stereotools=mlev=0.03",
Compressor: "compand=points=-80/-105|-62/-80|-15.4/-15.4|0/-12|20/-7.6",
Expander:
"compand=attacks=0:points=-80/-169|-54/-80|-49.5/-64.6|-41.1/-41.1|-25.8/-15|-10.8/-4.5|0/0|20/8.3",
"Soft Limiter": "compand=attacks=0:points=-80/-80|-12.4/-12.4|-6/-8|0/-6.8|20/-2.8",
Chorus: "chorus=0.7:0.9:55:0.4:0.25:2",
"Fade In": "afade=t=in:ss=0:d=10",
Dimming:
"afftfilt=\"'real=re * (1-clip((b/nb)*b,0,1))':imag='im * (1-clip((b/nb)*b,0,1))'\"",
Earrape: "channelsplit,sidechaingate=level_in=64"
};
private switches_ = new Set<string>();
public toggled(): [string, string][] {
return Object.entries(Filter.filters)
.filter((value) => this.switches_.has(value[0]))
.map((value) => [value[0], value[1]]);
}
public toggle(query?: string): boolean {
if (!query) {
this.switches_.clear();
return false;
}
if (!this.switches_.delete(query) && Object.hasOwn(Filter.filters, query)) {
this.switches_.add(query);
return true;
}
return false;
}
public size(): number {
return this.switches_.size;
}
public empty(): boolean {
return this.size() === 0;
}
public toString(): string {
return this.toggled()
.map((value) => value[1])
.join(",");
}
}
+59
View File
@@ -0,0 +1,59 @@
import { AudioResource } from "@discordjs/voice";
import { LoopOption, Track } from "./types.js";
const STATUSBAR_LENGTH = 15;
export function statusBarGenerator(resource?: AudioResource<Track>): string {
const duration = resource?.metadata.duration || 1;
const playback = Math.min((resource?.playbackDuration || 0) / 1000, duration);
const filled = Array<string>(Math.floor((STATUSBAR_LENGTH * playback) / duration)).fill("🔹");
const empty = Array<string>(STATUSBAR_LENGTH - filled.length).fill("▫️");
return `[${filled.join("")}${empty.join("")}] ${toISOTime(playback)}/${toISOTime(duration)}`;
}
export function toISOTime(amount: number): string {
const h = Math.floor(amount / 3600);
const m = Math.floor((amount % 3600) / 60);
const s = Math.floor((amount % 3600) % 60);
const hDisplay = h > 0 ? `${h}:` : "";
const mDisplay = `${Math.floor(m / 10)}${Math.floor(m % 10)}:`;
const sDisplay = `${Math.floor(s / 10)}${Math.floor(s % 10)}`;
return hDisplay + mDisplay + sDisplay;
}
export async function asleep(amount: number): Promise<unknown> {
return new Promise((r) => setTimeout(r, amount));
}
export function volumeMoji(amount: number): string {
return amount > 100 ? "🔊" : amount > 50 ? "🔉" : amount > 0 ? "🔈" : "🔇";
}
export function loopMoji(loop: LoopOption): string {
return loop === "AUTO" ? "🔀" : loop === "LOOP" ? "🔁" : loop === "NONE" ? "⤵️" : "🔂";
}
export function largestCommonSequence(s1: string, s2: string) {
s1 = s1.toLowerCase().slice(0, 100);
s2 = s2.toLowerCase().slice(0, 100);
const buffer = Array.from(Array(s1.length + 1), () => new Array<number>(s2.length + 1).fill(0));
for (let i = 1; i <= s1.length; i++) {
for (let j = 1; j <= s2.length; j++) {
if (s1[i - 1] === s2[j - 1]) {
buffer[i][j] = buffer[i - 1][j - 1] + 1;
} else {
buffer[i][j] = Math.max(buffer[i - 1][j], buffer[i][j - 1]);
}
}
}
return buffer[s1.length][s2.length];
}
+36
View File
@@ -0,0 +1,36 @@
import { Collection, Guild, GuildTextBasedChannel } from "discord.js";
import logger from "../../../lib/logger.js";
import Player from "./player.js";
export default class Music {
private players_ = new Collection<string, Player>();
public get(guild: Guild, channel?: GuildTextBasedChannel): Player | undefined {
const player = this.players_.get(guild.id);
if (player) {
if (channel) {
player.channel = channel;
}
return player;
}
}
public set(guild: Guild, channel: GuildTextBasedChannel): Player {
const player = new Player(guild, this, channel);
this.players_.set(guild.id, player);
logger.info("Player was created.", { player });
return player;
}
public delete(guildId: string): void {
logger.info("Player was deleted.", { guildId });
this.players_.delete(guildId);
}
}
+287
View File
@@ -0,0 +1,287 @@
import {
AudioPlayer,
AudioPlayerStatus,
AudioResource,
createAudioPlayer,
createAudioResource,
DiscordGatewayAdapterCreator,
joinVoiceChannel,
VoiceConnection
} from "@discordjs/voice";
import { Guild, GuildTextBasedChannel, Message, User, VoiceBasedChannel } from "discord.js";
import { fetchInfo, ytdlStream } from "./fetch.js";
import Filter from "./filter.js";
import { largestCommonSequence } from "./misc.js";
import Music from "./music.js";
import Queue from "./queue.js";
import replies from "./replies.js";
import { Track } from "./types.js";
export default class Player {
private music: Music;
private guild: Guild;
private channel_: GuildTextBasedChannel;
public get channel(): GuildTextBasedChannel {
return this.channel_;
}
public set channel(x: GuildTextBasedChannel) {
this.channel_ = x;
}
private message_?: Message;
private connection_?: VoiceConnection;
public get connection(): VoiceConnection | undefined {
return this.connection_;
}
private player_: AudioPlayer;
public get player(): AudioPlayer {
return this.player_;
}
private resource_: AudioResource<Track> | undefined;
public get resource(): AudioResource<Track> | undefined {
return this.resource_;
}
private volume_ = 100;
public get volume(): number {
return this.volume_;
}
public set volume(x: number) {
this.volume_ = Math.max(0, Math.min(150, x));
if (this.resource_ && this.resource_.volume) {
this.resource_.volume.setVolumeLogarithmic(this.volume_ / 100);
}
}
public readonly queue = new Queue();
public readonly filter = new Filter();
public readonly createdAt: Date = new Date();
public constructor(guild: Guild, music: Music, channel: GuildTextBasedChannel) {
this.music = music;
this.guild = guild;
this.channel_ = channel;
this.player_ = createAudioPlayer();
this.player_.on(AudioPlayerStatus.Idle, async () => this.resourceEndResolvable());
}
private resourceGenerator(track: Track, seek?: number) {
const stream = ytdlStream(track.url, {
opusEncoded: true,
filter: "audioonly",
highWaterMark: 1 << 25,
seek: seek ? seek / 1000 : undefined,
encoderArgs: !this.filter.empty() ? ["-af", this.filter.toString()] : undefined
});
this.resource_ = createAudioResource(stream, {
inlineVolume: true,
metadata: track
});
if (seek) {
this.resource_.playbackDuration = seek;
}
if (this.resource_.volume) {
this.resource_.volume.setVolumeLogarithmic(this.volume_ / 100);
}
return this.resource_;
}
private resourceEndResolvable(): void {
if (this.resource_) {
this.resource_.encoder?.destroy();
}
if (this.queue.next()) {
this.play();
} else {
this.player_.stop(true);
this.resource_ = undefined;
}
}
private async messageResolvable(track: Track) {
if (this.message_?.deletable) {
await this.message_.delete().catch();
}
this.message_ = await this.channel_.send(replies.nowPlaying(track));
}
private async search(query: string, requester: User): Promise<Track[] | undefined> {
const info = await fetchInfo(query);
if (info.length === 0) {
return undefined;
}
return info.map((value) => {
return { ...value, requester: requester };
});
}
public async play(seek?: number): Promise<void> {
const track = this.queue.current();
if (!this.connection_ || !track) {
return;
}
this.player_.play(this.resourceGenerator(track, seek));
this.connection_.subscribe(this.player_);
await this.messageResolvable(track);
}
public connect(channel: VoiceBasedChannel): void {
if (
this.connection_?.joinConfig.channelId === channel.id &&
this.connection_.joinConfig.guildId === channel.guildId
) {
return;
}
if (this.connection_) {
this.connection_.destroy();
}
this.connection_ = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guildId,
adapterCreator: channel.guild.voiceAdapterCreator as DiscordGatewayAdapterCreator
});
this.connection_.subscribe(this.player_);
}
public async add(query: string, requester: User, index?: number): Promise<Track | undefined> {
const tracks = await this.search(query, requester);
if (!tracks) {
return;
}
this.queue.push(tracks, index);
return tracks[0];
}
public jump(query: number | string): number | undefined {
let position = typeof query === "number" ? query : -1;
let diff = 0;
if (typeof query === "string") {
this.queue.tracks.forEach((track, index) => {
const tempDiff = largestCommonSequence(track.title, query);
if (diff < tempDiff) {
diff = tempDiff;
position = index;
}
});
}
if (position !== -1 && this.queue.jump(position)) {
this.play();
return position;
}
return undefined;
}
public remove(query?: number | string): Track | undefined {
const oldPosition = this.queue.position;
let newPosition = typeof query === "number" ? query : this.queue.position;
let diff = 0;
if (typeof query === "string") {
this.queue.tracks.forEach((track, index) => {
const tempDiff = largestCommonSequence(track.title, query);
if (diff < tempDiff) {
diff = tempDiff;
newPosition = index;
}
});
}
const track = this.queue.pop(newPosition);
if (track) {
if (oldPosition === newPosition) {
this.play();
}
return track;
}
return undefined;
}
public seek(time: number): void {
this.play(time);
}
public clear(): void {
this.queue.clear();
this.resource_ = undefined;
if (this.player_) {
this.player_.stop();
}
}
public destroy(): void {
if (this.connection_) {
this.connection_.destroy();
}
this.player_.stop();
this.music.delete(this.guild.id);
}
public pause(): boolean {
if (this.player_.state.status === AudioPlayerStatus.Paused) {
this.player_.unpause();
return false;
} else {
this.player_.pause();
return true;
}
}
public shuffle(): void {
this.queue.shuffle();
if (this.resource_) {
this.player_.stop();
this.play();
}
}
public skip(): void {
this.player_.stop();
}
public setFilter(filter?: string): boolean {
const status = this.filter.toggle(filter);
if (this.resource_) {
this.play(this.resource_.playbackDuration);
}
return status;
}
}
+119
View File
@@ -0,0 +1,119 @@
import { LoopOption, Track } from "./types.js";
export default class Queue {
private tracks_: Track[] = [];
public get tracks(): Track[] {
return this.tracks_;
}
private position_ = 0;
public get position(): number {
return this.position_;
}
private loop_: LoopOption = "NONE";
public get loop(): LoopOption {
return this.loop_;
}
public set loop(x: LoopOption) {
this.loop_ = x;
}
private duration_ = 0;
public get duration(): number {
return this.duration_;
}
public next(): Track | undefined {
if (this.loop_ === "SONG") {
return this.current();
}
if (this.loop_ === "AUTO") {
this.position_ = Math.floor(Math.random() * this.tracks_.length);
return this.current();
}
if (this.position_ + 1 < this.tracks_.length) {
this.position_++;
return this.current();
} else if (this.loop_ === "LOOP") {
this.position_ = 0;
return this.current();
} else if (this.loop_ === "NONE") {
this.position_ = 0;
return undefined;
}
}
public shuffle(): void {
let currentIndex = this.tracks_.length;
while (currentIndex != 0) {
const randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
[this.tracks_[currentIndex], this.tracks_[randomIndex]] = [
this.tracks_[randomIndex],
this.tracks_[currentIndex]
];
}
this.position_ = 0;
}
public push(tracks: Track[], index?: number): Track {
for (const track of tracks) {
this.duration_ += track.duration;
}
if (index === undefined || index >= this.tracks_.length) {
this.tracks_ = this.tracks_.concat(tracks);
return this.tracks_[this.tracks_.length - 1];
}
this.tracks_.splice(Math.max(0, index), 0, ...tracks);
if (this.position_ >= index) {
this.position_ += tracks.length;
}
return this.tracks_[Math.max(0, index)];
}
public pop(query: number): Track | undefined {
if (query >= 0 && query < this.tracks_.length) {
const track = this.tracks_[query];
this.tracks_.splice(query, 1);
this.position_ = Math.max(0, this.position_ - 1);
this.duration_ -= track.duration;
return track;
}
return undefined;
}
public jump(query: number): Track | undefined {
if (query >= 0 && query < this.tracks_.length) {
const track = this.tracks_[query];
this.position_ = query;
return track;
}
return undefined;
}
public current(): Track {
return this.tracks_[this.position_];
}
public empty(): boolean {
return this.tracks_.length === 0;
}
public clear(): void {
this.tracks_ = [];
this.position_ = 0;
}
}
+376
View File
@@ -0,0 +1,376 @@
import { AudioResource } from "@discordjs/voice";
import { BaseMessageOptions, EmbedBuilder, italic } from "discord.js";
import config from "../../../config.js";
import { loopMoji, statusBarGenerator, toISOTime, volumeMoji } from "./misc.js";
import Player from "./player.js";
import Queue from "./queue.js";
import { LoopOption, Track } from "./types.js";
const replies = {
notExists: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.warning)
.setTitle("⚠️ Command ignored - player does not exist")
.setDescription("Use '/play' to create a new one.");
return { embeds: [embed] };
},
searching: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.default)
.setTitle("🔍 Searching...")
.setDescription("It will take longer if playlist or non-youtube URL was queried.");
return { embeds: [embed] };
},
notPlaying: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.default)
.setTitle("💿 Insert the disk...")
.setURL("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
.setDescription("Use '/play' to start the playback.");
return { embeds: [embed] };
},
nowPlaying: (track: Track): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.default)
.setAuthor({
iconURL: track.requester.avatarURL() ?? undefined,
name: track.requester.username
})
.setTitle(track.title)
.setURL(track.url)
.setDescription("playing now.")
.setThumbnail(track.thumbnail);
return { embeds: [embed] };
},
okConnected: (channel: string): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(`✅ Successfuly connected to: ${italic(channel)}`)
.setDescription("Will leave after some time, if left alone.");
return { embeds: [embed] };
},
notConnected: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.error)
.setTitle("❗ Cannot create new player.")
.setDescription("Make yourself connected to a voice channel beforehand.");
return { embeds: [embed] };
},
destroyed: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.error)
.setTitle("💀 Destroying the player")
.setDescription("Everything is lost now. Use '/play' to create a new one.");
return { embeds: [embed] };
},
alone: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.default)
.setTitle("🥬 I have decided to leave to conserve my energy")
.setDescription("Since there was nobody in the voice channel.");
return { embeds: [embed] };
},
paused: (state: boolean): BaseMessageOptions => {
let embed: EmbedBuilder;
if (state) {
embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle("▶️ The playback was resumed");
} else {
embed = new EmbedBuilder()
.setColor(config.colors.warning)
.setTitle("⏸️ The playback was paused")
.setDescription("Invoke this command again to resume.");
}
return { embeds: [embed] };
},
seeked: (from: number, to: number): BaseMessageOptions => {
let embed: EmbedBuilder;
if (from < to) {
embed = new EmbedBuilder()
.setColor(config.colors.info)
.setTitle(`⏩ Fast-forwarding by ${toISOTime(to - from)}`);
} else {
embed = new EmbedBuilder()
.setColor(config.colors.info)
.setTitle(`⏪ Fast-reversing by ${toISOTime(from - to)}`);
}
embed.setDescription(
`Moving playback from ${italic(toISOTime(from))} to ${italic(toISOTime(to))}.`
);
return { embeds: [embed] };
},
looped: (option: LoopOption) => {
let embed: EmbedBuilder;
switch (option) {
case "AUTO": {
embed = new EmbedBuilder()
.setColor(config.colors.default)
.setTitle(`${loopMoji(option)} Shuffle mode.`)
.setDescription("Does not affect the queue order. Endless playback.");
break;
}
case "LOOP": {
embed = new EmbedBuilder()
.setColor(config.colors.info)
.setTitle(`${loopMoji(option)} Looping over the queue.`)
.setDescription("Will start over after final track. Endless playback.");
break;
}
case "SONG": {
embed = new EmbedBuilder()
.setColor(config.colors.warning)
.setTitle(`${loopMoji(option)} Looping a single track.`)
.setDescription("Endless playback of a single track. Over and over again...");
break;
}
case "NONE": {
embed = new EmbedBuilder()
.setColor(config.colors.error)
.setTitle(`${loopMoji(option)} Drop on final.`)
.setDescription(
"Will end playback after final track. Action will be needed to continue."
);
break;
}
}
return { embeds: [embed] };
},
reshuffle: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle("✅ Successfuly reshuffled queue")
.setDescription("Use 'random' mode, if you want shuffle without reshuffle.");
return { embeds: [embed] };
},
skipped: (): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.info)
.setTitle("⏭️ Skipping current track")
.setDescription("Behavior depends on the loop option.");
return { embeds: [embed] };
},
jumped: (previous?: Track, to?: number): BaseMessageOptions => {
if (!to) {
const embed = new EmbedBuilder()
.setColor(config.colors.error)
.setTitle("❗ Cannot perfome jump over the queue")
.setDescription("Either not found by query, or index is not in range.");
return { embeds: [embed] };
}
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(`✅ Jumping over the queue`);
if (previous) {
embed.setDescription(`Switching from ${italic(previous.title)}.`);
} else {
embed.setDescription("Playback will start again.");
}
return { embeds: [embed] };
},
appended: (track?: Track): BaseMessageOptions => {
let embed: EmbedBuilder;
if (track) {
embed = new EmbedBuilder()
.setColor(config.colors.success)
.setAuthor({
iconURL: track.requester.avatarURL() ?? undefined,
name: track.requester.username
})
.setTitle(track.title)
.setURL(track.url)
.setDescription("has been added to the queue.")
.setThumbnail(track.thumbnail)
.setTimestamp();
} else {
embed = new EmbedBuilder()
.setColor(config.colors.error)
.setTitle("❗ Cannot add track to the queue")
.setDescription("Either not found by query, or URL is broken.");
}
return { embeds: [embed] };
},
removed: (track?: Track): BaseMessageOptions => {
let embed: EmbedBuilder;
if (track) {
embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(track.title)
.setURL(track.url)
.setDescription("was removed from the queue.")
.setThumbnail(track.thumbnail)
.setTimestamp();
} else {
embed = new EmbedBuilder()
.setColor(config.colors.error)
.setTitle("❗ Cannot delete track from queue")
.setDescription("Either not found by query, or index is not in range.");
}
return { embeds: [embed] };
},
cleared: (amount: number): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(`♻️ Queue has been cleared`)
.setDescription(
`${italic(amount.toString())} track${amount > 1 ? "s were" : " was"} deleted.`
);
return { embeds: [embed] };
},
filtered: (filter?: string, status = true): BaseMessageOptions => {
let embed: EmbedBuilder;
if (filter) {
embed = new EmbedBuilder().setTitle(
`✅ ${italic(filter)} was ${status ? "applied to the playback" : "declined"}.`
);
} else {
embed = new EmbedBuilder().setTitle("♻️ All filters were declined");
}
embed
.setColor(config.colors.success)
.setDescription("Playback can experience some lags during initial transformation.");
return { embeds: [embed] };
},
volumeSet: (amount: number): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(`${volumeMoji(amount)} Volume has been set to ${amount}%`)
.setDescription("This will affect everyone listening.");
return { embeds: [embed] };
},
queue: (queue: Queue, position = 0, resource?: AudioResource<Track>): BaseMessageOptions => {
if (queue.empty()) {
const embed = new EmbedBuilder()
.setColor(config.colors.warning)
.setTitle("⚠️ Queue is empty")
.setDescription("Use '/play' to add some tracks.");
return { embeds: [embed] };
}
let embed: EmbedBuilder;
if (resource) {
embed = new EmbedBuilder()
.setTitle(`${queue.position + 1}. ${resource.metadata.title}`)
.setAuthor({
iconURL: resource.metadata.requester.avatarURL() ?? undefined,
name: resource.metadata.requester.username
})
.setURL(resource.metadata.url)
.setDescription(statusBarGenerator(resource))
.setThumbnail(resource.metadata.thumbnail);
} else {
embed = new EmbedBuilder()
.setTitle("💿 Insert the disk...")
.setURL("https://www.youtube.com/watch?v=5mGuCdlCcNM&ab_channel=Ra%C3%BAlBlanco")
.setDescription(statusBarGenerator())
.setThumbnail("https://img.youtube.com/vi/5mGuCdlCcNM/default.jpg");
}
embed.setColor(config.colors.info).setFields(
queue.tracks.slice(position, position + 10).map((value, index) => ({
name: `${position + index + 1}. ${value.title.padEnd(35)}`,
value: `[${toISOTime(value.duration)}] | ${value.requester.username}`
}))
);
return { embeds: [embed] };
},
info: (player: Player): BaseMessageOptions => {
let embed: EmbedBuilder;
if (player.resource) {
embed = new EmbedBuilder()
.setTitle(`${player.queue.position + 1}. ${player.resource.metadata.title}`)
.setAuthor({
iconURL: player.resource.metadata.requester.avatarURL() ?? undefined,
name: player.resource.metadata.requester.username
})
.setURL(player.resource.metadata.url)
.setDescription(statusBarGenerator(player.resource))
.setThumbnail(player.resource.metadata.thumbnail);
} else {
embed = new EmbedBuilder()
.setTitle("💿 Insert the disk...")
.setURL("https://www.youtube.com/watch?v=dQw4w9WgXcQ")
.setDescription(statusBarGenerator());
}
embed.setColor(config.colors.info).addFields([
{
name: "Applied Filters",
value:
player.filter
.toggled()
.map((value) => value[0])
.join("\n") + "\ndefault",
inline: true
},
{
name: "Queue Length",
value: `🔢 ${player.queue.tracks.length}`,
inline: true
},
{
name: "Queue Duration",
value: `💿 ${toISOTime(player.queue.duration)}`,
inline: true
},
{
name: "Queue Looping",
value: `${loopMoji(player.queue.loop)} ${player.queue.loop}`,
inline: true
},
{
name: "Volume Amount",
value: `${volumeMoji(player.volume)} ${player.volume}/150`,
inline: true
},
{
name: "Player Lifetime",
value: `🕓 ${toISOTime((Date.now() - player.createdAt.getTime()) / 1000)}`,
inline: true
}
]);
return { embeds: [embed] };
}
};
export default replies;
+43
View File
@@ -0,0 +1,43 @@
import { User } from "discord.js";
import { downloadOptions } from "ytdl-core";
export interface Track {
url: string;
title: string;
thumbnail: string;
duration: number;
requester: User;
}
export type LoopOption = "LOOP" | "SONG" | "NONE" | "AUTO";
export interface YtdlDump {
id: string;
original_url: string;
title?: string;
uploader?: string;
duration?: number;
extractor_key: string;
thumbnail?: string;
}
export interface YtdlResult {
url: string;
title: string;
thumbnail: string;
duration: number;
}
export interface YtdlStreamOptions extends downloadOptions {
seek?: number;
encoderArgs?: string[];
fmt?: string;
opusEncoded?: boolean;
}
export interface StreamOptions {
seek?: number;
encoderArgs?: string[];
fmt?: string;
opusEncoded?: boolean;
}
+15
View File
@@ -0,0 +1,15 @@
import path from "path";
import { fileURLToPath } from "url";
import Music from "./lib/music.js";
const name = "music";
const description = "Music module";
const author = "unknowableshade";
const tag = "2.0.0";
const controller = new Music();
const rootDir = path.dirname(fileURLToPath(import.meta.url));
export { author, controller, description, name, rootDir, tag };
+95
View File
@@ -0,0 +1,95 @@
import {
ChatInputCommandInteraction,
Events,
PermissionFlagsBits,
SlashCommandBuilder
} from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.inCachedGuild()) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const subcommand = interaction.options.getSubcommand();
const event = interaction.options.getString("event", true);
switch (subcommand) {
case "role": {
const role = interaction.options.getRole("role", true);
await interaction.deferReply();
try {
await client.db.event.upsert({
where: {
eventIdentifier: {
title: event,
action: subcommand,
guildId: interaction.guildId
}
},
update: { metadata: [role.id] },
create: {
Guild: {
connectOrCreate: {
where: {
id: interaction.guildId
},
create: {
id: interaction.guildId
}
}
},
title: event,
action: subcommand,
metadata: [role.id]
}
});
await interaction.editReply(replies.auto("add role to a member", event));
} catch (error) {
logger.error("Error occured while quering db.", { error });
} finally {
await client.db.$disconnect();
}
return;
}
}
}
const AUTO_EVENT_CHOICES = [
{
name: "Member Joins",
value: Events.GuildMemberAdd
}
];
const data = new SlashCommandBuilder()
.setName("auto")
.setDescription("Quetza's automatization engine.")
.addSubcommand((subcommand) =>
subcommand
.setName("role")
.setDescription("Auto: give role.")
.addStringOption((option) =>
option
.setName("event")
.setDescription("Event when perfome an action.")
.setChoices(...AUTO_EVENT_CHOICES)
.setRequired(true)
)
.addRoleOption((option) =>
option.setName("role").setDescription("Role to grant on event.").setRequired(true)
)
)
.setDefaultMemberPermissions(PermissionFlagsBits.Administrator)
.setDMPermission(false);
export { data, execute };
+98
View File
@@ -0,0 +1,98 @@
import { ChatInputCommandInteraction, PermissionFlagsBits, SlashCommandBuilder } from "discord.js";
import Client from "../../../lib/client.js";
import logger from "../../../lib/logger.js";
import replies from "../lib/replies.js";
async function execute(client: Client, interaction: ChatInputCommandInteraction): Promise<void> {
if (!interaction.isChatInputCommand() || !interaction.inCachedGuild()) {
logger.warn("Interaction rejected.", { interaction });
return;
}
const subcommand = interaction.options.getSubcommand();
switch (subcommand) {
case "check": {
const user = interaction.options.getUser("member", true);
const member = await interaction.guild.members.fetch(user).catch(() => undefined);
if (member) {
await interaction.reply(replies.roleList(user.username, member.roles.cache));
} else {
await interaction.reply(replies.notMember("edited", user));
}
return;
}
case "edit": {
const user = interaction.options.getUser("member", true);
const role = interaction.options.getRole("role", true);
const reason = interaction.options.getString("reason") ?? undefined;
const member = await interaction.guild.members.fetch(user).catch(() => undefined);
if (member) {
if (member.roles.cache.some((memberRole) => role.id === memberRole.id)) {
await member.roles.remove(role.id, reason);
await interaction.reply(
replies.roleAction("revoked from", interaction.user, role.name, reason)
);
} else {
await member.roles.add(role.id, reason);
await interaction.reply(
replies.roleAction("granted to", interaction.user, role.name, reason)
);
}
} else {
await interaction.reply(replies.notMember("edited", user));
}
return;
}
case "list": {
const roles = await interaction.guild.roles.fetch();
await interaction.reply(replies.roleList(interaction.guild.name, roles));
return;
}
}
}
const data = new SlashCommandBuilder()
.setName("role")
.setDescription("Quetza's role manager.")
.addSubcommand((subcommand) =>
subcommand.setName("list").setDescription("Role: list guild's roles.")
)
.addSubcommand((subcommand) =>
subcommand
.setName("check")
.setDescription("Role: check user roles.")
.addUserOption((option) =>
option.setName("member").setDescription("Member to check.").setRequired(true)
)
)
.addSubcommand((subcommand) =>
subcommand
.setName("edit")
.setDescription("Role: edit role for a specific user.")
.addUserOption((option) =>
option.setName("member").setDescription("Member to edit.").setRequired(true)
)
.addRoleOption((option) =>
option.setName("role").setDescription("Member's role to edit.").setRequired(true)
)
.addStringOption((option) =>
option.setName("reason").setDescription("Reason for an action.")
)
)
.setDefaultMemberPermissions(PermissionFlagsBits.ManageRoles)
.setDMPermission(false);
export { data, execute };
@@ -0,0 +1,23 @@
import { Events, GuildMember } from "discord.js";
import Client from "../../../lib/client.js";
async function execute(client: Client, eventee: [GuildMember]): Promise<void> {
const [member] = eventee;
try {
const event = await client.db.event.findFirst({
where: { guildId: member.guild.id, title: name }
});
if (event) {
await member.roles.add(event.metadata as string[]);
}
} finally {
await client.db.$disconnect();
}
}
const name = Events.GuildMemberAdd;
export { execute, name };
+80
View File
@@ -0,0 +1,80 @@
import {
BaseMessageOptions,
bold,
Collection,
EmbedBuilder,
InteractionReplyOptions,
italic,
Role,
underscore,
User
} from "discord.js";
import config from "../../../config.js";
const replies = {
error: (): InteractionReplyOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.error)
.setTitle("Internal error occured while resolving interaction.")
.setDescription("Submit an issue (bio). Logs were saved.")
.setTimestamp();
return { embeds: [embed], ephemeral: true };
},
notMember: (action: string, user: User): InteractionReplyOptions => {
const embed = new EmbedBuilder()
.setColor("Blue")
.setTitle(`${user.username} cannot be ${action}`)
.setDescription("They're not a guild member.")
.setTimestamp();
return { embeds: [embed], ephemeral: true };
},
roleAction: (
action: string,
user: User,
roleName: string,
reason?: string
): InteractionReplyOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(`Role ${roleName} was ${action} user ${user.username}`)
.setDescription(reason ?? "No reason provided.")
.setTimestamp();
return { embeds: [embed], ephemeral: true };
},
roleList: (observed: string, roles: Collection<string, Role>): InteractionReplyOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(`${observed} roles:`)
.addFields(
roles.map((role) => {
return {
name: role.name,
value: italic(role.id)
};
})
)
.setTimestamp();
return { embeds: [embed], ephemeral: true };
},
auto: (action: string, event: string): BaseMessageOptions => {
const embed = new EmbedBuilder()
.setColor(config.colors.success)
.setTitle(
bold(
`From now I will ${underscore(italic(action))} when ${underscore(
italic(event)
)} event happens`
)
)
.setTimestamp();
return { embeds: [embed] };
}
};
export default replies;
+11
View File
@@ -0,0 +1,11 @@
import path from "path";
import { fileURLToPath } from "url";
const name = "server";
const description = "Server utilities module";
const author = "unknowableshade";
const tag = "0.0.1";
const rootDir = path.dirname(fileURLToPath(import.meta.url));
export { author, description, name, rootDir, tag };
+1 -1
View File
@@ -15,5 +15,5 @@
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
"exclude": ["node_modules", "dist", "src/commands", "src/events"]
}