How do I use a local image on a discord.js rich embed? - discord.js

I have this code:
var datos = ["dato1","dato2","dato3"]
console.log ("》" + message.author.username + " introdujo el comando: " + message.content + " en " + message.guild.name);
let embed = new discord.RichEmbed()
.setTitle("Datos sobre gatos 🐈")
.setColor(12118406)
.setDescription(datos[Math.floor(Math.random() * datos.length)])
.setFooter("© 2018 República Gamer LLC", bot.user.avatarURL)
.setImage("http://i.imgur.com/sYyH2IM.png")
message.channel.send({embed})
.catch ((err) => {
console.error(err);
let embed = new discord.RichEmbed()
.setColor(15806281)
.setTitle("❌ Ocurrió un error")
.setDescription("Ocurrió un error durante la ejecución del comando")
message.channel.send({embed})
})
How can I use a local image path in place of a URL (on the .setImage() line)

Updated Luke's code to Discord.js v12 for anyone else in 2020 who has this same problem
const attachment = new Discord
.MessageAttachment('./card_images/sample.png', 'sample.png');
const embed = new Discord.MessageEmbed()
.setTitle('Wicked Sweet Title')
.attachFiles(attachment)
.setImage('attachment://sample.png');
message.channel.send({embed});

In discord.js v13 and on, MessageEmbed#attachFiles has been deprecated. You should directly add the files into the response from now on.
MessageEmbed#attachFiles has been removed; files should now be
attached directly to the message instead of the embed.
// Before v13
const embed = new Discord.MessageEmbed().setTitle('Attachments').attachFiles(['./image1.png', './image2.jpg']);
channel.send(embed);
// v13
const embed = new Discord.MessageEmbed().setTitle('Attachment').setImage('attachment://image.png');
channel.send({ embeds: [embed], files: ['./image.png'] });

This works for me.
const attachment = new Discord.Attachment('./card_images/sample.png', 'sample.png');
const embed = new RichEmbed()
.setTitle('Wicked Sweet Title')
.attachFile(attachment)
.setImage('attachment://sample.png');
message.channel.send({embed}).catch(console.error)

The other way to do it would be:
const attachment = new Discord.MessageAttachment('./help.png', 'help.png');
message.channel.send({
embed: {
files: [
attachment
],
image: {
url: 'attachment://help.png'
}
}
});

Hello! Unfortunately, Discord's API only accepts URLs and not local paths.
You can only upload your images to a server/image hosting website and get the URL.

Related

discordjs v14 - How to modify embed?

i try make embed
const exampleEmbed = new EmbedBuilder()
.setAuthor({ name: `name : ${name}` })
.setColor(0x0099ff)
.setTitle(`title: ${title}`)
.setDescription(`content : ${content}`)
make embed!!
looking for discordjs14 guide
// Resending a received embed
const receivedEmbed = message.embeds[0];
const exampleEmbed = EmbedBuilder.from(receivedEmbed).setTitle('New title');
channel.send({ embeds: [exampleEmbed] });
----------------------------------------------
// Editing the embedded message content
const exampleEmbed = new EmbedBuilder()
.setTitle('Some title')
.setDescription('Description after the edit');
message.edit({ embeds: [exampleEmbed] });
i try to get message.embed[0]
async execute(interaction) {
...
console.log(interaction.embed[0])
...
}
error:
i hope search title and edit embed...
If you want to send an embed and edit it on an event, You should make thay message a var.
const channel = <client>.channels.cache.get('channel_id');
let message = await channel.send({embeds: [exampleEmbed] });
// editing it
await message.edit({ embeds: [exampleEmbed1] });
Notes: Replace <client> with what you declared your client. it could be client , bot or anything you have declared it.
fist you need to make embed message
const embed = new EmbedBuilder()
.setColor("Your Color")
.setTitle("YourTitle")
.setThumbnail("your google image address")
.setImage("Your Google Image address")
.setDescription("Your Description")
and so much more stuff just type .set or .add it will show you so many of them
and for send the embed
message.reply({embeds : [embed]});

Discord.js v13 TypeError in slash command handler

I want to create a basic mute command that simply adds a role to the user without a time parameter, how can I implement this in Discord.js v13? I already have slash commands and a handler command setup however I am receiving the following error:
TypeError: Cannot read properties of undefined (reading 'cache')
My Code:
const { SlashCommandBuilder } = require("#discordjs/builders")
const { MessageEmbed } = require("discord.js")
const Discord = require("discord.js")
module.exports = {
data: new SlashCommandBuilder()
.setName("mute")
.setDescription("El bot muteara a un usuario del server")
.addUserOption(option =>
option
.setName("miembro") // target
.setDescription("Mencione al miembro que desea mutear")
.setRequired(true)
)
.addStringOption(option =>
option
.setName("razon") // reason
.setDescription("Razon por la que el usuario sera muteado")
.setRequired(true)
),
async run(client, interaction){
const target = interaction.options.getUser("miembro");
const reason = interaction.options.getString("razon");
if(!interaction.guild.roles.cache.get('902652079762468975')) return interaction.followUp({ embeds: [new MessageEmbed().setColor("RED").setDescription("El rol de muteado no existe")]})
await target.roles.cache.add("902652079762468975");
interaction.followUp({ embeds: [new MessageEmbed().setColor("GREEN").setDescription(`✅ ${target} ha sido muteado. Razon:${reason}`)]})
}
}
Assuming you are on the latest version of djs13, You want to use option.getMember() instead of option.getUser.
getUser returns the User object which does not have any guild information, including roles. getMember returns the GuildMember object which has reference to the roles cache. This will only work if the command is fired from a guild channel.
If you want your command available outside of the guild, you must use getUser and look the user's id up in the guild's member cache manually.
This may require changes to your command registration to accommodate the change in value type.
Documentation
This is the final code
async run(client, interaction){
const target = interaction.options.getMember("miembro");
const reason = interaction.options.getString("razon");
const embed = new Discord.MessageEmbed()
.setColor("GREEN")
.setDescription(`✅ ${target} has been muted. Reason:${reason}`)
await target.roles.add('role-id');
interaction.reply({ embeds: [embed]})
}

How do I make the returned message a embed? DISCORD.JS

Hey how do I make the returned message an embed?
return message.reply(`**Here is a list of commands:** \n *Type y!catagory for the commands of the catagory!* \n \n **Economy** \n *y!economy* `);
};
exports.help = {
name: "help",
aliases: ["h"],
usage: "help"
}
You can check v12 embeds guide or v13 embeds guide which can help you
Also some code example:
const embed = new Discord.MessageEmbed()
.setDescription(your_text)
.setTitle("Test Embed")
.setColor("RANDOM");
message.channel.send(embed)
Please note this code is for discord.js v12.x
For v13 you need to use the embeds property
const embed = new Discord.MessageEmbed()
.setDescription(your_text)
.setTitle("Test Embed")
.setColor("RANDOM");
message.channel.send({ embeds: [embed] })

How do I make my discord bot send an attachment when certain word is sent

I'm new to working with discord bot and decided to try it out, to start I just wanted to make the bot send an attachment (image, video, etc) when for example, "sendpicture" is written in chat.
I've changed the code several times yet I get the same error everytime, "Attachment is not a constructor" or "Discord.Attachment is not a constructor".
My current code looks like this:
const client = new Discord.Client();
client.once(`ready`, () => {
console.log("online");
});
const PREFIX = "!"
//replying with a text message
client.on('message', msg => {
if (msg.content === 'test1') {
msg.channel.send('working');
}
});
//replying with attachment
client.on("message", function(message){
let args = message.content.substring(PREFIX.lenght).split(" ");
switch(args[0]) {
case "test2":
message.channel.send(new Discord.Attachment(`.a/this/bestpic.png`, `bestpic.png`) )
.then(msg => {
//aaaaaaaa
})
.catch(console.error);
break;
}
})
tyia
Had you tried looking at the official documentation ?
I don't think you should use new Discord.Attachment(), try this instead :
switch(args[0]) {
case "test2":
message.channel.send({
files: [{
attachment: '.a/this/bestpic.png',
name: 'bestpic.png'
}]
}).then(msg => {
//aaaaaaaa
}).catch(console.error);
break;
}
Discord.Attachment() is not a thing, i believe the answer you are looking for is this :)
new Discord.MessageAttachment()
Try this code, short and simple to use.
if (message.content.toLowerCase() === 'word') { //only word, without prefix
message.channel.send({ files: ['./path_to_your_file'] })
}
You should try using MessageAttachment because Discord.Attachment is not a thing, then add the attachment into the files property
I would consider making the attachment a variable instead of putting it directly into the function, it is optional tho
const { MessageAttachment } = require("discord.js");
const attachment = new MessageAttachment("url", "fileName(optional)", data(optional));
message.channel.send({ files: [attachment] }).then(//code...)
Let me know if it works

Embed not settings image and thumnail

When a user joins the server the bot will send an embed. Everything works fine except the image and thumbnail.
Client.on('guildMemberAdd', member => {
const embed = new Discord.MessageEmbed()
.setTitle(`Welcome ***${member.displayName}***`)
.setColor("#2163D7")
.addFields({ name: `**${member.displayName}**`, value: 'Please read the **rules**'},{ name: `You are our ` , value: `***${member.guild.memberCount}*** member!`})
.setImage(member.user.avatarURL)
.setThumbnail(member.user.avatarURL)
console.log(member.user.avatarURL);
let channel = member.guild.channels.cache.find(channel => channel.name === "🚪┊𝙱𝚒𝚎𝚗𝚟𝚎𝚗𝚞𝚎");
channel.send(embed);
});
Image of what it returns
Thanks for your help :)
In Discord JS v12, avatarURL is a method. So you'll have to use:
member.user.avatarURL()

Resources