lavalink.js
A Lavalink client for discord.js ported from eris-lavalink
Links
Install
npm install lavalink.js
Implementation
Start by creating the PlayerManager
and passing a list of nodes and optional list of regions
const { PlayerManager } = require('lavalink.js');
let nodes = [
{ host: 'localhost', port: 8080, region: 'eu', password: 'youshallnotpass' }
];
let regions = {
eu: ['eu', 'amsterdam', 'frankfurt', 'russia', 'hongkong', 'singapore', 'sydney'],
us: ['us', 'brazil'],
};
const voiceConnections = new PlayerManager(client, nodes, {
numShards: shardCount,
userId: userid,
regions: regions,
defaultRegion: 'eu',
});
To resolve a track, use the Lavalink rest api
const superagent = require('superagent');
async function resolveTracks(node, search) {
try {
var result = await superagent.get(`http://${node.host}:2333/loadtracks?identifier=${search}`)
.set('Authorization', node.password)
.set('Accept', 'application/json');
} catch (err) {
throw err;
}
if (!result) {
throw 'Unable play that video.';
}
return result.body;
}
resolveTracks(node, 'ytsearch:the 30 second video').then(tracks => {
if (!tracks) {
}
})
To join and leave voice channels, use the Lavalink client rather than using eris.
function getPlayer(channel) {
if (!channel || !channel.guild) {
return Promise.reject('Not a guild channel.');
}
let player = voiceConnections.get(channel.guild.id);
if (player) {
return Promise.resolve(player);
}
let options = {};
if (channel.guild.region) {
options.region = channel.guild.region;
}
return voiceConnections.join(channel.guild.id, channel.id, options);
}
getPlayer(channel).then(player => {
player.play(track);
player.on('disconnect', (err) => {
if (err) {
}
});
player.on('error', err => {
});
player.on('stuck', msg => {
})
player.once('end', data => {
if (data.reason && data.reason === 'REPLACED') {
return;
}
});
});
getPlayer(channel).then(player => {
player.stop();
if (leave) {
player.leave();
}
})