Discord Bot crashed after some time - node.js

So I have a discord bot which works perfectly fine, but after some time (about 30 minutes) the bot crashes with this error message:
Error: Unhandled "error" event. ([object Object])
at Client.emit (events.js:186:19)
at WebSocketConnection.onError (C:\Users\Paul\Desktop\Hype-Bot\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:374:17)
at WebSocket.onError (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\event-target.js:128:16)
at emitOne (events.js:116:13)
at WebSocket.emit (events.js:211:7)
at _receiver.cleanup (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\websocket.js:211:14)
at Receiver.cleanup (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\receiver.js:557:13)
at WebSocket.finalize (C:\Users\Paul\Desktop\Hype-Bot\node_modules\ws\lib\websocket.js:206:20)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at emitErrorNT (internal/streams/destroy.js:64:8)
at _combinedTickCallback (internal/process/next_tick.js:138:11)
at process._tickDomainCallback (internal/process/next_tick.js:218:9)
Does someone know how to solve this?

I've been looking for someone who needs some help with this sort of thing, and lo and behold here you are. I too have run into this issue. You have a network error that happens when your bot sends something called a heartbeat to the servers to say to them: i am online. Then the server will send it back. If it is sent and there is not a message returned from the server then it will give you your error. All you have to do is go into the following path in your bot folder /node_modules/discord.js/src/client/websocket/WebSocketConnection.js
Then in that file go to a section that looks like this:
onError(error) {
if (error && error.message === 'uWs client connection error') {
this.reconnect();
return;
}
/**
* Emitted whenever the client's WebSocket encounters a connection error.
* #event Client#error
* #param {Error} error The encountered error
*/
this.client.emit(Constants.Events.ERROR, error);
}
and what I did is change it to this:
onError(error) {
if (error && error.message === 'uWs client connection error') {
this.reconnect();
return;
}
console.log("Attempting to reconnect!")
return this.reconnect()
/**
* Emitted whenever the client's WebSocket encounters a connection error.
* #event Client#error
* #param {Error} error The encountered error
*/
this.client.emit(Constants.Events.ERROR, error);
}
I hope this helps!
Wishing you luck,
Zaedus

Related

localhost not responding for nodejs project [duplicate]

This question already has answers here:
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
(5 answers)
Closed 5 months ago.
I am new to nodejs and still learning so please help me out here.
const http=require('http')
const server=http.createServer((req,res)=>{
if(req.url==='/'){
res.end('Welcome to our home page')
}
if(req.url==='/about'){
res.end("Here is our short abt page")
}
res.end(`
<h1>OOps!</h1>
<p>We can't seem to find the page you are looking for</p>
<a href='/'>Go back home</a>
`)
})
server.listen(2000)
The above mentioned code gives the following error:
node:events:505
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:372:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (c:\Users\Hp\Desktop\node\app.js:10:9)
at Server.emit (node:events:527:28)
at parserOnIncoming (node:_http_server:956:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
PS C:\Users\Hp\Desktop\node> node "c:\Users\Hp\Desktop\node\app.js"
node:events:505
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (node:internal/errors:372:5)
at ServerResponse.end (node:_http_outgoing:846:15)
at Server.<anonymous> (c:\Users\Hp\Desktop\node\app.js:10:9)
at Server.emit (node:events:527:28)
at parserOnIncoming (node:_http_server:956:12)
at HTTPParser.parserOnHeadersComplete (node:_http_common:128:17)
Emitted 'error' event on ServerResponse instance at:
at emitErrorNt (node:_http_outgoing:726:9)
at processTicksAndRejections (node:internal/process/task_queues:84:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
The page at localhost:2000 works at times for the main page (mostly) but gives the "site can't be reached" error for the rest. Do I need to start the xampp apache?
Here we should observe the code execution clearly.
When we visit localhost:2000, First mentioned if condition will be executed and send the response as Welcome to our home page
if(req.url==='/'){
res.end('Welcome to our home page')
}
Then after it tries to check the second if condition and as the if condition is false that block of code will not be executed
if(req.url==='/about'){
res.end("Here is our short abt page")
}
Then it tries to execute the last block of code
res.end(`
<h1>OOps!</h1>
<p>We can't seem to find the page you are looking for</p>
<a href='/'>Go back home</a>
`)
As the res is already sent with first block of if condition, Now again these last lines of code will try to send the response, which will result in an error and the app will be crashed. Because the response is already ended its process.
To overcome these issues, try to change the code in the below-mentioned way.
const server=http.createServer((req,res)=>{
if(req.url==='/'){
res.end('Welcome to our home page')
return
}
if(req.url==='/about'){
res.end("Here is our short abt page")
return;
}
res.end(`
<h1>OOps!</h1>
<p>We can't seem to find the page you are looking for</p>
<a href='/'>Go back home</a>
`)
})
The above-mentioned code snippet will work fine and fixes the issue.

NodeJS : Error: read ECONNRESET at TCP.onStreamRead (internal/stream_base_commons.js:111:27)

Using Polling like below to check if the content of the file is changed then, other two functions are called
var poll_max_date=AsyncPolling(function (end,err) { if(err) {
console.error(err); } var stmp_node_id=fs.readFileSync(path.join(__dirname,'node_id'),"utf8");
console.log("--------loaded node : "+stmp_node_id);
if(druid_stmp_node_id!=stmp_node_id) {
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// // DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire();
druid_stmp_node_id=stmp_node_id; }
end(); }, 1800000).run();//30 mins
Its working fine for sometime, but then getting below error like after 4 - 5hours :
events.js:167
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:111:27) Emitted 'error' event at:
at emitErrorNT (internal/streams/destroy.js:82:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:50:3)
tried using fs.watch to monitor the changes in the file instead of polling like below :
let md5Previous = null; let fsWait = false;
fs.watch(dataSourceLogFile, (event, filename) => { if (filename) {
if (fsWait) return;
fsWait = setTimeout(() => {
fsWait = false;
}, 1000);
const md5Current = md5(fs.readFileSync(dataSourceLogFile));
if (md5Current === md5Previous) {
return;
}
md5Previous = md5Current;
console.log(`${filename} file Changed`);
// MAX DATA CUT-OFF DRUID QUERY
druid_exe.max_date_query_fire();
// DRUID QUERY FOR GLOBAL DATA
druid_exe.global_druid_query_fire(); } });
Its is also working fine for sometime, but then getting same error like after 4 - 5hours :
events.js:167 throw er; // Unhandled 'error' event ^
Error: read ECONNRESET at TCP.onStreamRead
(internal/stream_base_commons.js:111:27) Emitted 'error' event at: at
emitErrorNT (internal/streams/destroy.js:82:8) at emitErrorAndCloseNT
(internal/streams/destroy.js:50:3)
But when run in Local Machine, its working fine. the error occurs only when run in remote Linux Machine.
somebody can help me how I can fix that problem?
Use fs.watchFile once , because fs.watch is not consistent across platforms,
https://nodejs.org/docs/latest/api/fs.html#fs_fs_watchfile_filename_options_listener
Change your code according to the requirement.
It has been happening since the users are closing the browser before the data request is received, leading to Connection Reset.
Used PM2 (http://pm2.keymetrics.io/) to run the application, and it is working great now .

UDP multicast failing - NodeJS / Windows 10

I am beating my brains out trying to get this to work. I read all the other answers related to NodeJS UDP on SO already, but to no avail. I am on Windows 10.
Here is the error I am getting:
Uncaught Exception: Error: write ENOTSUP
at exports._errnoException (util.js:1022:11)
at ChildProcess.target._send (internal/child_process.js:654:20)
at ChildProcess.target.send (internal/child_process.js:538:19)
at sendHelper (cluster.js:751:15)
at send (cluster.js:534:12)
at cluster.js:509:7
at SharedHandle.add (cluster.js:99:3)
at queryServer (cluster.js:501:12)
at Worker.onmessage (cluster.js:450:7)
at ChildProcess.<anonymous> (cluster.js:765:8)
at emitTwo (events.js:111:20)
at ChildProcess.emit (events.js:191:7)
at process.nextTick (internal/child_process.js:744:12)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickDomainCallback [as _tickCallback] (internal/process/next_tick.js:122:9)
Here is my code:
let dgram = require('dgram'),
server = dgram.createSocket('udp4'),
multicastAddress = '239.255.255.250',
multicastPort = 1900,
myIp = '192.168.51.133';
server.bind(multicastPort, myIp, function () {
server.setBroadcast(true);
server.setMulticastTTL(128);
server.setInterface.getbyname(myIp);
server.addMembership(multicastAddress, myIp);
});
//wait for incoming messages and print ip address
server.on('message', function (data, rinfo) {
console.log(new Date() + ' RECEIVER received from ', rinfo.address, ':');
console.log(data.toString());
});
//Set up discovery message. Make sure to leave out any extra space in the message.
var discover_message = new Buffer('M-SEARCH * HTTP/1.1\r\nHost: 239.255.255.250:1900\r\nMan: ssdp:discover\r\nST: colortouch:ecp\r\n');
server.send(discover_message, 0, discover_message.length, 1900, multicastAddress);
Finally found an answer for this. The issue is due to being on Windows and using clusters in Node. The problem is on the server.bind call. Here is the correct, working code:
server.bind({port: 1900, exclusive: true}, function () {
console.log('PORT BIND SUCCESS');
server.setBroadcast(true);
server.setMulticastTTL(128);
server.addMembership(multicastAddress, myIp);
});
The fix was to pass in the object {port: 1900, exclusive: true}. Source: https://github.com/misterdjules/node/commit/1a87a95d3d7ccc67fd74145c6f6714186e56f571

RangeError: Invalid status code: 0 error in node, express?

if i give error message like this it working fine without problem
res.status(401).send('not found, please register');
but when i change to this one i am getting error
return res.status('EXTINF-10202').json({
'message': 'not found, please register'
});
i am getting error like this
F:\test\node_modules\mongoose\node_modules\mongodb\lib\utils.js:97
process.nextTick(function() { throw err; });
^
RangeError: Invalid status code: 0
at ServerResponse.writeHead (_http_server.js:192:11)
at ServerResponse.writeHead (F:\test\node_modules\on-headers\index.js:
55:19)
at ServerResponse.res.writeHead (F:\test\node_modules\express-session\
index.js:169:17)
at ServerResponse._implicitHeader (_http_server.js:157:8)
at ServerResponse.res.write (F:\test\node_modules\compression\index.js
:90:14)
at ServerResponse.res.end (F:\test\node_modules\compression\index.js:1
11:14)
at F:\test\node_modules\express-session\index.js:182:13
at F:\test\node_modules\connect-mongo\lib\connect-mongo.js:365:9
at handleCallback (F:\test\node_modules\mongoose\node_modules\mongodb\
lib\utils.js:95:12)
at F:\test\node_modules\mongoose\node_modules\mongodb\lib\collection.j
s:666:5
at F:\test\node_modules\mongoose\node_modules\mongodb-core\lib\topolog
ies\server.js:795:13
at Callbacks.emit (F:\test\node_modules\mongoose\node_modules\mongodb-
core\lib\topologies\server.js:94:3)
at Connection.messageHandler (F:\test\node_modules\mongoose\node_modul
es\mongodb-core\lib\topologies\server.js:235:23)
at Socket.<anonymous> (F:\test\node_modules\mongoose\node_modules\mong
odb-core\lib\connection\connection.js:259:22)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
If you take a look at the ExpressJS source for res.status you will see that the function expects a Number, not a String:
/**
* Set status `code`.
*
* #param {Number} code
* #return {ServerResponse}
* #public
*/
res.status = function status(code) {
this.statusCode = code;
return this;
};
https://github.com/expressjs/express/blob/9722202df964bfbfc0f579e4baeb5a4e1b43b344/lib/response.js#L57-L68

node connect-timeout: how to suppress "ServiceUnavailableError: Response timeout" log message

I'm using the connect-timeout module. When the timeout fires, it seems to dump the following error message to the console:
ServiceUnavailableError: Response timeout
at IncomingMessage.<anonymous> (/app/node_modules/connect-timeout/index.js:75:8)
at emitOne (events.js:96:13)
at IncomingMessage.emit (events.js:188:7)
at Timeout._onTimeout (/app/node_modules/connect-timeout/index.js:48:11)
at ontimeout (timers.js:365:14)
at tryOnTimeout (timers.js:237:5)
at Timer.listOnTimeout (timers.js:207:5)
How do I suppress these log messages? I don't particularly want to see them, because the timeout firing is not really an indicator that there is a problem... it's just doing its job. And this is especially because I can add my own error handling middleware to express that can pick and choose what (if anything) to do with the error.
You need to catch this from express, the code should look like:
function errorHandler (err, req, res, next) {
console.log("Oops")
}
app.use(errorHandler)
For more info:
https://expressjs.com/en/guide/error-handling.html

Resources