Error: WebSocket was closed before the connection was established - node.js

I have Discord Music bot and it's been running for almost a year. Since yesterday, I got an issue that says:
Unable to play a music:
Error: WebSocket was closed before the connection was established
Here is my code:
try {
var connection = await voiceChannel.join();
if(guild.me.hasPermission("DEAFEN_MEMBERS")) guild.me.voice.setDeaf(true);
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0], message);
} catch (err) {
queue.delete(message.guild.id);
errorMessage(message, "1058");
console.error("Unable to play a music: ");
return console.error(err);
}
play function:
async function play(guild, song, message) {
const serverQueue = queue.get(guild.id);
if (!song) {
if(serverQueue.voiceChannel){
serverQueue.voiceChannel.leave();
}
else {
guild.voice.channel.leave();
}
queue.delete(guild.id);
return;
}
try {
let player = await ytdl(song.url, {filter: 'audioonly', quality: 'highestaudio', highWaterMark: 1 << 25, opusEncoded: true, encoderArgs: ['-af', 'bass=g=0']});
const dispatcher = serverQueue.connection.play(player, { type: 'opus', highWaterMark: 1, bitrate: 'auto', fec: true, volume: false })
.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0], message);
})
.on("error", error => {
console.error(error);
});
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
} catch(err){
errorMessage(message, "1060");
}
}
I have no idea what's the issue. Any ideas? And what does this error exactly mean?

It happens when you call close() on websocket when connection is not established. The code you include in the question does not include a close(); check for a close(), and make sure you don't call it if connection is not established.
discord.js uses ws, this is the place error is thrown:
https://github.com/websockets/ws/blob/a2c0d447af711ca245cb534159fa7c4d9ae67e64/lib/websocket.js#L222
so if websocket is in CONNECTING state and you call close() the error is thrown.
References:
https://stackoverflow.com/a/12503628/9483495

Related

Nestjs | grpc : How to handle remote error from client side

Remote Server
#Catch(RpcException)
export class RpcExceptionHandler implements RpcExceptionFilter<RpcException> {
catch(exception: RpcException, host: ArgumentsHost): Observable<any> {
return throwError(exception.getError());
}
}
#UseFilters(new RpcExceptionHandler())
#GrpcMethod('AppController', 'Accumulate')
async accumulate(numberArray: INumberArray, metadata: any): Promise<ISumOfNumberArray> {
throw new RpcException({
code: 5,
message: 'Data Not Found'
})
}
Client code
#Get('add')
async getSumc(#Query('data') data: number[]) {
try {
let ata = await this.grpcService.accumulate({ data });
return ata;
} catch (err) {
//logic here if error comes
return err;
}
}
Proto defination.
syntax = "proto3";
package app;
// Declare a service for each controller you have
service AppController {
// Declare an rpc for each method that is called via gRPC
rpc Accumulate (NumberArray) returns (SumOfNumberArray);
}
// Declare the types used above
message NumberArray {
repeated double data = 1;
}
message SumOfNumberArray {
double sum = 1;
}
If error comes it is not going to catch block, just showing the server error.
I want to catch the error if remote throwing any error.
Try this one:
#Get('add')
async getSumc(#Query('data') data: number[]) {
try {
let ata = await this.grpcService.accumulate({ data }).toPromise();
return ata;
} catch (e) {
throw new RpcException(e);
}
}
Example here

Discord.js maximum number of webhooks error

Have this slash command code and turned it into webhook. It worked when I used it once but it stopped working after that. I got this error DiscordAPIError: Maximum number of webhooks reached (10). Does anyone have any idea on how to fix this?
Code:
run: async (client, interaction, args) => {
if(!interaction.member.permissions.has('MANAGE_CHANNELS')) {
return interaction.followUp({content: 'You don\'t have the required permission!', ephemeral: true})
}
const [subcommand] = args;
const embedevent = new MessageEmbed()
if(subcommand === 'create'){
const eventname = args[1]
const prize = args[2]
const sponsor = args[3]
embedevent.setDescription(`__**Event**__ <a:w_right_arrow:945334672987127869> ${eventname}\n__**Prize**__ <a:w_right_arrow:945334672987127869> ${prize}\n__**Donor**__ <a:w_right_arrow:945334672987127869> ${sponsor}`)
embedevent.setFooter(`${interaction.guild.name}`, `${interaction.guild.iconURL({ format: 'png', dynamic: true })}`)
embedevent.setTimestamp()
}
await interaction.followUp({content: `Event started!`}).then(msg => {
setTimeout(() => {
msg.delete()
}, 5000)
})
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
}
}
You cannot fix that error, discord limits webhooks per channel (10 webhooks per channel).
However, if you don't want your code to return an error you can just chock that code into a try catch or add a .catch
Here is an example of how to handle the error:
try {
interaction.channel.createWebhook(interaction.user.username, {
avatar: interaction.user.displayAvatarURL({dynamic: true})
}).then(webhook => {
webhook.send({content: `<#&821578337075200000>`, embeds: [embedevent]})
})
} catch(e) {
return // do here something if there is an error
}

CPU usage gets higher as more WebRTC peers are added?

I'm streaming video/audio from a server with an electron app to get the desktop. When one user is connected CPU usage on both cores is 30-50%. As more users join the usage gets higher, when there were ~6 users it was a constant 100% on both cores and video quality becomes laggy and poor.
It's like it's encoding the video for each user that joins? How can I make it encode once and send that stream to everyone? That's my only guess as to why cpu usage would get so much higher anyway, maybe I'm wrong about why. Thank you for any help you can give! I'm open to other ways of doing this as well, as only the server needs to send video out.
Getting the video and audio:
function getAudio(audioID){
navigator.mediaDevices.getUserMedia( { video: false, audio: {deviceId: {exact: audioID},
autoGainControl: false, channelCount: 2, echoCancellation: false, noiseSuppression: false, sampleRate: 44100, sampleSize: 16 } } )
.then(function(stream) {
console.log("audio got??");
var audio = stream.getAudioTracks()[0];
mediaStream.addTrack(audio);
})
.catch(function(err) {
console.log(err.message);
});
}
desktopCapturer.getSources({ types: ['screen'] })
.then(async sources => {
console.log(sources);
let constraints2 = {
audio: false,
video: {
mandatory: {
chromeMediaSource: 'desktop',
maxWidth: 1280,
maxHeight: 720
}
}
}
let constraints3 = {
frameRate: {max: 24}
}
navigator.mediaDevices.getUserMedia(constraints2)
.then(function(stream){
mediaStream = stream;
let track = stream.getVideoTracks()[0];
track.applyConstraints(constraints3);
setTimeout(function(){
getAudio(audioID, 0);
}, 2000);
})
.catch(console.error);
})
.catch(console.error);
Calling the peers that join:
peer = new Peer(myPeerID, {host: 'selfhostedpeerjs.com', port: 9000, path: '/', key: 'peerjs', config: {'iceServers': [{ url: 'stun:stun.l.google.com:19302' },
{url:'stun:stun1.l.google.com:19302'},
{url:'stun:stun2.l.google.com:19302'},
{url:'stun:stun3.l.google.com:19302'},
{url:'stun:stun4.l.google.com:19302'}
]}
});
peer.on('open', function(id){
console.log("My peer id is: " + id);
});
peer.on('connection', function(conn)
{
conn.on('open', function(){
console.log("connection opened");
var id = conn.peer;
//conn.send('Hello!');
console.log("Trying to call now");
var call = peer.call(id, mediaStream);
call.on('error', function(err){
console.log('calling error');
console.log(err);
})
});

NodeJS VM2 proper way to access console when set to 'redirect'

I'm using the VM2 package to run user code. I'm trying to intercept console output and have set the NodeVM object's console property to 'redirect':
// Create a new sandbox VM for this request
const vm = new NodeVM( {
console: 'redirect',
timeout: 30000,
sandbox: { request, state, response },
require: {
external: true
}
});
According to the documentation that redirects console output to 'events'. I'm new to NodeJS, how do I hook into those events to capture the console.log messages executed inside the Sandbox?
After digging through the source code, I found this file where the event emit is occuring:
sandbox.js
if (vm.options.console === 'inherit') {
global.console = Contextify.readonly(host.console);
} else if (vm.options.console === 'redirect') {
global.console = {
log(...args) {
vm.emit('console.log', ...Decontextify.arguments(args));
return null;
},
info(...args) {
vm.emit('console.info', ...Decontextify.arguments(args));
return null;
},
warn(...args) {
vm.emit('console.warn', ...Decontextify.arguments(args));
return null;
},
error(...args) {
vm.emit('console.error', ...Decontextify.arguments(args));
return null;
},
dir(...args) {
vm.emit('console.dir', ...Decontextify.arguments(args));
return null;
},
time: () => {},
timeEnd: () => {},
trace(...args) {
vm.emit('console.trace', ...Decontextify.arguments(args));
return null;
}
};
}
All you need to do to listen to these events is to bind an event listener on the vm you've created:
// Create a new sandbox VM for this request
const vm = new NodeVM( {
console: 'redirect',
require: {
external: ['request']
}
});
vm.on('console.log', (data) => {
console.log(`VM stdout: ${data}`);
});
Likewise, you can bind to console.log, console.info, console.warn, console.error, console.dir, and console.trace. Hopefully this will save someone else some time.

Getting an error when subscribing a queue

My backend pushes messages to rabbitmq queue and I need to fetch those messages to display in the frontend part of the messages, since the messages have to be in specific order, I cannot use an asynchronous approach.
I have written this code
var open require("amqplib").connect("amqp://guest:guest#localhost:5682");
var queue = "developer";
export default {
name: 'Subsriber',
data: function() {
return {
selected: "",
services: [],
}
},
mounted() {
var url = "http://10.0.9.134:5060/services/scripts";
this.services = []; // empty the existing list first.
setTimeout(() => {
axios.get(url)
.then(response => {
this.services = response.data;
})
}, 2000)
open.then(function(conn){
return conn.createChannel();
}).then(function(ch){
return ch.assertQueue(queue).then(function(ok){
return ch.consume(queue, function(msg){
if (msg != null){
console.log(msg.content.toString());
}
});
});
});
}
but I get this error:
"Unhandled rejection TypeError: QS.unescape is not a function
openFrames#webpack-internal:///./node_modules/_amqplib#0.5.2#amqplib/lib/connect.js:50:1
connect#webpack-internal:///./node_modules/_amqplib#0.5.2#amqplib/lib/connect.js:145:14
connect/<#webpack-internal:///./node_modules/_amqplib#0.5.2#amqplib/channel_api.js:7:12
connect#webpack-internal:///./node_modules/_amqplib#0.5.2#amqplib/channel_api.js:6:10
#webpack-internal:///./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/SelectServices.vue:56:12
["./node_modules/babel-loader/lib/index.js!./node_modules/vue-loader/lib/selector.js?type=script&index=0!./src/components/SelectServices.vue"]#http://10.0.9.134/app.js:1251:1
__webpack_require__#http://10.0.9.134/app.js:679:1
hotCreateRequire/fn#http://10.0.9.134/app.js:89:20
#webpack-internal:///./src/components/SelectServices.vue:1:148
["./src/components/SelectServices.vue"]#http://10.0.9.134/app.js:1804:1
__webpack_require__#http://10.0.9.134/app.js:679:1
hotCreateRequire/fn#http://10.0.9.134/app.js:89:20
#webpack-internal:///./src/router/index.js:4:85
["./src/router/index.js"]#http://10.0.9.134/app.js:1820:1
__webpack_require__#http://10.0.9.134/app.js:679:1
hotCreateRequire/fn#http://10.0.9.134/app.js:89:20
#webpack-internal:///./src/main.js:4:66
["./src/main.js"]#http://10.0.9.134/app.js:1812:1
__webpack_require__#http://10.0.9.134/app.js:679:1
hotCreateRequire/fn#http://10.9.0.134/app.js:89:20
[0]#http://10.9.1.147/app.js:1829:18
__webpack_require__#http://10.0.9.134/app.js:679:1
#http://10.9.0.134/app.js:725:18
#http://10.9.0.134/app.js:1:1"

Resources