Search code examples
javascriptembeddiscorddiscord.js

Discord.js - how do I edit message.embed() statements?


I am making a ping command - It is very simple to code, but I haven't got the slightest idea how to edit the embed I'm using. Here is my code - I'm using a command handler explaining the exports.run statement.

const Discord = require('discord.js')

exports.run = (bot, message, args) => {  
const pingUpdate = new Discord.MessageEmbed()
.setColor('#0099ff')
.setDescription('pinging...')
message.channel.send(pingUpdate);
}

exports.help = {
  name: 'ping'
}

I need to edit the ping update embed to make the .description edit to perform this (simple ping calculation)

message.channel.send('pinging...').then((m) => m.edit(`${m.createdTimestamp - message.createdTimestamp}ms`))

This would make the description change from 'pinging...' to 'examplepingms'

Thank you in advance


Solution

  • You don't actually have to create a new embed. You can edit the original:

    UPDATE: Per the docs, it is recommended to create new embeds, but you use the original embed to pre-populate the new embed. Then, just update what you need and edit the message with the new embed:

    // the original embed posted during collected.on('end')
    const embed = new MessageEmbed()
                        .setColor('0xff4400')
                        .setTitle(`My Awesome Embed`)
                        .setDescription('\u200b')
                        .setAuthor(collected.first().user.username, collected.first().user.displayAvatarURL())
                        .setImage(`https://via.placeholder.com/400x300.png/808080/000000?text=Placeholder`)
                        .setTimestamp(new Date())
                        .setThumbnail('https://via.placeholder.com/200x200.png/808080/000000?text=Placeholder');
    
    // In the original embed, I have a placeholder image that the user
    // can replace by posting a new message with the image they want
    client.on('messageCreate', async message => {
        // adding image to original embed
        if (message.attachments.size > 0 && !message.author.bot) {
            // get all messages with attachments
            const messages = await client.channels.cache.get('<CHANNEL>').messages.fetch();
                
            // get the newest message by the user
            const d = messages.filter(msg => msg.embeds.length > 0).filter(m => message.author.username === m.embeds[0].author.name).first();
            
            // create new embed using original as starter
            const tempEmbed = new MessageEmbed(d.embeds[0])
    
            // update desired values
            tempEmbed.setImage(message.attachments.first().url);
        
            // edit/update the message
            d.edit({ embeds: [tempEmbed] });
            
            // delete the posted image
            message.delete();
        }
    });