Added issue templates; Removed packet managers, switched to npm; Fixed a lot of Bugs; Added new Versioning; Added types and reworked docs; Refactored project structure;

This commit is contained in:
Lechner Julian - FrauJulian
2025-12-16 16:01:33 +01:00
parent 431c720162
commit b0dc3ba52b
25 changed files with 11038 additions and 22118 deletions
+9
View File
@@ -0,0 +1,9 @@
*.ts text eol=crlf linguist-language=TypeScript
*.tsx text eol=crlf linguist-language=TypeScript
*.mts text eol=crlf linguist-language=TypeScript
*.cts text eol=crlf linguist-language=TypeScript
*.js text eol=crlf linguist-language=JavaScript
*.jsx text eol=crlf linguist-language=JavaScript
*.mjs text eol=crlf linguist-language=JavaScript
*.cjs text eol=crlf linguist-language=JavaScript
+42
View File
@@ -0,0 +1,42 @@
name: 🐛 Bug Report
description: Report a bug or unexpected behavior
title: '🐛 [BUG]: '
body:
- type: textarea
id: information
attributes:
label: Information
description: Provide all information about the issue.
placeholder: 'What happened? What did you expect to happen?'
validations:
required: false
- type: textarea
id: steps
attributes:
label: Steps to Reproduce
description: Step-by-step instructions to reproduce the issue.
placeholder: |
1. Go to ...
2. Click on ...
3. Observe ...
validations:
required: false
- type: textarea
id: logs
attributes:
label: Logs or Error Messages
description: Paste any relevant console output, stack traces, or screenshots.
placeholder: 'Console output, stacktrace, or screenshots here'
validations:
required: false
- type: input
id: occurrence
attributes:
label: Occurrence Version
description: Specify in which version the issue occurred
placeholder: 'v0.1.TTMMJJ-hhmm'
validations:
required: true
+1
View File
@@ -0,0 +1 @@
blank_issues_enabled: false
+29
View File
@@ -0,0 +1,29 @@
name: 💡 Enhancement
description: Suggest a new feature or improvement
title: '💡 [ENHANCEMENT]: '
body:
- type: textarea
id: description
attributes:
label: Description
description: Describe the new feature or improvement!
placeholder: 'What problem does it solve or what value does it add?'
validations:
required: true
- type: textarea
id: proposal
attributes:
label: Proposed Solution
placeholder: 'Describe how the feature should work.'
validations:
required: false
- type: input
id: implementation
attributes:
label: Implementation Version
description: Specify in which version the enhancement should be released.
placeholder: 'v0.1'
validations:
required: true
+39
View File
@@ -0,0 +1,39 @@
name: ⚙️ Improvement
description: Suggest an improvement to existing functionality, code quality, or performance
title: '⚙️ [Improvement]: '
body:
- type: textarea
id: context
attributes:
label: Current Situation / Context
description: Describe the current behavior or implementation that could be improved.
placeholder: 'Currently, the system loads all users at once, which slows down response time.'
validations:
required: false
- type: textarea
id: proposal
attributes:
label: Proposed Improvement
description: Describe your proposed change or improvement in detail.
placeholder: 'Implement pagination for user loading to reduce memory usage and response time.'
validations:
required: false
- type: textarea
id: benefits
attributes:
label: Expected Benefits
description: Explain how this improvement will help (e.g., better performance, cleaner code, easier maintenance).
placeholder: 'Faster load times, improved scalability, and reduced database load.'
validations:
required: false
- type: input
id: implementation
attributes:
label: Implementation Version
description: Specify in which version the improvement should be released.
placeholder: 'v0.1'
validations:
required: true
+1 -1
View File
@@ -1,4 +1,4 @@
name: Build Rollout name: Release and Deploy Build
on: on:
workflow_dispatch: workflow_dispatch:
+1
View File
@@ -1,6 +1,7 @@
name: Build Validation name: Build Validation
on: on:
workflow_dispatch:
pull_request: pull_request:
types: [opened, synchronize, reopened] types: [opened, synchronize, reopened]
+2 -3
View File
@@ -1,4 +1,3 @@
#!/usr/bin/env sh #!/usr/bin/env sh
npm run format || exit 1 npm run format:check || exit 1
npm run lint:fix || exit 1 npm run lint || exit 1
tsc || exit 1
+22 -9
View File
@@ -1,16 +1,29 @@
.idea
.git
.github .github
.git
.idea
.vscode
dist
node_modules
.husky
src
set-version.js
README.md
SECURITY.md
CODEOWNERS
.gitignore .gitignore
.npmignore .npmignore
.husky .prettierignore
node_modules .prettierrc
src .gitattributes
README.md
tsconfig.json tsconfig.json
tsconfig.eslint.json
tsup.config.ts tsup.config.ts
eslint.config.js eslint.config.js
.prettierrc
.vscode
eslint.config.typeaware.cjs eslint.config.typeaware.cjs
tsconfig.eslint.json package-lock.json
+5
View File
@@ -0,0 +1,5 @@
node_modules
dist
.git
.idea
.vscode
+2 -2
View File
@@ -1,6 +1,6 @@
{ {
"printWidth": 140, "printWidth": 120,
"tabWidth": 2, "tabWidth": 4,
"useTabs": false, "useTabs": false,
"singleQuote": true, "singleQuote": true,
"trailingComma": "all", "trailingComma": "all",
+1
View File
@@ -0,0 +1 @@
FrauJulian
+67 -58
View File
@@ -4,10 +4,23 @@
![GitHub package.json version](https://img.shields.io/github/package-json/v/FrauJulian/discord-audio-stream) ![GitHub package.json version](https://img.shields.io/github/package-json/v/FrauJulian/discord-audio-stream)
![GitHub Repo stars](https://img.shields.io/github/stars/FrauJulian/discord-audio-stream?style=social) ![GitHub Repo stars](https://img.shields.io/github/stars/FrauJulian/discord-audio-stream?style=social)
**This module is designed to work with [discord.js/voice](https://www.npmjs.com/package/@discordjs/voice) v0.18. This **This module is designed to work with [discord.js/voice](https://www.npmjs.com/package/@discordjs/voice) v0.19. This
package doesn't support older package doesn't support older
versions!** versions!**
> **Designed for 24/7 audio playing on discord.**
> Discord has many unwanted rate limits, especially in the audio area. This package does all the work and ensures that
> your music never stops playing due to ffmpeg or Discord, with as little effort as possible.
> **Recommended best Practise:**
> Create a global Map<GuildId, AudioManager> (Map<KEY, OBJ>) list. When the feature is used on a guild, add a new
> instance of AudioManager to the Map. When starting the connection or audio, overwrite the respective configuration with
> the override methods provided. To finally start, use the respective method. For each call and each change, retrieve the
> AudioManager object from the list and perform your actions. When the feature get stopped, first execute StopConnection
> and then Dispose to save as much power as possible. Garbage collection does the rest.
> **For large systems:** For large systems, it is recommended to queue each start with the
> packet [p-queue](https://www.npmjs.com/package/p-queue), to give ffmpeg enough time..
## 👋 Support ## 👋 Support
Please create an [issue](https://github.com/FrauJulian/DiscordAudioStreamNPM/issues) on github or write [ Please create an [issue](https://github.com/FrauJulian/DiscordAudioStreamNPM/issues) on github or write [
@@ -15,52 +28,51 @@ Please create an [issue](https://github.com/FrauJulian/DiscordAudioStreamNPM/iss
## 📝 Usage ## 📝 Usage
### Install ### Installation
> **Supported package managers:** npm, yarn, pnpm, bun **Node.js 22.12.0 or newer is required.**
#### Recommended:
```bash ```bash
npm install discord-audio-stream @snazzah/davey @discordjs/opus npm install discord-audio-stream
yarn add discord-audio-stream @snazzah/davey @discordjs/opus yarn add discord-audio-stream
pnpm add discord-audio-stream @snazzah/davey @discordjs/opus pnpm add discord-audio-stream
bun add discord-audio-stream @snazzah/davey @discordjs/opus bun add discord-audio-stream
``` ```
You need `@snazzah/davey` and one of the encryption libraries to run this package! #### Required Dependencies
**Encryption Libraries (npm install):** - > You only need to install `libsodium-wrappers` if your system does not support `aes-256-gcm` (verify by running
> You only need to install one of these libraries if your system does not support `aes-256-gcm` (verify by running
> `require('node:crypto').getCiphers().includes('aes-256-gcm')`). > `require('node:crypto').getCiphers().includes('aes-256-gcm')`).
- `@snazzah/davey`
- `sodium-native`
- `sodium`
- `@stablelib/xchacha20poly1305`
- `@noble/ciphers`
- `libsodium-wrappers`
**Opus Libraries (npm install):**
- `@discordjs/opus`
- `opusscript` - `opusscript`
- `prism-media`
**FFmpeg:** - **FFmpeg** (one of those)
- [`FFmpeg`](https://ffmpeg.org/) (installed and added to environment) - [`FFmpeg`](https://ffmpeg.org/) (installed and added to environment)
- `ffmpeg-static` - `ffmpeg-static`
### Create Instance ### AudioManager Instance
```js #### Options
let audioManager = new AudioManager();
**Declaration:**
```
AudioManager(ffmpegMode: string, renewInMs, number, connectionData: VoiceConnectionDataModel, audioData: VoiceAudioDataModel): IDisposable, IAudioManager
``` ```
or (with parameters) - `ffmpegMode`: 'Native' or 'Standalone'
- Native: [`FFmpeg`](https://ffmpeg.org/) installed on your system
- Standalone: FFmpeg-static as NodeJs library
- `renewInMs`: renewal time > default is 1,5h (5400000ms)
- `connectionData`: Options for voice connection. (type of **VoiceConnectionDataModel**)
- `audioData`: Options for audio player. (type of **VoiceAudioDataModel**)
#### Example
```js ```js
let audioManager = new AudioManager( let audioManager = new AudioManager(
'Native',
5400000,
{ {
VoiceChannelId: 0, //voice channel id where to play music VoiceChannelId: 0, //voice channel id where to play music
GuildId: 0, //guild id GuildId: 0, //guild id
@@ -73,47 +85,44 @@ let audioManager = new AudioManager(
); );
``` ```
### Properties of the AudioManager ### Fields and Methods of AudioManager
#### Properties #### Fields
| Callable with | Type | Description | | Name | Type | Security | Description |
| ----------------- | ---------------------------- | ----------------------------------------------- | | --------- | -------- | --------- | ------------------------------------- |
| `VoiceConnection` | **VoiceConnection** | VoiceConnection instance from discord.js/voice. | | `Active` | **bool** | protected | To check if the connection is active. |
| `AudioPlayer` | **AudioPlayer** | AudioPlayer instance from discord.js/voice. | | `Playing` | **bool** | protected | To check if it is playing audio. |
| `AudioResource` | **AudioResource** | AudioResource instance from discord.js/voice. |
| `ConnectionData` | **VoiceConnectionDataModel** | Global variable for connection data. |
| `AudioData` | **AudioDataModel** | Global variable for audio data. |
#### Methods #### Methods
| Callable with | Parameters | Return type | Description | | | Name | Parameters | Return type | Description |
| ------------------------------ | ------------------------------------------------------- | ----------- | ------------------------------------------------------------- | -------------------------------------- | | ----------------------------- | ------------------------------------------------------- | ------------- | ---------------------------------------- |
| `OverrideVoiceConnectionData` | `connectionData` (type of **VoiceConnectionDataModel**) | void | Method to override global connectionData variable. | | | `OverrideVoiceConnectionData` | `connectionData` (type of **VoiceConnectionDataModel**) | void | To override intern connectionData field. |
| `OverrideVoiceAudioDataModel` | `audioData` (type of **VoiceAudioDataModel**) | void | Method to override global audioData variable. | | | `OverrideVoiceAudioDataModel` | `audioData` (type of **VoiceAudioDataModel**) | void | To override intern audioData field. |
| `OverrideRenewInMs` | `renewInMs` (type of int, default value is 5400000) | void | Method to override global renewInMs variable. | | | `CreateAndPlay` | | Promise<void> | Join channel and start playing audio. |
| `CreateConnection` | `isRenew` (type of boolean, default value is false) | void | Method to join the voice connection. | | | `CreateConnection` | | void | Let it connect to voice channel. |
| `PlayAudioOnConnection` | | void | Method to play audio on the existing voice connection. | | | `PlayAudio` | | Promise<void> | To start playing audio. |
| `PauseAudio` | | void | Method to pause the audio. | | | `PauseAudio` | | void | Pause the audio, if it is playing |
| `ResumeAudio` | | void | Method to resume the audio. | | | `ResumeAudio` | | void | Resume the audio, if it is paused. |
| `StopAudioOnConnection` | | void | Method to stop the audio without destroying voice connection. | | | `SetVolume` | `volume` (type of number, 0 - 100 percent) | void | To set the audio volume. |
| `CreateConnectionAndPlayAudio` | | void | Method to join the voice connection and play audio. | | | `StopConnection` | | Promise<void> | Method to disconnect the voice channel. |
| `DestroyConnection` | | void | Method to destroy the voice connection. | | | `Dispose` | | void | Dispose all data in object. |
| `Dispose` | | void | Dispose all data in object. | |
| `SetVolume` | `volume` (type of number, 0 - 100 percent) | void | Method to set the audio volume. | Method to set the volume of the audio. |
| `SetMaxListeners` | `maxListeners` (type of number) | void | Method to set the max listeners of the audio stream. | |
##### Types History ## 📝 Types
- [**VoiceConnection** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/VoiceConnection.ts#L166) - [**VoiceConnection** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/VoiceConnection.ts#L166)
- [**AudioPlayer** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioPlayer.ts#L155) - [**AudioPlayer** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioPlayer.ts#L155)
- [**AudioResource** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioResource.ts#L44) - [**AudioResource** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/audio/AudioResource.ts#L44)
- [**VoiceConnectionDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceConnectionDataModel.d.ts#L3) - [**DiscordGatewayAdapterCreator** by discord.js/voice](https://github.com/discordjs/discord.js/blob/main/packages/voice/src/util/adapter.ts#L50)
- [**VoiceAudioDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/main/src/Models/VoiceAudioDataModel.d.ts#L1) - [**VoiceConnectionDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/master/src/types.d.ts#L3)
- [**VoiceAudioDataModel** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/master/src/types.d.ts#L21)
- [**IDisposable** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/master/src/types.d.ts#L38)
- [**IAudioManager** by discord-audio-stream](https://github.com/FrauJulian/Discord-Audio-Stream/blob/master/src/types.d.ts#L45)
## 📋 Contributors: ## 📋 Contributors:
~ [**FrauJulian - Julian Lechner**](https://fraujulian.xyz/). ~ [**FrauJulian - Julian Lechner**](https://fraujulian.xyz/) - CODEOWNER
## 🤝 Enjoy the package? ## 🤝 Enjoy the package?
-1316
View File
File diff suppressed because it is too large Load Diff
+9 -19
View File
@@ -1,20 +1,17 @@
/** @type {import('eslint').Linter.FlatConfig[]} */ /** @type {import('eslint').Linter.FlatConfig[]} */
const config = [ const config = [
// Globale Ignores (ersetzt .eslintignore)
{ {
ignores: ['dist/', 'node_modules/'], ignores: ['dist/', 'node_modules/'],
}, },
// Haupt-Setup für TS/JS-Dateien
{ {
files: ['**/*.{ts,tsx,js,cjs,mjs}'], files: ['**/*.{ts,tsx,js,cjs,mjs}'],
languageOptions: { languageOptions: {
ecmaVersion: 'latest', ecmaVersion: 'latest',
sourceType: 'module', // du schreibst TS mit ES-Imports; Laufzeit ist CJS nach Transpile sourceType: 'module',
parser: require('@typescript-eslint/parser'), parser: require('@typescript-eslint/parser'),
parserOptions: { parserOptions: {
// schnelles Profil: kein Type-Checker, nur Syntax-Linting
ecmaFeatures: {}, ecmaFeatures: {},
}, },
}, },
@@ -28,23 +25,18 @@ const config = [
}, },
rules: { rules: {
/* Basis */ /* Base */
'no-debugger': 'warn', 'no-debugger': 'warn',
/* TypeScript */ /* TypeScript */
'@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }], '@typescript-eslint/consistent-type-imports': ['warn', { prefer: 'type-imports' }],
'@typescript-eslint/no-unused-vars': 'off', // schneller über unused-imports '@typescript-eslint/no-unused-vars': 'off',
'unused-imports/no-unused-imports': 'warn', 'unused-imports/no-unused-imports': 'warn',
'unused-imports/no-unused-vars': [ 'unused-imports/no-unused-vars': [
'warn', 'warn',
{ { vars: 'all', varsIgnorePattern: '^_', args: 'after-used', argsIgnorePattern: '^_' },
vars: 'all',
varsIgnorePattern: '^_',
args: 'after-used',
argsIgnorePattern: '^_',
},
], ],
'@typescript-eslint/no-explicit-any': 'off', // pragmatisch für großen Bot '@typescript-eslint/no-explicit-any': 'off',
/* Imports */ /* Imports */
'import/first': 'error', 'import/first': 'error',
@@ -63,15 +55,15 @@ const config = [
}, },
], ],
/* Node (wir kompilieren TS → CJS; ES-Syntax erlauben) */ /* Node */
'n/no-missing-import': 'off', // TypeScript-Resolver übernimmt 'n/no-missing-import': 'off',
'n/no-unsupported-features/es-syntax': 'off', 'n/no-unsupported-features/es-syntax': 'off',
/* Promises (Discord-/DB-/HTTP-Logik) */ /* Promis */
'promise/catch-or-return': 'warn', 'promise/catch-or-return': 'warn',
'promise/always-return': 'off', 'promise/always-return': 'off',
/* bewusste „Fire-and-forget“-Promises mit `void` */ /* „Fire-and-forget“-Promises `void` */
'no-void': ['warn', { allowAsStatement: true }], 'no-void': ['warn', { allowAsStatement: true }],
}, },
@@ -79,14 +71,12 @@ const config = [
'import/resolver': { 'import/resolver': {
typescript: { typescript: {
alwaysTryTypes: true, alwaysTryTypes: true,
// nutzt automatisch deine tsconfig-Pfade
}, },
node: true, node: true,
}, },
}, },
}, },
// Reine JS/CJS-Skripte (Build/Hooks) dürfen require/exporte nutzen
{ {
files: ['**/*.{js,cjs}'], files: ['**/*.{js,cjs}'],
languageOptions: { languageOptions: {
+1366 -925
View File
File diff suppressed because it is too large Load Diff
+25 -19
View File
@@ -1,8 +1,8 @@
{ {
"name": "discord-audio-stream", "name": "discord-audio-stream",
"version": "0.6.20", "version": "0.7.DDDhhmm",
"license": "LGPL-2.1-only", "license": "LGPL-2.1-only",
"description": "NodeJS library to make stream any audio on discord easier.", "description": "Discord library to make stream any audio easier.",
"exports": { "exports": {
".": { ".": {
"require": { "require": {
@@ -25,15 +25,14 @@
"lib": "src" "lib": "src"
}, },
"scripts": { "scripts": {
"update:dependencies": "npx npm-check-updates --upgrade",
"update:version": "node set-version.js",
"lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs", "lint": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs",
"lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix", "lint:fix": "eslint . --ext .ts,.tsx,.js,.cjs,.mjs --fix",
"lint:types": "eslint . --config eslint.config.typeaware.cjs --ext .ts,.tsx", "lint:types": "eslint . --config eslint.config.typeaware.cjs --ext .ts,.tsx",
"format": "prettier --write .", "format": "prettier --write .",
"format:check": "prettier --check .", "format:check": "prettier --check .",
"update:dependencies": "npx npm-check-updates --upgrade && pnpm install && bun install && npm install && yarn install && echo PLEASE delete your node_modules directory and install again with your package manager.", "build": "del-cli dist && npm run update:version && tsup",
"update:version": "npm version patch --no-git-tag-version",
"clean:dist": "del-cli dist",
"build": "npm run clean:dist && npm run update:version && tsup",
"prepare": "husky" "prepare": "husky"
}, },
"repository": "https://github.com/FrauJulian/Discord-Audio-Stream", "repository": "https://github.com/FrauJulian/Discord-Audio-Stream",
@@ -41,10 +40,11 @@
"funding": "https://ko-fi.com/FrauJulian", "funding": "https://ko-fi.com/FrauJulian",
"keywords": [ "keywords": [
"discordjs", "discordjs",
"discord.js",
"discordjs/voice", "discordjs/voice",
"music",
"voice",
"audio", "audio",
"voice" "24/7"
], ],
"contributors": [ "contributors": [
"FrauJulian - Lechner Julian <fraujulian@lechner.top>" "FrauJulian - Lechner Julian <fraujulian@lechner.top>"
@@ -59,30 +59,36 @@
] ]
}, },
"dependencies": { "dependencies": {
"@discordjs/voice": "^0.19.0", "@typescript-eslint/eslint-plugin": "^8.50.0",
"@typescript-eslint/eslint-plugin": "^8.46.0", "@typescript-eslint/parser": "^8.50.0"
"@typescript-eslint/parser": "^8.46.0"
}, },
"devDependencies": { "devDependencies": {
"@types/ejs": "^3.1.5", "@types/ejs": "^3.1.5",
"@types/node": "^24.7.1", "@types/node": "^25.0.2",
"del-cli": "^7.0.0", "del-cli": "^7.0.0",
"eslint": "^9.37.0", "eslint": "^9.39.2",
"eslint-config-prettier": "^10.1.8", "eslint-config-prettier": "^10.1.8",
"eslint-import-resolver-typescript": "^4.4.4", "eslint-import-resolver-typescript": "^4.4.4",
"eslint-plugin-import": "^2.32.0", "eslint-plugin-import": "^2.32.0",
"eslint-plugin-n": "^17.23.1", "eslint-plugin-n": "^17.23.1",
"eslint-plugin-promise": "^7.2.1", "eslint-plugin-promise": "^7.2.1",
"eslint-plugin-unused-imports": "^4.2.0", "eslint-plugin-unused-imports": "^4.3.0",
"husky": "^9.1.7", "husky": "^9.1.7",
"npm-check-updates": "^19.0.0", "npm-check-updates": "^19.2.0",
"prettier": "^3.6.2", "prettier": "^3.7.4",
"ts-jest": "^29.4.5", "ts-jest": "^29.4.6",
"tsup": "^8.5.0", "tsup": "^8.5.1",
"typescript": "^5.9.3" "typescript": "^5.9.3"
}, },
"peerDependencies": {
"@discordjs/voice": "^0.19.0",
"@snazzah/davey": "^0.1.8",
"libsodium-wrappers": "^0.7.15",
"opusscript": "^0.0.8",
"prism-media": "^1.3.5"
},
"engines": { "engines": {
"node": ">=18" "node": ">=22.12.0"
}, },
"private": false, "private": false,
"publishConfig": { "publishConfig": {
-5965
View File
File diff suppressed because it is too large Load Diff
-3
View File
@@ -1,3 +0,0 @@
ignoredBuiltDependencies:
- esbuild
- unrs-resolver
+21
View File
@@ -0,0 +1,21 @@
const fs = require('fs');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8').toString());
const [major, minor] = pkg.version.split('.');
const prefix = `${major}.${minor}.`;
const now = new Date();
const start = new Date(now.getFullYear(), 0, 0);
const diff = now - start;
const dayOfYear = Math.floor(diff / (1000 * 60 * 60 * 24));
const hh = String(now.getHours()).padStart(2, '0');
const mm = String(now.getMinutes()).padStart(2, '0');
const newVersion = `${prefix}${String(dayOfYear).padStart(3, '0')}${hh}${mm}`;
pkg.version = newVersion;
fs.writeFileSync('package.json', JSON.stringify(pkg, null, 2));
console.log('Version set to: ', newVersion);
+144 -106
View File
@@ -1,159 +1,197 @@
import type { AudioPlayer, AudioResource, VoiceConnection } from '@discordjs/voice'; import type { AudioPlayer, AudioResource, VoiceConnection } from '@discordjs/voice';
import { createAudioPlayer, createAudioResource, joinVoiceChannel } from '@discordjs/voice'; import {
createAudioPlayer,
createAudioResource,
entersState,
joinVoiceChannel,
NoSubscriberBehavior,
StreamType,
VoiceConnectionStatus,
} from '@discordjs/voice';
import { join } from 'node:path'; import { join } from 'node:path';
import type { VoiceAudioDataModel, VoiceConnectionDataModel } from './types'; import type { IAudioManager, IDisposable, VoiceAudioDataModel, VoiceConnectionDataModel } from './types';
import { spawn } from 'node:child_process';
import type { Readable } from 'node:stream';
export default class AudioManager { export default class AudioManager implements IAudioManager, IDisposable {
public VoiceConnection?: VoiceConnection; private voiceConnection?: VoiceConnection | null;
public AudioPlayer?: AudioPlayer; private audioPlayer?: AudioPlayer | null;
public AudioResource?: AudioResource; private audioResource?: AudioResource | null;
protected IsActive?: boolean; protected Active?: boolean | null;
protected IsAudioPlaying?: boolean; protected Playing?: boolean | null;
protected ConnectionData?: VoiceConnectionDataModel; private timeout?: NodeJS.Timeout | null;
protected AudioData?: VoiceAudioDataModel; private ffmpegProcess?: ReturnType<typeof spawn> | null;
private pcmStream?: Readable | null;
private TimeoutHandle?: NodeJS.Timeout; constructor(
private RenewInMs?: number; private readonly ffmpegMode: 'Native' | 'Standalone',
private renewMs: number | null = null,
constructor(connectionData?: VoiceConnectionDataModel, audioData?: VoiceAudioDataModel, renewInMs = 5400000) { private connectionData: VoiceConnectionDataModel | null = null,
this.RenewInMs = renewInMs; private audioData: VoiceAudioDataModel | null = null,
this.ConnectionData = connectionData; ) {
this.AudioData = audioData; this.renewMs = renewMs ? renewMs : 5400000;
}
public OverrideRenewInMs(renewInMs: number = 5400000): void {
this.RenewInMs = renewInMs;
} }
public OverrideVoiceConnectionData(connectionData: VoiceConnectionDataModel): void { public OverrideVoiceConnectionData(connectionData: VoiceConnectionDataModel): void {
this.ConnectionData = connectionData; this.connectionData = connectionData;
} }
public OverrideVoiceAudioDataModel(audioData: VoiceAudioDataModel): void { public OverrideVoiceAudioDataModel(audioData: VoiceAudioDataModel): void {
this.AudioData = audioData; this.audioData = audioData;
} }
public CreateConnection(isRenew: boolean = false): void { public CreateConnection(): void {
this.CheckIfNull(this.ConnectionData); this.voiceConnection = joinVoiceChannel({
channelId: this.connectionData!.VoiceChannelId,
if (!isRenew) { guildId: this.connectionData!.GuildId,
if (this.IsActive) { adapterCreator: this.connectionData!.VoiceAdapter,
this.DestroyConnection(false);
} else {
this.IsActive = true;
}
}
this.VoiceConnection = joinVoiceChannel({
channelId: this.ConnectionData!.VoiceChannelId.toString(),
guildId: this.ConnectionData!.GuildId.toString(),
adapterCreator: this.ConnectionData!.VoiceAdapter,
}); });
this.TimeoutHandle = setTimeout((): void => { this.timeout = setTimeout(async (): Promise<void> => {
this.DestroyConnection(false); await this.StopConnection();
if (this.IsActive) { await this.CreateAndPlay();
this.CreateConnection(true); }, this.renewMs!);
if (this.IsAudioPlaying) {
this.PlayAudioOnConnection();
}
}
}, this.RenewInMs);
} }
public PlayAudioOnConnection(): void { public async PlayAudio(): Promise<void> {
this.CheckIfNull(this.AudioData); if (!this.audioData || !this.voiceConnection) return;
if (this.AudioData!.ResourceType === 'File') { await entersState(this.voiceConnection!, VoiceConnectionStatus.Ready, 20_000);
this.AudioResource = createAudioResource(join(__dirname, this.AudioData!.Resource), { inlineVolume: true });
} else if (this.AudioData!.ResourceType === 'Link') { if (this.ffmpegProcess) {
this.AudioResource = createAudioResource(this.AudioData!.Resource, { inlineVolume: true }); this.ffmpegProcess.kill('SIGKILL');
this.ffmpegProcess = null;
}
let source: string;
if (this.audioData!.ResourceType === 'File') {
source = join(__dirname, this.audioData!.Resource);
} else if (this.audioData!.ResourceType === 'Link') {
source = this.audioData!.Resource;
} else { } else {
throw new Error('Invalid resource type.'); throw new TypeError('Invalid resource type.');
} }
this.AudioPlayer = createAudioPlayer(); this.ffmpegProcess = spawn(
this.AudioPlayer.play(this.AudioResource); this.ffmpegMode === 'Native' ? 'ffmpeg' : require('ffmpeg-static'),
[
'-loglevel',
'error',
'-i',
source,
'-analyzeduration',
'0',
'-f',
's16le',
'-ar',
'48000',
'-ac',
'2',
'pipe:1',
],
{
stdio: ['ignore', 'pipe', 'pipe'],
},
);
this.VoiceConnection!.subscribe(this.AudioPlayer!); this.pcmStream = this.ffmpegProcess!.stdout as Readable;
this.IsAudioPlaying = true;
}
public StopAudioOnConnection(): void { this.audioResource = createAudioResource(this.pcmStream, {
if (this.IsAudioPlaying) { inputType: StreamType.Raw,
this.DestroyConnection(false); inlineVolume: true,
this.CreateConnection(); });
} else {
throw new Error('Audio is not playing.'); this.audioPlayer = createAudioPlayer({
} behaviors: {
noSubscriber: NoSubscriberBehavior.Play,
},
});
this.voiceConnection!.subscribe(this.audioPlayer);
this.audioPlayer.play(this.audioResource);
this.Playing = true;
} }
public PauseAudio(): void { public PauseAudio(): void {
if (this.IsAudioPlaying) { if (this.Playing) {
this.AudioPlayer!.pause(); this.audioPlayer!.pause();
this.IsAudioPlaying = false; this.Playing = false;
} else { } else {
throw new TypeError('Audio is not playing.'); throw new ReferenceError('Audio is not playing.');
} }
} }
public ResumeAudio(): void { public ResumeAudio(): void {
if (!this.IsAudioPlaying) { if (!this.Playing) {
this.AudioPlayer!.unpause(); this.audioPlayer!.unpause();
this.IsAudioPlaying = true; this.Playing = true;
} else { } else {
throw new TypeError('Audio is playing.'); throw new ReferenceError('Audio is playing.');
} }
} }
public CreateConnectionAndPlayAudio(): void { public async CreateAndPlay(): Promise<void> {
this.CreateConnection(); this.CreateConnection();
this.PlayAudioOnConnection(); await this.PlayAudio();
} }
public DestroyConnection(resetValidationParameters: boolean = true): void { public async StopConnection(): Promise<void> {
if (this.CheckIfNull(this.VoiceConnection)) return; this.voiceConnection?.disconnect();
this.VoiceConnection!.destroy(); this.voiceConnection?.destroy();
this.voiceConnection = null;
if (resetValidationParameters) { this.Active = false;
this.IsActive = false; this.Playing = false;
this.IsAudioPlaying = false;
}
}
public SetMaxListeners(maxListeners: number): void {
if (this.CheckIfNull(this.VoiceConnection)) return;
this.VoiceConnection!.setMaxListeners(maxListeners);
} }
public SetVolume(volumeInPercent: number): void { public SetVolume(volumeInPercent: number): void {
if (volumeInPercent < 0 || volumeInPercent > 100) throw new Error('Volume must be between 0 and 100.'); if (volumeInPercent < 0 || volumeInPercent > 100) throw new Error('Volume must be between 0 and 100.');
this.audioResource!.volume!.setVolume(volumeInPercent / 100);
if (this.CheckIfNull(this.VoiceConnection)) return;
this.AudioResource!.volume!.setVolume(volumeInPercent / 100);
} }
public Dispose(): void { public Dispose(): void {
this.VoiceConnection = undefined; try {
this.AudioPlayer = undefined; if (this.timeout) {
this.AudioResource = undefined; clearTimeout(this.timeout);
this.IsActive = undefined;
this.IsAudioPlaying = undefined;
this.ConnectionData = undefined;
this.AudioData = undefined;
this.TimeoutHandle = undefined;
this.RenewInMs = undefined;
} }
private CheckIfNull<T>(value: T | null): boolean { if (this.audioPlayer) {
if (value === null) { this.audioPlayer.stop(true);
throw new Error(`${value} cannot be null in this case.`);
} }
return true; if (this.audioPlayer) {
this.audioPlayer!.stop();
if (this.audioResource && this.audioResource.playStream) {
this.audioResource!.playStream.destroy();
}
}
if (this.voiceConnection) {
this.voiceConnection!.destroy();
}
if (this.ffmpegProcess) {
this.ffmpegProcess.kill('SIGKILL');
this.ffmpegProcess = null;
}
this.pcmStream?.destroy();
this.pcmStream = null;
this.audioPlayer = null;
this.audioResource = null;
this.voiceConnection = null;
this.timeout = null;
this.Active = null;
this.Playing = null;
this.connectionData = null;
this.audioData = null;
this.renewMs = null;
} catch {}
} }
} }
+23
View File
@@ -30,3 +30,26 @@ export type VoiceAudioDataModel = {
*/ */
Resource: string | any; Resource: string | any;
}; };
/**
* An interface which is implemented in audio manager
* for a proper Dispose functionality.
*/
export type IDisposable = {
Dispose(): void;
};
/**
* An interface to handle instances later on.
*/
export type IAudioManager = {
OverrideVoiceConnectionData(connectionData: VoiceConnectionDataModel): void;
OverrideVoiceAudioDataModel(audioData: VoiceAudioDataModel): void;
CreateAndPlay(): Promise<void>;
CreateConnection(): void;
PlayAudio(): Promise<void>;
PauseAudio(): void;
ResumeAudio(): void;
StopConnection(): Promise<void>;
SetVolume(volumeInPercent: number): void;
};
+31 -14
View File
@@ -1,20 +1,37 @@
{ {
"compilerOptions": { "compilerOptions": {
"strict": true,
"allowJs": false,
"noImplicitAny": true,
"esModuleInterop": true,
"strictNullChecks": true,
"target": "ES2022", "target": "ES2022",
"moduleResolution": "Node", "lib": ["ES2022"],
"module": "CommonJS", "module": "commonjs",
"declaration": true, "moduleResolution": "node",
"isolatedModules": true, "resolveJsonModule": true,
"noEmit": true, "types": [],
"outDir": "dist", "rootDir": "./",
"types": ["node"], "outDir": "./dist",
"typeRoots": ["node_modules/@types"] "baseUrl": "./",
"paths": {
"@/*": ["src/*"]
},
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"strictPropertyInitialization": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noUncheckedIndexedAccess": true,
"exactOptionalPropertyTypes": true,
"noFallthroughCasesInSwitch": true,
"useUnknownInCatchVariables": true,
"skipLibCheck": true,
"noEmitOnError": true
}, },
"include": ["src"], "include": ["src"],
"exclude": ["node_modules"] "exclude": ["node_modules", "dist"]
} }
-4480
View File
File diff suppressed because it is too large Load Diff