Utility Functions and Classes
Core utilities provided by Moonlink.js for extending and customizing functionality.
All utilities are available through the main module and can be imported directly.
Utility Functions
validateProperty
Validate Property
Validates a property based on a validation function.
Parameters
Returns & Example
Returns
• void
- Throws error if property is invalid
// Validate port number
validateProperty(
options.port,
value => value === undefined || (value >= 0 && value <= 65535),
"Invalid port value. Must be between 0 and 65535."
);
// Validate string
validateProperty(
options.identifier,
value => value === undefined || typeof value === "string",
"Invalid identifier. Must be a string."
);
delay
Delay
Creates a promise that resolves after specified milliseconds.
Parameters
Returns & Example
Returns
• Promise<void>
// Wait for 1 second
await delay(1000);
// Use in async function
async function reconnect() {
console.log('Reconnecting in 5 seconds...');
await delay(5000);
console.log('Reconnecting now');
}
decodeTrack
Decode Track
Decodes a base64-encoded track string.
Parameters
Returns & Example
Returns
• ITrack
- Decoded track object
const track = decodeTrack('base64EncodedTrackString');
console.log(track.info.title);
console.log(track.info.author);
console.log(track.info.length);
encodeTrack
Encode Track
Encodes track information into a base64 string.
Parameters
Returns & Example
Returns
• string
- Base64-encoded track string
const encodedTrack = encodeTrack({
title: 'Song Name',
author: 'Artist',
length: 180000,
identifier: 'trackId',
isStream: false,
uri: 'https://example.com/track',
sourceName: 'youtube'
});
generateUUID
Generate UUID
Generates a unique identifier (UUID) based on host and port using SHA256 hashing.
Parameters
Returns & Example
Returns
• string
- SHA256 hashed UUID
const uuid = generateUUID('localhost', 2333);
console.log(uuid); // e.g., 'a6a945ab2b79527275c7b01a25c5c465'
compareVersions
Compare Versions
Compares two version strings (e.g., "1.0.0", "1.2.3") and returns a number indicating their relative order.
Parameters
Returns & Example
Returns
• number
- A negative number if current
is less than required
, a positive number if current
is greater than required
, or 0
if they are equal.
const result1 = compareVersions("1.0.0", "1.0.0"); // 0
const result2 = compareVersions("1.0.0", "1.1.0"); // -1 (current is less than required)
const result3 = compareVersions("1.2.0", "1.1.0"); // 1 (current is greater than required)
stringifyWithReplacer
Stringify with Replacer
Converts a JavaScript value to a JSON string, handling circular references by replacing them with "[Circular Refs]"
.
Parameters
Returns & Example
Returns
• string
- A JSON string representation of the value.
const obj = {};
obj.a = obj;
const jsonString = stringifyWithReplacer(obj);
console.log(jsonString); // {"a":"[Circular Refs]"}
Log
Log
Logs a message to a specified file.
Parameters
Returns & Example
Returns
• void
Log('Player created', './logs/moonlink.log');
makeRequest
Make Request
Makes an HTTP request and returns JSON response. Now supports retries and timeouts.
Parameters
Returns & Example
Returns
• Promise<T | undefined>
- Generic type response or undefined
if request fails after retries.
// GET request with custom timeout and retries
const data = await makeRequest('https://api.example.com/data', {
method: 'GET',
headers: { 'Content-Type': 'application/json' }
}, 5000, 5);
// POST request
const response = await makeRequest('https://api.example.com/data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key: 'value' })
});
isSourceBlacklisted
Is Source Blacklisted
Checks if a given source name is blacklisted in the Manager options.
Parameters
Returns & Example
Returns
• boolean
- true
if the source is blacklisted, false
otherwise.
const isBlacklisted = isSourceBlacklisted(manager, 'spotify');
if (isBlacklisted) {
console.log('Spotify is blacklisted.');
}
Utility Classes
Structure
Structure Class
Abstract class for extending and customizing Moonlink.js structures. Provides static methods for managing the Manager instance and extending core classes.
Static Methods
Player
, Node
) with custom functionality. Example Usage
// Extend Player class
Structure.extend('Player', Player => {
return class CustomPlayer extends Player {
constructor(manager, options) {
super(manager, options);
this.customProperty = 'custom value';
}
customMethod() {
return this.customProperty;
}
};
});
// Use custom player
const player = manager.players.create({
guildId: '123456789',
voiceChannelId: '123456789',
textChannelId: '123456789'
});
console.log(player.customProperty);
player.customMethod();
Plugin
Plugin Class
Base class for creating Moonlink.js plugins. Plugins can extend core functionalities and integrate with the Manager.
Properties
Property | Type | Description |
---|---|---|
name | string | The name of the plugin. |
version | string | The version of the plugin. |
description | string | A brief description of the plugin's purpose. |
author | `string | Record<string, any>` |
minVersion | string | The minimum Moonlink.js version required by this plugin. |
Methods
Method | Description |
---|---|
load(manager) | Called when the plugin is loaded by the Manager. |
unload(manager) | Called when the plugin is unloaded from the Manager. |
Example Usage
class CustomPlugin extends Plugin {
constructor() {
super();
this.name = 'CustomPlugin';
this.version = '1.0.0';
this.description = 'A custom plugin';
this.author = 'Your Name';
this.minVersion = '1.0.0'; // Specify minimum Moonlink.js version
}
load(manager) {
console.log(`${this.name} loaded`);
// Add custom functionality
Structure.extend('Player', Player => {
return class CustomPlayer extends Player {
constructor(manager, options) {
super(manager, options);
this.pluginProperty = 'plugin value';
}
};
});
}
unload(manager) {
console.log(`${this.name} unloaded`);
}
}
// Register plugin
manager.plugins.register(new CustomPlugin());