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.
Related
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
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.
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?
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")
I am new to node.js and mongoDB Atlas. I am having an issue connecting to Mongo Atlas using the Node.js version 3.0 or later connection string.
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
When I use this connection string I get the following error -
MongoDB connection error: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0-nnezr.mongodb.net'
}
(node:38809) UnhandledPromiseRejectionWarning: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19)
(Use node --trace-warnings ... to show where the warning was created)
(node:38809) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside ofan 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:38809) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections thatare not handled will terminate the Node.js process with a non-zero exit code.
I have found a workaround using the previous connection string for node.js version 2.2.12 -
mongodb://<user>:<password>#cluster0-shard-00-00-nnezr.mongodb.net:27017,cluster0-shard-00-01-nnezr.mongodb.net:27017,cluster0-shard-00-02-nnezr.mongodb.net:27017/<dbname>?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority
When connecting I have to add {useUnifiedTopology: true}
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
Can anyone give me a little insight on what im doing wrong with the new connection string?
Thanks!
have write user, password and maybe also database ,
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
user = your mongodb user name
password = your mongodb password
dbname = Database name
and don't forget to create a new user in MongoDB atlas.