Twitter Bot Error - Unhandled Promise Rejection? - javascript

I wrote this twitter weather bot, which worked fine since last month, but an hour ago it crashed and I can't seem to bring it back up.
Can anyone simply explain me what it is and also what the error is, when it arises and what I have to check to get rid of this warning?
I did search up how to fix an "unhandled promise rejection" but could not find out what it is.
const Twit = require('twit');
const config = require('./config');
const rp = require('request-promise-native');
async function setup(location) {
const options = {
url: "http://api.apixu.com/v1/current.json",
qs: {
key: API_KEY,
q: location
},
json: true
};
let result = await rp(options);
let condition = result.current.condition.text;
let tweetText = `The condition in ${location} is currently ${condition}, and the temperature is ${result.current.temp_c}°C.`;
console.log(tweetText);
sendTweet(tweetText)
}
function sendTweet(text) {
const T = new Twit(config);
var r = Math.floor(Math.random()*1000);
const tweet = {
status: '[' + r + '] ' + text
}
T.post('statuses/update', tweet);
}
setup('Colombo');
2019-08-21T06:41:52.820595+00:00 app[scheduler.8141]: at setup (/app/bot.js:25:36)
2019-08-21T06:41:52.820597+00:00 app[scheduler.8141]: at process._tickCallback (internal/process/next_tick.js:68:7)
2019-08-21T06:41:52.820719+00:00 app[scheduler.8141]: (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
2019-08-21T06:41:52.820834+00:00 app[scheduler.8141]: (node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2019-08-21T06:41:52.903455+00:00 heroku[scheduler.8141]: State changed from up to complete
2019-08-21T06:41:52.880762+00:00 heroku[scheduler.8141]: Process exited with status 0```

When you call the api with:
let result = await rp(options);
You are setting result as a promise to wait for the API call, but your request is not accepted for some reason and then you are getting a promise rejection but not handling.
Please use:
await rp(options).catch(err => console.log(err))
So you can log your error, then we can investigate your error.
---------- EDIT ------------
Just tested it myself, and we are getting a 503 HTTP Status code:
Here is the log print
It means that the service is not available, not receiving requests.
---------- EDIT -----------
It is working again, tried here, I'm getting 200 HTTP Status code and a good response, now you should be good to go

Related

Discord bot returning permission errors

My Discord bot keeps returning these errors and I'm not sure how to deal with them since I'm still very new to this whole coding thing.
UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:15) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 39)
It seems to happen whenever someone attempts to use a command in a Discord channel where my bot cannot send messages.
This is the code I use for a command:
client.on("message", async message => {
if (message.author.bot || message.content.trim() == "") return;
if (message.content.toLowerCase().trim() == "cat") {
const { file } = await fetch("https://aws.random.cat/meow").then(response =>
response.json()
);
return message.channel.send(new $().setColor("RANDOM").setTitle("Your Cat").setImage(file).setFooter('Powered by Catastic'));
}
});
I hope ya'll can help me!
Your bot doesn't have permissions to send a message to the channel the user have written in. Try giving the "Send Messages" permission in that channel using the Permissions menu.

Why am I getting multiple responses when I'm using async/await?

I'm writing a simple voting web api for a class. I'm currently working on PUT and my code is working, but I'm getting a strange error in my command line terminal. Here is the code I'm using to call PUT:
async addVotes(item) {
try {
let response = await axios.put("/api/candidates/" + item._id);
this.getItems();
return true;
}
catch (error) {
console.log(error);
}
console.log(item.name + " is checked");
},
async submitVotes(items) {
for (var item of this.items) {
if (item.selected) {
this.addVotes(item);
}
else {
console.log(item.name + " is not checked");
}
}
},
and here is the PUT code for the api:
app.put('/api/candidates/:id', async(req, res) => {
console.log("initiated put(edit) request");
try {
let candidate = await Candidate.findOne({ _id: req.params.id });
candidate.numVotes += 1;
candidate.save();
res.send(candidate);
res.sendStatus(200);
}
catch (error) {
console.log(error);
res.sendStatus(500);
}
});
I'm getting an error saying this:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:102:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (/var/www/html/MidRev/node_modules/express/lib/response.js:771:10)
at ServerResponse.contentType (/var/www/html/MidRev/node_modules/express/lib/response.js:599:15)
at ServerResponse.sendStatus (/var/www/html/MidRev/node_modules/express/lib/response.js:357:8)
at app.put (/var/www/html/MidRev/start.js:106:9)
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:13246) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:13246) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
From what I've researched online I'm getting this error because I'm getting more than one response, but I am using async/await so I don't understand why I should be getting that error.
The way you add status to the response is incorrect.
Instead of
res.send(candidate);
res.sendStatus(200);
You should do it this way
res.status(200).send(candidate)
sendStatus sends an 'OK' message on top of setting the status code. You may refer to the Express API reference here https://expressjs.com/en/api.html
The problem is with your PUT API implementation in which you're sending the response twice:
res.send(candidate); // sending json response back to client
res.sendStatus(200); // trying to send response status
So if you're sending a json response then you do not need to send response status explicitly.
res.send(candidate); OR res.json(candidate);
However, if you want to specify the response status then you can do chaining like:
res.status(500).send({ error: "boo" });

My API endpoint is not returning the expected output

I have written a backend app with Express JS to retrieve info from a database through GET requests from an API endpoint. The query that I have used to GET from API endpoint is working in the Database , but I could not fetch the same details in a Web Browser as Response using Express JS. Tried my best to find out the issue, but I couldn't.
I tried to check whether I had a problem with my query, but the query is fetching the correct details, but I couldn't get any response in the web browser.
Here is my code where I think I had a bug :
const { rows } = await pool.query(
'SELECT branches.ifsc, branches.bank_id, branches.branch, branches.address, branches.city, branches.district, branches.state FROM branches WHERE branches.branch LIKE $1% LIMIT $2 OFFSET $3' ,
[q, limit, offset]
);
res.send(rows[0]);
});
SQL Query used to Fetch Details:
SELECT branches.ifsc, branches.bank_id, branches.branch, branches.address, branches.city, branches.district, branches.state FROM branches WHERE branches.branch LIKE '%RTGS%' ORDER BY branches.ifsc LIMIT 3;
Error Log:
Server is running on 7000
(node:19484) UnhandledPromiseRejectionWarning: error: syntax error at or near "LIMIT"
at Connection.parseE (/home/kiddo/Desktop/backend/node_modules/pg/lib/connection.js:604:11)
at Connection.parseMessage (/home/kiddo/Desktop/backend/node_modules/pg/lib/connection.js:401:19)
at Socket.<anonymous> (/home/kiddo/Desktop/backend/node_modules/pg/lib/connection.js:121:22)
at Socket.emit (events.js:200:13)
at addChunk (_stream_readable.js:294:12)
at readableAddChunk (_stream_readable.js:275:11)
at Socket.Readable.push (_stream_readable.js:210:10)
at TCP.onStreamRead (internal/stream_base_commons.js:166:17)
(node:19484) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:19484) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I suspect using $1% is causing issues in your sql statement. Try the following instead.
const { rows } = await pool.query(
'SELECT branches.ifsc, branches.bank_id, branches.branch, branches.address, branches.city, branches.district, branches.state FROM branches WHERE branches.branch LIKE $1 LIMIT $2 OFFSET $3' ,
['%'+q+'%', limit, offset]);
Try With Callback function.
con.query("YOUR SQL QUERY HERE", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
parameter substitution Example
var sql = "SELECT * FROM table WHERE field1 = ? AND field2 >= ?";
connection.query(sql, [value1, value2], function(err, result, fields) {
//do your operations HERE
console.log(result);
});

Socket Hang Up error with no common symptoms

I'm running a small HTTP server on an RPI3B. It logs every request made, so in Postman, I can make a request to the server and it is received, logged and returns the correct value. However, using this function:
function get(action, path, content) {
return new Promise(function(resolve, reject) {
let body = "";
let req = http.request({
host: "10.0.0.12",
method: content ? "post" : "get",
path: `${action}?path=${path}`,
headers: {
token
}
}, res => {
res.on('data', data => {
body += data;
})
res.on("end", e => {
resolve(body.toString());
})
});
req.end(content);
req.on("error", e => {
reject(e);
})
});
}
I get the following error:
(node:24956) UnhandledPromiseRejectionWarning: Error: socket hang up
at createHangUpError (_http_client.js:313:15)
at Socket.socketOnEnd (_http_client.js:416:23)
at Socket.emit (events.js:187:15)
at endReadableNT (_stream_readable.js:1081:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
(node:24956) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an asyn
c function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:24956) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not
handled will terminate the Node.js process with a non-zero exit code.
I have looked at common symptoms of this error and noted that I receive the error immediately after the request is sent (as opposed to when the request times out). I also noted that I have the req.end() method called to ensure the request is ended, but the result remains the same.
Any insight as to how this might be caused and how it might be resolvable would be greatly appreciated.
Note Both sides are written in Node.JS

Getting an array from folder and sending a random file with discord.js

I'm trying to create a command, when requested will send a random image from a folder. I don't want to have to name them cause I have a server with a PHP server where my friends can upload images for the bot to post. This is what I have:
if(command === "meme") {
const path = '/img/memes/';
const fs = require('fs');
fs.readdirSync(path).forEach(file => {
ranfile = Math.floor(Math.random()*file.length);
message.channel.sendFile(ranfile);
})
return;
}
When I run the bot with Node.js I get this error:
(node:4840) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
Anyone know what the issue is?
This is probably just a regular error wrapped in an UnhandledPromiseRejectionWarning. Have you tried running with --trace-warnings?
This should solve the problem of getting to the actual issue by providing a reasonable stack trace.

Categories

Resources