Unhandled promise warn. How to fix it? - javascript

I have bot which get user message content, delete user message, then send private message to message.author and then send content of user message in embed.
After few messages bot sends 2 messages instead of 1 and warn appears. Any idea how to fix it?
Warn:
superadmin#vps-XXXXXX:~/path$ node test.js (node:1059)
UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Message
at RequestHandler.execute (path/node_modules/discord.js/src/rest/RequestHandler.js:170:25)
at processTicksAndRejections (internal/process/task_queues.js:97:5) (node:1059)
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: 1) (node:1059) [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.
Script:
const discord = require('discord.js');
const client = new discord.Client;
client.on('message', message => {
if (message.author === client.user && message.channel.id !== (508728211837026325)) {
return;
}
if (message.channel.id == (508728211837026325)) {
message.delete();
message.author.send("Success!");
message.channel.send({
"embed": {
"color": 61183,
"description": message.content + "\n\nCreated by: " + "<#" + message.author.id + ">",
"author": {
"icon_url": "imgururl;",
"url": "imgururl",
"name": "test",
},
timestamp: new Date()
}
})
}
})
client.login('token');

The behavior you describe is probably caused by the fact that your bot is launched twice at the same time. Indeed, if your bot is launched twice:
you're getting the Unknown Message warning, as the message was already deleted by another instance of the bot.
the bot sends the message twice.
Read this post, it should fix your issue.

The bot is being activated by himself.
if (message.author === client.user && message.channel.id !== (508728211837026325))
# should probably be
if (message.author === client.user || message.channel.id !== (508728211837026325))
On another note, the channel id is a twitter snowflake, which can be as big as a uint64, for javascript, that means you can't handle an id that is too large because the limit is 9007199254740991, so you should use the string versions.
if (message.channel.id === "508728211837026325")

Related

(node:42790) UnhandledPromiseRejectionWarning: Error: socket hang up

I am trying to send POST request from a NodeJs script to Python server (running with flask and waitress).
Most of the times the request is failed with the below error.
(node:42790) UnhandledPromiseRejectionWarning: Error: socket hang up
at connResetException (internal/errors.js:639:14)
at TLSSocket.socketOnEnd (_http_client.js:499:23)
at TLSSocket.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1334:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:42790) 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: 2)
(node:42790) [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 am using NodeJs with axios package to send the request, and the configuration is as given below:
let axiosClient = axios.create({
timeOut: 300000,
maxContentLength: Infinity,
maxBodyLength: Infinity,
httpsAgent: new https.Agent({ keepAlive: true }),
httpAgent: new http.Agent({ keepAlive: true }),
});
let response = await axiosClient.post(end_point_url, data);
And when I checked in the server I could see that the 200 response is being sent, however in the client it is throwing an error.
My expectation is it should be successful in the first try, hence catching the error and retrying may not help in my case as most of the times it fails anyways.
Could you please guide in finding the root cause and fixing the same.
Thank you
let response = await axiosClient.post(end_point_url, data);
You should check end points correctly and use it in try and catch block

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.

Discord.MessageAttachment() not attaching to embed

So I am trying to attach an image to a discord embed (preferably as the thumbnail). The image is locally stored on my hard drive. I am currently doing it this way:
attachment = await new discord.MessageAttachment('serverFavicon.png', 'favicon.png');
embed.setThumbnail(attachment);
and this returns this error and not send the embed:
(node:60598) UnhandledPromiseRejectionWarning: DiscordAPIError: Invalid Form Body
embed.thumbnail.url: Could not interpret "{'attachment': 'serverFavicon.png', 'name': 'favicon.png'}" as string.
at RequestHandler.execute (/Users/manders/Desktop/Bots/Minecraft Server Discord Bot/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async RequestHandler.push (/Users/manders/Desktop/Bots/Minecraft Server Discord Bot/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:60598) 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: 1)
(node:60598) [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.
The strange thing is if I do
message.channel.send('Image', attachment);
It will successfully send the image.
So I am wondering why it won't attach to the embed, but it can send to a channel.
setThumbnail only accepts a string (the URL of the image), not a MessageAttachment.
In your example, you can simply use the URL of the image:
embed.setThumbnail('serverFavicon.png');
If you want to rename the image, you can attach the MessageAttachment when sending the message and use attachment://image-name.png for the thumbnail URL:
// You also don't need to use await here; constructors can't be async
const attachment = new discord.MessageAttachment('serverFavicon.png', 'favicon.png');
embed.setThumbnail('attachment://favicon.png');
// ...
// Discord.js v12:
message.channel.send({embed, files: [attachment]});
// Discord.js v13:
message.channel.send({embeds: [embed], files: [attachment]});
See the Discord developer docs for more information on using attachments in embeds.

Post url-encoded Api in nodejs but still got error

Hi I'm new in javascript, I try to post url-encoded Api from lala.ai. I,m followed the instructions from the internet but still got an error. below I put the code and results.
//This is the instruction
POST /api/preview/
Puts a file in the preview queue (the first minute of vocals).
Parameters (form-urlencoded):
id (str): File id obtained from /upload/ method.
filter_type (int, optional): Number of postprocess iterations with MWF.
webpush-callback (json, optional): Client data for sending push notifications.
Returns (json):
{
"status": "success" | "error"
"error": Error description if the status is "error"
}
Examples:
$ curl --url https://www.lalal.ai/api/preview/ --form-string "id=9a3ae258-7693-4046-87c2-ef577eb752bb" --form-string "filter_type=2"
{"status": "success"}
$ curl --url https://www.lalal.ai/api/preview/
{"status": "error", "error": "No file id"}
This is what I have tried
const qs = require("qs");
axios
.post(
"https://www.lalal.ai/api/preview/",
{
data: qs.stringify({
id: "4d2f9262-e578-4290-97d3-43303fffbf56",
filter_type: "2",
}),
},
{
headers: {
"content-type": "application/x-www-form-urlencoded;charset=utf-8",
},
}
)
.then((result) => {
console.log(result);
});
This the error result I got
(node:34480) UnhandledPromiseRejectionWarning: Error: Request failed with status code 403
at createError (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\createError.js:16:15)
at settle (D:\reactjs\upload_lalal\server\node_modules\axios\lib\core\settle.js:17:12)
at IncomingMessage.handleStreamEnd (D:\reactjs\upload_lalal\server\node_modules\axios\lib\adapters\http.js:244:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:34480) 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: 2)
(node:34480) [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.
Can someone explain to me why that is error and how to fix it? Thanks.
Your error is... HTTP 403, which means
The HTTP 403 is a HTTP status code meaning access to the requested resource is forbidden
Do you need an access token to use the API?

Sending message to specific channel based on an argument

I have searched up and found multiple forum posts on both Reddit and StackOverflow where users are asking how to send a message to the specific channel, but I cannot find one where you can send to a specific channel using an Argument. What I mean is that you use
return bot.channels.get(channel).send(embed);
I have been testing around with this "function" and have managed to send the message to a specific channel, but it also includes the arg[0] aka the channel id. The command is
announce "CHANNEL ID" "MESSAGE"
It does send the embed with the message to that specific channel I input, but It adds the CHANNEL ID to the embed, so I tried to use arg[0] in the embed's .setDescription(arg[0]) but it didn't work. It spat out an error message to me which I have no idea what means. But maybe one if you pro's out there know what I can do. Here is the entire command Code:
if (cmd === `${prefix}announce`) {
console.log(message.author.username + " executed an Announcement in the channel #" + message.channel.name);
const embed = new Discord.RichEmbed()
.setColor("#e56b00")
.setAuthor("Announcement from " + message.author.username, message.author.avatarURL)
.setDescription(arg)
.setFooter(message.author.username)
.setTimestamp();
return bot.channels.get(channel).send(embed);
}
And here is the error code. Note that the error only pops up when I put arg[0] in the .setDescription() part of the embed. The channel let works fine with arg[1]
(node:7900) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'send' of undefined
at Client.bot.on (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\index.js:32:34)
at Client.emit (events.js:182:13)
at MessageCreateHandler.handle (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\node_modules\discord.js\src\client\websocket\packets\handlers\MessageCreate.js:9:34)
at WebSocketPacketManager.handle (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\node_modules\discord.js\src\client\websocket\packets\WebSocketPacketManager.js:103:65)
at WebSocketConnection.onPacket (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:333:35)
at WebSocketConnection.onMessage (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\node_modules\discord.js\src\client\websocket\WebSocketConnection.js:296:17)
at WebSocket.onMessage (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\node_modules\ws\lib\event-target.js:120:16)
at WebSocket.emit (events.js:182:13)
at Receiver._receiver.onmessage (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\node_modules\ws\lib\websocket.js:137:47)
at Receiver.dataMessage (C:\Users\Admin\Desktop\Discord Bots\DISCORDBOSS.js\node_modules\ws\lib\receiver.js:409:14)
(node:7900) 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:7900) [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.
You could use the message.mentions property. So you would do the following:
let announceChannel = message.mentions.channels.first();
Then to send the message do the following;
message.guild.channels.find(t => t.id == announceChannel.id).send(myMessage);

Categories

Resources